This commit is contained in:
Jorijn van der Graaf 2026-11-01 18:35:23 +01:00
commit 1ea50c50bc
62 changed files with 9982 additions and 608 deletions

4
.gitignore vendored
View file

@ -1,2 +1,4 @@
bin/
build/
build/
# written by every build from AGENTS.template.md
/AGENTS.md

115
AGENTS.consumer.md Normal file
View file

@ -0,0 +1,115 @@
## nostro
nostro is a banking client for Linux in three parts. The library is a C++26 module, `import Nostro;`, that talks to a bank's API directly (bunq so far), keeps the credentials in one private JSON file, caches transactions in Crafter.DB tables, and lists, syncs, pays, requests and schedules. nostrod is a system daemon that runs that library for every local user, one worker process each, behind D-Bus and polkit. The `nostro` CLI is a client of nostrod. A consumer does one of three things:
- links the library and holds the credentials itself, in its own process (`--lib --banks=bunq`);
- talks to nostrod through `Nostro::Client` (`--lib --banks=bunq --dbus`), as the CLI does;
- or, as an app that only needs a customer to pay an order, links the `Nostro.Checkout` module alone (`--product=checkout`), see "Checkout".
Everything is in `namespace Nostro`: the OpenSSL helpers in `Nostro::Crypto`, the D-Bus names and wire in `Nostro::Bus`, the checkout in `Nostro::Checkout`. Linux only (Crafter.DB, the POSIX calls in its file layer, libsystemd), built by crafter-build's clang 23 with `import std;`. LGPL-3.0-only; `lib/json.hpp` is nlohmann/json 3.12.0 (MIT). The README is the user-facing manual; these notes are its `AGENTS.consumer.md`: a fix to them goes there, not into the copy crafter-build writes.
### Building against it
- `GitProject` with nostro's repository, or `LocalProject({ .projectFile = "<checkout>/project.cpp", .args = nostroArgs })` for a checkout, into `cfg.dependencies`. `nostroArgs` is your own `ProjectArgs()` plus `--lib` and `--banks=bunq`, built once inside `CrafterBuildProject`: without `--lib` nostro's `project.cpp` returns the CLI executable configuration (with the library as its dependency, which you cannot import from), and without `--banks=` it throws "must enable atleast one bank" and the whole build stops at load. `--banks=` is a comma-separated list and `bunq` is the only name it accepts.
- `--dbus` with `--lib` adds the partitions that talk to nostrod, `:Bus`, `:Client` and `:Daemon`, and links `-lsystemd` (sd-bus) for you; it needs bunq on, since the wire carries bunq's types. Without it the library does not depend on libsystemd. `--product=checkout` instead returns the `nostro-checkout` library alone: the module `Nostro.Checkout`, needing neither `--lib` nor `--banks=`, and linking libsystemd and nothing else of nostro's (no OpenSSL, Crafter.Network or Crafter.DB).
- nostro strips its own args (`--lib`, `--banks=`, `--dbus`, `--product=`, `--coverage`, `--profile-runtime=`) from what it hands its dependencies and forwards the rest, adding `--no-quic` for Crafter.Network: nostro speaks HTTP/1.1 only, and msquic would tie the binary to the building user's cache. A consumer that also loads Crafter.Network gives it that same list, `--no-quic` included, and Crafter.DB the list without it, or the build stops with two loads that disagree on their args.
- What comes with it: Crafter.Network (with Crafter.Thread behind it), Crafter.DB, `-lssl -lcrypto`, and with `--dbus` `-lsystemd`, all as link flags you do not declare. Nothing in nostro uses the thread pool, so `ThreadPool::Start()` is not needed for it.
- Defines do not cross a dependency. nostro compiles with `NOSTRO_BUNQ_ENABLED`, `NOSTRO_OPENSSL_ENABLED` and, under `--dbus`, `NOSTRO_DBUS_ENABLED`, and the PCMs carry the result: `import Nostro;` exports `BunqConnector` and `Client`, and `EnabledBanks` lists bunq, whatever your configuration defines (nostro's own CLI compiles without them). Your own `#ifdef NOSTRO_BUNQ_ENABLED` sees it only when you push the same `Define` into your `cfg.defines`, as nostro's CLI configuration does with `execfg.defines = libcfg.defines`.
- `import Nostro;` is enough for everything below; nothing exposed needs `import Crafter.Network;` or `import Crafter.DB;`. The raw bunq calls (`Get`, `Post`, `Put`, `Delete`, `List`) take and return `nlohmann::json`: hold the result in `auto`, and include `lib/json.hpp` where you have to name or build one.
- Static initialisers run at load: `Nostro::configPath` and `cachePath` read `XDG_CONFIG_HOME` and `XDG_CACHE_HOME`, else `HOME`, and throw (so `std::terminate`) when neither is set. The HTTPS clients are function-local statics, made on the first bunq call.
### Money, currencies and time
- `Currency` is an `enum class` with `Euro` alone. `GetCurrency("EUR")` (or `"eur"`) is the only parse; anything else throws `std::runtime_error("unsupported currency '…'")`. `RefreshAccounts` skips a bank account in another currency with a `Note` instead. `GetCurrencyCode` gives `"EUR"`, `GetCurrencySymbol` `"€"`, `GetCurrencyDecimals` 2; `std::format("{}", Currency::Euro)` is the symbol. All `constexpr`.
- Amounts and balances are `std::int64_t` in the minor unit, so `1250` is €12.50, outgoing negative. `ParseAmount("12.50", Currency::Euro)` is `1250`: an optional leading `-`, digits, an optional `.` with at most `decimals` digits, nothing else, or `std::runtime_error("malformed amount '…'")`. `FormatAmount(1250, Currency::Euro)` is `"12.50"`, `FormatAmount(-5, …)` `"-0.05"`, and `FormatMoney(-102, …)` `"-€1.02"`, the sign before the symbol. All `constexpr`.
- `ParseTimestamp("2026-10-31 12:34:56.123456")` is a `std::chrono::system_clock::time_point`, read as UTC: exactly `YYYY-MM-DD HH:MM:SS`, optionally `.` and one to six fraction digits, no zone, or `std::runtime_error("malformed timestamp '…'")`. `FormatTimestamp` is its inverse, bunq's format. libc++'s `system_clock` ticks in microseconds, which is also what the tables store.
- For dates a person types: `ParseLocalDate("2026-10-31")` or `ParseLocalDate("2026-10-31 09:30")` in the local time zone (through `mktime`), or `std::runtime_error` naming the format; `ParseLocalDate(day, 1)` is the midnight that ends `day`, counted by the calendar, so a day the clocks change is 23 or 25 hours. `FormatLocalTime(time)` is `"YYYY-MM-DD hh:mm"` in local time.
- `UrlEncode` percent-encodes all but RFC 3986's unreserved characters; `UrlDecode` undoes it and reads `+` as a space; `QueryParameter(url, name)` is the decoded value from the query string, or `std::nullopt`. `EscB(text)` escapes text for inside a JSON string literal; nostro itself no longer builds JSON by hand.
### Connectors, the config file and the process
- `Connector::LoadConnectors()` reads `<config>/connectors.json`. A missing file is no connectors yet, not an error. It fills every bank's `connectors` first and then calls `RefreshAccounts()` on each, a network round trip per connector. A connector whose refresh throws keeps no accounts and is reported through `Note` (`bunq connector '<name>' is unavailable: …`), so the others stay usable. A file that is not JSON throws `std::runtime_error("<path> is not valid JSON (it breaks at byte N)")`, which never quotes the file, as nlohmann's own message could quote a private key (since 2026-11-01; it was a `nlohmann::json::parse_error`). Valid JSON with a missing or mistyped key still throws nlohmann's `json::exception`. Call it once at start-up, on the thread that will do the bank calls.
- `Connector::SaveConnectors()` writes the file for every enabled bank: to `connectors.json.tmp-<pid>` (`0600` in a `0700` directory, through `CreatePrivateFile`), `fsync`, rename over the old file, `fsync` of the directory. A crash or power cut leaves one whole file. `Create` does not call it. nostro does, by itself, after it renews a session and after it fetches a missing server key, so the connectors you hold must be the ones in `BunqConnector::connectors`. The file holds the API key or OAuth token, both tokens and the unencrypted RSA private key PEM, per connector `environment`, `apiKey`, `installationToken`, `sessionToken`, `sessionId`, `privateKey`, `serverPublicKey`, `userType`, `name`, `id`, `ownerId`; treat it accordingly and never commit one. Files from before 2026-10-31 lack `environment`, `sessionId`, `serverPublicKey`, `userType` and `ownerId`; they load as sandbox connectors, the only host then.
- Both take an exclusive `flock` on `<config>/connectors.lock` and hold it until the process ends. A second nostro process blocks in its first load or save, after the `Note` `waiting for another nostro process to finish`. A long-running front end therefore makes every CLI run wait for it to exit.
- `Note(text)` is where the library's warnings go: a connector that could not be refreshed, an account skipped, a request made but not read back, the wait for the lock. It calls the global `noteSink`, a `std::function<void(std::string_view)>` that prints a line on stderr until you replace it: collect them instead to show them in your own UI, as a daemon does to send them to its client.
- `<config>` is `GetConfigPath()`: `$XDG_CONFIG_HOME/.config/nostro` when `XDG_CONFIG_HOME` is set (the `.config` is inserted, as of 2026-10-31), else `$HOME/.config/nostro`. `<cache>` is `GetCachePath()`: `$XDG_CACHE_HOME/nostro`, else `$HOME/.cache/nostro`. The globals `configPath` and `cachePath` are those values, read once at load; a test redirects both through the environment before the process starts.
- `ReadSecret(prompt)` reads a trimmed line from stdin; on a terminal it prompts on stderr and turns echo off, so a key stays out of shell history and the process list. It throws `std::runtime_error` when stdin ends first.
- Generic code over the enabled banks is `tuple_for<EnabledBanks>([&]<typename Bank>() { for (Bank& bank : Bank::connectors) { … } });`, a template lambda. Every `Bank` has `static constexpr std::string connectorId` (`"bunq"`), `static std::deque<Bank> connectors`, `using Account`, `std::vector<Account> accounts`, `std::string name`, `TestConnector()`, `RefreshAccounts()`, `RefreshSession()`, `GetNewTransactions()` and `GetNewTransactions(account)`, `Logout()`, `StorageKey()`, a static `Create(…)` and `Remove(bank)`, and formats as its name. Its accounts have `StorageKey()` and format as `name<TAB>bic iban<TAB>€12.50` (`std::format` works on `Account` and on every type derived from it). Anything else, such as requests or cards, is bunq's own; `if constexpr (requires { account.Requests(); })` is how nostro's CLI asks.
- `Account { name, bic, iban, currency, balance }` plus the transaction store, keyed by a storage key you pass as the `connector` argument. For bunq that is `account.StorageKey()`, `bunq/<production|sandbox>/<user id>/<account id>`.
- `GetLastTransactionTime(key)`: the newest stored `timePoint`, `time_point::min()` for an empty or new table.
- `SaveTransactions(key, std::vector<Transaction>)`: sorts by time, appends the rows newer than the last stored one, flushes. At the last stored timestamp a row is appended when its `id` is not stored there yet. When a row stored there has no id (version 1 data), everything at that timestamp is taken as stored. Older rows are dropped silently.
- `FindTransactions(key, TransactionQuery)`: newest first, at most `limit`. `TransactionQuery` takes designated initialisers: `.search` (ASCII case-insensitive substring of the counterparty name, the description or the IBAN; empty matches all), `.amount` (`std::optional<std::int64_t>`, exact, minor units, negative for outgoing), `.from` and `.to` (inclusive `time_point`s, the whole range by default), `.limit` (100). The time range is a binary search on the ordered table; the rest is a backwards scan that stops at `limit`.
- The tables are `<cache>/transactions/<key>/<account name>.cdb`, with a `/` in the name written as `_`, opened on first use and kept open for the rest of the process, or until `Account::ForgetTransactions(key)` closes and deletes every table under `key` (a connector's storage key covers all its accounts; `Remove` calls it). A renamed account starts a new table and syncs again. Tables written before 2026-10-31 sit at `<cache>/transactions/bunq/<account name>.cdb` and are no longer read.
- `Transaction { name, bic, iban, description, currency, amount, timePoint, id, kind }` is an aggregate and the on-disk row type (`version = 2`, `orderedBy = timePoint`, 120 bytes). `id` is the bank's own id as text and `kind` its classification (bunq's `"MASTERCARD/PAYMENT"`, `"EBA_SDD/SDD"`); both are empty in rows migrated from version 1. A version 1 table migrates on its first open and keeps `<file>.v1.bak`. Do not add members to it from outside.
### The bunq connector
- **Two environments.** `BunqConnector::environment` is `BunqEnvironment::Production` (`api.bunq.com`, real money) or `Sandbox` (`public-api.sandbox.bunq.com`). `BunqConnector::EnvironmentOfKey(key)` is `Sandbox` for a key starting `sandbox_`; an OAuth token does not say, so the caller decides. Only the sandbox has been exercised (2026-10-31). `BunqConnector::Endpoint(environment)` is the `BunqEndpoint` (`host`, `port`, `caPem`) its calls go to. Each endpoint has one `ClientHTTP1`, shared by its connectors; every call is synchronous on the calling thread and the client serves one caller at a time, so keep bunq calls on one thread.
- **For tests:** `BunqConnector::RedirectTo(BunqEndpoint{.host = "127.0.0.1", .port = …, .caPem = …})` sends every API and OAuth token call there for the rest of the process, whatever the environment. nostro's own tests point it at `tests/Support/FakeBunq.inc`, an in-process bunq that a consumer's test can include as well (after `lib/json.hpp`, `import std;`, `import Nostro;` and `import Crafter.Network;`).
- `BunqConnector::Create(std::string&& apiKey, std::string_view allowedIps, BunqEnvironment environment)` registers an installation with a fresh RSA-2048 key, the device with the key and opens a session. `allowedIps` is a plain comma-separated list (`"203.0.113.4, 198.51.100.7"`), `"*"` for any address (it makes the key a wildcard key, which a phone with a changing address needs), or empty for the address the call comes from. It returns a reference into `BunqConnector::connectors`, a `std::deque`, so a later `Create` leaves earlier references and every account's `connector` pointer valid. The same bunq user (`ownerId`) in the same environment connected the same way replaces the old connector, logging its session out: that is how a key is renewed. Connected the other way (API key against OAuth), `Create` logs the new session out and throws, because every account would otherwise be listed twice. Follow it with `Connector::SaveConnectors()` or the connector is gone at exit.
- `BunqConnector::Remove(connector)` deletes its stored transactions (through `Account::ForgetTransactions`, which first closes the tables this process has open, so the same user added again syncs into new files) and erases it from `connectors`, re-pointing the remaining accounts; references to other connectors you held are invalidated, as with any `deque::erase` in the middle. It does not log out: call `Logout()` first (`DELETE /v1/session/{sessionId}`, not renewed; a session already gone counts as logged out). Then `SaveConnectors()`.
- After `LoadConnectors` or `Create` a connector has `environment`, `name` (bunq's `display_name` of the user; for OAuth of the user who granted access), `id` (the user id in API paths; for OAuth the `UserApiKey`'s own), `ownerId`, `userType` (`UserPerson`, `UserCompany`, `UserApiKey` or `UserPaymentServiceProvider`; `IsOAuth()` is `UserApiKey`), `sessionToken`, `sessionId`, `installationToken`, `privateKey` and `serverPublicKey` (`Crypto::Key`, a `std::shared_ptr<EVP_PKEY>`), `apiKey`, and `accounts` of `BunqAccount` (`Account` plus `id`, bunq's object `type` such as `MonetaryAccountSavings`, and a `connector` back-pointer).
- Every call goes through `Get`, `Post`, `Put` or `Delete` (a path below `/v1`, or a pagination URL) and `List` (every item of a listing, pages of 200 followed through `older_url`, newest first). Bodies are signed. Every 2xx must carry a valid `x-bunq-server-signature` for the stored server key, which an old connector fetches before its first call, or the call throws. A 429 is waited out: 3 s up to five times, 31 s up to twice for `session-server`. A 401, or a 403 "Insufficient authentication.", opens a new session once, saves, and retries. A POST, PUT or DELETE goes over a new connection, because `ClientHTTP1` would replay one on a reused connection after a read timeout. When the outcome of such a write is unknown (a transport error, a 5xx, an unreadable or unverifiable answer), the error ends in `; the request may have been carried out, check before trying again`. Any other error response is a `BunqError`.
- `RefreshAccounts()` rebuilds `accounts` from scratch (references into it go stale): every `MonetaryAccount…` type whose status is `ACTIVE` or `BLOCKED`, the IBAN alias as `iban`, `BUNQNL2A` as `bic` for a bunq IBAN. `TestConnector()` is `GET /v1/user/{id}` and returns `false` on any exception rather than throwing. `GetNewTransactions(account)` (and `GetNewTransactions()` for all) pages the payments newest first until one older than the last stored row, fills `id` and `kind` (`"<type>/<sub_type>"`), and calls `SaveTransactions(account.StorageKey(), …)`; the first sync walks the whole history, 200 a call.
- On a `BunqAccount`, amounts are positive minor units, or `std::invalid_argument`. Counterparties go through `BunqCounterparty::Parse(value, name)`: an `@` makes an e-mail address, a leading `+` a phone number (spaces, dashes and brackets dropped), anything else an IBAN. An IBAN is upper-cased, has its spaces removed and its check digits verified, so a typo throws `std::invalid_argument` before anything is sent. bunq needs `name` for an IBAN outside bunq.
- `Send`, `Draft` (one-entry draft payment, paid once someone accepts it) and `Schedule(…, BunqSchedule)` return bunq's id. `BunqSchedule { start, end, unit ("ONCE", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"), every }` is UTC; an unknown unit or `every == 0` throws `std::invalid_argument`.
- `Request(from, name, amount, currency, description)` asks for money with bunq.me allowed and returns a `BunqPaymentRequest`, whose `shareUrl` anyone can pay through. When reading it back fails, the request still exists: it comes back `PENDING` without a share URL, with a `Note`.
- The listings, newest first: `Requests()` (sent, `BunqPaymentRequest`), `IncomingRequests()` (`BunqIncomingRequest`, incoming SEPA direct debits included as `DIRECT_DEBIT`), `ScheduledPayments()`, `DraftPayments()`. One of each, as bunq has it now: `IncomingRequest(id)` and `DraftPayment(id)`. The answers: `RevokeRequest(id)`, `CancelScheduledPayment(id)`, and two that take the object you showed the user: `RespondToRequest(shown, accept)` pays `shown.amount` and `shown.currency`, whatever the request asks by then, and `RespondToDraftPayment(shown, accept)` sends `shown.updated` (bunq's own timestamp, kept as text), so bunq refuses an answer to a draft that changed since. Read it, show it, answer with what you read. A request has one id on each side: the asker's inquiry id is not the payer's response id.
- `Cards()` lists the user's cards (`BunqCard`: `id`, `status`, `productType`, `lastFour`, `expiry`, the paying `iban`, …). `SetCardStatus(id, "DEACTIVATED" | "ACTIVE" | "LOST" | "STOLEN")` returns the card as bunq has it afterwards, which can differ from the request without an error: a card that was never activated stays `DEACTIVATED`.
- OAuth instead of an API key: `OAuthAuthorizationUrl(environment, clientId, redirectUri, state)` is where the user approves with the bunq app. bunq then redirects to `redirectUri` with `code` and `state` (check `state` yourself). `OAuthExchangeCode(environment, clientId, clientSecret, redirectUri, code)` returns the access token, which `Create` takes in place of an API key. bunq grants OAuth payments between the user's own accounts, draft payments, cards, and creating requests, but no paying of incoming ones. The exchange was verified up to bunq refusing a fake code; a full approval needs a person and the bunq app.
- Every type above formats with `std::format` as one tab-separated line (a draft adds a line per entry), the way nostro's CLI prints them.
### nostrod, through Nostro::Client
nostrod is the system daemon that holds every local user's connectors, in a worker process per user under its own state directory, which the users cannot read. It answers `net.catcrafts.Nostro1` on the system bus (published as `packaging/dbus/net.catcrafts.Nostro1.xml`), for the calling user only, after asking polkit: viewing and the changes that move no money pass in an active session, while paying, scheduling, accepting a request or a draft, unfreezing or blocking a card, changing the connectors and choosing the checkout account ask for the user's password each time. A front end that should not hold the credentials itself (`--dbus`) talks to it through `Nostro::Client`:
- `Client::System(timeout = 10min)` connects to the system bus with interactive authorization allowed, so polkit can ask for the password, and a call timeout long enough for the user and for bunq's rate limits. D-Bus starts nostrod with the first call. Keep one `Client` per thread; it is not shared between threads.
- One method per D-Bus method, with nostro's own types: `Connectors()` (`ConnectorSummary`: `name`, `bank`, `environment`, `auth` "api key" or "oauth", `working`), `AddBunq(apiKey, allowedIps, environment)` and `AddBunqOAuth(environment, clientId, clientSecret, redirectUri, code)` (`AddedConnector`; an empty environment takes the key's), `RemoveConnector(name or number)`, `Accounts()` (`ConnectorAccounts`), `Transactions(account, TransactionQuery)` (synced first), `Send`, `Schedule`, `Draft` (`Created`: bunq's `id` and the `currency`), `Request` (`BunqPaymentRequest`), the listings, `RevokeRequest`, `RespondToRequest(account, id, accept)`, `CancelScheduledPayment`, `RespondToDraftPayment(account, id, accept)`, `Cards()` (`ConnectorCards`), `SetCardStatus(card, status)`, `DefaultCheckoutAccount()` (`std::optional<Account>`) and `SetDefaultCheckoutAccount(account)`. `account` is an account's name or IBAN. Accepting a request or a draft pays it as nostrod read it to show the user.
- `TakeNotes()` returns, and clears, the library's warnings from the calls so far (a connector unavailable, a request made but not read back): show them.
- Errors: `std::invalid_argument` for what nostrod refused before doing anything (it names the problem, as the library's own messages do); `DaemonError`, a `std::runtime_error` with the D-Bus error `name`, for the rest: `Bus::errorBank` (bunq's refusal, as bunq said it), `Bus::errorOAuthCannotPay`, `Bus::errorCancelled` (the user closed the password dialog), `Bus::errorNoCheckoutAccount`, `Bus::errorFailed`, `org.freedesktop.DBus.Error.AccessDenied` (the system's policy, or polkit not answering) and `InteractiveAuthorizationRequired`. A missing nostrod is a `std::runtime_error` saying it is not running; a call that moves money or changes something and gets no answer in time is a `std::runtime_error` saying it may have been carried out; text that is not UTF-8 is a `std::invalid_argument` before anything is sent.
- The API key and the OAuth client secret travel once, in messages marked sensitive. Read them with `ReadSecret`, never from `argv`, which every local user can read and polkit logs.
### Checkout
An app that only needs a customer to pay an order links `Nostro.Checkout` (`--product=checkout`, `import Nostro.Checkout;`), which has nothing of the library in it. nostrod pays the order from the account the user chose with `nostro checkout account <account>`, once the user has confirmed it at a password prompt that shows the amount, the payee, the reference and that account. The app never names nor sees the account.
- `Nostro::Checkout::Pay(Order{.payeeIban, .payeeName, .amount, .currency = "EUR", .reference}, timeout = 10min)` returns `Paid{paymentId, repeated}`. It blocks until the user has answered: call it off the UI thread. The payee is an IBAN alone, the amount positive minor units, the reference not empty.
- An order is paid once: `Pay` again with the same IBAN and reference, after a timeout or a crash, answers with the first payment and `repeated` set, without asking the user, and while the first call is still at the prompt the second waits for it. The same reference with another amount is refused. Any app the user runs with access to the checkout can learn this way whether an order was paid, so references should be hard to guess.
- It throws `Checkout::Cancelled` (the user did not confirm) and `Checkout::NoCheckoutAccount` (none chosen, or the chosen one is gone), both `Checkout::Error`, which every other refusal is, with the D-Bus `name`: `Checkout::errorInvalidArgument`, `errorBank` (its message says when it may have paid all the same), `errorFailed` (also for an earlier call whose outcome was lost, which may have paid), `org.freedesktop.DBus.Error.AccessDenied`, and `ServiceUnknown`, which means nostro is not installed. No answer within `timeout` is an `Error` saying the order may have been paid, and asking again is safe. Text that is not UTF-8 is a `std::invalid_argument`; a failure of the bus itself a `std::system_error`.
- On the wire it is `net.catcrafts.Nostro1.Checkout`, its own bus name, with one method, `Pay(ssxssa{sv}) -> (ta{sv})`, published as `packaging/dbus/net.catcrafts.Nostro1.Checkout.xml` for apps in other languages. Options and results are dictionaries so they can grow: nostrod ignores options it does not know, and the client skips results it does not know. A Flatpak app asks for `--system-talk-name=net.catcrafts.Nostro1.Checkout`, which reaches nothing else of nostrod: the name is served by a connection of its own.
- A payment id is the paying bank's: confirm the money arrived with your own bank.
### Errors
- `BunqError` is a `std::runtime_error` with the HTTP `status` (bunq also uses 466, 490 and 491), its message `bunq <METHOD> <path>: <error_description> (<status>)`.
- `std::invalid_argument` is for input refused before anything is sent: an IBAN, amount or schedule.
- Everything else nostro throws is a `std::runtime_error`: an unverifiable or unreadable bunq answer, `"unsupported currency '…'"`, `"malformed amount '…'"`, `"malformed timestamp '…'"`, `"bunq response has no '<key>' object"`, `"openssl error"` (after `ERR_print_errors_fp(stderr)`), `"XDG_CONFIG_HOME and HOME not set"`.
- Around it come:
- `nlohmann::json::exception`s from a `connectors.json` or a bank response with a missing key or a wrong type (a `std::exception`, not a `runtime_error`).
- `std::system_error` from the file layer and the lock.
- Crafter.Network's `SocketErrorException`, `SocketTimeoutException`, `TLSException` and `HTTP1::HTTP1ProtocolError` from a GET (a write wraps them as above).
- Crafter.DB's `Error` family from the tables.
- Catch `std::exception` at the top of a command, as nostro's `main` does.
### Testing a consumer
- Point `XDG_CONFIG_HOME` and `XDG_CACHE_HOME` at a scratch directory before the process starts, or set `Nostro::configPath` and `cachePath` first thing in `main`. No `connectors.json` needs seeding.
- A consumer of `Client` or of `Nostro.Checkout` needs nostrod on a system bus, and a build sandbox has none. nostro's `tests/Support/FakeBus.inc` is one in the test's own process: the bus driver, logind and polkit (with scripted answers: allow, a password, deny, a closed dialog, none, slow), giving each connection a uid of the test's choosing. Set `DBUS_SYSTEM_BUS_ADDRESS` to `Fake::Bus::Address(path)` before any thread starts, and start nostrod as a process of its own: `tests/ShouldServeEveryUser` compiles `implementations/nostrod.cpp` in with its `main` renamed and runs its own executable again as nostrod (`Fake::StartNostrod`), pointed at a fake bunq through the environment (`Fake::Bunq::ExportRedirect`, `RedirectFromEnvironment`).
- Without bunq: `RedirectTo` a fake (see "For tests" above), as every one of nostro's own tests does.
- A throwaway bunq user: `POST https://public-api.sandbox.bunq.com/v1/sandbox-user-person` (or `-company`) without authentication returns `Response[0].ApiKey.api_key`. Pass it to `Create` with `"*"` and `EnvironmentOfKey(key)`, then `SaveConnectors()`. The new account holds €0; `account.Request("sugardaddy@bunq.com", "Sugar Daddy", 50000, Currency::Euro, "…")` is paid within seconds, and the payment appears in the next `GetNewTransactions(account)`. A second user to pay to comes from the same endpoint: its IBAN is on its account, and its e-mail and phone aliases are in the creation response.
- Rate limits are waited out, but a burst slows everything down; keep test runs light, and let one process end before the next starts (the lock makes it wait anyway).
- nostro's own `implementations/main.cpp` exercises every call above, and its README lists the commands; its tests (`tests/`) show each call against the fake, failures included.
### Names to get right
`Connector::LoadConnectors` and `SaveConnectors` are statics on a struct with nothing else. On `BunqConnector`: `connectorId` is `"bunq"`, `connectors` the static deque, `Create` and `Remove` the static constructor and remover, plus `EnvironmentOfKey`, `OAuthAuthorizationUrl` and `OAuthExchangeCode`, `Get`/`Post`/`Put`/`Delete`/`List`, `RefreshSession`, `RefreshAccounts`, `GetNewTransactions`, `TestConnector`, `Logout`, `Cards`, `SetCardStatus`, `StorageKey`, `IsOAuth`, `Endpoint` and `RedirectTo`. On `BunqAccount`: `Send`, `Draft`, `Schedule`, `Request`, `Requests`, `IncomingRequests`, `ScheduledPayments`, `DraftPayments`, `IncomingRequest`, `DraftPayment`, `RevokeRequest`, `RespondToRequest`, `CancelScheduledPayment`, `RespondToDraftPayment`, `Path` and `StorageKey`. On `Account`, the static `ForgetTransactions`. The warnings: `Note` and `noteSink`. Other names:
- the bunq types: `BunqEnvironment`, `BunqEndpoint`, `BunqError`, `BunqCounterparty`, `BunqLabel`, `BunqPaymentRequest`, `BunqIncomingRequest`, `BunqSchedule`, `BunqScheduledPayment`, `BunqDraftPayment`, `BunqCard`;
- `EnabledBanks` and `tuple_for` in `:Banks`;
- `ParseAmount`, `FormatAmount`, `FormatMoney`, `GetCurrency`, `GetCurrencyCode`, `GetCurrencySymbol` and `GetCurrencyDecimals`;
- in `:Utils`: `ParseTimestamp`, `FormatTimestamp`, `ParseLocalDate`, `FormatLocalTime`, `UrlEncode`, `UrlDecode`, `QueryParameter` and `EscB`;
- `FindTransactions` (not Query, Load or List), `SaveTransactions` and `GetLastTransactionTime`;
- `TransactionQuery` with `search`, `amount`, `from`, `to` and `limit`;
- in `Nostro::Crypto`: `Key`, `OwnKey`, `SignBody`, `VerifyBody`, `CreateKey` (a `std::tuple<EVP_PKEY*, std::string>`, the public PEM second), `LoadKeyFromPem`, `LoadPublicKeyFromPem`, `PrivateKeyToPem`, `PublicKeyToPem`, `RandomHex` and `ThrowOnOpenssl`;
- `configPath`, `cachePath`, `CreatePrivateFile` and `ReadSecret`;
- for nostrod: `Client` (`System`, `TakeNotes`, `DefaultCheckoutAccount`, `SetDefaultCheckoutAccount`), `DaemonError`, `ConnectorSummary`, `AddedConnector`, `ConnectorAccounts`, `ConnectorCards`, `Created`, and `Bus::busName`, `Bus::errorBank` and the other `Bus::error…` names;
- for checkout: `Nostro::Checkout::Pay`, `Order`, `Paid`, `Error`, `Cancelled`, `NoCheckoutAccount`, and the module `Nostro.Checkout`, with a dot.

214
AGENTS.template.md Normal file
View file

@ -0,0 +1,214 @@
# AGENTS.md
Guidance for coding agents and contributors working on nostro itself. The [README](README.md) is the user-facing manual (what nostro is for, the CLI, how to contribute a bank), and [AGENTS.consumer.md](AGENTS.consumer.md) is what agents working in a *consumer* of the library read: crafter-build copies it into the dependency-notes section of the consumer's `AGENTS.md` on every build. When any of the three disagrees with the code, the code wins; the interfaces under `interfaces/` are the contract, `Transaction` in `interfaces/Nostro-Transaction.cppm` is the contract for the bytes on disk, and `packaging/dbus/*.xml` with `packaging/system/net.catcrafts.Nostro1.policy` are the contract on the system bus, which a test holds to what nostrod serves. This file is written by crafter-build from `AGENTS.template.md`; the section at its end holds the notes of the libraries nostro builds against (Crafter.Network, Crafter.DB), straight from their repositories.
## Project overview
nostro is a banking client for Linux, phones first: a library that talks to bank APIs directly; nostrod, a system daemon that runs it for every local user behind D-Bus and polkit, so no program of the user's can read the bank's secrets or move money without the user's password; and a small CLI that only talks to nostrod. Linux phones have no banking apps; nostro is the open-source answer, one connector per bank. One C++26 module, `Nostro`, with twelve partitions behind the umbrella and ten implementation units, and a second module, `Nostro.Checkout`, for apps that have nostrod pay an order. `project.cpp` makes one product per build: the static library `nostro` with the CLI `nostro` (`implementations/main.cpp`), `nostrod` (`--product=daemon`, `implementations/nostrod.cpp`), or the static library `nostro-checkout` (`--product=checkout`). The bunq connector is the only bank so far and the model for the next one. It depends on Crafter.Network (HTTPS to the bank), Crafter.DB (the local transaction tables and the checkout record), OpenSSL (request signing, response verification), libsystemd (sd-bus and sd-event, for nostrod and its clients) and a vendored nlohmann/json. It ships as a Flatpak, `net.catcrafts.Nostro`, that systemd runs nostrod from as the system user `nostro`.
| Path | What lives there |
|---|---|
| `interfaces/Nostro.cppm` | The umbrella: `export import`s every partition; `:Bunq` and `:Crypto` only under their defines, `:Bus`, `:Client` and `:Daemon` only under `NOSTRO_DBUS_ENABLED`. |
| `interfaces/Nostro-<Partition>.cppm` | One partition per file, `Nostro:<Partition>`. |
| `implementations/Nostro-<Partition>.cpp` | The implementation units, `Nostro:<Partition>_impl`: `Account`, `File` and `Connector` always; `Bunq`, `BunqPayments` (`Nostro-Bunq-Payments.cpp`: counterparties, payments, drafts, requests, schedules) and `Crypto` when their bank is enabled; `Bus`, `Client`, `Daemon` (nostrod's front) and `DaemonWorker` (`Nostro-Daemon-Worker.cpp`: a user's worker, the polkit gate, the checkout) under D-Bus. |
| `interfaces/Nostro.Checkout.cppm`, `implementations/Nostro.Checkout.cpp` | The module `Nostro.Checkout`: the checkout's names and wire, and a blocking `Pay` over sd-bus. A module of its own, so `--product=checkout` builds it without the rest. |
| `implementations/main.cpp` | The CLI, a client of nostrod: `argv` parsing (positional arguments, `--name value` options, `--sandbox`), one function per command over `Client`, output through the `std::formatter`s, the notes on stderr, errors caught in `main` and printed with exit status 1. |
| `implementations/nostrod.cpp` | nostrod's `main`: `--state`, `--idle`, `--prompt-timeout`, and `--worker <uid> <name>` for the worker processes it starts itself. |
| `project.cpp` | The build description: reads `--banks=`, `--lib`, `--dbus`, `--product=`, `--coverage` and `--profile-runtime=`, forwards the other args to the dependencies (with `--no-quic` for Crafter.Network), returns the product. |
| `packaging/dbus/` | The published D-Bus interfaces, `net.catcrafts.Nostro1.xml` and `net.catcrafts.Nostro1.Checkout.xml`. |
| `packaging/system/` | What a Flatpak cannot install: the polkit policy, the D-Bus policy and activation files, `nostrod.service`, the sysusers entry, the `nostro` command, `install.sh` and `uninstall.sh`. |
| `packaging/flatpak/`, `packaging/arch/` | The Flatpak manifest (on crafter-build's Flatpak as its base app), metainfo and `.flatpakref`; the Arch package of the system files, `nostro-system`. |
| `lib/json.hpp` | nlohmann/json 3.12.0 (MIT), included in the global module fragment of `:Bunq` and of the `Connector`, `Bunq` and `BunqPayments` implementation units. |
| `tests/<Name>/main.cpp`, `tests/Support/`, `tests/coverage.sh` | The tests, their checks, fake bunq and fake system bus, and the coverage run; see "Testing instructions". |
| `README.md`, `LICENSE`, `LICENSE.GPL` | The manual; LGPL-3.0-only and the GPL it incorporates. |
| `AGENTS.template.md`, `AGENTS.consumer.md` | The source of this file, and the notes for consumers. `AGENTS.md` is gitignored: edit the template. |
| `.vscode/` | A build task and an lldb launch configuration, both stale; see "Gotchas". |
| `bin/`, `build/` | Generated and gitignored. The library and the CLI are both named `nostro`, so one build leaves two `bin/nostro-<target>-<march>-<mtune>-<hash>/` directories: the library's (`libnostro.a`, the PCMs, `std.pcm`) and the executable's (`nostro`). Glob for the one holding `nostro`. nostrod builds into `bin/nostrod-…/`, the checkout library into `bin/nostro-checkout-…/`. |
Partitions, from the bottom up (each imports only the ones above it):
- `:Currency`: `Currency` (an `enum class : std::uint16_t` with `Euro` alone), `GetCurrency` (from `"EUR"` or `"eur"`, throws for anything else), `GetCurrencyCode`, `GetCurrencySymbol`, `GetCurrencyDecimals`, `ParseAmount` (decimal string to minor units), `FormatAmount` (back) and `FormatMoney` (`-€1.02`), all `constexpr`, and `std::formatter<Currency>`, which prints the symbol.
- `:Utils`: `ParseTimestamp` and `FormatTimestamp` (bunq's `YYYY-MM-DD HH:MM:SS[.ffffff]`, UTC), `ParseLocalDate` and `FormatLocalTime` (dates a person types and reads, local time through `mktime`/`localtime`), `UrlEncode`, `UrlDecode` and `QueryParameter` (for OAuth), `EscB` (JSON string escaping, no longer used by nostro itself), and `Note` with its replaceable `noteSink`, where every warning of the library goes (stderr by default).
- `:Transaction`: the `Transaction` aggregate, which is also the row type of the Crafter.DB tables: `version = 2` (`id` and `kind` added on 2026-10-31), `orderedBy = &Transaction::timePoint`, `using Previous = TransactionV1` (unexported, kept for the migration), and its `std::formatter` (one tab-separated line).
- `:Account`: `TransactionQuery` and `Account` (`name`, `bic`, `iban`, `currency`, `balance` in minor units) with the three methods over the transaction store and the static `ForgetTransactions` (which closes this process's open tables under a storage key before deleting them), and the `std::formatter` for `Account` and everything derived from it. The implementation unit owns the Crafter.DB tables and pins the schema with two `static_assert`s.
- `:File`: `GetConfigPath`, `GetCachePath`, the globals `configPath` and `cachePath` they initialise at static-init time, `CreatePrivateFile` (a `0600` file in a `0700` directory), and `ReadSecret` (a line from stdin, not echoed on a terminal).
- `:Crypto` (under `NOSTRO_OPENSSL_ENABLED`; OpenSSL headers in the global module fragment), in `namespace Nostro::Crypto`: `ThrowOnOpenssl`, `Key` (`std::shared_ptr<EVP_PKEY>` freeing itself) and `OwnKey`, `SignBody` (RSA SHA-256, base64) and `VerifyBody` (its check against a public key), `CreateKey` (RSA 2048 and its public PEM), `LoadKeyFromPem`, `LoadPublicKeyFromPem`, `PrivateKeyToPem`, `PublicKeyToPem`, `RandomHex` (the OAuth `state`).
- `:Bunq` (under `NOSTRO_BUNQ_ENABLED`; `json.hpp` and `openssl/types.h` in the global module fragment; the implementation units import Crafter.Network): `BunqEnvironment`, `BunqError`, `BunqCounterparty`, the listing types (`BunqLabel`, `BunqPaymentRequest`, `BunqIncomingRequest`, `BunqSchedule`, `BunqScheduledPayment`, `BunqDraftPayment`, `BunqCard`) and their formatters, `BunqAccount : Account` (`id`, `type`, `connector`, the payment calls), `BunqConnector` (environment, keys, tokens, user, `accounts`, the raw `Get`/`Post`/`Put`/`Delete`/`List`, the static deque `connectors`, `Create`, `Remove`, the OAuth helpers, and `Endpoint`/`RedirectTo` with `BunqEndpoint`), `to_json`/`from_json`, and the unexported `BunqJson` helpers both implementation units share.
- `:Banks`: `tuple_for<Tuple>(f)` and `EnabledBanks`, the `std::tuple` of enabled connector types; every generic loop in the CLI and in `:Connector` is a `tuple_for<EnabledBanks>`.
- `:Connector`: `Connector::SaveConnectors()` and `LoadConnectors()`, `connectors.json` out (synced, then renamed into place) and in, both under the process-wide `connectors.lock`.
- `:Bus` (under `NOSTRO_DBUS_ENABLED`; `sd-bus.h` in the global module fragment): the wire nostrod and its clients share. The names, the error names (the checkout's from `Nostro.Checkout`), the polkit actions, the method tables `methods` and `checkoutMethods` (member, signatures, argument names, sensitive), the result structs (`ConnectorSummary`, `AddedConnector`, `ConnectorAccounts`, `ConnectorCards`, `Created`), `Wire<T>` with `Append` and `Read` for every type that travels (a struct as its members, a time as microseconds, a currency as its code, an optional as an array of zero or one), `AppendQuery`/`ReadQuery`, `Vtable`, `ThrowOnSdBus`, and the `BusPtr`/`MessagePtr`/`Error` owners.
- `:Client`: `Client::System()`, one method per method of `net.catcrafts.Nostro1`, `TakeNotes()`, and `DaemonError`.
- `:Daemon`: `DaemonOptions`, `RunDaemon` (the front) and `RunWorker` (one user's worker).
`Nostro.Checkout`, a module of its own that imports nothing of `Nostro`: the checkout's bus name, interface, `Pay`'s signatures and argument names, the error names apps tell apart, `Order`, `Paid`, `Error` with `Cancelled` and `NoCheckoutAccount`, and `Pay`. `:Bus` and the daemon take their names from it.
The bunq connector end to end:
- **Requests** (`implementations/Nostro-Bunq.cpp`): every call goes through the private `BunqConnector::Call`, behind the public `Get`, `Post`, `Put`, `Delete` and `List`. It talks to `BunqConnector::Endpoint(environment)`: `api.bunq.com` or `public-api.sandbox.bunq.com` by the connector's environment, or wherever `RedirectTo` sent everything (the tests' fake), with one `ClientHTTP1` per endpoint.
- It signs every body except the installation's.
- It refuses a 2xx whose `x-bunq-server-signature` does not verify against `serverPublicKey`, which an old connector fetches first (`EnsureServerPublicKey`).
- It waits out a 429, and renews the session once on a 401 or a 403 "Insufficient authentication.", then saves.
- It sends a POST, PUT or DELETE over a fresh connection, because `ClientHTTP1` replays a request on a reused connection that fails before any answer, even after a read timeout. A write whose outcome is unknown says it may have been carried out.
- Every other error is a `BunqError` with bunq's `error_description`.
- **Connecting:** `Create(apiKey, allowedIps, environment)` makes an RSA key, then `POST /installation` (installation token and server key), `POST /device-server` with `permitted_ips` as a JSON array, and `RefreshSession()`. The session is `POST /session-server`, signed: the token, the session id, and the user from `UserPerson`, `UserCompany`, `UserPaymentServiceProvider` or, for OAuth, `UserApiKey` (its own id in paths, `ownerId` and the name from `granted_by_user`).
- **Accounts and history:** `RefreshAccounts()` lists every `MonetaryAccount…` type that is `ACTIVE` or `BLOCKED`. `GetNewTransactions(account)` pages the payments newest first until one older than the last stored row, and hands them to `Account::SaveTransactions` under `account.StorageKey()`.
- **Payments** (`implementations/Nostro-Bunq-Payments.cpp`): `BunqCounterparty::Parse` reads an IBAN (check digits verified), an e-mail address or a phone number. `Send`, `Draft`, `Schedule` and `Request` build their bodies from it, the listings read bunq's objects into the listing types, and the responses are PUTs or a DELETE. Accepting a request or a draft takes the object as it was read and shown (`IncomingRequest(id)`, `DraftPayment(id)`), so what gets paid is what the user saw.
- **OAuth:** `OAuthAuthorizationUrl` and `OAuthExchangeCode` (the token endpoint reads query parameters only). The token then goes to `Create` like an API key.
nostrod end to end:
- **The front** (`implementations/Nostro-Daemon.cpp`, `RunDaemon`) is one sd-event loop with two system bus connections. One owns `net.catcrafts.Nostro1` and serves that interface. The other owns `net.catcrafts.Nostro1.Checkout` and serves the checkout alone: a Flatpak allowed to talk to that name can call its owner's unique name too, and on that connection there is nothing else. Every method of both is one forwarding handler. It asks the bus for the caller's uid (`GetConnectionCredentials`), and logind for that uid's name, starts the uid's worker if there is none (`posix_spawn` of `/proc/self/exe --worker <uid> <name> …`, a socketpair end as fd 3, D-Bus peer to peer over it), and passes a copy of the call on, from the caller's unique name and allowing a dialog only when the caller did. The answer is relayed when it comes, so one user's open dialog holds up nobody. A worker that dies under a call is answered `Failed` with "may have been carried out". It holds no connector and no secret. It ends once idle with no worker left, on SIGTERM, or when the bus goes; D-Bus activation starts it again.
- **A worker** (`implementations/Nostro-Daemon-Worker.cpp`, `RunWorker`) is one user's library: `configPath` and `cachePath` are `<state>/users/<uid>`, the connectors are read on the first call, and it is not dumpable. A directory records whose it is (`owner`): a uid that logind now names differently, after a user was deleted and another given their uid, is refused. Every handler reads and checks the call first (the account, the counterparty, what is to be paid, or for a request or a draft the object as bunq has it), builds a `Prompt` (the polkit action, a summary from its own data, and details for polkit rules), and hands it to `Gate`. `Gate` asks polkit asynchronously (`CheckAuthorization` about the caller's bus name, cancelled if it does not answer in time) and runs the call's work only once polkit says yes. It fails closed: no polkit, an error or a timeout is `AccessDenied`. A dialog the user closed is `Cancelled`, which polkit says with `polkit.dismissed` or, from Plasma's agent, `polkit.result` `auth_…`. A challenge to a call that allowed no dialog is `InteractiveAuthorizationRequired`. Every answer of the main interface ends with the notes. A summary's text from a caller or the bank goes through `Shown()` (no control, invisible or direction characters, `<` and `>` replaced, `$(` broken, 64 characters at most) and names the address before the name. The worker ends once idle with no dialog open, on SIGTERM, or when the front goes.
- **Checkout** (the same file): `Order::Read` refuses a payee that is not an IBAN, an amount that is not positive, an unknown currency or an empty reference. An order already in `checkouts.cdb` (a Crafter.DB table, `CheckoutRecord`) is answered with its payment, `repeated`, without a dialog, or refused when its amount differs, or when its payment is still 0: a payment whose outcome was lost. An order being paid makes the next call for it wait, and `Settle` gives it the first call's answer. `ChooseAccount` picks the account (the one in `checkout-account`, set by `SetDefaultCheckoutAccount`; an account of an OAuth connector is refused there) and answers through a continuation, so an account picker can take its place later. The dialog (`net.catcrafts.Nostro1.Checkout`) shows the order and that account. `PayOrder` records the order, with no payment, before it pays, and takes the record away again only when bunq refused before doing anything, below 500.
- **The client** (`implementations/Nostro-Client.cpp`) allows interactive authorization and waits 10 minutes by default; nostrod's `InvalidArgument` becomes `std::invalid_argument`, `ServiceUnknown` a "not running" message, a write without an answer "may have been carried out", and the rest a `DaemonError` with its name. `Nostro.Checkout`'s `Pay` does the same for the checkout with its own types.
## Dev environment
crafter-build is the only build tool. It compiles with its clang 23 and libc++, `-std=c++26` and `import std;`, and links `-lssl -lcrypto`, and `-lsystemd` for anything with D-Bus in it (libsystemd's `sd-bus.h` and `sd-event.h`; crafter-build's Flatpak SDK has them). Packaging uses flatpak-builder.
- Every build needs the network: Crafter.Network (with Crafter.Thread behind it; nostro builds it `--no-quic`, so without msquic) and Crafter.DB are `GitProject`s on their default branches, and Crafter.LintRules a `#pragma crafter dependency` of `project.cpp`, so each build `git pull`s them from `forgejo.catcrafts.net`, and the notes at the end of this file follow their HEAD. A `.commit` (in the pragma, `commit "<sha>"`) would pin them.
- Where the connectors live depends on who runs the library. nostrod's worker keeps each user's under `<state>/users/<uid>/`: `connectors.json`, the transaction tables, `checkouts.cdb`, `checkout-account` and `owner`, with `<state>` from `--state`, else `$XDG_DATA_HOME`, else `$HOME/.local/share`. Installed, that is `/var/lib/nostro/.var/app/net.catcrafts.Nostro/data/`, readable by the user `nostro` alone. The library used directly reads `connectors.json` from `$XDG_CONFIG_HOME/.config/nostro/` (sic, see "Gotchas") or `$HOME/.config/nostro/`, and keeps the transaction tables under `$XDG_CACHE_HOME/nostro/transactions/` or `$HOME/.cache/nostro/transactions/`. A real connectors file holds a real API key: point every experiment elsewhere.
- No test uses the system bus: they run on `tests/Support/FakeBus.inc`. Running anything by hand that talks to `net.catcrafts.Nostro1` reaches the installed nostrod, if there is one, and its dialogs. A Flatpak sandbox with the system bus (`flatpak run`, `flatpak build`) sets `DBUS_SYSTEM_BUS_ADDRESS` itself, over an `--env` of yours: keep a sandboxed experiment off the bus with `--nosocket=system-bus`.
- To read a `constexpr` value such as `DB::Layout<Transaction>::fingerprint`, `static_assert(x == 0)` it and read "expression evaluates to" in the error.
## Build, test and style commands
```bash
crafter-build --banks=bunq # the library, then the CLI: bin/nostro-<variant>/nostro
crafter-build --banks=bunq --product=daemon # nostrod: bin/nostrod-<variant>/nostrod
crafter-build --product=checkout # the Nostro.Checkout library alone; no bank needed
crafter-build --banks=bunq --lib # the library alone (what a consumer builds), without D-Bus
crafter-build --banks=bunq --lib --dbus # the library with :Bus, :Client and :Daemon
crafter-build --debug --banks=bunq # debug build
crafter-build -v --banks=bunq # with the compiler commands
crafter-build clean # delete bin/ and build/
crafter-build test --banks=bunq # the tests in tests/, against a fake bunq; none talks to bunq itself
tests/coverage.sh [profile runtime] # the tests with coverage: a report per file and every line no test ran
crafter-build lint --banks=bunq # the Crafter.LintRules lite rules project.cpp registers, report only
flatpak run --filesystem=<dir> org.flatpak.Builder --user --force-clean --repo=<dir>/repo --state-dir=<dir>/state <dir>/build packaging/flatpak/net.catcrafts.Nostro.yaml
```
`--banks=` is mandatory except for `--product=checkout`: without it `project.cpp` throws "must enable atleast one bank" and nothing is built; an unknown name throws "unknown connector", an unknown product "unknown product". flatpak-builder needs crafter-build's own Flatpak (`net.catcrafts.CrafterBuild`, stable) installed as its base app, the network during the build, and, run as a Flatpak itself, `--filesystem=` for a build directory outside your home, or the build commands cannot find it. Install the result for a test with `sudo packaging/system/install.sh --repo <dir>/repo`. There is no CI. The tests run every line, function and region of nostro's own sources (2026-11-01), and a change keeps them doing so; the README's rule for contributed connectors applies on top: not blind, also tried against the sandbox or the live API ("Testing instructions").
## Testing instructions
`crafter-build test --banks=bunq` builds and runs `tests/<Name>/main.cpp` for each name in `project.cpp`'s list, each linked against the library, in parallel; a test exits 0 when every check passed and prints each failed one with its line. They are:
| Test | What it covers |
|---|---|
| `ShouldHandleMoneyAndText` | `:Currency` and `:Utils`: every parse with what it refuses, every format, local dates in a fixed time zone |
| `ShouldSignAndVerify` | `:Crypto`: keys, PEM, signatures and each way one fails to verify |
| `ShouldStoreTransactions` | `:Account`: what a sync stores and drops, the queries, a version 1 table migrating |
| `ShouldKeepFilesPrivate` | `:File`: the paths, private files and their failures, `ReadSecret` from a pipe and from a pseudo-terminal |
| `ShouldSaveConnectors` | `:Connector`: loading, the synced save, and every way the lock and the save fail |
| `ShouldTalkToBunq` | the connector: every user type, signatures, rate limits, session renewal, errors, accounts, the sync, cards, OAuth, old connectors |
| `ShouldMoveMoney` | payments, drafts, schedules and requests, and their formatters |
| `ShouldRunCommands` | the CLI: `implementations/main.cpp` compiled in with its `main` renamed, every command run in-process against a real nostrod on the fake bus |
| `ShouldServeEveryUser` | nostrod: users kept apart, a uid handed to a new user, every polkit answer and what each dialog says, calls that wait on each other or do not, the checkout and its retries, the checkout client, workers that die, idle exits, every error as the client gets it, and the published contract (the XML and the polkit policy) |
How they are built:
- `tests/Support/Check.inc` holds the checks (`Check`, `Equal`, `Throws`) and a temporary `Directory`; `tests/Support/FakeBunq.inc` is a bunq in the test's own process, HTTPS on 127.0.0.1 with Crafter.Network's self-signed certificate. It signs what it answers, checks the client's signatures, keeps users, accounts, payments, requests, schedules, drafts and cards, and fails on request (`Fake::Fault`). `BunqConnector::RedirectTo` points nostro at it; each test has a port of its own (47301 to 47305), and port 443 on 127.0.0.1 stands for a host that refuses the connection.
- `tests/Support/FakeBus.inc` is a system bus in the test's own process, an sd-bus server on a unix socket: it routes calls by name with the caller's unique name, and plays the bus driver (`GetConnectionCredentials` with the uid the test chose for a connection of its own process, the real one for nostrod's), logind (`GetUser` and the user's `Name`) and polkit (each check recorded; allow, a password, deny, a closed dialog, absent, silent or slow, per action). The two nostrod tests start their own executable again as nostrod (`Fake::StartNostrod`, with `NOSTRO_TEST_ROLE` set; its `main` then runs `implementations/nostrod.cpp`'s, compiled in with `main` renamed), which finds the fake bunq through the environment (`Fake::Bunq::ExportRedirect`, `RedirectFromEnvironment`). Everything a child reads from the environment is set before any thread starts. A worker that cannot be spawned is made with `prlimit` on nostrod (`Fake::Limit`), and workers are stopped with SIGTERM, which they handle, so their coverage counts are written.
- What a disk or a kernel will not do on demand (`flock` failing or interrupted, `fsync` failing, a chosen OAuth state from `RAND_bytes`) the test defines itself as an `extern "C"` function: the linker takes it over libc's or OpenSSL's, and it calls the real one through `dlsym(RTLD_NEXT, …)` when nothing is scripted. A file size limit (`RLIMIT_FSIZE`) makes a write fail part way.
- Each test sets `configPath` and `cachePath` to a temporary directory first, and `TZ` where it formats local time.
Coverage is clang's source-based coverage: `tests/coverage.sh` builds with `--coverage`, runs the tests with `LLVM_PROFILE_FILE` set (with `%p`, so nostrod and every worker write their own), merges the profiles and reports with `llvm-cov`, leaving `build/coverage/sources.txt` annotated. A toolchain without compiler-rt's profile library, which crafter-build's Flatpak lacks, takes one as the script's argument (`--profile-runtime=` to `project.cpp`). On 2026-11-01 lines, functions and regions were all at 100% and branches at 95%: what is left is mostly defensive checks no input can flip and per-instantiation counts in `main.cpp`'s templates.
The bunq sandbox is still the check for what a fake cannot show. Since nostrod (2026-11-01) the CLI needs an installed nostrod: build the Flatpak, install it with `sudo packaging/system/install.sh --repo <dir>/repo`, and use the CLI as yourself; real polkit dialogs then ask for your password. A second local user shows the separation. The library alone still runs from an isolated config and cache, never from `~/.config/nostro`. The recipe, as it worked on 2026-10-31 with the CLI of then, which held the connectors itself:
1. Build (in place or in a scratch copy made with `rsync -a --exclude build/ --exclude bin/ --exclude .git/`) and run the binary with `XDG_CONFIG_HOME` and `XDG_CACHE_HOME` pointing into a scratch directory. No `connectors.json` needs seeding.
2. Throwaway users: `POST https://public-api.sandbox.bunq.com/v1/sandbox-user-person` (or `-company`) with no authentication returns `Response[0].ApiKey.api_key`; `nostro connectors add bunq`, given the key on stdin, recognises the sandbox by its prefix. The response also holds the user's e-mail and phone aliases, for paying by those. Make two, so there is someone to pay; sandbox accounts are all called "Bank Account", so name them by IBAN.
3. The CLI reaches every bunq call (`nostro help` lists them). Session renewal is tried by ending the session behind nostro's back (`DELETE /v1/session/0` with the stored `sessionToken`), signature checking by putting another public key in `serverPublicKey`.
4. A new sandbox account holds €0 and no payments. Fund it with `nostro request <iban> sugardaddy@bunq.com "Sugar Daddy" 50000`: it is paid within seconds. A hundred rows at once: `POST …/payment-batch` with `{"payments": […]}` (more than 200 exercises the paging). `curl` can call as the same user with the `sessionToken` from the scratch file, and sign with `openssl dgst -sha256 -sign` over the body using its `privateKey` PEM, base64, in `X-Bunq-Client-Signature`. A sandbox virtual card (`POST /v1/user/{id}/card-debit` with `order_status: VIRTUAL_DELIVERY`) cannot be activated through the API, so `cards unfreeze` can only show bunq keeping it `DEACTIVATED`. OAuth stops at the token exchange: approving needs a person and the bunq app.
5. bunq allows 3 GETs, 5 POSTs and 2 PUTs per three seconds per endpoint and one session per 30 seconds; nostro waits a 429 out, so a burst of runs is slow rather than failing. Concurrent nostro processes queue on `connectors.lock`, so two never hold the same account's table.
A bug fix comes with a test that fails without it, and states in its commit how it was reproduced; a new bank comes with tests against a fake of it and with the same check against its sandbox or live API.
## Code style
- `crafter-build lint --banks=bunq` reports nothing. A finding at a C boundary (`main`'s `argv`, a `char*` an OpenSSL or POSIX call hands out) is suppressed with `// lint-disable-next-line <rule>` and a comment saying why; anything else is fixed. The rules that need an AST cannot parse a file that `#include`s a standard header before `import std;` (the nine that include `json.hpp`: four in the library, five tests), so lint exits 1 for those alone until Crafter.Build issue #46 is fixed: check them by hand, and prefer C headers (`<errno.h>`, not `<cerrno>`) elsewhere. Tests are linted like the rest.
- The first two lines of every source are `// SPDX-License-Identifier: LGPL-3.0-only` and `// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®`, then a blank line. `project.cpp` carries them too.
- Four-space indentation, LF, K&R braces with `} else {`, one declaration per statement. `if(`, `for(`, `while(`, `switch(` without a space in most files (`:Utils` has the space; match the file). Lines run long rather than wrap.
- `import std;` everywhere; `#include`s only in a global module fragment (`module;` first), and only for OpenSSL, the vendored `json.hpp`, sd-bus and sd-event, and the POSIX calls of `:File`, `:Connector` and nostrod. `namespace fs = std::filesystem;` where paths appear.
- Interfaces are `export module Nostro:<P>;` with `export namespace Nostro { … }` when the partition is free functions (`:Currency`, `:Utils`, `:File`, `:Crypto`) and `namespace Nostro { export struct … }` when it is types. A `std::formatter` specialisation sits after the namespace, unexported, which importers still find. Implementation units are `module Nostro:<P>_impl;` followed by `import :<P>;`. `Nostro.Checkout` is a module of its own (`export module Nostro.Checkout;`, implemented in `module Nostro.Checkout;`) because a shop app links it without the rest.
- An sd-bus callback returns 0 or more and never throws: a negative result closes the connection it came on, and an exception would unwind through C. Every worker handler catches everything (`Handle`) and answers with an error instead.
- `PascalCase` for types, functions and member functions; `camelCase` for variables, members and constants (`sessionToken`, `connectorId`, `configPath`); `enum class` only; fixed-width integers (`std::int64_t` for money, `std::uint64_t` for bunq ids, `std::uint16_t` under `Currency`). `tuple_for`, `to_json` and `from_json` are the snake_case exceptions, the last two because nlohmann/json looks them up by that name.
- Parameters are `std::string_view`, or `std::string&&` where the callee stores them (the account constructors, `Create`). `std::format` and `std::println` for all text; iostreams only for `connectors.json`.
- Errors are exceptions with a `std::format`ted message that names the thing: `std::runtime_error` (`"malformed amount '{}'"`), `BunqError` with the HTTP status for a bunq error response (`"bunq {} {}: {} ({})"`, method, path, description, status), `std::invalid_argument` for input refused before anything is sent. Every OpenSSL return goes through `ThrowOnOpenssl`, which prints OpenSSL's error stack to stderr first. No error codes, no `std::expected`.
- Comments say why, and are kept: the table cache in `Nostro-Account.cpp`, the schema warning on `Transaction`, the `opensslEnabled` line in `project.cpp`. New non-obvious code gets the same.
## Design rules
1. **Banks are chosen at build time.** `--banks=` lists them, each gets a `NOSTRO_<BANK>_ENABLED` define, its partition and implementation unit exist only under it, and `EnabledBanks` is the `std::tuple` of what is in. Generic code is `tuple_for<EnabledBanks>` over duck-typed connector types; there is no virtual base, no registry, no runtime plug-in. A binary knows exactly the banks it was built with.
2. **A connector is a struct with a known shape.** `static constexpr std::string connectorId`, `static std::deque<Self> connectors` (a deque, so an account's `connector` pointer survives the next `Create`), `using Account = <Bank>Account`, `std::vector<Account> accounts`, `name`, `TestConnector()`, `RefreshAccounts()`, `GetNewTransactions()` and `GetNewTransactions(account)`, `Logout()`, `StorageKey()`, static `Create(…)` and `Remove(connector)`, `to_json`/`from_json` for `connectors.json`, and a `std::formatter` that prints its name; its account derives from `Account` and has `StorageKey()` and `Send(to, name, amount, currency, description)`. `main.cpp` and `:Connector` compile against that shape; anything a bank offers beyond it (bunq's requests, schedules, drafts and cards) the CLI reaches through `if constexpr (requires { … })`. (Revised 2026-10-31 for the MVP connector: the deque, `Logout`, `Remove` and the storage keys.)
3. **Money is an integer.** Amounts and balances are `std::int64_t` in the currency's minor unit, outgoing negative, with the `Currency` beside them; decimal strings exist only at the API boundary and go through `ParseAmount` and `FormatAmount`. No floating point anywhere near an amount.
4. **Secrets live in one private file, out of the user's reach.** `connectors.json` holds the API key or OAuth token, both tokens and the RSA private key, `0600` under a `0700` directory made by `CreatePrivateFile`; nothing prints them, nothing else persists them. Installed, the file is nostrod's, under the state directory of the system user `nostro`, so no program the user runs can read it; the CLI reads a key or a client secret at a prompt (`ReadSecret`), never from `argv`, which every local user can read and polkit logs, and passes it to nostrod once, in a message marked sensitive. (Revised 2026-11-01 for nostrod.)
5. **Transactions are a local, append-only cache in Crafter.DB.** One table per account, under a storage key the connector chooses (bunq's: environment, user id, account id), ordered by `timePoint`; a sync appends what is newer than the last stored row, and at that last timestamp what has an `id` not stored yet; queries are answered from the table, never from the bank. `Transaction` is the on-disk schema: a change to its members bumps `version` and keeps the old struct as `Previous` (see the Crafter.DB notes below), and the `static_assert`s on `rowSize` (120) and `fingerprint` in `Nostro-Account.cpp`, and those pinning the previous version, are updated in the same commit.
6. **Synchronous HTTPS, one client per bank host.** `ClientHTTP1::Send` on the calling thread, a persistent connection for reads and a fresh one for every write, no thread pool, default TLS verification. A bank's own request function owns the protocol: signing, verifying, waiting out rate limits and renewing an expired session once. Every other error is an exception; whether to retry a write is the caller's decision, and an unknown outcome is reported as such. (Revised 2026-10-31: the retries moved from the transaction sync into the request function.)
7. **Signing is opt-in per bank.** `:Crypto` and `-lssl -lcrypto` are pulled in by `opensslEnabled`, the OR of the banks that sign; a bank that does not sign must not make the build depend on OpenSSL.
8. **The library is the product, the CLI is a thin client.** `--lib` returns the library configuration; the CLI adds `main.cpp` alone, which parses `argv`, calls nostrod through `Client` and prints through the formatters, and nostrod adds `nostrod.cpp` alone. Logic goes into a partition (the daemon's into `:Daemon`), not into `main.cpp`. (Revised 2026-11-01: the CLI talks to nostrod, not to the bank.)
9. **nostrod answers each caller for their own money, and asks polkit first.** The front maps a caller's uid, asked of the bus, to that uid's own worker process; nothing of one user's is ever in another's process. Every method has one polkit action, decided by what the call does (`View`, `Change`, `Pay`, `UnfreezeCard`, `BlockCard`, `Connectors`, `Checkout`), and the dialog's summary and details are built from the worker's own data after the call is read and checked, never from text the caller formatted: what the dialog shows is what gets paid. Every action is owned by `unix-user:nostro` in the policy, or polkit refuses nostrod's checks. Every method is `SD_BUS_VTABLE_UNPRIVILEGED`, since polkit decides, not sd-bus. It fails closed. No action keeps an authorization: polkit keeps one per process, so the CLI would ask every time anyway.
10. **The wire is a published contract.** `packaging/dbus/*.xml` is what nostrod serves (`ShouldServeEveryUser` compares them with its introspection), and apps in other languages generate their proxies from it. A method may be added; changing a method's signature or meaning means a new interface (`…Nostro2`). The checkout's `options` and `results` are dictionaries so that it can grow without one: unknown options are ignored, unknown results skipped.
## Adding a bank
The checklist, from the bunq connector:
1. `interfaces/Nostro-<Bank>.cppm`: `export module Nostro:<Bank>;` with everything under `#ifdef NOSTRO_<BANK>_ENABLED`, defining `<Bank>Account : Account` and `<Bank>Connector` to design rule 2; `implementations/Nostro-<Bank>.cpp` as `module Nostro:<Bank>_impl;`.
2. `interfaces/Nostro.cppm`: `export import :<Bank>;` under the define. `interfaces/Nostro-Banks.cppm`: `import :<Bank>;` under the define and the type in `EnabledBanks`; with two optional entries the comma between them needs a condition of its own, or the tuple does not parse when only one bank is on.
3. `project.cpp`: the name in the `--banks=` loop, its define, its implementation unit, and `opensslEnabled` if it signs. Both configurations get the defines (`execfg.defines = libcfg.defines`).
4. `implementations/main.cpp`: the `connectors add <bank> …` branch, plus any command for what the bank offers beyond design rule 2, behind `if constexpr (requires { … })`. `README.md`: the CLI lines and the supported-banks list. `AGENTS.consumer.md`: what consumers need to know about the bank.
5. A fake of the bank in `tests/Support/` and tests that run every line of its connector, as `FakeBunq.inc` and the bunq tests do; then try it against the bank's sandbox or live API, and say in the commit how. The README refuses blind connector submissions.
## Commit and PR guidelines
- Patches go by mail to jorijnvdgraaf@catcrafts.net, as the README says. Branch off `master`.
- Take the commit voice from the sibling Crafter repositories: `type(scope): imperative summary` with `feat`, `fix`, `refactor`, `docs` or `build`, and the partition or the CLI as the scope (`bunq`, `account`, `currency`, `connector`, `file`, `bus`, `client`, `daemon`, `checkout`, `cli`, `build`, `packaging`). The body says what was wrong, why, and how it was verified against the sandbox. Add a `Co-Authored-By:` trailer when an agent wrote it.
- The README is the manual: keep its CLI section true to `main.cpp`. Update `AGENTS.consumer.md` in the same change when a signature, a path, a default, a file format or an error behaviour consumers lean on changes; consumers pick it up on their next build.
- A change to `Transaction` is a schema change (design rule 5), and the commit message says so.
- A change to the D-Bus interfaces or the polkit policy changes the published contract (design rule 10); the XML, the policy and the test that holds them change together.
- Never commit `bin/`, `build/`, `AGENTS.md`, or a `connectors.json`.
## Security considerations
- `connectors.json` is the crown jewels: the bunq API key or OAuth token, the installation and session tokens and the unencrypted RSA private key, as plain text. Its protection is `0600` in a `0700` directory, and installed, the directory of a system user of its own (`/var/lib/nostro`) under a service that keeps the rest of the system read-only to it; it is replaced by a synced rename, never rewritten in place. There is no encryption at rest: root, and a disk taken out of the machine, read it. Never print it, never log a token or a signature, never copy a real one into a scratch directory or a commit. The transaction tables are the user's financial history, kept private the same way by Crafter.DB.
- What nostrod does not stop: a program running as the user can still draw a dialog that looks like polkit's and ask for the password; only the system's own agent is the real one. On a session without a polkit agent (SSH, a TTY without one) nothing can confirm, so every call that needs a password is `Cancelled`. polkit logs the calling process's command line, which is why no secret is ever an argument.
- A worker makes itself undumpable, and the service sets `LimitCORE=0`: a core dump would hold the keys. A text that reaches a dialog goes through `Shown()`, so neither a payee's name nor a description can fake another amount or payee in it.
- The checkout answers a repeated order with its payment id without a dialog, so any app with access to the checkout can learn whether the user paid an order whose IBAN, reference and amount it knows (README, "Checkout for apps").
- A connector's `environment` decides between `api.bunq.com`, where `send` moves real money, and the sandbox. Sandbox API keys are recognised by their `sandbox_` prefix; anything else is production. Only the sandbox has been exercised; test production with small amounts first.
- Request bodies are `nlohmann::json` values serialised once (`dump` with invalid UTF-8 replaced), and the signature covers those exact bytes; nothing is spliced into JSON text by hand. Responses are used only after their server signature verifies.
- A write is never replayed by the transport (fresh connection) and only resent by nostro after a 429, which bunq refuses before acting. An IBAN's check digits are verified before anything is sent.
- TLS is Crafter.Network's default `TLSClientCredentials{}`: the chain against the system store and the hostname. Do not reach for `insecureNoServerValidation`.
- The private key signs every request body (`SignBody`, RSA SHA-256). Key material lives in `Crypto::Key`s (freed with the last copy) for the process's life; there is no zeroisation.
- `project.cpp` executes the `project.cpp` of three unpinned dependencies (Crafter.Network, Crafter.DB, Crafter.LintRules) on every build, fetched from the Catcrafts Forgejo at HEAD, and the Flatpak build does the same with the network on. Pin a commit on each for a build that is reproducible and offline after the first fetch.
- `install.sh --repo` installs from an unsigned local repository, for a build of your own. A published Flatpak comes from the GPG-signed Catcrafts remote; `packaging/flatpak/net.catcrafts.Nostro.flatpakref` carries the same placeholder for the key as Crafter.Build's, for the publishing side to fill in.
- Input from the bank is parsed with nlohmann/json's `at()` and `get()`, which throw on a missing key or a wrong type: a malformed response is an exception, not undefined behaviour. `ParseAmount` and `ParseTimestamp` reject anything outside their grammar.
## Gotchas
The state of the code on 2026-11-01; each is a fact to work with.
- crafter-build makes one configuration per run, so nostrod and the checkout library are products chosen with `--product=`, as in imsd. The library is one shared `Configuration*`: two configurations exporting the same module in one build are an error.
- systemd's hardening and bubblewrap, which flatpak runs nostrod in, disagree in places, found on 2026-11-01 under `systemd-run --user`: bubblewrap needs `AF_NETLINK` (it brings up loopback), `@mount`, `unshare` and `setns`, and a `/proc` of its own; `RestrictSUIDSGID=` makes systemd answer `openat2()` with ENOSYS, which bubblewrap 0.13 does not fall back from. `nostrod.service` says which options are left out and why.
- polkit as seen on that day (polkit 127, Plasma): closing Plasma's dialog sends no `polkit.dismissed`, only `polkit.result` `auth_self`, so `Cancelled` is read from either; a kept authorization is the calling process's alone; the command line of the process asking is logged.
- sd-bus holds a vtable method's answer to the signature the vtable declares: an answer of another shape becomes `System.Error.ENOMSG`. A test that must send a malformed answer (`FakeCheckout` in `ShouldServeEveryUser`) registers a plain object (`sd_bus_add_object`) instead.
- A worker or nostrod killed with SIGKILL writes no coverage counts; both handle SIGTERM (systemd's stop signal too) by ending the loop, and the tests stop them that way.
- `--product=checkout` returns before the bank check, so it needs no `--banks=`; every other product does.
- **`GetConfigPath()` with `XDG_CONFIG_HOME` set returns `$XDG_CONFIG_HOME/.config/nostro`**, not `$XDG_CONFIG_HOME/nostro`; the cache path has no such insertion. An open bug, kept as is so existing files are still found; the sandbox recipe above accounts for it.
- bunq's spec is not always what the API does. Verified in the sandbox:
- The scheduled payment listing names its objects `ScheduledPayment`, not `SchedulePayment`.
- An ended session answers 403 "Insufficient authentication.", unsigned, not 401.
- The OAuth token endpoint ignores a form body: its parameters go in the query string.
- `UserPerson` has no `name`; every user type has `display_name`.
- `PUT …/card/{id}` answers with the card as it is, even when it ignored the status asked for.
- Check a listing's object name against a real response before relying on it.
- The transaction cache moved on 2026-10-31 to `<cache>/transactions/bunq/<environment>/<user id>/<account id>/<name>.cdb`. Tables from before sit at `transactions/bunq/<name>.cdb`, are no longer read, and stay on disk until deleted by hand; a connector re-syncs its history on first use.
- `connectors.lock` is held for the whole process. Under nostrod that is the user's worker, which lives until it is idle; a program using the library directly on the same directory waits for it, and before nostrod a command waiting at a prompt held up the next one.
- A sandbox virtual card cannot be activated through the API: `cards unfreeze` reports bunq keeping it `DEACTIVATED`, which is the real answer, not a bug.
- `RespondToDraftPayment` sends the shown draft's `updated` as `previous_updated_timestamp`; bunq refuses a response to a draft that changed since it was read. `RespondToRequest` pays the shown request's amount, not what bunq holds by the time it runs.
- The `std::formatter` for accounts is a constrained partial specialisation (`template<std::derived_from<Nostro::Account> T>`) because an explicit `std::formatter<Account>` does not apply to `BunqAccount`; every new account type is covered by it. Non-exported formatter specialisations in a partition are found by importers.
- `.vscode/tasks.json` runs `crafter-build build --debug --banks=bunq`: `build` is not a crafter-build verb, it passes through as a project arg, nostro forwards it to its dependencies, and everything builds into variant directories of its own. `.vscode/launch.json` names a variant directory and a `balance` command that no longer exist.
- `connectorId` is a `static constexpr std::string`, which compiles only because `"bunq"` is short enough for libc++'s inline buffer; a long id needs a `std::string_view`.
- `tuple_for` takes a template lambda, `[&]<typename Bank>() { … }`, and calls `func.template operator()<Ts>()` for each tuple element; a lambda that captures by reference what it mutates is the pattern throughout `main.cpp`.

129
README.md
View file

@ -4,28 +4,137 @@ The primary problem with linux phones is that they don't have banking apps, Nost
By making a open source app that interfaces with bank APIs.
## How Nostro runs
Nostro keeps your bank connections out of reach of the programs you run. Its daemon, nostrod, runs as a system user of its own and holds the bank connections of every user of the machine, each user's in a process of its own. The `nostro` command asks nostrod over the system bus, and nostrod asks polkit whether you may:
- Looking at accounts, transactions, requests and cards needs nothing more in your desktop session.
- Paying, scheduling a payment, accepting a request or a draft payment, unfreezing or blocking a card, and changing your bank connections ask for your password every time.
Your desktop draws the password dialog, and it says what it is for: the amount, who is paid, and from which account. Nothing secret goes on the command line: Nostro asks for an API key at a prompt.
## Installing
Nostro comes as a Flatpak, `net.catcrafts.Nostro`, installed for the whole system. A Flatpak cannot install a few system files Nostro needs: nostrod's user, its D-Bus and polkit policies, its systemd unit, and the `nostro` command. Install both as root:
```
flatpak install --system packaging/flatpak/net.catcrafts.Nostro.flatpakref # the Flatpak, from the Catcrafts repository
packaging/system/install.sh # the system files
```
To install a Flatpak you built yourself (see Building) instead, run `packaging/system/install.sh --repo <dir>/repo`. On Arch Linux, `makepkg -si` in `packaging/arch` installs the system files as the `nostro-system` package instead of `install.sh`. nostrod starts with the first `nostro` command and stops by itself once it has nothing to do.
`packaging/system/uninstall.sh` removes everything again. Your bank connections stay in `/var/lib/nostro` until you give it `--purge`.
## Moving from an older Nostro
Before nostrod, Nostro kept your bank connections in `~/.config/nostro/connectors.json`, where any program you ran could read your API key, and the `nostro` command warns while that file exists. To move:
1. Revoke the key in the bunq app, under Developers, then API keys.
2. Add a new key with `nostro connectors add bunq`.
3. Delete `~/.config/nostro` and `~/.cache/nostro`.
Nostro fetches your transaction history from bunq again.
## Building
This project uses [Crafter.Build](https://forgejo.catcrafts.net/Catcrafts/Crafter.Build) for its building system
```
crafter-build --banks={lists of banks you want to enable}
crafter-build --banks={lists of banks you want to enable} # the library and the nostro command
crafter-build --banks=bunq --product=daemon # nostrod
crafter-build --product=checkout # the checkout library for apps, see Checkout for apps
```
The `nostro` command talks to an installed nostrod, so it needs one to do anything. The Flatpak builds on crafter-build's own Flatpak, which must be installed:
```
flatpak run --filesystem=<dir> org.flatpak.Builder --user --force-clean --repo=<dir>/repo --state-dir=<dir>/state <dir>/build packaging/flatpak/net.catcrafts.Nostro.yaml
```
`--filesystem=` is only needed for a `<dir>` outside your home.
## CLI
```
nostro connectors # shows currently added connectors and their status
nostro accounts # shows all accounts of all connectors
nostro connectors add {type} {...}
nostro connectors add bunq {api key} {allowed ip, optional}
nostro send {account name} {recipient iban} {recipient name} {amount} {description} # amount is in the smallest unit of your currency, so for EUR 100 = €1.00
nostro connectors # connectors, numbered, and whether they work
nostro connectors add bunq [allowed ips, default *] [--sandbox] # asks for the API key
nostro connectors add bunq-oauth {client id} {redirect uri} [--sandbox] # asks for the client secret
nostro connectors remove {name or number} # logs out and deletes its stored transactions
nostro accounts # all accounts of all connectors
nostro transactions {account} [--search text] [--amount n] [--from date] [--to date] [--limit n]
nostro send {account} {to} {name} {amount} {description, optional}
nostro request {account} {from} {name} {amount} {description, optional}
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, optional} [--every n] [--until date]
nostro scheduled {account} [cancel {id}]
nostro draft {account} {to} {name} {amount} {description, optional}
nostro drafts {account} [accept|reject {id}]
nostro cards [freeze|unfreeze|lost|stolen {card id}]
nostro checkout account [{account}] # the account apps may ask you to pay from, see Checkout
```
- `{account}` is an account's name or its IBAN. Use the IBAN when two accounts share a name.
- `{to}` and `{from}` are an IBAN, an e-mail address, or a phone number starting with `+`. IBANs are checked before anything is sent.
- Amounts are in the smallest unit of your currency, so for EUR `1250` is €12.50.
- Dates are `YYYY-MM-DD` or `"YYYY-MM-DD hh:mm"`, in local time.
## bunq
Connect with an API key: in the bunq app's settings, open Developers, then API keys, and add one. Nostro asks for it without echoing it, or reads it from stdin, and never takes it from the command line, which every user of the machine can read. A key added with the default allowed IP `*` works from any address, which a phone needs. Sandbox keys start with `sandbox_` and connect to the sandbox automatically. Adding the same bunq user again replaces the connector, which is how you renew a key.
OAuth is the other way in. Any bunq user can create an OAuth client in the bunq app or at [bunq Developer](https://developer.bunq.com) and register a redirect URL for it. `nostro connectors add bunq-oauth` prints an address to open, where you approve the connection by scanning a QR code with the bunq app. Paste the address your browser lands on afterwards back into Nostro. bunq only lets OAuth connections pay between your own accounts. A payment to someone else has to be a draft payment (`nostro draft`) that you approve in the bunq app, and incoming requests can be read but not paid. An API key has none of these limits.
## Supported banks
[Bunq](https://doc.bunq.com/api-reference/start-here)
## Checkout for apps
An app, such as a shop, can have the user's Nostro pay an order. Nostro pays it from the account the user chose once with `nostro checkout account {account}`, after the user has confirmed the payment with their password at a prompt that shows the amount, the payee, the reference and that account. The app never names or sees the account, and gets back only the payment's id. An account connected through OAuth cannot pay a shop, so it cannot be chosen.
Apps talk to `net.catcrafts.Nostro1.Checkout` on the system bus. A Flatpak app asks for it with `--system-talk-name=net.catcrafts.Nostro1.Checkout` in its finish-args, which reaches nothing else of Nostro. The interface is one method, documented in [packaging/dbus/net.catcrafts.Nostro1.Checkout.xml](packaging/dbus/net.catcrafts.Nostro1.Checkout.xml):
```
Pay(payeeIban s, payeeName s, amount x, currency s, reference s, options a{sv}) -> (paymentId t, results a{sv})
```
- The payee is an IBAN. The amount is in the currency's smallest unit (`1250` is €12.50), and the currency is `EUR`. The reference is your order number: it becomes the payment's description, and it tells orders apart.
- Allow interactive authorization on the call, make the call asynchronously, and give it a timeout of minutes, because the user may take a while at the prompt.
- An order is paid once. Calling `Pay` again with the same IBAN and reference, after a timeout or a crash, returns the first payment with `repeated` set to true in `results`, without asking the user. While the user is still at the prompt, the second call waits for the first. The same reference with another amount is refused.
- `net.catcrafts.Nostro1.Error.Cancelled` means the user did not confirm, and `NoCheckoutAccount` that they have not chosen an account. `org.freedesktop.DBus.Error.ServiceUnknown` means Nostro is not installed. The XML lists the other errors.
- Ignore keys you do not know in `results`, because later versions may add some. Nostro ignores options it does not know.
- A payment id is not a receipt. Confirm the money arrived with your own bank.
From a shell:
```
busctl call --system --timeout=10min net.catcrafts.Nostro1.Checkout /net/catcrafts/Nostro1 \
net.catcrafts.Nostro1.Checkout Pay 'ssxssa{sv}' NL91ABNA0417164300 'Shop BV' 1250 EUR order-1234 0
```
Generate a proxy from the XML with `gdbus-codegen` (GLib and GTK), `qdbusxml2cpp` (Qt) or `zbus-xmlgen` (Rust). A C++ app built with Crafter.Build can depend on Nostro with `--product=checkout` instead. That builds the `Nostro.Checkout` module alone, which links only libsystemd:
```cpp
import Nostro.Checkout;
const Nostro::Checkout::Paid paid = Nostro::Checkout::Pay({.payeeIban = "NL91ABNA0417164300", .payeeName = "Shop BV", .amount = 1250, .reference = "order-1234"});
```
`Pay` blocks until the user has answered, so call it off the UI thread. It throws `Nostro::Checkout::Cancelled`, `Nostro::Checkout::NoCheckoutAccount`, or `Nostro::Checkout::Error` with the D-Bus error name.
Any app the user runs with access to the checkout can ask whether an order was paid, by asking for it again with the same IBAN, reference and amount: it gets the payment id without a prompt. Nostro cannot tell which app is asking, so a reference should be hard to guess.
## Testing
```
crafter-build test --banks=bunq # every test, against a fake bunq and a fake system bus in the test itself
tests/coverage.sh # the same with coverage: a report per file, and every line no test ran
```
`tests/coverage.sh` needs `llvm-profdata` and `llvm-cov`, and a toolchain with compiler-rt's profile runtime; for one without it, pass the path of its `libclang_rt.profile` archive as the argument.
## Contributing
Nostro gladly accepts contributions to add more banks!
@ -40,6 +149,14 @@ For 100% certainity blind submissions for connectors are not be accepted, they m
Please report security vuneribilities to jorijnvdgraaf@catcrafts.net before publishing them.
What Nostro protects you from, and what it does not:
- Programs you run cannot read your bank connections, which belong to nostrod's own user, and cannot move money without your password.
- The password dialog is your desktop's. A program running as you could still draw one that looks the same, so type your password only for something you asked for, and check what the dialog says.
- Over SSH, or in any session without a polkit agent, nothing can ask for your password, so whatever needs it is refused.
- The bank connections are not encrypted on disk: root, and anyone holding the disk, can read them. Use full-disk encryption.
- An administrator can change what needs a password with polkit rules in `/etc/polkit-1/rules.d/`, for example an amount above which an administrator must approve a payment. Each dialog gives rules `amount_minor`, `currency`, `counterparty`, `account_iban` and `environment`, and at checkout `reference`.
## License
LGPL-3.0-only, see [LICENSE](LICENSE).

View file

@ -1,210 +1,117 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module Nostro:Account_impl;
import :Account;
import :File;
import std;
import Crafter.DB;
using namespace Nostro;
using namespace Crafter;
namespace fs = std::filesystem;
// Transaction is the on-disk schema of the tables below. These fail when it changes, as a reminder to bump
// Transaction::version; update them together with it.
static_assert(DB::Layout<Transaction>::rowSize == 120);
static_assert(DB::Layout<Transaction>::fingerprint == 0x1ceea246dfcdf4f0);
// Version 1, which existing tables migrate from. It must never change.
static_assert(DB::Layout<Transaction::Previous>::rowSize == 88);
static_assert(DB::Layout<Transaction::Previous>::fingerprint == 0x6b478e471876761f);
namespace {
// An account name is the file name of its table: one with a '/' in it would be a path.
std::string FileName(std::string_view account) {
std::string name(account);
std::ranges::replace(name, '/', '_');
return std::format("{}.cdb", name);
}
// Each table is opened on first use and kept open for the rest of the process, or until its connector is
// forgotten: an open maps the whole file, and a second writable Table on the same file would throw DB::LockedError.
std::map<fs::path, DB::Table<Transaction>>& Tables() {
static std::map<fs::path, DB::Table<Transaction>> tables;
return tables;
}
DB::Table<Transaction>& GetTable(std::string_view connector, std::string_view account) {
const fs::path path = cachePath / "transactions" / connector / FileName(account);
return Tables().try_emplace(path, path).first->second;
}
// ASCII case folding: enough for names and descriptions, IBANs are upper case anyway.
char Lower(char c) {
return c >= 'A' && c <= 'Z' ? static_cast<char>(c + ('a' - 'A')) : c;
}
// `search` is lower case already.
bool Contains(std::string_view text, std::string_view search) {
return !std::ranges::search(text, search, {}, Lower).empty();
}
}
std::chrono::system_clock::time_point Account::GetLastTransactionTime(std::string_view connector) const {
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
if(!fs::exists(path) || fs::file_size(path) == 0) {
const DB::Table<Transaction>& table = GetTable(connector, name);
if(table.Empty()) {
return std::chrono::system_clock::time_point::min();
}
std::ifstream file(path, std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
file.seekg(-static_cast<std::streamoff>(sizeof(std::int64_t)), std::ios::end);
std::int64_t lastTime;
file.read(reinterpret_cast<char*>(&lastTime), sizeof(lastTime));
return std::chrono::system_clock::time_point(std::chrono::microseconds(lastTime));
return table.Back()[&Transaction::timePoint];
}
void Account::SaveTransactions(std::string_view connector) {
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
CreatePrivateFile(path);
std::ofstream file(path, std::ios::in | std::ios::out | std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
void Account::SaveTransactions(std::string_view connector, std::vector<Transaction> transactions) {
DB::Table<Transaction>& table = GetTable(connector, name);
const std::chrono::system_clock::time_point last = GetLastTransactionTime(connector);
std::uint32_t pendingIndex = transactions.size();
for(std::uint32_t i = 0; i < transactions.size(); i++) {
if(transactions[i].timePoint > last) {
pendingIndex = i;
break;
}
}
file.seekp(0, std::ios::end);
for(std::uint32_t i = pendingIndex; i < transactions.size(); i++) {
WriteString(file, transactions[i].name);
WriteString(file, transactions[i].bic);
WriteString(file, transactions[i].iban);
WriteString(file, transactions[i].description);
file.write(reinterpret_cast<char*>(&transactions[i].amount), sizeof(transactions[i].amount));
file.write(reinterpret_cast<char*>(&transactions[i].currency), sizeof(Currency));
std::int64_t time = std::chrono::duration_cast<std::chrono::microseconds>(transactions[i].timePoint.time_since_epoch()).count();
file.write(reinterpret_cast<char*>(&time), sizeof(time));
}
}
Transaction& Account::LoadTransaction(std::ifstream& file) {
Transaction& tr = transactions.emplace_back();
ReadString(file, tr.name);
ReadString(file, tr.bic);
ReadString(file, tr.iban);
ReadString(file, tr.description);
file.read(reinterpret_cast<char*>(&tr.amount), sizeof(tr.amount));
file.read(reinterpret_cast<char*>(&tr.currency), sizeof(tr.currency));
std::int64_t time;
file.read(reinterpret_cast<char*>(&time), sizeof(time));
tr.timePoint = std::chrono::system_clock::time_point(std::chrono::duration_cast<std::chrono::system_clock::duration>(std::chrono::microseconds(time)));
return tr;
}
void Account::LoadTransactions(std::string_view connector) {
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
if(!fs::exists(path)) {
return;
}
std::fstream file(path, std::ios::in | std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
while(file.peek() != std::fstream::traits_type::eof()) {
LoadTransaction();
}
}
std::ifstream Account::LoadUntilFrom(std::string_view connector, std::chrono::system_clock::time_point from) {
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
if(!fs::exists(path)) {
return;
}
std::ifstream file(path, std::ios::in | std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
while(file.peek() != std::fstream::traits_type::eof()) {
std::uint16_t seeked = SeekString();
seeked += SeekString();
seeked += SeekString();
seeked += SeekString();
in.seekg(sizeof(tr.amount)+sizeof(tr.Currency), std::ios::cur);
std::int64_t timeI;
file.read(reinterpret_cast<char*>(&timeI), sizeof(tr.timeI));
std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::from_time_t(timeI);
if(timePoint > from) {
in.seekg(-seeked-sizeof(tr.amount)-sizeof(tr.Currency)-sizeof(tr.timeI), std::ios::cur);
LoadTransaction();
break;
}
}
return file;
}
void Account::LoadTransactions(std::string_view connector, std::chrono::system_clock::time_point from, std::chrono::system_clock::time_point to) {
std::ifstream file = LoadUntilFrom(connector, from);
while(file.peek() != std::fstream::traits_type::eof()) {
Transaction& tr = LoadTransaction();
if(tr.timePoint > to) {
transactions.pop_back();
break;
}
}
}
void Account::LoadTransactions(std::string_view connector, std::chrono::system_clock::time_point from) {
std::ifstream file = LoadUntilFrom(connector, from);
while(file.peek() != std::fstream::traits_type::eof()) {
LoadTransaction();
}
}
void Account::LoadTransactionsByProperty(std::string_view connector, std::string_view property) {
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
if(!fs::exists(path)) {
return;
}
std::ifstream file(path, std::ios::in | std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
while(file.peek() != std::fstream::traits_type::eof()) {
std::uint16_t seeked = SeekString();
seeked += SeekString();
seeked += SeekString();
std::uint16_t size;
file.read(reinterpret_cast<char*>(&size), sizeof(size));
if(description.size() == size) {
std::string readDescription;
readDescription.resize(size);
file.read(readDescription.data(), size);
if(readDescription == description) {
in.seekg(-seeked-readDescription.size()-sizeof(size), std::ios::cur);
Transaction& tr = transactions.emplace_back();
ReadString(file, tr.name);
ReadString(file, tr.bic);
ReadString(file, tr.iban);
SeekString();
file.read(reinterpret_cast<char*>(&tr.amount), sizeof(tr.amount));
file.read(reinterpret_cast<char*>(&tr.currency), sizeof(tr.Currency));
file.read(reinterpret_cast<char*>(&tr.time), sizeof(tr.time));
// The ids stored at the last timestamp: a fetch that includes that timestamp again brings them back. A row there
// without an id (stored by version 1) cannot be matched, so then nothing at that timestamp is taken as new.
std::vector<std::string> known;
bool unmatchable = false;
if(!table.Empty()) {
for(DB::RowId id = table.LowerBound<&Transaction::timePoint>(last); id < table.SlotCount(); id++) {
const DB::Row<Transaction> row = table[id];
if(!row.Erased()) {
const std::string_view stored = row[&Transaction::id];
unmatchable = unmatchable || stored.empty();
known.emplace_back(stored);
}
}
}
// The table is ordered by timePoint and refuses a row older than its last one. A row at the last timestamp is
// new when its id is.
std::ranges::stable_sort(transactions, {}, &Transaction::timePoint);
std::erase_if(transactions, [last, unmatchable, &known](const Transaction& transaction) {
return transaction.timePoint < last || (transaction.timePoint == last && (unmatchable || transaction.id.empty() || std::ranges::contains(known, transaction.id)));
});
table.Append(std::span<const Transaction>(transactions));
table.Flush();
}
void Account::LoadTransactionsByIban(std::string_view connector, std::string_view iban) {
transactions.clear();
void Account::ForgetTransactions(std::string_view connector) {
const fs::path directory = cachePath / "transactions" / connector;
std::erase_if(Tables(), [&directory](const std::pair<const fs::path, DB::Table<Transaction>>& table) {
return std::mismatch(directory.begin(), directory.end(), table.first.begin(), table.first.end()).first == directory.end();
});
fs::remove_all(directory);
}
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
if(!fs::exists(path)) {
return;
}
std::vector<Transaction> Account::FindTransactions(std::string_view connector, const TransactionQuery& query) const {
const DB::Table<Transaction>& table = GetTable(connector, name);
const std::string search = query.search | std::views::transform(Lower) | std::ranges::to<std::string>();
std::ifstream file(path, std::ios::in | std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
while(file.peek() != std::fstream::traits_type::eof()) {
std::uint16_t seeked = SeekString();
seeked += SeekString();
std::uint16_t size;
file.read(reinterpret_cast<char*>(&size), sizeof(size));
if(iban.size() == size) {
std::string readIban;
readIban.resize(size);
file.read(readIban.data(), size);
if(readIban == iban) {
in.seekg(-seeked-readIban.size()-sizeof(size), std::ios::cur);
Transaction& tr = transactions.emplace_back();
ReadString(file, tr.name);
ReadString(file, tr.bic);
SeekString();
ReadString(file, tr.description);
file.read(reinterpret_cast<char*>(&tr.amount), sizeof(tr.amount));
file.read(reinterpret_cast<char*>(&tr.currency), sizeof(tr.Currency));
file.read(reinterpret_cast<char*>(&tr.time), sizeof(tr.time));
}
// Walk the time range backwards from the newest row and stop at the limit, so a search that matches often
// returns early; only a rare or failed one reads the whole range.
const DB::RowId first = table.LowerBound<&Transaction::timePoint>(query.from);
std::vector<Transaction> rows;
for(DB::RowId id = table.UpperBound<&Transaction::timePoint>(query.to); id > first && rows.size() < query.limit; id--) {
const DB::Row<Transaction> row = table[id - 1];
if(row.Erased() || (query.amount && row[&Transaction::amount] != *query.amount)) {
continue;
}
if(search.empty() || Contains(row[&Transaction::name], search) || Contains(row[&Transaction::description], search) || Contains(row[&Transaction::iban], search)) {
rows.push_back(row.Materialize());
}
}
}
return rows;
}

View file

@ -0,0 +1,333 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include "../lib/json.hpp"
module Nostro:BunqPayments_impl;
import std;
import :Bunq;
import :Currency;
import :Utils;
using namespace Nostro;
using namespace nlohmann;
namespace {
// ISO 13616: with the first four characters moved to the end and letters read as 10 to 35, the number is 1 mod 97.
bool ValidIban(std::string_view iban) {
if(iban.size() < 15 || iban.size() > 34 || !std::isalpha(static_cast<std::uint8_t>(iban[0])) || !std::isalpha(static_cast<std::uint8_t>(iban[1])) || !std::isdigit(static_cast<std::uint8_t>(iban[2])) || !std::isdigit(static_cast<std::uint8_t>(iban[3]))) {
return false;
}
std::uint32_t remainder = 0;
const std::string rearranged = std::format("{}{}", iban.substr(4), iban.substr(0, 4));
for(const char c : rearranged) {
if(c >= '0' && c <= '9') {
remainder = (remainder * 10 + static_cast<std::uint32_t>(c - '0')) % 97;
} else if(c >= 'A' && c <= 'Z') {
remainder = (remainder * 100 + static_cast<std::uint32_t>(c - 'A' + 10)) % 97;
} else {
return false;
}
}
return remainder == 1;
}
void RequirePositive(std::int64_t amount) {
if(amount <= 0) {
throw std::invalid_argument("the amount must be more than zero");
}
}
std::uint64_t CreatedId(const json& response) {
return BunqJson::Item(response, "Id").at("id").get<std::uint64_t>();
}
// The objects of one type in a listing, skipping anything else bunq puts in it. Some listings name their objects
// differently from the spec (scheduled payments come as ScheduledPayment, not SchedulePayment): every name in
// `types` is taken.
template<typename T, typename Read>
std::vector<T> ReadAll(const std::vector<json>& items, std::initializer_list<std::string_view> types, Read&& read) {
std::vector<T> out;
for(const json& item : items) {
for(const std::string_view type : types) {
if(const json::const_iterator object = item.find(type); object != item.end()) {
out.push_back(read(*object));
break;
}
}
}
return out;
}
std::chrono::system_clock::time_point Timestamp(const json& object, std::string_view key) {
const std::string text = BunqJson::String(object, key);
return text.empty() ? std::chrono::system_clock::time_point() : ParseTimestamp(text);
}
BunqPaymentRequest ReadRequest(const json& inquiry) {
const auto [currency, amount] = BunqJson::ReadAmount(inquiry.at("amount_inquired"));
BunqPaymentRequest out{
.id = inquiry.at("id").get<std::uint64_t>(),
.status = BunqJson::String(inquiry, "status"),
.counterparty = BunqJson::ReadLabel(inquiry.at("counterparty_alias")),
.currency = currency,
.amount = amount,
.amountPaid = std::nullopt,
.description = BunqJson::String(inquiry, "description"),
.created = Timestamp(inquiry, "created"),
.shareUrl = BunqJson::String(inquiry, "bunqme_share_url"),
};
if(const json::const_iterator paid = inquiry.find("amount_responded"); paid != inquiry.end() && paid->is_object()) {
out.amountPaid = BunqJson::ReadAmount(*paid).second;
}
return out;
}
BunqIncomingRequest ReadIncoming(const json& response) {
const auto [currency, amount] = BunqJson::ReadAmount(response.at("amount_inquired"));
return BunqIncomingRequest{
.id = response.at("id").get<std::uint64_t>(),
.status = BunqJson::String(response, "status"),
.type = BunqJson::String(response, "type"),
.counterparty = BunqJson::ReadLabel(response.at("counterparty_alias")),
.currency = currency,
.amount = amount,
.description = BunqJson::String(response, "description"),
.created = Timestamp(response, "created"),
};
}
BunqScheduledPayment ReadScheduled(const json& scheduled) {
const json& payment = scheduled.at("payment");
const json& schedule = scheduled.at("schedule");
const auto [currency, amount] = BunqJson::ReadAmount(payment.at("amount"));
BunqSchedule when{
.start = Timestamp(schedule, "time_start"),
.end = std::nullopt,
.unit = BunqJson::String(schedule, "recurrence_unit"),
.every = schedule.value("recurrence_size", std::uint32_t{1}),
.status = BunqJson::String(scheduled, "status"),
.next = std::nullopt,
};
if(!BunqJson::String(schedule, "time_end").empty()) {
when.end = Timestamp(schedule, "time_end");
}
if(!BunqJson::String(schedule, "time_next").empty()) {
when.next = Timestamp(schedule, "time_next");
}
if(when.status.empty()) {
when.status = BunqJson::String(schedule, "status");
}
return BunqScheduledPayment{
.id = scheduled.at("id").get<std::uint64_t>(),
.counterparty = BunqJson::ReadLabel(payment.at("counterparty_alias")),
.currency = currency,
// Each run sends this much; bunq lists it as positive or negative depending on the endpoint.
.amount = amount < 0 ? -amount : amount,
.description = BunqJson::String(payment, "description"),
.schedule = std::move(when),
};
}
BunqDraftPayment ReadDraft(const json& draft) {
BunqDraftPayment out{
.id = draft.at("id").get<std::uint64_t>(),
.status = BunqJson::String(draft, "status"),
.createdBy = std::string(),
.entries = {},
.updated = BunqJson::String(draft, "updated"),
};
if(const json::const_iterator creator = draft.find("user_alias_created"); creator != draft.end()) {
out.createdBy = BunqJson::String(*creator, "display_name");
}
if(const json::const_iterator entries = draft.find("entries"); entries != draft.end() && entries->is_array()) {
for(const json& entry : *entries) {
const auto [currency, amount] = BunqJson::ReadAmount(entry.at("amount"));
out.entries.push_back(BunqDraftPayment::Entry{
.counterparty = BunqJson::ReadLabel(entry.at("counterparty_alias")),
.currency = currency,
.amount = amount < 0 ? -amount : amount,
.description = BunqJson::String(entry, "description"),
});
}
}
return out;
}
// What a payment, draft entry and scheduled payment share.
json PaymentBody(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) {
RequirePositive(amount);
return json{
{"amount", BunqJson::Amount(amount, currency)},
{"counterparty_alias", BunqJson::Pointer(BunqCounterparty::Parse(to, name))},
{"description", std::string(description)},
};
}
}
BunqCounterparty BunqCounterparty::Parse(std::string_view value, std::string_view name) {
while(value.starts_with(' ')) {
value.remove_prefix(1);
}
while(value.ends_with(' ')) {
value.remove_suffix(1);
}
if(value.contains('@')) {
return BunqCounterparty{"EMAIL", std::string(value), std::string(name)};
}
if(value.starts_with('+')) {
std::string phone = "+";
for(const char c : value.substr(1)) {
if(c >= '0' && c <= '9') {
phone += c;
} else if(c != ' ' && c != '-' && c != '(' && c != ')') {
throw std::invalid_argument(std::format("'{}' is not a phone number", value));
}
}
if(phone.size() < 8) {
throw std::invalid_argument(std::format("'{}' is not a phone number", value));
}
return BunqCounterparty{"PHONE_NUMBER", std::move(phone), std::string(name)};
}
std::string iban;
for(const char c : value) {
if(c != ' ') {
iban += static_cast<char>(std::toupper(static_cast<std::uint8_t>(c)));
}
}
if(!ValidIban(iban)) {
throw std::invalid_argument(std::format("'{}' is not a valid IBAN, e-mail address or phone number (+31...)", value));
}
return BunqCounterparty{"IBAN", std::move(iban), std::string(name)};
}
std::uint64_t BunqAccount::Send(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
return CreatedId(connector->Post(std::format("{}/payment", Path()), PaymentBody(to, name, amount, currency, description)));
}
std::uint64_t BunqAccount::Draft(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
const json body = {
{"entries", json::array({PaymentBody(to, name, amount, currency, description)})},
{"number_of_required_accepts", 1},
};
return CreatedId(connector->Post(std::format("{}/draft-payment", Path()), body));
}
void BunqSchedule::Check() const {
constexpr std::array<std::string_view, 6> units = {"ONCE", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"};
if(!std::ranges::contains(units, unit)) {
throw std::invalid_argument(std::format("'{}' is not a schedule: once, hourly, daily, weekly, monthly or yearly", unit));
}
if(every == 0) {
throw std::invalid_argument("a schedule repeats at least every 1 unit");
}
}
std::uint64_t BunqAccount::Schedule(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description, const BunqSchedule& schedule) const {
schedule.Check();
json when = {
{"time_start", FormatTimestamp(schedule.start)},
{"recurrence_unit", schedule.unit},
{"recurrence_size", schedule.every},
};
if(schedule.end) {
when["time_end"] = FormatTimestamp(*schedule.end);
}
const json body = {
{"payment", PaymentBody(to, name, amount, currency, description)},
{"schedule", std::move(when)},
};
return CreatedId(connector->Post(std::format("{}/schedule-payment", Path()), body));
}
BunqPaymentRequest BunqAccount::Request(std::string_view from, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
RequirePositive(amount);
const json body = {
{"amount_inquired", BunqJson::Amount(amount, currency)},
{"counterparty_alias", BunqJson::Pointer(BunqCounterparty::Parse(from, name))},
{"description", std::string(description)},
{"allow_bunqme", true},
};
const std::uint64_t id = CreatedId(connector->Post(std::format("{}/request-inquiry", Path()), body));
// The share URL is only on the object, not in the creation's response. The request exists whatever happens to
// this read: failing here would look like a failed request, and asking again would ask twice.
try {
return ReadRequest(BunqJson::Item(connector->Get(std::format("{}/request-inquiry/{}", Path(), id)), "RequestInquiry"));
} catch(const std::exception& e) {
Note(std::format("request {} was made, but reading it back failed: {}", id, e.what()));
const BunqCounterparty counterparty = BunqCounterparty::Parse(from, name);
return BunqPaymentRequest{
.id = id,
.status = "PENDING",
.counterparty = BunqLabel{counterparty.name, counterparty.type == "IBAN" ? counterparty.value : std::string()},
.currency = currency,
.amount = amount,
.amountPaid = std::nullopt,
.description = std::string(description),
.created = std::chrono::system_clock::now(),
.shareUrl = std::string(),
};
}
}
std::vector<BunqPaymentRequest> BunqAccount::Requests() const {
return ReadAll<BunqPaymentRequest>(connector->List(std::format("{}/request-inquiry", Path())), {"RequestInquiry"}, ReadRequest);
}
std::vector<BunqIncomingRequest> BunqAccount::IncomingRequests() const {
return ReadAll<BunqIncomingRequest>(connector->List(std::format("{}/request-response", Path())), {"RequestResponse"}, ReadIncoming);
}
std::vector<BunqScheduledPayment> BunqAccount::ScheduledPayments() const {
return ReadAll<BunqScheduledPayment>(connector->List(std::format("{}/schedule-payment", Path())), {"ScheduledPayment", "SchedulePayment"}, ReadScheduled);
}
std::vector<BunqDraftPayment> BunqAccount::DraftPayments() const {
return ReadAll<BunqDraftPayment>(connector->List(std::format("{}/draft-payment", Path())), {"DraftPayment"}, ReadDraft);
}
BunqIncomingRequest BunqAccount::IncomingRequest(std::uint64_t id) const {
return ReadIncoming(BunqJson::Item(connector->Get(std::format("{}/request-response/{}", Path(), id)), "RequestResponse"));
}
BunqDraftPayment BunqAccount::DraftPayment(std::uint64_t id) const {
return ReadDraft(BunqJson::Item(connector->Get(std::format("{}/draft-payment/{}", Path(), id)), "DraftPayment"));
}
void BunqAccount::RevokeRequest(std::uint64_t id) const {
connector->Put(std::format("{}/request-inquiry/{}", Path(), id), json{{"status", "REVOKED"}});
}
void BunqAccount::RespondToRequest(const BunqIncomingRequest& shown, bool accept) const {
const std::string path = std::format("{}/request-response/{}", Path(), shown.id);
if(!accept) {
connector->Put(path, json{{"status", "REJECTED"}});
return;
}
// Accepting names the amount paid: the amount that was shown, not what the request asks by the time this runs,
// which the asker can change in between.
connector->Put(path, json{{"amount_responded", BunqJson::Amount(shown.amount, shown.currency)}, {"status", "ACCEPTED"}});
}
void BunqAccount::CancelScheduledPayment(std::uint64_t id) const {
connector->Delete(std::format("{}/schedule-payment/{}", Path(), id));
}
void BunqAccount::RespondToDraftPayment(const BunqDraftPayment& shown, bool accept) const {
// bunq refuses a response to a draft that changed since it was read, by its updated timestamp: the one of the
// draft that was shown, so a change made after that is refused rather than accepted unseen.
json body = {{"status", accept ? "ACCEPTED" : "REJECTED"}};
if(!shown.updated.empty()) {
body["previous_updated_timestamp"] = shown.updated;
}
connector->Put(std::format("{}/draft-payment/{}", Path(), shown.id), body);
}

View file

@ -1,14 +1,10 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include "../lib/json.hpp"
#include <openssl/types.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/err.h>
module Nostro:Bunq_impl;
@ -16,6 +12,9 @@ import std;
import :Bunq;
import :Connector;
import :Crypto;
import :Currency;
import :File;
import :Transaction;
import :Utils;
import Crafter.Network;
@ -24,250 +23,655 @@ using namespace Nostro::Crypto;
using namespace nlohmann;
using namespace Crafter;
std::vector<BunqConnector> BunqConnector::connectors;
std::deque<BunqConnector> BunqConnector::connectors;
json InResponse(const json& doc, std::string_view key) {
for (const json& item : doc.at("Response")) {
if (item.is_object()) {
if (const json::const_iterator v = item.find(key); v != item.end()) {
return *v;
namespace {
constexpr std::string_view userAgent = "Nostro";
constexpr std::string_view maybeCarriedOut = "; the request may have been carried out, check before trying again";
// Where BunqConnector::RedirectTo sends everything.
std::optional<BunqEndpoint>& Redirected() {
static std::optional<BunqEndpoint> redirected;
return redirected;
}
// A request's authority: the host, with the port when it is not HTTPS's own.
std::string Authority(const BunqEndpoint& endpoint) {
return endpoint.port == 443 ? endpoint.host : std::format("{}:{}", endpoint.host, endpoint.port);
}
// One persistent connection per endpoint, dialled on first use.
ClientHTTP1& ApiClient(const BunqEndpoint& endpoint) {
static std::map<std::string, std::unique_ptr<ClientHTTP1>> clients;
std::unique_ptr<ClientHTTP1>& client = clients[Authority(endpoint)];
if(!client) {
client = std::make_unique<ClientHTTP1>(endpoint.host, endpoint.port, TLSClientCredentials{.caPem = endpoint.caPem});
}
return *client;
}
// How often a 429 is waited out, and how long each time. bunq allows 3 GETs, 5 POSTs and 2 PUTs per endpoint in
// any 3 seconds, and one session per 30 seconds: the second entry is session-server's.
struct RateLimit {
std::uint32_t retries;
std::chrono::seconds wait;
};
constexpr std::array<RateLimit, 2> rateLimits = {{
{5, std::chrono::seconds(3)},
{2, std::chrono::seconds(31)},
}};
std::uint16_t ParseStatus(std::string_view status) {
std::uint16_t value = 0;
std::from_chars(status.data(), status.data() + status.size(), value);
return value;
}
// bunq's {"Error": [{"error_description": ...}]}, or the OAuth server's {"error": ..., "error_description": ...}.
std::string ErrorMessage(std::string_view body) {
const json doc = json::parse(body, nullptr, false);
std::string message;
if(doc.is_object()) {
if(const json::const_iterator errors = doc.find("Error"); errors != doc.end() && errors->is_array()) {
for(const json& error : *errors) {
const std::string description = BunqJson::String(error, "error_description");
if(!description.empty()) {
message += message.empty() ? description : std::format("; {}", description);
}
}
}
if(message.empty()) {
message = BunqJson::String(doc, "error_description");
}
if(message.empty()) {
message = BunqJson::String(doc, "error");
}
}
if(message.empty()) {
message = body.empty() ? std::string("no details") : std::string(body.substr(0, 300));
}
return message;
}
// bunq has no BIC on its own accounts; an IBAN with bank code BUNQ is one of them.
std::string BicOf(std::string_view iban, std::string bic) {
if(bic.empty() && iban.size() >= 8 && iban.substr(4, 4) == "BUNQ") {
return "BUNQNL2A";
}
return bic;
}
}
BunqError::BunqError(std::uint16_t status, const std::string& message) : std::runtime_error(message), status(status) {
}
json BunqJson::Item(const json& response, std::string_view key) {
for(const json& item : response.at("Response")) {
if(item.is_object()) {
if(const json::const_iterator value = item.find(key); value != item.end()) {
return *value;
}
}
}
throw std::runtime_error(std::format("bunq response has no '{}' object", key));
}
json GetUser(std::string_view body) {
try {
return InResponse(json::parse(body), "UserCompany");
} catch(std::runtime_error e) {
return InResponse(json::parse(body), "UserPerson");
std::pair<std::string, const json*> BunqJson::Only(const json& item) {
if(!item.is_object() || item.size() != 1) {
return {std::string(), nullptr};
}
const json::const_iterator only = item.begin();
return {only.key(), &only.value()};
}
std::string StringOrEmpty(const json& object, std::string_view key) {
json BunqJson::Amount(std::int64_t amount, Currency currency) {
return json{{"value", FormatAmount(amount, currency)}, {"currency", std::string(GetCurrencyCode(currency))}};
}
json BunqJson::Pointer(const BunqCounterparty& counterparty) {
json pointer = {{"type", counterparty.type}, {"value", counterparty.value}};
if(!counterparty.name.empty()) {
pointer["name"] = counterparty.name;
}
return pointer;
}
std::pair<Currency, std::int64_t> BunqJson::ReadAmount(const json& amount) {
const Currency currency = GetCurrency(amount.at("currency").get<std::string>());
return {currency, ParseAmount(amount.at("value").get<std::string>(), currency)};
}
BunqLabel BunqJson::ReadLabel(const json& label) {
BunqLabel out{String(label, "display_name"), String(label, "iban")};
if(out.name.empty() && label.is_object()) {
if(const json::const_iterator user = label.find("label_user"); user != label.end()) {
out.name = String(*user, "display_name");
}
}
return out;
}
std::string BunqJson::String(const json& object, std::string_view key) {
if(!object.is_object()) {
return std::string();
}
const json::const_iterator value = object.find(key);
if(value == object.end() || !value->is_string()) {
return "";
}
return value->get<std::string>();
return value != object.end() && value->is_string() ? value->get<std::string>() : std::string();
}
BunqAccount::BunqAccount(std::string&& name, std::string&& bic, std::string&& iban, Currency currency, std::int64_t balance, std::uint32_t id, BunqConnector* connector) : Account(std::move(name), std::move(bic), std::move(iban), currency, balance), id(id), connector(connector) {
json BunqConnector::Call(std::string_view method, std::string_view path, const json* body, Auth auth, bool renew) {
// Nothing a session call returns is used unverified: a connector saved before the server key was kept fetches it first.
if(auth == Auth::Session && !serverPublicKey && !fetchingServerKey) {
EnsureServerPublicKey();
}
const bool write = method != "GET";
const std::string target = path.starts_with("/v1/") ? std::string(path) : std::format("/v1{}", path);
// The signature covers these exact bytes. Text that is not UTF-8 (a description typed in another encoding) is
// replaced rather than refused.
const std::string payload = body ? body->dump(-1, ' ', false, json::error_handler_t::replace) : std::string();
std::unordered_map<std::string, std::string> headers = {
{"User-Agent", std::string(userAgent)},
{"Cache-Control", "no-cache"},
{"Accept", "application/json"},
};
if(body) {
headers.emplace("Content-Type", "application/json");
// Only sessions and payments need a signature, but signing every body costs nothing and covers whatever
// else bunq starts to require one for. The installation call is the one that may not carry it.
if(auth != Auth::None) {
headers.emplace("X-Bunq-Client-Signature", SignBody(privateKey.get(), payload));
}
}
bool renewed = false;
for(std::uint32_t attempt = 0;; attempt++) {
if(auth == Auth::Installation) {
headers["X-Bunq-Client-Authentication"] = installationToken;
} else if(auth == Auth::Session) {
headers["X-Bunq-Client-Authentication"] = sessionToken;
}
// ClientHTTP1 sends a request again on a reused connection that fails before any of the response arrives,
// which includes a read timeout: for a payment bunq booked before its answer was lost, that pays twice. It
// never replays on a new connection, so a write gets one.
const BunqEndpoint endpoint = Endpoint(environment);
ClientHTTP1& client = ApiClient(endpoint);
if(write) {
client.Disconnect();
}
HTTPResponse response;
try {
response = client.Send(CreateRequestHTTP(std::string(method), target, Authority(endpoint), headers, payload));
} catch(const std::exception& e) {
if(write) {
throw std::runtime_error(std::format("bunq {} {}: {}{}", method, path, e.what(), maybeCarriedOut));
}
throw;
}
const std::uint16_t status = ParseStatus(response.status);
// A 429 is refused before anything happens, so even a payment is safe to send again.
const RateLimit& limit = rateLimits[target.starts_with("/v1/session-server")];
if(status == 429 && attempt < limit.retries) {
std::this_thread::sleep_for(limit.wait);
continue;
}
if(status >= 200 && status < 300) {
// An error response can come unsigned; nothing but its message is used. A success is used, so it must verify.
if(serverPublicKey && auth != Auth::None) {
const std::unordered_map<std::string, std::string>::const_iterator signature = response.headers.find("x-bunq-server-signature");
if(signature == response.headers.end() || !VerifyBody(serverPublicKey.get(), response.body, signature->second)) {
// The check comes after the fact: a payment may have been made all the same, and sending it again
// could pay twice.
throw std::runtime_error(std::format("bunq {} {}: the response is not signed by bunq's server key{}", method, path, write ? maybeCarriedOut : ""));
}
}
try {
return response.body.empty() ? json::object() : json::parse(response.body);
} catch(const json::exception& e) {
throw std::runtime_error(std::format("bunq {} {}: unreadable response: {}{}", method, path, e.what(), write ? maybeCarriedOut : ""));
}
}
const std::string message = ErrorMessage(response.body);
// An expired or ended session is a 401, or a 403 "Insufficient authentication.": open a new one, once.
if(auth == Auth::Session && renew && !renewed && (status == 401 || (status == 403 && message.contains("authentication")))) {
renewed = true;
RefreshSession();
Connector::SaveConnectors();
continue;
}
// A 5xx says nothing about whether a write went through.
throw BunqError(status, std::format("bunq {} {}: {} ({}){}", method, path, message, status, write && status >= 500 ? maybeCarriedOut : ""));
}
}
void BunqAccount::Send(std::string_view iban, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
const std::string body = std::format("{{\"amount\": {{\"value\":\"{}\", \"currency\":\"{}\"}},\"counterparty_alias\":{{\"type\":\"IBAN\",\"value\":\"{}\", \"name\":\"{}\"}}, \"description\":\"{}\"}}", amount, GetCurrencyCode(currency), iban, name, description);
const std::string route = std::format("/v1/user/{}/monetary-account/{}/payment", connector->id, id);
json BunqConnector::Get(std::string_view path) {
return Call("GET", path, nullptr, Auth::Session);
}
HTTPResponse response = connector->client.Send(CreateRequestHTTP("POST", route, "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", connector->sessionToken}, {"X-Bunq-Client-Signature", EscB(SignBody(connector->privateKey, body))}},
body
));
json BunqConnector::Post(std::string_view path, const json& body) {
return Call("POST", path, &body, Auth::Session);
}
if(response.status != "200") {
throw std::runtime_error(std::format("{} non 200 status code: {}", route, response.body));
json BunqConnector::Put(std::string_view path, const json& body) {
return Call("PUT", path, &body, Auth::Session);
}
json BunqConnector::Delete(std::string_view path) {
return Call("DELETE", path, nullptr, Auth::Session);
}
std::vector<json> BunqConnector::List(std::string_view path) {
std::vector<json> items;
std::string next = std::format("{}{}count=200", path, path.contains('?') ? '&' : '?');
while(!next.empty()) {
json page = Get(next);
for(json& item : page.at("Response")) {
items.push_back(std::move(item));
}
next.clear();
if(const json::const_iterator pagination = page.find("Pagination"); pagination != page.end()) {
if(const json::const_iterator older = pagination->find("older_url"); older != pagination->end() && older->is_string()) {
next = older->get<std::string>();
}
}
}
return items;
}
void BunqConnector::ReadUser(const json& response) {
const auto displayName = [](const json& user) {
constexpr std::array<std::string_view, 4> keys = {"display_name", "name", "legal_name", "public_nick_name"};
for(const std::string_view key : keys) {
std::string value = BunqJson::String(user, key);
if(!value.empty()) {
return value;
}
}
return std::string();
};
for(const json& item : response.at("Response")) {
const auto [type, user] = BunqJson::Only(item);
if(!user) {
continue;
}
if(type == "UserPerson" || type == "UserCompany" || type == "UserPaymentServiceProvider") {
userType = type;
id = user->at("id").get<std::uint64_t>();
ownerId = id;
name = displayName(*user);
return;
}
if(type == "UserApiKey") {
// An OAuth connection: its own user id goes in paths; the name and owner are the bunq user who granted access.
userType = type;
id = user->at("id").get<std::uint64_t>();
const auto [grantedType, granted] = BunqJson::Only(user->at("granted_by_user"));
name = granted ? displayName(*granted) : std::string();
ownerId = granted ? granted->at("id").get<std::uint64_t>() : id;
return;
}
}
throw std::runtime_error("bunq session names no user");
}
void BunqConnector::RefreshSession() {
const json body = {{"secret", apiKey}};
const json response = Call("POST", "/session-server", &body, Auth::Installation);
sessionToken = BunqJson::Item(response, "Token").at("token").get<std::string>();
sessionId = BunqJson::Item(response, "Id").at("id").get<std::uint64_t>();
ReadUser(response);
}
void BunqConnector::EnsureServerPublicKey() {
// Connectors saved before the key was kept: fetch it once. These two calls cannot be verified yet; TLS still
// authenticates the host.
fetchingServerKey = true;
struct Reset {
bool& flag;
~Reset() { flag = false; }
} reset{fetchingServerKey};
const std::uint64_t installation = BunqJson::Item(Get("/installation"), "Id").at("id").get<std::uint64_t>();
const json key = Get(std::format("/installation/{}/server-public-key", installation));
serverPublicKey = OwnKey(LoadPublicKeyFromPem(BunqJson::Item(key, "ServerPublicKey").at("server_public_key").get<std::string>()));
Connector::SaveConnectors();
}
BunqConnector& BunqConnector::Create(std::string&& apiKey, std::string_view allowedIps, BunqEnvironment environment) {
BunqConnector connector;
connector.environment = environment;
connector.apiKey = std::move(apiKey);
const auto [key, publicKey] = CreateKey();
connector.privateKey = OwnKey(key);
const json installation = {{"client_public_key", publicKey}};
const json installed = connector.Call("POST", "/installation", &installation, Auth::None);
connector.installationToken = BunqJson::Item(installed, "Token").at("token").get<std::string>();
connector.serverPublicKey = OwnKey(LoadPublicKeyFromPem(BunqJson::Item(installed, "ServerPublicKey").at("server_public_key").get<std::string>()));
json device = {{"description", "Nostro"}, {"secret", connector.apiKey}};
if(!allowedIps.empty()) {
json ips = json::array();
for(const auto part : std::views::split(allowedIps, ',')) {
std::string_view ip(part.begin(), part.end());
while(ip.starts_with(' ')) {
ip.remove_prefix(1);
}
while(ip.ends_with(' ')) {
ip.remove_suffix(1);
}
if(!ip.empty()) {
ips.push_back(std::string(ip));
}
}
device["permitted_ips"] = std::move(ips);
}
connector.Call("POST", "/device-server", &device, Auth::Installation);
connector.RefreshSession();
// One connector per bunq user: the same accounts under two connectors would make every one of them ambiguous.
// Adding the user again the same way (a renewed API key, a new OAuth grant) replaces the old connector.
const std::deque<BunqConnector>::iterator existing = std::ranges::find_if(connectors, [&connector](const BunqConnector& other) {
return other.environment == connector.environment && other.ownerId == connector.ownerId;
});
if(existing != connectors.end()) {
if(existing->IsOAuth() != connector.IsOAuth()) {
try {
connector.Logout();
} catch(const std::exception&) {
// The new session expires by itself.
}
throw std::runtime_error(std::format("{} is already connected {}: remove that connector first", connector.name, existing->IsOAuth() ? "through OAuth" : "with an API key"));
}
try {
existing->Logout();
} catch(const std::exception&) {
// A key that no longer works has no session to end.
}
}
BunqConnector& added = existing != connectors.end() ? (*existing = std::move(connector)) : connectors.emplace_back(std::move(connector));
added.RefreshAccounts();
return added;
}
void BunqConnector::Remove(BunqConnector& connector) {
const std::deque<BunqConnector>::iterator it = std::ranges::find_if(connectors, [&connector](const BunqConnector& other) { return &other == &connector; });
if(it == connectors.end()) {
throw std::invalid_argument("that connector is not in BunqConnector::connectors");
}
Account::ForgetTransactions(connector.StorageKey());
connectors.erase(it);
// Erasing from the middle of a deque moves the connectors around it: point their accounts at where they are now.
for(BunqConnector& remaining : connectors) {
for(BunqAccount& account : remaining.accounts) {
account.connector = &remaining;
}
}
}
BunqEnvironment BunqConnector::EnvironmentOfKey(std::string_view apiKey) {
return apiKey.starts_with("sandbox_") ? BunqEnvironment::Sandbox : BunqEnvironment::Production;
}
std::string BunqConnector::OAuthAuthorizationUrl(BunqEnvironment environment, std::string_view clientId, std::string_view redirectUri, std::string_view state) {
return std::format("https://{}/auth?response_type=code&client_id={}&redirect_uri={}&state={}", environment == BunqEnvironment::Production ? "oauth.bunq.com" : "oauth.sandbox.bunq.com", UrlEncode(clientId), UrlEncode(redirectUri), UrlEncode(state));
}
BunqEndpoint BunqConnector::Endpoint(BunqEnvironment environment) {
return Redirected().value_or(BunqEndpoint{.host = environment == BunqEnvironment::Production ? "api.bunq.com" : "public-api.sandbox.bunq.com", .port = 443, .caPem = std::string()});
}
void BunqConnector::RedirectTo(BunqEndpoint endpoint) {
Redirected() = std::move(endpoint);
}
std::string BunqConnector::OAuthExchangeCode(BunqEnvironment environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code) {
// The token endpoint has a host of its own, which a redirect replaces like the API's.
const BunqEndpoint endpoint = Redirected().value_or(BunqEndpoint{.host = environment == BunqEnvironment::Production ? "api.oauth.bunq.com" : "api-oauth.sandbox.bunq.com", .port = 443, .caPem = std::string()});
ClientHTTP1 client(endpoint.host, endpoint.port, TLSClientCredentials{.caPem = endpoint.caPem});
const std::string host = Authority(endpoint);
// The token endpoint reads its parameters from the query string only: sent as a form body they are reported missing.
const std::string target = std::format("/v1/token?grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&client_secret={}", UrlEncode(code), UrlEncode(redirectUri), UrlEncode(clientId), UrlEncode(clientSecret));
const HTTPResponse response = client.Send(CreateRequestHTTP("POST", target, host, {{"User-Agent", std::string(userAgent)}, {"Accept", "application/json"}}));
const std::uint16_t status = ParseStatus(response.status);
const json doc = json::parse(response.body, nullptr, false);
const std::string token = BunqJson::String(doc, "access_token");
if(status == 200 && !token.empty()) {
return token;
}
throw BunqError(status, std::format("bunq OAuth token exchange: {} ({})", ErrorMessage(response.body), status));
}
void BunqConnector::RefreshAccounts() {
std::vector<BunqAccount> refreshed;
for(const json& item : List(std::format("/user/{}/monetary-account", id))) {
const auto [type, account] = BunqJson::Only(item);
if(!account || !type.starts_with("MonetaryAccount")) {
continue;
}
// A closed account stays listed. A blocked one is still the user's, with its balance.
const std::string status = BunqJson::String(*account, "status");
if(status != "ACTIVE" && status != "BLOCKED") {
continue;
}
std::string description = BunqJson::String(*account, "description");
Currency currency;
try {
currency = GetCurrency(BunqJson::String(*account, "currency"));
} catch(const std::runtime_error& e) {
Note(std::format("skipping bunq account '{}': {}", description, e.what()));
continue;
}
std::string iban;
if(const json::const_iterator aliases = account->find("alias"); aliases != account->end() && aliases->is_array()) {
for(const json& alias : *aliases) {
if(BunqJson::String(alias, "type") == "IBAN") {
iban = BunqJson::String(alias, "value");
}
}
}
std::int64_t balance = 0;
if(const json::const_iterator value = account->find("balance"); value != account->end() && value->is_object()) {
balance = BunqJson::ReadAmount(*value).second;
}
std::string bic = BicOf(iban, std::string());
refreshed.emplace_back(std::move(description), std::move(bic), std::move(iban), currency, balance, account->at("id").get<std::uint64_t>(), std::string(type), this);
}
accounts = std::move(refreshed);
}
void BunqConnector::GetNewTransactions() {
for(BunqAccount& account : accounts) {
account.transactions.clear();
GetNewTransactions(account);
}
}
const std::chrono::system_clock::time_point last = account.GetLastTransactionTime(connectorId);
void BunqConnector::GetNewTransactions(BunqAccount& account) {
const std::string key = account.StorageKey();
const std::chrono::system_clock::time_point last = account.GetLastTransactionTime(key);
std::vector<Transaction> fetched;
std::string route = std::format("/v1/user/{}/monetary-account/{}/payment?count=200", id, account.id);
while(!route.empty()) {
HTTPResponse response = client.Send(CreateRequestHTTP("GET", route, "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", sessionToken}}));
std::string next = std::format("{}/payment?count=200", account.Path());
while(!next.empty()) {
const json page = Get(next);
next.clear();
if(response.status == "429") {
std::this_thread::sleep_for(std::chrono::seconds(2));
bool reachedStored = false;
for(const json& item : page.at("Response")) {
const json::const_iterator payment = item.find("Payment");
if(payment == item.end()) {
continue;
}
if(response.status != "200") {
throw std::runtime_error(std::format("{} non 200 status code: {}", route, response.body));
// Listed newest first. One at the last stored timestamp may still be new: SaveTransactions tells by id.
const std::chrono::system_clock::time_point created = ParseTimestamp(payment->at("created").get<std::string>());
if(created < last) {
reachedStored = true;
break;
}
const json doc = json::parse(response.body);
const json& counterparty = payment->at("counterparty_alias");
const auto [currency, amount] = BunqJson::ReadAmount(payment->at("amount"));
std::string iban = BunqJson::String(counterparty, "iban");
std::string bic = BicOf(iban, BunqJson::String(counterparty, "swift_bic"));
fetched.push_back(Transaction{
.name = BunqJson::ReadLabel(counterparty).name,
.bic = std::move(bic),
.iban = std::move(iban),
.description = BunqJson::String(*payment, "description"),
.currency = currency,
.amount = amount,
.timePoint = created,
.id = std::to_string(payment->at("id").get<std::uint64_t>()),
.kind = std::format("{}/{}", BunqJson::String(*payment, "type"), BunqJson::String(*payment, "sub_type")),
});
}
const json& olderUrl = doc.at("Pagination").at("older_url");
if( olderUrl.is_null()) {
route.clear();
} else {
route = olderUrl.get<std::string>();
}
for(const json& item : doc.at("Response")) {
const json::const_iterator paymentIt = item.find("Payment");
if(paymentIt == item.end()) {
continue;
if(!reachedStored) {
if(const json::const_iterator pagination = page.find("Pagination"); pagination != page.end()) {
if(const json::const_iterator older = pagination->find("older_url"); older != pagination->end() && older->is_string()) {
next = older->get<std::string>();
}
const json& paymentJ = *paymentIt;
const std::chrono::system_clock::time_point timePoint = ParseTimestamp(paymentJ.at("created").get<std::string>());
if(timePoint <= last) {
route.clear();
break;
}
const json& counterpartyJ = paymentJ.at("counterparty_alias");
const Currency currency = GetCurrency(paymentJ.at("amount").at("currency").get<std::string>());
account.transactions.emplace_back(
StringOrEmpty(counterpartyJ, "display_name"),
StringOrEmpty(counterpartyJ, "swift_bic"),
StringOrEmpty(counterpartyJ, "iban"),
StringOrEmpty(paymentJ, "description"),
currency,
ParseAmount(paymentJ.at("amount").at("value").get<std::string>(), currency),
timePoint
);
}
}
std::ranges::reverse(account.transactions);
account.SaveTransactions();
}
}
void BunqConnector::RefreshSession() {
const std::string body = std::format("{{\"secret\": \"{}\"}}", apiKey);
HTTPResponse response = client.Send(CreateRequestHTTP("POST", "/v1/session-server", "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", installationToken}, {"X-Bunq-Client-Signature", EscB(SignBody(privateKey, body))}},
body
));
if(response.status != "200") {
throw std::runtime_error(std::format("/v1/session-server non 200 status code: {}", response.body));
}
sessionToken = InResponse(json::parse(response.body), "Token").at("token");
json user = GetUser(response.body);
name = user.at("name");
id = user.at("id");
}
BunqConnector& BunqConnector::Create(std::string&& apiKey, std::string_view allowedIp) {
BunqConnector& connector = connectors.emplace_back();
std::tuple<EVP_PKEY*, std::string> keys = CreateKey();
connector.apiKey = std::move(apiKey);
connector.privateKey = std::get<0>(keys);
HTTPResponse response = client.Send(CreateRequestHTTP("POST", "/v1/installation", "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}},
std::format("{{\"client_public_key\": \"{}\"}}", EscB(std::get<1>(keys)))
));
if(response.status != "200") {
throw std::runtime_error(std::format("/v1/installation non 200 status code: {}", response.body));
}
connector.installationToken = InResponse(json::parse(response.body), "Token").at("token");
response = client.Send(CreateRequestHTTP("POST", "/v1/device-server", "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", connector.installationToken}},
std::format("{{\"description\": \"Nostro\", \"secret\": \"{}\", \"permitted_ips\": [{}]}}", connector.apiKey, allowedIp)
));
if(response.status != "200") {
throw std::runtime_error(std::format("/v1/device-server non 200 status code: {}", response.body));
}
connector.RefreshSession();
return connector;
}
void BunqConnector::RefreshAccounts() {
HTTPResponse response = client.Send(CreateRequestHTTP("GET", std::format("/v1/user/{}/monetary-account", id), "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", sessionToken}}));
if(response.status != "200") {
throw std::runtime_error(std::format("/v1/user/{}/monetary-account non 200 status code: {}", id, response.body));
}
for(const json& item : json::parse(response.body).at("Response")) {
json::const_iterator accountIt = item.find("MonetaryAccountBank");
if(accountIt == item.end()) {
accountIt = item.find("MonetaryAccountSavings");
}
if(accountIt == item.end()) {
continue;
}
const json& accountJ = *accountIt;
const std::uint32_t accountId = accountJ.at("id").get<std::uint32_t>();
const Currency currency = GetCurrency(accountJ.at("currency").get<std::string>());
const std::int64_t balance = ParseAmount(accountJ.at("balance").at("value").get<std::string>(), currency);
const std::vector<BunqAccount>::iterator existing = std::ranges::find(accounts, accountId, &BunqAccount::id);
if(existing != accounts.end()) {
existing->balance = balance;
continue;
}
std::string_view iban;
for(const json& alias : accountJ.at("alias")) {
if(alias.at("type").get<std::string>() == "IBAN") {
iban = alias.at("value").get_ref<const std::string&>();
}
}
accounts.emplace_back(accountJ.at("description").get<std::string>(), "", std::string(iban), currency, balance, accountId, this);
}
account.SaveTransactions(key, std::move(fetched));
}
bool BunqConnector::TestConnector() {
HTTPResponse response = client.Send(CreateRequestHTTP("GET", std::format("/v1/user/{}/monetary-account", id), "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", sessionToken}}));
if(response.status == "200") {
try {
Get(std::format("/user/{}", id));
return true;
} else {
RefreshSession();
HTTPResponse response = client.Send(CreateRequestHTTP("GET", std::format("/v1/user/{}/monetary-account", id), "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", sessionToken}}));
if(response.status == "200") {
return true;
} else {
return false;
}
} catch(const std::exception&) {
return false;
}
}
void BunqConnector::Logout() {
try {
// Not renewed: opening a session to close it would leave the new one open.
Call("DELETE", std::format("/session/{}", sessionId), nullptr, Auth::Session, false);
} catch(const BunqError& e) {
// A session that already ended is logged out.
if(e.status != 401 && e.status != 403) {
throw;
}
}
sessionToken.clear();
}
namespace {
BunqCard ReadCard(std::string_view kind, const json& card) {
BunqCard out{
.id = card.at("id").get<std::uint64_t>(),
.kind = std::string(kind),
.productType = BunqJson::String(card, "product_type"),
.status = BunqJson::String(card, "status"),
.orderStatus = BunqJson::String(card, "order_status"),
.nameOnCard = BunqJson::String(card, "name_on_card"),
.secondLine = BunqJson::String(card, "second_line"),
.lastFour = std::string(),
.expiry = BunqJson::String(card, "expiry_date"),
.iban = std::string(),
};
if(const json::const_iterator numbers = card.find("primary_account_numbers"); numbers != card.end() && numbers->is_array() && !numbers->empty()) {
out.lastFour = BunqJson::String(numbers->front(), "four_digit");
}
if(const json::const_iterator current = card.find("label_monetary_account_current"); current != card.end()) {
out.iban = BunqJson::String(*current, "iban");
}
return out;
}
}
std::vector<BunqCard> BunqConnector::Cards() {
std::vector<BunqCard> cards;
for(const json& item : List(std::format("/user/{}/card", id))) {
const auto [kind, card] = BunqJson::Only(item);
if(card) {
cards.push_back(ReadCard(kind, *card));
}
}
return cards;
}
BunqCard BunqConnector::SetCardStatus(std::uint64_t card, std::string_view status) {
// bunq answers with the card as it is now, which is not always as asked: a card that was never activated stays
// DEACTIVATED, without an error.
const json response = Put(std::format("/user/{}/card/{}", id, card), json{{"status", std::string(status)}});
for(const json& item : response.at("Response")) {
const auto [kind, updated] = BunqJson::Only(item);
if(updated && kind.starts_with("Card")) {
return ReadCard(kind, *updated);
}
}
throw std::runtime_error("bunq did not return the card it updated");
}
std::string BunqConnector::StorageKey() const {
return std::format("{}/{}/{}", connectorId, environment == BunqEnvironment::Production ? "production" : "sandbox", id);
}
bool BunqConnector::IsOAuth() const {
return userType == "UserApiKey";
}
BunqAccount::BunqAccount(std::string&& name, std::string&& bic, std::string&& iban, Currency currency, std::int64_t balance, std::uint64_t id, std::string&& type, BunqConnector* connector) : Account(std::move(name), std::move(bic), std::move(iban), currency, balance), id(id), type(std::move(type)), connector(connector) {
}
std::string BunqAccount::Path() const {
return std::format("/user/{}/monetary-account/{}", connector->id, id);
}
std::string BunqAccount::StorageKey() const {
return std::format("{}/{}", connector->StorageKey(), id);
}
void Nostro::to_json(json& j, const BunqConnector& connector) {
BIO* bio = ThrowOnOpenssl(BIO_new(BIO_s_mem()));
ThrowOnOpenssl(PEM_write_bio_PrivateKey(bio, connector.privateKey, nullptr, nullptr, 0, nullptr, nullptr));
char* data;
const long len = ThrowOnOpenssl(BIO_get_mem_data(bio, &data));
std::string privateKey(data, len);
BIO_free(bio);
j = json{
{"sessionToken", connector.sessionToken},
{"installationToken", connector.installationToken},
{"privateKey", std::move(privateKey)},
{"environment", connector.environment == BunqEnvironment::Production ? "production" : "sandbox"},
{"apiKey", connector.apiKey},
{"installationToken", connector.installationToken},
{"sessionToken", connector.sessionToken},
{"sessionId", connector.sessionId},
{"privateKey", PrivateKeyToPem(connector.privateKey.get())},
{"userType", connector.userType},
{"name", connector.name},
{"id", connector.id},
{"ownerId", connector.ownerId},
};
if(connector.serverPublicKey) {
j["serverPublicKey"] = PublicKeyToPem(connector.serverPublicKey.get());
}
}
void Nostro::from_json(const json& j, BunqConnector& connector) {
j.at("sessionToken").get_to(connector.sessionToken);
j.at("installationToken").get_to(connector.installationToken);
// Connectors saved before the environment was kept were all made against the sandbox, then the only host.
connector.environment = j.value("environment", std::string("sandbox")) == "production" ? BunqEnvironment::Production : BunqEnvironment::Sandbox;
j.at("apiKey").get_to(connector.apiKey);
j.at("installationToken").get_to(connector.installationToken);
j.at("sessionToken").get_to(connector.sessionToken);
connector.sessionId = j.value("sessionId", std::uint64_t{0});
connector.privateKey = OwnKey(LoadKeyFromPem(j.at("privateKey").get<std::string>()));
if(const json::const_iterator key = j.find("serverPublicKey"); key != j.end() && key->is_string()) {
connector.serverPublicKey = OwnKey(LoadPublicKeyFromPem(key->get<std::string>()));
}
connector.userType = j.value("userType", std::string());
j.at("name").get_to(connector.name);
j.at("id").get_to(connector.id);
const std::string& pem = j.at("privateKey").get_ref<const std::string&>();
BIO* bio = ThrowOnOpenssl(BIO_new_mem_buf(pem.data(), static_cast<int>(pem.size())));
EVP_PKEY* pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
connector.privateKey = ThrowOnOpenssl(pkey);
}
// Connectors saved before the owner was kept all used API keys, whose user is the owner.
connector.ownerId = j.value("ownerId", connector.id);
}

View file

@ -0,0 +1,554 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include <errno.h>
#include <systemd/sd-bus.h>
module Nostro:Bus_impl;
import std;
import :Bus;
import :Account;
import :Bunq;
import :Currency;
import :Transaction;
using namespace Nostro;
using namespace Nostro::Bus;
std::int32_t Bus::ThrowOnSdBus(std::int32_t result, std::string_view what) {
if(result < 0) {
throw std::system_error(-result, std::generic_category(), std::format("cannot {}", what));
}
return result;
}
namespace {
// A C string sd-bus handed out, as a string; null is empty.
// lint-disable-next-line no-char-pointer
std::string Text(const char* text) {
return text ? std::string(text) : std::string();
}
}
std::string Bus::Sender(sd_bus_message* message) {
return Text(sd_bus_message_get_sender(message));
}
std::string Bus::Interface(sd_bus_message* message) {
return Text(sd_bus_message_get_interface(message));
}
std::string Bus::Member(sd_bus_message* message) {
return Text(sd_bus_message_get_member(message));
}
std::string Bus::ErrorName(const sd_bus_error& error) {
return Text(error.name);
}
std::string Bus::ErrorMessage(const sd_bus_error& error) {
return Text(error.message);
}
bool Bus::IsSensitive(std::string_view member) {
return std::ranges::any_of(methods, [member](const Method& method) { return method.member == member && method.sensitive; });
}
std::string Bus::ReadText(sd_bus_message* message, char type) {
// sd-bus hands out strings as C strings into the message, valid while it lives.
// lint-disable-next-line no-char-pointer
const char* value = nullptr;
ThrowOnSdBus(sd_bus_message_read_basic(message, type, &value), "read a string");
return Text(value);
}
void Bus::BusUnref::operator()(sd_bus* bus) const {
sd_bus_flush_close_unref(bus);
}
void Bus::MessageUnref::operator()(sd_bus_message* message) const {
sd_bus_message_unref(message);
}
Bus::Error::~Error() {
sd_bus_error_free(&error);
}
std::vector<sd_bus_vtable> Bus::Vtable(std::span<const Method> table, const std::function<sd_bus_message_handler_t(std::string_view member)>& handler) {
std::vector<sd_bus_vtable> vtable = {SD_BUS_VTABLE_START(0)};
for(const Method& method : table) {
const std::uint64_t flags = SD_BUS_VTABLE_UNPRIVILEGED | (method.sensitive ? SD_BUS_VTABLE_SENSITIVE : 0);
sd_bus_vtable entry = SD_BUS_METHOD_WITH_NAMES_OFFSET(method.member.data(), method.in.data(), "", method.out.data(), "", handler(method.member), 0, flags);
// The names of the arguments and of the reply, which the macro would only take as literals to join.
entry.x.method.names = method.names.data();
vtable.push_back(entry);
}
vtable.push_back(SD_BUS_VTABLE_END);
return vtable;
}
void Bus::Enter(sd_bus_message* message, char type, std::string_view contents) {
// Every message was checked against its signature before it got here, so the container is there.
ThrowOnSdBus(sd_bus_message_enter_container(message, type, std::string(contents).c_str()), "read a container");
}
void Bus::Leave(sd_bus_message* message) {
ThrowOnSdBus(sd_bus_message_exit_container(message), "leave a container");
}
void Bus::Open(sd_bus_message* message, char type, std::string_view contents) {
ThrowOnSdBus(sd_bus_message_open_container(message, type, std::string(contents).c_str()), "open a container");
}
void Bus::Close(sd_bus_message* message) {
ThrowOnSdBus(sd_bus_message_close_container(message), "close a container");
}
namespace {
// A basic value, or an exception when the message holds something else or has ended.
template<typename T>
T ReadBasic(sd_bus_message* message, char type) {
T value{};
ThrowOnSdBus(sd_bus_message_read_basic(message, type, &value), "read a value");
return value;
}
std::chrono::system_clock::time_point FromMicroseconds(std::int64_t microseconds) {
return std::chrono::system_clock::time_point(std::chrono::microseconds(microseconds));
}
std::int64_t ToMicroseconds(std::chrono::system_clock::time_point time) {
return std::chrono::duration_cast<std::chrono::microseconds>(time.time_since_epoch()).count();
}
}
void Bus::Wire<std::string>::Append(sd_bus_message* message, const std::string& value) {
// D-Bus carries UTF-8 only: sd-bus refuses anything else.
const std::int32_t result = sd_bus_message_append_basic(message, 's', value.c_str());
if(result == -EINVAL) {
throw std::invalid_argument("text that is not UTF-8 cannot be sent to nostrod");
}
ThrowOnSdBus(result, "append a string");
}
std::string Bus::Wire<std::string>::Read(sd_bus_message* message) {
return ReadText(message, 's');
}
void Bus::Wire<bool>::Append(sd_bus_message* message, bool value) {
const std::int32_t b = value ? 1 : 0;
ThrowOnSdBus(sd_bus_message_append_basic(message, 'b', &b), "append a boolean");
}
bool Bus::Wire<bool>::Read(sd_bus_message* message) {
return ReadBasic<std::int32_t>(message, 'b') != 0;
}
void Bus::Wire<std::uint32_t>::Append(sd_bus_message* message, std::uint32_t value) {
ThrowOnSdBus(sd_bus_message_append_basic(message, 'u', &value), "append a number");
}
std::uint32_t Bus::Wire<std::uint32_t>::Read(sd_bus_message* message) {
return ReadBasic<std::uint32_t>(message, 'u');
}
void Bus::Wire<std::int64_t>::Append(sd_bus_message* message, std::int64_t value) {
ThrowOnSdBus(sd_bus_message_append_basic(message, 'x', &value), "append a number");
}
std::int64_t Bus::Wire<std::int64_t>::Read(sd_bus_message* message) {
return ReadBasic<std::int64_t>(message, 'x');
}
void Bus::Wire<std::uint64_t>::Append(sd_bus_message* message, std::uint64_t value) {
ThrowOnSdBus(sd_bus_message_append_basic(message, 't', &value), "append a number");
}
std::uint64_t Bus::Wire<std::uint64_t>::Read(sd_bus_message* message) {
return ReadBasic<std::uint64_t>(message, 't');
}
void Bus::Wire<std::chrono::system_clock::time_point>::Append(sd_bus_message* message, std::chrono::system_clock::time_point value) {
Wire<std::int64_t>::Append(message, ToMicroseconds(value));
}
std::chrono::system_clock::time_point Bus::Wire<std::chrono::system_clock::time_point>::Read(sd_bus_message* message) {
return FromMicroseconds(Wire<std::int64_t>::Read(message));
}
void Bus::Wire<Currency>::Append(sd_bus_message* message, Currency value) {
Wire<std::string>::Append(message, std::string(GetCurrencyCode(value)));
}
Currency Bus::Wire<Currency>::Read(sd_bus_message* message) {
return GetCurrency(Wire<std::string>::Read(message));
}
void Bus::Wire<Account>::Append(sd_bus_message* message, const Account& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.bic);
Bus::Append(message, value.iban);
Bus::Append(message, value.currency);
Bus::Append(message, value.balance);
Close(message);
}
Account Bus::Wire<Account>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
Account value{};
value.name = Bus::Read<std::string>(message);
value.bic = Bus::Read<std::string>(message);
value.iban = Bus::Read<std::string>(message);
value.currency = Bus::Read<Currency>(message);
value.balance = Bus::Read<std::int64_t>(message);
Leave(message);
return value;
}
void Bus::Wire<Transaction>::Append(sd_bus_message* message, const Transaction& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.bic);
Bus::Append(message, value.iban);
Bus::Append(message, value.description);
Bus::Append(message, value.currency);
Bus::Append(message, value.amount);
Bus::Append(message, value.timePoint);
Bus::Append(message, value.id);
Bus::Append(message, value.kind);
Close(message);
}
Transaction Bus::Wire<Transaction>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
Transaction value{};
value.name = Bus::Read<std::string>(message);
value.bic = Bus::Read<std::string>(message);
value.iban = Bus::Read<std::string>(message);
value.description = Bus::Read<std::string>(message);
value.currency = Bus::Read<Currency>(message);
value.amount = Bus::Read<std::int64_t>(message);
value.timePoint = Bus::Read<std::chrono::system_clock::time_point>(message);
value.id = Bus::Read<std::string>(message);
value.kind = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqLabel>::Append(sd_bus_message* message, const BunqLabel& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.iban);
Close(message);
}
BunqLabel Bus::Wire<BunqLabel>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqLabel value;
value.name = Bus::Read<std::string>(message);
value.iban = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqPaymentRequest>::Append(sd_bus_message* message, const BunqPaymentRequest& value) {
Open(message, 'r', contents);
Bus::Append(message, value.id);
Bus::Append(message, value.status);
Bus::Append(message, value.counterparty);
Bus::Append(message, value.currency);
Bus::Append(message, value.amount);
Bus::Append(message, value.amountPaid);
Bus::Append(message, value.description);
Bus::Append(message, value.created);
Bus::Append(message, value.shareUrl);
Close(message);
}
BunqPaymentRequest Bus::Wire<BunqPaymentRequest>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqPaymentRequest value{};
value.id = Bus::Read<std::uint64_t>(message);
value.status = Bus::Read<std::string>(message);
value.counterparty = Bus::Read<BunqLabel>(message);
value.currency = Bus::Read<Currency>(message);
value.amount = Bus::Read<std::int64_t>(message);
value.amountPaid = Bus::Read<std::optional<std::int64_t>>(message);
value.description = Bus::Read<std::string>(message);
value.created = Bus::Read<std::chrono::system_clock::time_point>(message);
value.shareUrl = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqIncomingRequest>::Append(sd_bus_message* message, const BunqIncomingRequest& value) {
Open(message, 'r', contents);
Bus::Append(message, value.id);
Bus::Append(message, value.status);
Bus::Append(message, value.type);
Bus::Append(message, value.counterparty);
Bus::Append(message, value.currency);
Bus::Append(message, value.amount);
Bus::Append(message, value.description);
Bus::Append(message, value.created);
Close(message);
}
BunqIncomingRequest Bus::Wire<BunqIncomingRequest>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqIncomingRequest value{};
value.id = Bus::Read<std::uint64_t>(message);
value.status = Bus::Read<std::string>(message);
value.type = Bus::Read<std::string>(message);
value.counterparty = Bus::Read<BunqLabel>(message);
value.currency = Bus::Read<Currency>(message);
value.amount = Bus::Read<std::int64_t>(message);
value.description = Bus::Read<std::string>(message);
value.created = Bus::Read<std::chrono::system_clock::time_point>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqSchedule>::Append(sd_bus_message* message, const BunqSchedule& value) {
Open(message, 'r', contents);
Bus::Append(message, value.start);
Bus::Append(message, value.end);
Bus::Append(message, value.unit);
Bus::Append(message, value.every);
Bus::Append(message, value.status);
Bus::Append(message, value.next);
Close(message);
}
BunqSchedule Bus::Wire<BunqSchedule>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqSchedule value;
value.start = Bus::Read<std::chrono::system_clock::time_point>(message);
value.end = Bus::Read<std::optional<std::chrono::system_clock::time_point>>(message);
value.unit = Bus::Read<std::string>(message);
value.every = Bus::Read<std::uint32_t>(message);
value.status = Bus::Read<std::string>(message);
value.next = Bus::Read<std::optional<std::chrono::system_clock::time_point>>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqScheduledPayment>::Append(sd_bus_message* message, const BunqScheduledPayment& value) {
Open(message, 'r', contents);
Bus::Append(message, value.id);
Bus::Append(message, value.counterparty);
Bus::Append(message, value.currency);
Bus::Append(message, value.amount);
Bus::Append(message, value.description);
Bus::Append(message, value.schedule);
Close(message);
}
BunqScheduledPayment Bus::Wire<BunqScheduledPayment>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqScheduledPayment value{};
value.id = Bus::Read<std::uint64_t>(message);
value.counterparty = Bus::Read<BunqLabel>(message);
value.currency = Bus::Read<Currency>(message);
value.amount = Bus::Read<std::int64_t>(message);
value.description = Bus::Read<std::string>(message);
value.schedule = Bus::Read<BunqSchedule>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqDraftPayment::Entry>::Append(sd_bus_message* message, const BunqDraftPayment::Entry& value) {
Open(message, 'r', contents);
Bus::Append(message, value.counterparty);
Bus::Append(message, value.currency);
Bus::Append(message, value.amount);
Bus::Append(message, value.description);
Close(message);
}
BunqDraftPayment::Entry Bus::Wire<BunqDraftPayment::Entry>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqDraftPayment::Entry value{};
value.counterparty = Bus::Read<BunqLabel>(message);
value.currency = Bus::Read<Currency>(message);
value.amount = Bus::Read<std::int64_t>(message);
value.description = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqDraftPayment>::Append(sd_bus_message* message, const BunqDraftPayment& value) {
Open(message, 'r', contents);
Bus::Append(message, value.id);
Bus::Append(message, value.status);
Bus::Append(message, value.createdBy);
Bus::Append(message, value.entries);
Bus::Append(message, value.updated);
Close(message);
}
BunqDraftPayment Bus::Wire<BunqDraftPayment>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqDraftPayment value{};
value.id = Bus::Read<std::uint64_t>(message);
value.status = Bus::Read<std::string>(message);
value.createdBy = Bus::Read<std::string>(message);
value.entries = Bus::Read<std::vector<BunqDraftPayment::Entry>>(message);
value.updated = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqCard>::Append(sd_bus_message* message, const BunqCard& value) {
Open(message, 'r', contents);
Bus::Append(message, value.id);
Bus::Append(message, value.kind);
Bus::Append(message, value.productType);
Bus::Append(message, value.status);
Bus::Append(message, value.orderStatus);
Bus::Append(message, value.nameOnCard);
Bus::Append(message, value.secondLine);
Bus::Append(message, value.lastFour);
Bus::Append(message, value.expiry);
Bus::Append(message, value.iban);
Close(message);
}
BunqCard Bus::Wire<BunqCard>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqCard value{};
value.id = Bus::Read<std::uint64_t>(message);
value.kind = Bus::Read<std::string>(message);
value.productType = Bus::Read<std::string>(message);
value.status = Bus::Read<std::string>(message);
value.orderStatus = Bus::Read<std::string>(message);
value.nameOnCard = Bus::Read<std::string>(message);
value.secondLine = Bus::Read<std::string>(message);
value.lastFour = Bus::Read<std::string>(message);
value.expiry = Bus::Read<std::string>(message);
value.iban = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<ConnectorSummary>::Append(sd_bus_message* message, const ConnectorSummary& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.bank);
Bus::Append(message, value.environment);
Bus::Append(message, value.auth);
Bus::Append(message, value.working);
Close(message);
}
ConnectorSummary Bus::Wire<ConnectorSummary>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
ConnectorSummary value;
value.name = Bus::Read<std::string>(message);
value.bank = Bus::Read<std::string>(message);
value.environment = Bus::Read<std::string>(message);
value.auth = Bus::Read<std::string>(message);
value.working = Bus::Read<bool>(message);
Leave(message);
return value;
}
void Bus::Wire<ConnectorAccounts>::Append(sd_bus_message* message, const ConnectorAccounts& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.bank);
Bus::Append(message, value.accounts);
Close(message);
}
ConnectorAccounts Bus::Wire<ConnectorAccounts>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
ConnectorAccounts value;
value.name = Bus::Read<std::string>(message);
value.bank = Bus::Read<std::string>(message);
value.accounts = Bus::Read<std::vector<Account>>(message);
Leave(message);
return value;
}
void Bus::Wire<ConnectorCards>::Append(sd_bus_message* message, const ConnectorCards& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.bank);
Bus::Append(message, value.cards);
Close(message);
}
ConnectorCards Bus::Wire<ConnectorCards>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
ConnectorCards value;
value.name = Bus::Read<std::string>(message);
value.bank = Bus::Read<std::string>(message);
value.cards = Bus::Read<std::vector<BunqCard>>(message);
Leave(message);
return value;
}
void Bus::AppendQuery(sd_bus_message* message, const TransactionQuery& query) {
Open(message, 'a', "{sv}");
const auto entry = [message](std::string_view key, std::string_view type, const auto& value) {
Open(message, 'e', "sv");
Bus::Append(message, std::string(key));
Open(message, 'v', type);
Bus::Append(message, value);
Close(message);
Close(message);
};
if(!query.search.empty()) {
entry("search", "s", query.search);
}
if(query.amount) {
entry("amount", "x", *query.amount);
}
if(query.from != std::chrono::system_clock::time_point::min()) {
entry("from", "x", query.from);
}
if(query.to != std::chrono::system_clock::time_point::max()) {
entry("to", "x", query.to);
}
entry("limit", "t", static_cast<std::uint64_t>(query.limit));
Close(message);
}
TransactionQuery Bus::ReadQuery(sd_bus_message* message) {
TransactionQuery query;
Enter(message, 'a', "{sv}");
while(ThrowOnSdBus(sd_bus_message_at_end(message, 0), "read a query") == 0) {
Enter(message, 'e', "sv");
const std::string key = Bus::Read<std::string>(message);
if(key == "search") {
Enter(message, 'v', "s");
query.search = Bus::Read<std::string>(message);
Leave(message);
} else if(key == "amount") {
Enter(message, 'v', "x");
query.amount = Bus::Read<std::int64_t>(message);
Leave(message);
} else if(key == "from") {
Enter(message, 'v', "x");
query.from = Bus::Read<std::chrono::system_clock::time_point>(message);
Leave(message);
} else if(key == "to") {
Enter(message, 'v', "x");
query.to = Bus::Read<std::chrono::system_clock::time_point>(message);
Leave(message);
} else if(key == "limit") {
Enter(message, 'v', "t");
query.limit = Bus::Read<std::uint64_t>(message);
Leave(message);
} else {
ThrowOnSdBus(sd_bus_message_skip(message, "v"), "skip an unknown query key");
}
Leave(message);
}
Leave(message);
return query;
}

View file

@ -0,0 +1,246 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include <systemd/sd-bus.h>
module Nostro:Client_impl;
import std;
import :Client;
import :Bus;
import :Account;
import :Bunq;
import :Currency;
import :Transaction;
using namespace Nostro;
using namespace Nostro::Bus;
DaemonError::DaemonError(std::string name, const std::string& message) : std::runtime_error(message), name(std::move(name)) {
}
Client Client::System(std::chrono::seconds timeout) {
sd_bus* bus = nullptr;
ThrowOnSdBus(sd_bus_open_system_with_description(&bus, "nostro"), "connect to the system bus");
BusPtr owned(bus);
ThrowOnSdBus(sd_bus_set_method_call_timeout(bus, static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(timeout).count())), "connect to the system bus");
ThrowOnSdBus(sd_bus_set_allow_interactive_authorization(bus, 1), "connect to the system bus");
return Client(std::move(owned));
}
Client::Client(BusPtr bus) : bus(std::move(bus)) {
}
namespace {
// nostrod's error, as an exception: input it refused as std::invalid_argument, the rest as a DaemonError.
[[noreturn]] void Throw(const sd_bus_error& error, bool changes) {
const std::string name = ErrorName(error);
const std::string message = ErrorMessage(error);
if(name == SD_BUS_ERROR_SERVICE_UNKNOWN) {
throw std::runtime_error(std::format("nostrod is not running, and the system bus cannot start it: is it installed? ({})", message));
}
if(name == errorInvalidArgument) {
throw std::invalid_argument(message);
}
if(changes && (name == SD_BUS_ERROR_NO_REPLY || name == SD_BUS_ERROR_TIMEOUT)) {
throw std::runtime_error(std::format("nostrod did not answer in time ({}): what you asked for may have been carried out, check before trying again", message));
}
throw DaemonError(name, message);
}
// Calls `member` with what `append` appends, reads the answer with `read`, and keeps the notes that end it.
// `changes` says whether the call moves money or changes anything, for what a lost answer means.
template<typename AppendArguments, typename ReadAnswer>
auto Call(sd_bus* bus, std::vector<std::string>& notes, std::string_view member, bool changes, AppendArguments&& append, ReadAnswer&& read) {
sd_bus_message* raw = nullptr;
ThrowOnSdBus(sd_bus_message_new_method_call(bus, &raw, busName.data(), objectPath.data(), interfaceName.data(), std::string(member).c_str()), "call nostrod");
const MessagePtr call(raw);
if(IsSensitive(member)) {
ThrowOnSdBus(sd_bus_message_sensitive(raw), "call nostrod");
}
append(raw);
Error error;
sd_bus_message* answer = nullptr;
if(sd_bus_call(bus, raw, 0, &error.error, &answer) < 0) {
Throw(error.error, changes);
}
const MessagePtr reply(answer);
auto result = read(answer);
const std::vector<std::string> more = Read<std::vector<std::string>>(answer);
notes.insert(notes.end(), more.begin(), more.end());
return result;
}
void Nothing(sd_bus_message*) {
}
// The answer of a call that answers nothing but its notes.
std::monostate NoAnswer(sd_bus_message*) {
return std::monostate();
}
AddedConnector ReadAdded(sd_bus_message* reply) {
AddedConnector added;
added.name = Read<std::string>(reply);
added.environment = Read<std::string>(reply);
added.accounts = Read<std::uint32_t>(reply);
return added;
}
Created ReadCreated(sd_bus_message* reply) {
Created created;
created.id = Read<std::uint64_t>(reply);
created.currency = Read<Currency>(reply);
return created;
}
// The arguments a payment, a draft, a schedule and a request share.
auto PaymentArguments(std::string_view account, std::string_view counterparty, std::string_view name, std::int64_t amount, std::string_view description) {
return [=](sd_bus_message* call) {
Append(call, std::string(account));
Append(call, std::string(counterparty));
Append(call, std::string(name));
Append(call, amount);
Append(call, std::string(description));
};
}
auto AccountArgument(std::string_view account) {
return [account](sd_bus_message* call) {
Append(call, std::string(account));
};
}
auto AccountAndId(std::string_view account, std::uint64_t id) {
return [account, id](sd_bus_message* call) {
Append(call, std::string(account));
Append(call, id);
};
}
template<typename T>
T ReadAs(sd_bus_message* reply) {
return Read<T>(reply);
}
}
std::vector<ConnectorSummary> Client::Connectors() {
return Call(bus.get(), notes, "Connectors", false, Nothing, ReadAs<std::vector<ConnectorSummary>>);
}
AddedConnector Client::AddBunq(std::string_view apiKey, std::string_view allowedIps, std::string_view environment) {
return Call(bus.get(), notes, "AddBunq", true, [=](sd_bus_message* call) {
Append(call, std::string(apiKey));
Append(call, std::string(allowedIps));
Append(call, std::string(environment));
}, ReadAdded);
}
AddedConnector Client::AddBunqOAuth(std::string_view environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code) {
return Call(bus.get(), notes, "AddBunqOAuth", true, [=](sd_bus_message* call) {
Append(call, std::string(environment));
Append(call, std::string(clientId));
Append(call, std::string(clientSecret));
Append(call, std::string(redirectUri));
Append(call, std::string(code));
}, ReadAdded);
}
std::string Client::RemoveConnector(std::string_view connector) {
return Call(bus.get(), notes, "RemoveConnector", true, AccountArgument(connector), ReadAs<std::string>);
}
std::vector<ConnectorAccounts> Client::Accounts() {
return Call(bus.get(), notes, "Accounts", false, Nothing, ReadAs<std::vector<ConnectorAccounts>>);
}
std::vector<Transaction> Client::Transactions(std::string_view account, const TransactionQuery& query) {
return Call(bus.get(), notes, "Transactions", false, [account, &query](sd_bus_message* call) {
Append(call, std::string(account));
AppendQuery(call, query);
}, ReadAs<std::vector<Transaction>>);
}
Created Client::Send(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description) {
return Call(bus.get(), notes, "Send", true, PaymentArguments(account, to, name, amount, description), ReadCreated);
}
Created Client::Schedule(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, const BunqSchedule& schedule) {
const auto payment = PaymentArguments(account, to, name, amount, description);
return Call(bus.get(), notes, "Schedule", true, [&payment, &schedule](sd_bus_message* call) {
payment(call);
Append(call, schedule);
}, ReadCreated);
}
Created Client::Draft(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description) {
return Call(bus.get(), notes, "Draft", true, PaymentArguments(account, to, name, amount, description), ReadCreated);
}
BunqPaymentRequest Client::Request(std::string_view account, std::string_view from, std::string_view name, std::int64_t amount, std::string_view description) {
return Call(bus.get(), notes, "Request", true, PaymentArguments(account, from, name, amount, description), ReadAs<BunqPaymentRequest>);
}
std::vector<BunqPaymentRequest> Client::Requests(std::string_view account) {
return Call(bus.get(), notes, "Requests", false, AccountArgument(account), ReadAs<std::vector<BunqPaymentRequest>>);
}
void Client::RevokeRequest(std::string_view account, std::uint64_t id) {
Call(bus.get(), notes, "RevokeRequest", true, AccountAndId(account, id), NoAnswer);
}
std::vector<BunqIncomingRequest> Client::IncomingRequests(std::string_view account) {
return Call(bus.get(), notes, "IncomingRequests", false, AccountArgument(account), ReadAs<std::vector<BunqIncomingRequest>>);
}
void Client::RespondToRequest(std::string_view account, std::uint64_t id, bool accept) {
Call(bus.get(), notes, "RespondToRequest", true, [account, id, accept](sd_bus_message* call) {
Append(call, std::string(account));
Append(call, id);
Append(call, accept);
}, NoAnswer);
}
std::vector<BunqScheduledPayment> Client::ScheduledPayments(std::string_view account) {
return Call(bus.get(), notes, "ScheduledPayments", false, AccountArgument(account), ReadAs<std::vector<BunqScheduledPayment>>);
}
void Client::CancelScheduledPayment(std::string_view account, std::uint64_t id) {
Call(bus.get(), notes, "CancelScheduledPayment", true, AccountAndId(account, id), NoAnswer);
}
std::vector<BunqDraftPayment> Client::DraftPayments(std::string_view account) {
return Call(bus.get(), notes, "DraftPayments", false, AccountArgument(account), ReadAs<std::vector<BunqDraftPayment>>);
}
void Client::RespondToDraftPayment(std::string_view account, std::uint64_t id, bool accept) {
Call(bus.get(), notes, "RespondToDraftPayment", true, [account, id, accept](sd_bus_message* call) {
Append(call, std::string(account));
Append(call, id);
Append(call, accept);
}, NoAnswer);
}
std::vector<ConnectorCards> Client::Cards() {
return Call(bus.get(), notes, "Cards", false, Nothing, ReadAs<std::vector<ConnectorCards>>);
}
BunqCard Client::SetCardStatus(std::uint64_t card, std::string_view status) {
return Call(bus.get(), notes, "SetCardStatus", true, [card, status](sd_bus_message* call) {
Append(call, card);
Append(call, std::string(status));
}, ReadAs<BunqCard>);
}
std::optional<Account> Client::DefaultCheckoutAccount() {
return Call(bus.get(), notes, "DefaultCheckoutAccount", false, Nothing, ReadAs<std::optional<Account>>);
}
Account Client::SetDefaultCheckoutAccount(std::string_view account) {
return Call(bus.get(), notes, "SetDefaultCheckoutAccount", true, AccountArgument(account), ReadAs<Account>);
}
std::vector<std::string> Client::TakeNotes() {
return std::exchange(notes, {});
}

View file

@ -1,11 +1,12 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include "../lib/json.hpp"
#include <cerrno>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
@ -15,31 +16,130 @@ import std;
import :Connector;
import :Banks;
import :File;
import :Utils;
using namespace Nostro;
using namespace nlohmann;
namespace fs = std::filesystem;
namespace {
[[noreturn]] void ThrowErrno(std::string_view what, const fs::path& path) {
throw std::system_error(errno, std::generic_category(), std::format("cannot {} {}", what, path.string()));
}
// One nostro process at a time works on the connectors: two that each load, change and save the file would each
// write back their own view, and the later one would drop what the other added or renewed. The lock is taken by
// the first load or save and held until the process ends.
void LockConnectors() {
static std::int32_t lock = -1;
if(lock != -1) {
return;
}
const fs::path path = configPath/"connectors.lock";
CreatePrivateFile(path);
const std::int32_t fd = open(path.c_str(), O_RDWR | O_CLOEXEC);
if(fd == -1) {
ThrowErrno("open", path);
}
// Remembered only once it is held: a failure here leaves the next call to try again, not to think it locked.
std::int32_t result = flock(fd, LOCK_EX | LOCK_NB);
if(result == -1 && errno == EWOULDBLOCK) {
Note("waiting for another nostro process to finish");
do {
result = flock(fd, LOCK_EX);
} while(result == -1 && errno == EINTR);
}
if(result == -1) {
const std::int32_t error = errno;
close(fd);
errno = error;
ThrowErrno("lock", path);
}
lock = fd;
}
void WriteAll(std::int32_t fd, std::string_view data, const fs::path& path) {
while(!data.empty()) {
const ssize_t written = write(fd, data.data(), data.size());
if(written >= 0) {
data.remove_prefix(static_cast<std::size_t>(written));
} else if(errno != EINTR) {
ThrowErrno("write", path);
}
}
}
}
void Connector::SaveConnectors() {
LockConnectors();
const fs::path path = configPath/"connectors.json";
CreatePrivateFile(path);
const fs::path temporary = configPath/std::format("connectors.json.tmp-{}", getpid());
json jsonConnectors = json::object();
tuple_for<EnabledBanks>([&jsonConnectors]<typename Bank>() {
jsonConnectors[Bank::connectorId] = Bank::connectors;
});
const std::string text = jsonConnectors.dump(4);
std::ofstream out(path, std::ios::binary);
out << jsonConnectors.dump(4);
// The file holds the only copy of each connector's private key. The new one is on the disk before it replaces the
// old one, and the rename after, so a crash or a power cut leaves one whole file or the other.
CreatePrivateFile(temporary);
const std::int32_t fd = open(temporary.c_str(), O_WRONLY | O_TRUNC | O_CLOEXEC);
if(fd == -1) {
ThrowErrno("open", temporary);
}
try {
WriteAll(fd, text, temporary);
if(fsync(fd) == -1) {
ThrowErrno("sync", temporary);
}
} catch(...) {
close(fd);
fs::remove(temporary);
throw;
}
close(fd);
fs::rename(temporary, path);
const std::int32_t directory = open(configPath.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if(directory != -1) {
fsync(directory);
close(directory);
}
}
void Connector::LoadConnectors() {
std::ifstream f(configPath/"connectors.json");
const json jsonConnectors = json::parse(f);
tuple_for<EnabledBanks>([&jsonConnectors]<typename Bank>() {
Bank::connectors = std::move(jsonConnectors.at(Bank::connectorId).template get<std::vector<Bank>>());
for(Bank& bank : Bank::connectors) {
bank.RefreshAccounts();
LockConnectors();
const fs::path path = configPath/"connectors.json";
if(!fs::exists(path)) {
return;
}
std::ifstream f(path);
const json jsonConnectors = [&path, &f] {
try {
return json::parse(f);
} catch(const json::parse_error& e) {
// nlohmann's own message quotes the text it read last, which can be part of a private key: say where the
// file breaks, not what it holds.
throw std::runtime_error(std::format("{} is not valid JSON (it breaks at byte {})", path.string(), e.byte));
}
}();
// Every bank's list is in place before any refresh: a refresh can save, and a save writes all of them.
tuple_for<EnabledBanks>([&jsonConnectors]<typename Bank>() {
if(jsonConnectors.contains(Bank::connectorId)) {
Bank::connectors = jsonConnectors.at(Bank::connectorId).template get<std::remove_cvref_t<decltype(Bank::connectors)>>();
}
});
}
tuple_for<EnabledBanks>([]<typename Bank>() {
for(Bank& bank : Bank::connectors) {
try {
bank.RefreshAccounts();
} catch(const std::exception& e) {
Note(std::format("{} connector '{}' is unavailable: {}", Bank::connectorId, bank.name, e.what()));
}
}
});
}

View file

@ -1,5 +1,5 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
@ -7,6 +7,7 @@ module;
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/err.h>
#include <openssl/rand.h>
module Nostro:Crypto_impl;
import :Crypto;
@ -14,7 +15,19 @@ import std;
using namespace Nostro;
long Crypto::ThrowOnOpenssl(long status) {
namespace {
std::string ReadBio(BIO* bio) {
// BIO_get_mem_data hands out its buffer through a char*.
// lint-disable-next-line no-char-pointer
char* data;
const std::int64_t len = Crypto::ThrowOnOpenssl(BIO_get_mem_data(bio, &data));
std::string out(data, len);
BIO_free(bio);
return out;
}
}
std::int64_t Crypto::ThrowOnOpenssl(std::int64_t status) {
if(status <= 0) {
ERR_print_errors_fp(stderr);
throw std::runtime_error("openssl error");
@ -22,6 +35,10 @@ long Crypto::ThrowOnOpenssl(long status) {
return status;
}
Crypto::Key Crypto::OwnKey(EVP_PKEY* key) {
return Key(key, EVP_PKEY_free);
}
std::string Crypto::SignBody(EVP_PKEY* privateKey, std::string_view body) {
EVP_MD_CTX* ctx = ThrowOnOpenssl(EVP_MD_CTX_new());
ThrowOnOpenssl(EVP_DigestSignInit(ctx, nullptr, EVP_sha256(), nullptr, privateKey));
@ -32,30 +49,49 @@ std::string Crypto::SignBody(EVP_PKEY* privateKey, std::string_view body) {
std::string sig;
sig.resize(sigLen);
ThrowOnOpenssl(EVP_DigestSignFinal(ctx, reinterpret_cast<unsigned char*>(sig.data()), &sigLen));
ThrowOnOpenssl(EVP_DigestSignFinal(ctx, reinterpret_cast<std::uint8_t*>(sig.data()), &sigLen));
sig.resize(sigLen);
std::string sig64;
sig64.resize(4 * ((sig.size() + 2) / 3));
int n = EVP_EncodeBlock(reinterpret_cast<unsigned char*>(sig64.data()), reinterpret_cast<const unsigned char*>(sig.data()), static_cast<int>(sig.size()));
const std::int32_t n = EVP_EncodeBlock(reinterpret_cast<unsigned char*>(sig64.data()), reinterpret_cast<const unsigned char*>(sig.data()), static_cast<int>(sig.size()));
sig64.resize(n);
EVP_MD_CTX_free(ctx);
return sig64;
}
bool Crypto::VerifyBody(EVP_PKEY* publicKey, std::string_view body, std::string_view signature) {
// EVP_DecodeBlock keeps the bytes the '=' padding stands for, as zeros: count the padding and drop them.
if(signature.empty() || signature.size() % 4 != 0) {
return false;
}
std::string decoded(3 * (signature.size() / 4), '\0');
const int n = EVP_DecodeBlock(reinterpret_cast<unsigned char*>(decoded.data()), reinterpret_cast<const unsigned char*>(signature.data()), static_cast<int>(signature.size()));
if(n < 0) {
return false;
}
std::size_t padding = 0;
if(signature.ends_with("==")) {
padding = 2;
} else if(signature.ends_with('=')) {
padding = 1;
}
decoded.resize(static_cast<std::size_t>(n) - padding);
EVP_MD_CTX* ctx = ThrowOnOpenssl(EVP_MD_CTX_new());
const bool valid = EVP_DigestVerifyInit(ctx, nullptr, EVP_sha256(), nullptr, publicKey) == 1
&& EVP_DigestVerifyUpdate(ctx, body.data(), body.length()) == 1
&& EVP_DigestVerifyFinal(ctx, reinterpret_cast<const unsigned char*>(decoded.data()), decoded.size()) == 1;
EVP_MD_CTX_free(ctx);
// A failed verification leaves its reason on OpenSSL's error queue; it is not an error of the next call.
ERR_clear_error();
return valid;
}
std::tuple<EVP_PKEY*, std::string> Crypto::CreateKey() {
EVP_PKEY* pkey = ThrowOnOpenssl(EVP_RSA_gen(2048));
char* data;
BIO* pubBio = ThrowOnOpenssl(BIO_new(BIO_s_mem()));
ThrowOnOpenssl(PEM_write_bio_PUBKEY(pubBio, pkey));
const long len = ThrowOnOpenssl(BIO_get_mem_data(pubBio, &data));
std::string publicKey(data, len);
BIO_free(pubBio);
return {pkey, publicKey};
return {pkey, PublicKeyToPem(pkey)};
}
EVP_PKEY* Crypto::LoadKeyFromPem(std::string_view pem) {
@ -63,4 +99,33 @@ EVP_PKEY* Crypto::LoadKeyFromPem(std::string_view pem) {
EVP_PKEY* pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
return ThrowOnOpenssl(pkey);
}
}
EVP_PKEY* Crypto::LoadPublicKeyFromPem(std::string_view pem) {
BIO* bio = ThrowOnOpenssl(BIO_new_mem_buf(pem.data(), static_cast<int>(pem.size())));
EVP_PKEY* pkey = PEM_read_bio_PUBKEY(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
return ThrowOnOpenssl(pkey);
}
std::string Crypto::PrivateKeyToPem(EVP_PKEY* key) {
BIO* bio = ThrowOnOpenssl(BIO_new(BIO_s_mem()));
ThrowOnOpenssl(PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr, nullptr));
return ReadBio(bio);
}
std::string Crypto::PublicKeyToPem(EVP_PKEY* key) {
BIO* bio = ThrowOnOpenssl(BIO_new(BIO_s_mem()));
ThrowOnOpenssl(PEM_write_bio_PUBKEY(bio, key));
return ReadBio(bio);
}
std::string Crypto::RandomHex(std::size_t bytes) {
std::vector<unsigned char> random(bytes);
ThrowOnOpenssl(RAND_bytes(random.data(), static_cast<std::int32_t>(random.size())));
std::string out;
for(const unsigned char byte : random) {
out += std::format("{:02x}", byte);
}
return out;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,354 @@
// 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 <errno.h>
#include <signal.h>
#include <spawn.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
module Nostro:Daemon_impl;
import std;
import Nostro.Checkout;
import :Daemon;
import :Bus;
using namespace Nostro;
using namespace Nostro::Bus;
// The front holds no connector and no secret: it only learns who calls, starts that user's worker, and passes the call
// on. Each worker is a process of its own, so one user's connectors never share a process with another's, and the
// library's process-wide state (the connector list, the paths, the lock, the open tables) belongs to one user.
namespace {
struct Front;
// One user's worker: its process, and the D-Bus connection to it over a socketpair.
struct Worker {
Front* front = nullptr;
std::uint32_t uid = 0;
pid_t pid = -1;
BusPtr bus;
// Set once the connection is gone, to free it after the dispatch that noticed.
sd_event_source* reap = nullptr;
Worker() = default;
Worker(const Worker&) = delete;
Worker& operator=(const Worker&) = delete;
~Worker() {
sd_event_source_unref(reap);
}
};
struct Front {
DaemonOptions options;
sd_event* event = nullptr;
// Before the connections, so the connection each is registered with goes first however RunDaemon ends.
std::vector<sd_bus_vtable> vtable;
std::vector<sd_bus_vtable> checkoutVtable;
BusPtr bus;
// Checkout::busName, with net.catcrafts.Nostro1.Checkout alone, on a connection of its own: an app allowed to
// talk to that name and no other (a Flatpak's --system-talk-name) may call its owner's unique name too, and this
// one serves nothing else.
BusPtr checkout;
std::map<std::uint32_t, std::unique_ptr<Worker>> workers;
std::size_t inFlight = 0;
sd_event_source* idle = nullptr;
};
// A call handed to a worker, waiting for its answer.
struct Forwarded {
Front* front = nullptr;
MessagePtr call;
};
// Refused before any worker sees the call: a caller the bus cannot name, or a uid without a login session.
struct Refused : std::runtime_error {
using std::runtime_error::runtime_error;
};
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(Front& front) {
sd_event_source_set_time_relative(front.idle, Microseconds(front.options.idle));
sd_event_source_set_enabled(front.idle, SD_EVENT_ONESHOT);
}
// Once idle with no call under way and no worker left, the front ends; D-Bus activation starts it again.
std::int32_t OnIdle(sd_event_source*, std::uint64_t, void* userdata) {
Front& front = *static_cast<Front*>(userdata);
if(front.inFlight == 0 && front.workers.empty()) {
return sd_event_exit(front.event, 0);
}
Touch(front);
return 0;
}
std::int32_t OnBusGone(sd_bus_message*, void* userdata, sd_bus_error*) {
sd_event_exit(static_cast<Front*>(userdata)->event, 0);
return 0;
}
// Calls a method of a service on the system bus and returns its answer, or throws with what it said.
template<typename... Args>
MessagePtr CallSystem(sd_bus* bus, std::string_view destination, std::string_view path, std::string_view interface, std::string_view member, std::string_view types, Args... args) {
Error error;
sd_bus_message* reply = nullptr;
const std::int32_t result = sd_bus_call_method(bus, destination.data(), path.data(), interface.data(), member.data(), &error.error, &reply, types.data(), args...);
if(result < 0) {
throw std::runtime_error(std::format("{} {}: {}", destination, member, ErrorMessage(error.error)));
}
return MessagePtr(reply);
}
// The uid behind a connection, as the bus knows it. Asked of the bus itself rather than worked out by sd-bus, which
// behaves the same on every bus implementation.
std::uint32_t CallerUid(sd_bus* bus, const std::string& sender) {
const MessagePtr reply = CallSystem(bus, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetConnectionCredentials", "s", sender.c_str());
std::optional<std::uint32_t> uid;
Enter(reply.get(), 'a', "{sv}");
while(ThrowOnSdBus(sd_bus_message_at_end(reply.get(), 0), "read the caller's credentials") == 0) {
Enter(reply.get(), 'e', "sv");
if(Read<std::string>(reply.get()) == "UnixUserID") {
Enter(reply.get(), 'v', "u");
uid = Read<std::uint32_t>(reply.get());
Leave(reply.get());
} else {
ThrowOnSdBus(sd_bus_message_skip(reply.get(), "v"), "read the caller's credentials");
}
Leave(reply.get());
}
Leave(reply.get());
if(!uid) {
throw Refused(std::format("the bus did not say which user {} is", sender));
}
return *uid;
}
// The user name logind has for `uid`: the worker keeps it beside the user's files, so a uid handed to a new user
// after the old one was deleted does not open the old one's connectors. A uid logind does not know is refused.
std::string LogindName(sd_bus* bus, std::uint32_t uid) {
std::string path;
try {
const MessagePtr user = CallSystem(bus, "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetUser", "u", uid);
path = ReadText(user.get(), 'o');
} catch(const std::runtime_error& e) {
throw Refused(std::format("nostrod serves users with a login session, and logind knows no user {} ({})", uid, e.what()));
}
const MessagePtr name = CallSystem(bus, "org.freedesktop.login1", path, "org.freedesktop.DBus.Properties", "Get", "ss", "org.freedesktop.login1.User", "Name");
Enter(name.get(), 'v', "s");
std::string text = Read<std::string>(name.get());
Leave(name.get());
return text;
}
std::int32_t OnReap(sd_event_source*, void* userdata) {
Worker& worker = *static_cast<Worker*>(userdata);
Front& front = *worker.front;
waitpid(worker.pid, nullptr, 0);
front.workers.erase(worker.uid);
Touch(front);
return 0;
}
// A worker's connection ended: it went idle, or it died. Every call it still had was failed by sd-bus before this
// signal, so all that is left is to reap the process, which cannot happen inside the connection's own dispatch.
// (sd-bus callbacks return 0 whatever happens: a negative result from one closes the connection it came on.)
std::int32_t OnWorkerGone(sd_bus_message*, void* userdata, sd_bus_error*) {
Worker& worker = *static_cast<Worker*>(userdata);
if(sd_event_add_defer(worker.front->event, &worker.reap, OnReap, &worker) >= 0) {
sd_event_source_set_enabled(worker.reap, SD_EVENT_ONESHOT);
}
return 0;
}
// A socket that closes itself.
struct Descriptor {
std::int32_t fd = -1;
Descriptor() = default;
Descriptor(const Descriptor&) = delete;
Descriptor& operator=(const Descriptor&) = delete;
~Descriptor() {
if(fd != -1) {
close(fd);
}
}
};
// Starts `uid`'s worker: this executable again, as `nostrod --worker`, with its end of a socketpair as fd 3.
// posix_spawn rather than fork and exec: nothing of this process runs in the child before the exec.
std::unique_ptr<Worker> Spawn(Front& front, std::uint32_t uid, const std::string& name) {
std::array<std::int32_t, 2> ends{};
if(socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, ends.data()) == -1) {
throw std::system_error(errno, std::generic_category(), "cannot make a socket for a worker");
}
Descriptor ours;
ours.fd = ends[0];
Descriptor theirs;
theirs.fd = ends[1];
std::vector<std::string> args = {"nostrod", "--worker", std::to_string(uid), name, "--state", front.options.state.string(), "--idle", std::to_string(front.options.idle.count()), "--prompt-timeout", std::to_string(front.options.promptTimeout.count())};
// posix_spawn takes C strings.
// lint-disable-next-line no-char-pointer
std::vector<char*> argv;
for(std::string& arg : args) {
argv.push_back(arg.data());
}
argv.push_back(nullptr);
posix_spawn_file_actions_t actions;
posix_spawn_file_actions_init(&actions);
// Duplicated onto fd 3 without close-on-exec; POSIX clears the flag even when the socket already is fd 3.
posix_spawn_file_actions_adddup2(&actions, theirs.fd, 3);
pid_t pid = -1;
const std::int32_t spawned = posix_spawn(&pid, "/proc/self/exe", &actions, nullptr, argv.data(), environ);
posix_spawn_file_actions_destroy(&actions);
if(spawned != 0) {
throw std::system_error(spawned, std::generic_category(), "cannot start a worker");
}
std::unique_ptr<Worker> worker = std::make_unique<Worker>();
worker->front = &front;
worker->uid = uid;
worker->pid = pid;
sd_bus* bus = nullptr;
ThrowOnSdBus(sd_bus_new(&bus), "connect to a worker");
worker->bus.reset(bus);
ThrowOnSdBus(sd_bus_set_fd(bus, ours.fd, ours.fd), "connect to a worker");
// The connection owns the socket now.
ours.fd = -1;
ThrowOnSdBus(sd_bus_set_description(bus, std::format("worker for uid {}", uid).c_str()), "connect to a worker");
ThrowOnSdBus(sd_bus_start(bus), "connect to a worker");
ThrowOnSdBus(sd_bus_match_signal(bus, nullptr, "org.freedesktop.DBus.Local", "/org/freedesktop/DBus/Local", "org.freedesktop.DBus.Local", "Disconnected", OnWorkerGone, worker.get()), "watch a worker");
ThrowOnSdBus(sd_bus_attach_event(bus, front.event, SD_EVENT_PRIORITY_NORMAL), "connect to a worker");
return worker;
}
Worker& WorkerFor(Front& front, std::uint32_t uid) {
if(const auto existing = front.workers.find(uid); existing != front.workers.end()) {
return *existing->second;
}
const std::string name = LogindName(front.bus.get(), uid);
return *front.workers.emplace(uid, Spawn(front, uid, name)).first->second;
}
// The call as the worker gets it: the same method and arguments, from the caller's unique name, which is what the
// worker asks polkit about, and allowing a password prompt only when the caller did.
MessagePtr Copy(sd_bus* to, sd_bus_message* call, const std::string& sender) {
sd_bus_message* copy = nullptr;
ThrowOnSdBus(sd_bus_message_new_method_call(to, &copy, nullptr, sd_bus_message_get_path(call), sd_bus_message_get_interface(call), sd_bus_message_get_member(call)), "pass a call on");
MessagePtr owned(copy);
if(IsSensitive(Member(call))) {
ThrowOnSdBus(sd_bus_message_sensitive(copy), "pass a call on");
}
ThrowOnSdBus(sd_bus_message_rewind(call, 1), "pass a call on");
ThrowOnSdBus(sd_bus_message_copy(copy, call, 1), "pass a call on");
ThrowOnSdBus(sd_bus_message_set_sender(copy, sender.c_str()), "pass a call on");
ThrowOnSdBus(sd_bus_message_set_allow_interactive_authorization(copy, sd_bus_message_get_allow_interactive_authorization(call)), "pass a call on");
return owned;
}
// The worker's answer, as the answer to the caller.
std::int32_t OnWorkerReply(sd_bus_message* reply, void* userdata, sd_bus_error*) {
const std::unique_ptr<Forwarded> forwarded(static_cast<Forwarded*>(userdata));
Front& front = *forwarded->front;
front.inFlight--;
Touch(front);
sd_bus_message* call = forwarded->call.get();
if(sd_bus_message_is_method_error(reply, nullptr)) {
const sd_bus_error* error = sd_bus_message_get_error(reply);
// sd-bus fails a call whose worker went away, or did not answer in time, with errors of its own.
if(sd_bus_error_has_names(error, SD_BUS_ERROR_NO_REPLY, SD_BUS_ERROR_TIMEOUT, SD_BUS_ERROR_DISCONNECTED)) {
sd_bus_reply_method_errorf(call, errorFailed.data(), "nostrod's worker for you stopped before it answered (%s): what you asked for may have been carried out, check before trying again", ErrorMessage(*error).c_str());
} else {
sd_bus_reply_method_error(call, error);
}
return 0;
}
// These fail only when memory runs out; the caller's own timeout then answers for them.
sd_bus_message* answer = nullptr;
sd_bus_message_new_method_return(call, &answer);
const MessagePtr owned(answer);
sd_bus_message_rewind(reply, 1);
sd_bus_message_copy(answer, reply, 1);
sd_bus_send(nullptr, answer, nullptr);
return 0;
}
// Every method of the interface: passed on to the caller's worker, whose answer is relayed when it comes, so a
// password prompt one user leaves open holds up nobody else.
std::int32_t Forward(sd_bus_message* call, void* userdata, sd_bus_error* error) {
Front& front = *static_cast<Front*>(userdata);
Touch(front);
try {
const std::string sender = Sender(call);
Worker& worker = WorkerFor(front, CallerUid(sd_bus_message_get_bus(call), sender));
const MessagePtr copy = Copy(worker.bus.get(), call, sender);
std::unique_ptr<Forwarded> forwarded = std::make_unique<Forwarded>(&front, MessagePtr(sd_bus_message_ref(call)));
// Long enough for the prompt and then the bank, which waits out its rate limits.
ThrowOnSdBus(sd_bus_call_async(worker.bus.get(), nullptr, copy.get(), OnWorkerReply, forwarded.get(), Microseconds(front.options.promptTimeout + std::chrono::minutes(10))), "pass a call on");
// OnWorkerReply owns it now.
forwarded.release();
front.inFlight++;
return 1;
} catch(const Refused& e) {
return sd_bus_error_set(error, SD_BUS_ERROR_ACCESS_DENIED, e.what());
} catch(const std::exception& e) {
return sd_bus_error_set(error, errorFailed.data(), e.what());
}
}
// A system bus connection that serves `interface` under `name`, every method passed on by Forward, and ends the
// loop when the bus goes.
BusPtr Serve(Front& front, std::string_view description, std::string_view name, std::string_view interface, std::vector<sd_bus_vtable>& vtable) {
sd_bus* bus = nullptr;
ThrowOnSdBus(sd_bus_open_system_with_description(&bus, description.data()), "connect to the system bus");
BusPtr owned(bus);
ThrowOnSdBus(sd_bus_add_object_vtable(bus, nullptr, objectPath.data(), interface.data(), vtable.data(), &front), std::format("serve {}", interface));
ThrowOnSdBus(sd_bus_match_signal(bus, nullptr, "org.freedesktop.DBus.Local", "/org/freedesktop/DBus/Local", "org.freedesktop.DBus.Local", "Disconnected", OnBusGone, &front), "watch the system bus");
ThrowOnSdBus(sd_bus_request_name(bus, name.data(), 0), std::format("own {}", name));
ThrowOnSdBus(sd_bus_attach_event(bus, front.event, SD_EVENT_PRIORITY_NORMAL), std::format("serve {}", interface));
return owned;
}
}
std::int32_t Nostro::RunDaemon(const DaemonOptions& options) {
Front front;
front.options = options;
ThrowOnSdBus(sd_event_new(&front.event), "make an event loop");
// systemd stops the service with SIGTERM: the loop ends then, and everything is closed and flushed on the way out.
sigset_t terminate{};
sigemptyset(&terminate);
sigaddset(&terminate, SIGTERM);
sigprocmask(SIG_BLOCK, &terminate, nullptr);
ThrowOnSdBus(sd_event_add_signal(front.event, nullptr, SIGTERM, nullptr, nullptr), "watch for SIGTERM");
front.vtable = Vtable(methods, [](std::string_view) { return &Forward; });
front.checkoutVtable = Vtable(checkoutMethods, [](std::string_view) { return &Forward; });
// The main name last: systemd counts the service as started once it is owned, and by then both are.
front.checkout = Serve(front, "nostrod checkout", Checkout::busName, Checkout::interfaceName, front.checkoutVtable);
front.bus = Serve(front, "nostrod", busName, interfaceName, front.vtable);
ThrowOnSdBus(sd_event_add_time_relative(front.event, &front.idle, CLOCK_MONOTONIC, Microseconds(options.idle), 0, OnIdle, &front), "set the idle timer");
const std::int32_t result = sd_event_loop(front.event);
// Closing a worker's connection ends it; wait for each, so none outlives the front.
for(auto& [uid, worker] : front.workers) {
worker->bus.reset();
waitpid(worker->pid, nullptr, 0);
}
front.workers.clear();
front.bus.reset();
front.checkout.reset();
sd_event_source_unref(front.idle);
sd_event_unref(front.event);
ThrowOnSdBus(result, "run the event loop");
return 0;
}

View file

@ -1,10 +1,12 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include <cerrno>
#include <errno.h>
#include <sys/stat.h>
#include <termios.h>
#include <unistd.h>
module Nostro:File_impl;
import :File;
@ -13,31 +15,33 @@ import std;
using namespace Nostro;
namespace fs = std::filesystem;
namespace {
// An environment variable as a path, or nothing when it is not set.
std::optional<fs::path> Environment(const std::string& name) {
// getenv answers with a char*, null when the variable is not set.
// lint-disable-next-line no-char-pointer
const char* const value = std::getenv(name.c_str());
return value ? std::optional<fs::path>(value) : std::nullopt;
}
}
fs::path Nostro::GetConfigPath() {
const char* const xdg = std::getenv("XDG_CONFIG_HOME");
if(xdg) {
return fs::path(fs::path(std::move(xdg)) / ".config/nostro");
if(const std::optional<fs::path> xdg = Environment("XDG_CONFIG_HOME")) {
return *xdg / ".config/nostro";
}
const char* const home = std::getenv("HOME");
if(home) {
return fs::path(fs::path(std::move(home)) / ".config/nostro");
if(const std::optional<fs::path> home = Environment("HOME")) {
return *home / ".config/nostro";
}
throw std::runtime_error("XDG_CONFIG_HOME and HOME not set");
}
fs::path Nostro::GetCachePath() {
const char* const xdg = std::getenv("XDG_CACHE_HOME");
if(xdg) {
return fs::path(fs::path(std::move(xdg)) / "nostro");
if(const std::optional<fs::path> xdg = Environment("XDG_CACHE_HOME")) {
return *xdg / "nostro";
}
const char* const home = std::getenv("HOME");
if(home) {
return fs::path(fs::path(std::move(home)) / ".cache/nostro");
if(const std::optional<fs::path> home = Environment("HOME")) {
return *home / ".cache/nostro";
}
throw std::runtime_error("XDG_CACHE_HOME and HOME not set");
}
@ -60,22 +64,28 @@ void Nostro::CreatePrivateFile(const fs::path& path) {
}
}
void Nostro::WriteString(std::ofstream& file, std::string_view str) {
std::uint16_t size = str.size();
file.write(reinterpret_cast<char*>(&size), sizeof(size));
file.write(str.data(), size);
}
std::string Nostro::ReadSecret(std::string_view prompt) {
const bool terminal = isatty(STDIN_FILENO) == 1;
termios shown{};
if(terminal) {
std::print(std::cerr, "{}", prompt);
tcgetattr(STDIN_FILENO, &shown);
termios hidden = shown;
hidden.c_lflag &= ~static_cast<tcflag_t>(ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &hidden);
}
void Nostro::ReadString(std::ifstream& file, std::string& str) {
std::uint16_t size;
file.read(reinterpret_cast<char*>(&size), sizeof(size));
str.resize(size);
file.read(str.data(), size);
}
std::string line;
const bool read = static_cast<bool>(std::getline(std::cin, line));
if(terminal) {
tcsetattr(STDIN_FILENO, TCSANOW, &shown);
std::println(std::cerr);
}
if(!read) {
throw std::runtime_error(std::format("nothing given for '{}'", prompt));
}
std::uint16_t Nostro::SeekString(std::ifstream& file) {
std::uint16_t size;
file.read(reinterpret_cast<char*>(&size), sizeof(size));
file.seekg(size, std::ios::cur);
return size;
}
const std::size_t first = line.find_first_not_of(" \t\r");
const std::size_t last = line.find_last_not_of(" \t\r");
return first == std::string::npos ? std::string() : line.substr(first, last - first + 1);
}

View file

@ -1,13 +0,0 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module Nostro:Transaction_impl;
import :Transaction;
import std;
using namespace Nostro;
namespace fs = std::filesystem;
Transaction::Transaction(std::string&& name, std::string&& bic, std::string&& iban, std::string&& description, Currency currency, std::int64_t amount, std::chrono::system_clock::time_point timePoint): name(std::move(name)), bic(std::move(bic)), iban(std::move(iban)), description(std::move(description)), currency(currency), amount(amount), timePoint(timePoint) {
}

View file

@ -0,0 +1,121 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include <systemd/sd-bus.h>
#include <errno.h>
module Nostro.Checkout;
import std;
using namespace Nostro;
Checkout::Error::Error(std::string name, const std::string& message) : std::runtime_error(message), name(std::move(name)) {
}
namespace {
// What sd-bus hands out, freed at the end of the scope.
struct Connection {
sd_bus* bus = nullptr;
Connection() = default;
Connection(const Connection&) = delete;
Connection& operator=(const Connection&) = delete;
~Connection() {
sd_bus_flush_close_unref(bus);
}
};
struct Message {
sd_bus_message* message = nullptr;
Message() = default;
Message(const Message&) = delete;
Message& operator=(const Message&) = delete;
~Message() {
sd_bus_message_unref(message);
}
};
struct BusError {
sd_bus_error error = SD_BUS_ERROR_NULL;
BusError() = default;
BusError(const BusError&) = delete;
BusError& operator=(const BusError&) = delete;
~BusError() {
sd_bus_error_free(&error);
}
};
// Throws a std::system_error naming `what` when an sd-bus call returned a negative errno; returns the result.
std::int32_t ThrowOn(std::int32_t result, std::string_view what) {
if(result < 0) {
throw std::system_error(-result, std::generic_category(), std::format("cannot {}", what));
}
return result;
}
// sd-bus hands strings out as C strings, the ones of an error possibly none.
// lint-disable-next-line no-char-pointer
std::string Text(const char* text) {
return text ? std::string(text) : std::string();
}
std::string ReadString(sd_bus_message* message) {
// lint-disable-next-line no-char-pointer
const char* text = nullptr;
ThrowOn(sd_bus_message_read_basic(message, 's', &text), "read nostrod's answer");
return Text(text);
}
}
Checkout::Paid Checkout::Pay(const Order& order, std::chrono::seconds timeout) {
Connection connection;
ThrowOn(sd_bus_open_system_with_description(&connection.bus, "nostro checkout"), "connect to the system bus");
// The user confirms the order at a password prompt.
ThrowOn(sd_bus_set_allow_interactive_authorization(connection.bus, 1), "connect to the system bus");
Message call;
ThrowOn(sd_bus_message_new_method_call(connection.bus, &call.message, busName.data(), objectPath.data(), interfaceName.data(), "Pay"), "call nostrod");
// No options yet; a nostrod skips the ones it does not know, so adding one breaks no older nostrod.
const std::int32_t appended = sd_bus_message_append(call.message, "ssxssa{sv}", order.payeeIban.c_str(), order.payeeName.c_str(), order.amount, order.currency.c_str(), order.reference.c_str(), 0u);
if(appended == -EINVAL) {
throw std::invalid_argument("text that is not UTF-8 cannot be sent to nostrod");
}
ThrowOn(appended, "call nostrod");
BusError error;
Message reply;
if(sd_bus_call(connection.bus, call.message, static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(timeout).count()), &error.error, &reply.message) < 0) {
std::string name = Text(error.error.name);
const std::string message = Text(error.error.message);
if(name == errorCancelled) {
throw Cancelled(std::move(name), message);
}
if(name == errorNoCheckoutAccount) {
throw NoCheckoutAccount(std::move(name), message);
}
if(name == SD_BUS_ERROR_SERVICE_UNKNOWN) {
throw Error(std::move(name), std::format("nostro is not installed, or the system bus cannot start it ({})", message));
}
if(name == SD_BUS_ERROR_NO_REPLY || name == SD_BUS_ERROR_TIMEOUT) {
throw Error(std::move(name), std::format("nostrod did not answer in time ({}): the order may have been paid, and paying the same order again answers with its payment rather than paying twice", message));
}
throw Error(std::move(name), message);
}
Paid paid;
ThrowOn(sd_bus_message_read_basic(reply.message, 't', &paid.paymentId), "read nostrod's answer");
// The results: a later nostrod may add to them, and what this one does not know it skips.
ThrowOn(sd_bus_message_enter_container(reply.message, 'a', "{sv}"), "read nostrod's answer");
while(ThrowOn(sd_bus_message_enter_container(reply.message, 'e', "sv"), "read nostrod's answer") > 0) {
if(ReadString(reply.message) == "repeated") {
std::int32_t repeated = 0;
ThrowOn(sd_bus_message_read(reply.message, "v", "b", &repeated), "read nostrod's answer");
paid.repeated = repeated != 0;
} else {
ThrowOn(sd_bus_message_skip(reply.message, "v"), "read nostrod's answer");
}
ThrowOn(sd_bus_message_exit_container(reply.message), "read nostrod's answer");
}
ThrowOn(sd_bus_message_exit_container(reply.message), "read nostrod's answer");
return paid;
}

View file

@ -1,125 +1,388 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Nostro;
using namespace Nostro;
int main(int argc, char *argv[]) {
if(argc < 2) {
std::println("no command provided");
return -1;
}
namespace {
constexpr std::string_view usage = R"(usage:
nostro connectors list connectors and whether they work
nostro connectors add bunq [allowed ips] [--sandbox] 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 apps may ask you to pay from at checkout
Connector::LoadConnectors();
<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 anything that moves money, a checkout included.)";
std::string_view cmd = argv[1];
// 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;
if(cmd == "connectors") {
if(argc > 2) {
cmd = argv[2];
if(cmd == "add") {
if(argc > 3) {
cmd = argv[3];
if(cmd == "bunq") {
if(argc > 4) {
cmd = argv[4];
std::string ip;
if(argc > 5) {
ip = argv[5];
} else {
ip = "*";
}
BunqConnector::Create(std::string(cmd), std::move(ip));
} else {
std::println("api key not provided");
}
} else {
std::println("unknown connector type");
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 {
std::println("connector type not provided");
}
} else {
std::println("unknown command");
}
} else {
std::string out;
tuple_for<EnabledBanks>([&out]<typename Bank>() {
for(Bank& bank : Bank::connectors) {
out += std::format("{}\t{}\t{}\n", bank, Bank::connectorId, bank.TestConnector());
}
});
if(out.size()) {
out.pop_back();
}
std::println("{}", out);
}
} else if(cmd == "accounts") {
std::string out;
tuple_for<EnabledBanks>([&out]<typename Bank>() {
for(Bank& bank : Bank::connectors) {
out += std::format("{}\t{}\n", bank, Bank::connectorId);
for(typename Bank::Account& account : bank.accounts) {
out += std::format("\t{}\n", account);
positional.push_back(arg);
}
}
});
if(out.size()) {
out.pop_back();
}
std::println("{}", out);
} else if(cmd == "send") {
if(argc > 2) {
std::string_view accountName = argv[2];
bool notFound = true;
tuple_for<EnabledBanks>([argc, argv, accountName, &notFound]<typename Bank>() {
for(Bank& bank : Bank::connectors) {
for(typename Bank::Account& account : bank.accounts) {
if(account.name == accountName) {
notFound = false;
if(argc > 3) {
std::string_view iban = argv[3];
if(argc > 4) {
std::string_view name = argv[4];
if(argc > 5) {
std::int64_t amount = std::stoll(argv[5]);
if(argc > 6) {
account.Send(iban, name, amount, account.currency, argv[6]);
} else {
account.Send(iban, name, amount, account.currency, "");
}
} else {
std::println("amount not provided");
}
} else {
std::println("recipient name not provided");
}
} else {
std::println("iban not provided");
}
return;
}
}
}
});
if(notFound) {
std::println("account not found");
return -1;
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));
}
} else {
std::println("account name not provided");
return -1;
return positional[index];
}
} else {
std::println("unknown command");
return -1;
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 end of the day for a date without a time, so "--to 2026-10-31" includes that day.
std::chrono::system_clock::time_point ParseEnd(std::string_view text) {
return text.size() == 10 ? ParseLocalDate(text, 1) - std::chrono::microseconds(1) : ParseLocalDate(text);
}
// 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) {
// 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, "*"), args.sandbox ? "sandbox" : "");
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");
}
if(const std::optional<std::string> error = QueryParameter(redirected, "error")) {
throw std::runtime_error(std::format("bunq did not authorize: {} {}", *error, QueryParameter(redirected, "error_description").value_or("")));
}
const std::optional<std::string> code = QueryParameter(redirected, "code");
if(!code || code->empty()) {
throw std::runtime_error("that address has no code= in it");
}
if(QueryParameter(redirected, "state") != state) {
throw std::runtime_error("that address is not the answer to this authorization (its state differs): start again");
}
// 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 = ParseEnd(*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 = std::string(args.At(6, "recurrence"));
std::ranges::transform(schedule.unit, schedule.unit.begin(), [](char c) { return static_cast<char>(std::toupper(static_cast<std::uint8_t>(c))); });
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 = ParseEnd(*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);
if(card.status != status->second) {
throw std::runtime_error(std::format("bunq kept card {} {} (its order status is {}): a card can only be frozen or unfrozen once it has been activated", id, card.status, card.orderStatus));
}
std::println("card {} is now {}", id, card.status);
}
// Apps pay at checkout from one account, and the user confirms each payment with their 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("checkouts pay from {}", client.SetDefaultCheckoutAccount(args.positional[2]));
} else if(const std::optional<Account> chosen = client.DefaultCheckoutAccount()) {
std::println("{}", *chosen);
} else {
std::println("no account pays at checkout: `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;
}
}

View file

@ -0,0 +1,63 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// nostrod: the daemon that holds the connectors (Nostro:Daemon). This file only reads the command line:
// nostrod [--state <dir>] [--idle <seconds>] [--prompt-timeout <seconds>]
// nostrod --worker <uid> <name> ... what the daemon starts for one user, with its socket as fd 3
// Without --state the users' directories go below $XDG_DATA_HOME (which Flatpak points into the app's own data), or
// ~/.local/share.
import std;
import Nostro;
// 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[]) {
const std::vector<std::string_view> args(argv + 1, argv + argc);
try {
const auto value = [&args](std::size_t index) {
if(index >= args.size()) {
throw std::invalid_argument(std::format("{} needs a value", args[index - 1]));
}
return args[index];
};
const auto number = [](std::string_view text) {
std::uint32_t count = 0;
const std::from_chars_result result = std::from_chars(text.data(), text.data() + text.size(), count);
if(result.ec != std::errc() || result.ptr != text.data() + text.size()) {
throw std::invalid_argument(std::format("'{}' is not a whole number", text));
}
return count;
};
Nostro::DaemonOptions options;
// getenv answers with a char*, null when the variable is not set.
// lint-disable-next-line no-char-pointer
const char* const dataHome = std::getenv("XDG_DATA_HOME");
// lint-disable-next-line no-char-pointer
const char* const home = std::getenv("HOME");
options.state = dataHome ? std::filesystem::path(dataHome) : std::filesystem::path(home ? home : "/") / ".local/share";
std::optional<std::pair<std::uint32_t, std::string>> worker;
for(std::size_t i = 0; i < args.size(); i++) {
if(args[i] == "--state") {
options.state = value(++i);
} else if(args[i] == "--idle") {
options.idle = std::chrono::seconds(number(value(++i)));
} else if(args[i] == "--prompt-timeout") {
options.promptTimeout = std::chrono::seconds(number(value(++i)));
} else if(args[i] == "--worker") {
const std::uint32_t uid = number(value(++i));
worker = std::pair{uid, std::string(value(++i))};
} else {
throw std::invalid_argument(std::format("unknown argument '{}'", args[i]));
}
}
if(worker) {
return Nostro::RunWorker(3, worker->first, worker->second, options);
}
return Nostro::RunDaemon(options);
} catch(const std::exception& e) {
std::println(std::cerr, "nostrod: {}", e.what());
return 1;
}
}

View file

@ -1,5 +1,5 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:Account;
@ -8,33 +8,39 @@ import :Currency;
import :Transaction;
namespace Nostro {
// What a transaction list shows: the newest `limit` transactions that match every field. `from` and `to` are inclusive.
export struct TransactionQuery {
std::string search; // case-insensitive (ASCII), in the name, description or IBAN; empty matches all
std::optional<std::int64_t> amount; // exact, in the currency's minor unit, negative when outgoing
std::chrono::system_clock::time_point from = std::chrono::system_clock::time_point::min();
std::chrono::system_clock::time_point to = std::chrono::system_clock::time_point::max();
std::size_t limit = 100;
};
export struct Account {
std::string name;
std::string bic;
std::string iban;
Currency currency;
std::int64_t balance;
std::vector<Transaction> transactions;
// Transactions are stored per connector and account name, in a table ordered by time.
std::chrono::system_clock::time_point GetLastTransactionTime(std::string_view connector) const;
void SaveTransactions(std::string_view connector);
void LoadTransactions(std::string_view connector);
void LoadTransactions(std::string_view connector, std::chrono::system_clock::time_point from);
void LoadTransactions(std::string_view connector, std::chrono::system_clock::time_point from, std::chrono::system_clock::time_point to);
void LoadTransactionsByDescription(std::string_view connector, std::string_view description);
void LoadTransactionsByIban(std::string_view connector, std::string_view iban);
void LoadTransactions(std::string_view connector, std::int64_t amount);
// Appends the ones newer than the last stored transaction, in any order.
void SaveTransactions(std::string_view connector, std::vector<Transaction> transactions);
// Newest first.
std::vector<Transaction> FindTransactions(std::string_view connector, const TransactionQuery& query) const;
private:
std::ifstream LoadUntilFrom(std::string_view connector, std::chrono::system_clock::time_point from);
Transaction& LoadTransaction(std::ifstream& file);
// Deletes every table stored under `connector` (a connector's storage key covers all its accounts), closing the
// ones this process has open first: a table left open on deleted files would take the next sync's rows with it.
static void ForgetTransactions(std::string_view connector);
};
}
template<std::derived_from<Nostro::Account> T>
struct std::formatter<T> : std::formatter<std::string> {
auto format(const Nostro::Account& obj, std::format_context& ctx) const {
return std::formatter<std::string>::format(std::format("{}\t{} {}\t{}{}", obj.name, obj.bic, obj.iban, obj.currency, Nostro::FormatAmount(obj.balance, obj.currency)), ctx);
return std::formatter<std::string>::format(std::format("{}\t{} {}\t{}", obj.name, obj.bic, obj.iban, Nostro::FormatMoney(obj.balance, obj.currency)), ctx);
}
};

View file

@ -1,5 +1,5 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:Banks;

View file

@ -1,5 +1,5 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
@ -12,47 +12,266 @@ export module Nostro:Bunq;
#ifdef NOSTRO_BUNQ_ENABLED
import std;
import Crafter.Network;
import :Account;
import :Crypto;
import :Currency;
import :Transaction;
using namespace Crafter;
import :Utils;
namespace Nostro {
export struct BunqConnector;
// Which bunq a connector talks to: api.bunq.com, or the sandbox at public-api.sandbox.bunq.com. Sandbox API
// keys start with "sandbox_"; OAuth access tokens do not say.
export enum class BunqEnvironment : std::uint8_t {
Production,
Sandbox
};
// A server to send bunq's API and OAuth token calls to instead of bunq's own: a local fake, for tests.
export struct BunqEndpoint {
std::string host;
std::uint16_t port = 443;
std::string caPem; // a trust anchor beside the system store, for a self-signed certificate
};
// An error response from bunq, with its HTTP status (bunq also uses 466, 490 and 491) and error_description.
export struct BunqError : std::runtime_error {
std::uint16_t status;
BunqError(std::uint16_t status, const std::string& message);
};
// The other side of a payment or a request, as bunq addresses it.
export struct BunqCounterparty {
std::string type; // "IBAN", "EMAIL" or "PHONE_NUMBER"
std::string value; // an IBAN without spaces, an e-mail address, or a phone number in international format
std::string name; // required by bunq for an IBAN outside bunq
// `value` with an '@' is an e-mail address, one starting with '+' a phone number, anything else an IBAN,
// whose check digits are verified so a typo fails here rather than at the bank.
static BunqCounterparty Parse(std::string_view value, std::string_view name);
};
// How bunq shows a party in a listing.
export struct BunqLabel {
std::string name;
std::string iban; // empty when bunq gives none (a card merchant, or a party known by e-mail or phone)
};
// A request for money this account sent (a bunq RequestInquiry).
export struct BunqPaymentRequest {
std::uint64_t id;
std::string status; // PENDING, ACCEPTED, REJECTED, REVOKED or EXPIRED
BunqLabel counterparty;
Currency currency;
std::int64_t amount; // what was asked, in the currency's minor unit
std::optional<std::int64_t> amountPaid; // what was paid, once accepted
std::string description;
std::chrono::system_clock::time_point created;
std::string shareUrl; // a bunq.me link anyone can pay through, when bunq made one
};
// A request for money this account received (a bunq RequestResponse). Incoming SEPA direct debits are these too.
export struct BunqIncomingRequest {
std::uint64_t id;
std::string status; // PENDING, ACCEPTED, REJECTED, REFUND_REQUESTED, REFUNDED or REVOKED
std::string type; // INTERNAL, DIRECT_DEBIT, DIRECT_DEBIT_B2B, IDEAL or SOFORT
BunqLabel counterparty;
Currency currency;
std::int64_t amount; // what is asked, in the currency's minor unit
std::string description;
std::chrono::system_clock::time_point created;
};
// When a scheduled payment runs. bunq keeps these times in UTC.
export struct BunqSchedule {
std::chrono::system_clock::time_point start;
std::optional<std::chrono::system_clock::time_point> end;
std::string unit = "ONCE"; // ONCE, HOURLY, DAILY, WEEKLY, MONTHLY or YEARLY
std::uint32_t every = 1; // with WEEKLY, 2 is every other week
std::string status; // ACTIVE, FINISHED or CANCELLED; ignored when scheduling
std::optional<std::chrono::system_clock::time_point> next; // the next run, when bunq says; ignored when scheduling
// Throws std::invalid_argument for a unit bunq does not know or `every` of 0, as Schedule would.
void Check() const;
};
// A payment bunq makes on a schedule (a bunq SchedulePayment).
export struct BunqScheduledPayment {
std::uint64_t id;
BunqLabel counterparty;
Currency currency;
std::int64_t amount; // each payment, in the currency's minor unit
std::string description;
BunqSchedule schedule;
};
// A payment waiting for approval (a bunq DraftPayment): made through OAuth, which may not pay others directly, or
// for an account that needs a second approval.
export struct BunqDraftPayment {
struct Entry {
BunqLabel counterparty;
Currency currency;
std::int64_t amount;
std::string description;
};
std::uint64_t id;
std::string status; // PENDING, ACCEPTED, REJECTED or CANCELLED
std::string createdBy;
std::vector<Entry> entries; // each becomes a payment when the draft is accepted
std::string updated; // bunq's time of its last change, as bunq wrote it; empty when bunq gave none
};
export struct BunqCard {
std::uint64_t id;
std::string kind; // bunq's object: CardDebit, CardCredit, ...
std::string productType; // MASTERCARD_DEBIT, MAESTRO_DEBIT, ...
std::string status; // ACTIVE, DEACTIVATED, LOST, STOLEN, CANCELLED, EXPIRED or PIN_TRIES_EXCEEDED
std::string orderStatus;
std::string nameOnCard;
std::string secondLine;
std::string lastFour; // last four digits of the card number
std::string expiry; // YYYY-MM-DD
std::string iban; // the account it pays from
};
export struct BunqAccount : public Account {
std::uint32_t id;
std::uint64_t id;
std::string type; // bunq's object: MonetaryAccountBank, MonetaryAccountSavings, MonetaryAccountJoint, ...
BunqConnector* connector;
BunqAccount(std::string&& name, std::string&& bic, std::string&& iban, Currency currency, std::int64_t balance, std::uint32_t id, BunqConnector* connector);
void Send(std::string_view iban, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const;
BunqAccount(std::string&& name, std::string&& bic, std::string&& iban, Currency currency, std::int64_t balance, std::uint64_t id, std::string&& type, BunqConnector* connector);
// "/user/{user}/monetary-account/{id}", the API path everything below hangs from.
std::string Path() const;
// Where this account's transactions are stored (the `connector` argument of Account's transaction calls):
// the connector's StorageKey and the account id, so two accounts with one name never share a table.
std::string StorageKey() const;
// Amounts are in the currency's minor unit and positive; `to` and `from` are read by BunqCounterparty::Parse.
// Each returns the id bunq gave the new object.
std::uint64_t Send(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const;
std::uint64_t Draft(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const;
std::uint64_t Schedule(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description, const BunqSchedule& schedule) const;
// Asks `from` for money. bunq.me is allowed, so someone without bunq can pay through the returned share URL.
BunqPaymentRequest Request(std::string_view from, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const;
// Newest first.
std::vector<BunqPaymentRequest> Requests() const;
std::vector<BunqIncomingRequest> IncomingRequests() const;
std::vector<BunqScheduledPayment> ScheduledPayments() const;
std::vector<BunqDraftPayment> DraftPayments() const;
// One of each, as bunq has it now: what to show before answering it.
BunqIncomingRequest IncomingRequest(std::uint64_t id) const;
BunqDraftPayment DraftPayment(std::uint64_t id) const;
void RevokeRequest(std::uint64_t id) const;
// Answers the request as it was shown: accepting pays shown.amount from this account, whatever the request
// asks by now.
void RespondToRequest(const BunqIncomingRequest& shown, bool accept) const;
void CancelScheduledPayment(std::uint64_t id) const;
// Answers the draft as it was shown: bunq refuses the answer when the draft changed since (by shown.updated).
void RespondToDraftPayment(const BunqDraftPayment& shown, bool accept) const;
};
export struct BunqConnector {
std::string sessionToken;
BunqEnvironment environment = BunqEnvironment::Production;
std::string apiKey; // the API key, or the OAuth access token it was connected with
std::string installationToken;
EVP_PKEY* privateKey;
std::string apiKey;
std::string sessionToken;
std::uint64_t sessionId = 0; // 0 for connectors saved before it was kept: bunq logs out the current session for 0
Crypto::Key privateKey;
Crypto::Key serverPublicKey; // verifies every response; fetched on first use for connectors saved before it was kept
std::string userType; // UserPerson, UserCompany, UserApiKey (connected through OAuth) or UserPaymentServiceProvider
std::string name;
std::uint64_t id = 0; // the user id in API paths; for OAuth the UserApiKey's own id
std::uint64_t ownerId = 0; // the bunq user whose accounts these are: `id`, or for OAuth the user who granted access
std::vector<BunqAccount> accounts;
std::uint32_t id;
// One call to the bunq API: `path` is below /v1 ("/user/1/monetary-account"), or a pagination URL. Bodies are
// signed, responses verified against the server's key, rate limits waited out, and an expired session
// renewed once. Throws BunqError for an error response. A POST, PUT or DELETE goes over a new connection, so
// nothing below replays it; when its outcome is unknown (a lost connection, a 5xx) the error says so.
nlohmann::json Get(std::string_view path);
nlohmann::json Post(std::string_view path, const nlohmann::json& body);
nlohmann::json Put(std::string_view path, const nlohmann::json& body);
nlohmann::json Delete(std::string_view path);
// Every item of a listing, following its pages, newest first.
std::vector<nlohmann::json> List(std::string_view path);
void RefreshSession();
// All open accounts, of every kind bunq has. One in a currency Nostro does not know is skipped, with a Note.
void RefreshAccounts();
// Fetches each account's payments newer than the last stored one and stores them.
void GetNewTransactions();
void GetNewTransactions(BunqAccount& account);
bool TestConnector();
// Ends the session at bunq. The API key or OAuth grant stays valid; revoke it in the bunq app.
void Logout();
std::vector<BunqCard> Cards();
// DEACTIVATED and ACTIVE freeze and unfreeze a card; LOST and STOLEN block it for good. Returns the card as
// bunq has it afterwards, which can differ from what was asked: a card never activated stays DEACTIVATED.
BunqCard SetCardStatus(std::uint64_t card, std::string_view status);
// The directory of this connector's transaction tables below <cache>/transactions: bunq, the environment
// and the user id, so two connectors never share a table.
std::string StorageKey() const;
// Connected through OAuth: bunq then allows payments between the user's own accounts and draft payments only.
bool IsOAuth() const;
static constexpr std::string connectorId = "bunq";
inline static ClientHTTP1 client = ClientHTTP1("public-api.sandbox.bunq.com", 443, Crafter::TLSClientCredentials{});
static std::vector<BunqConnector> connectors;
static BunqConnector& Create(std::string&& apiKey, std::string_view allowedIp);
// A deque, so an account's `connector` stays valid when another connector is added.
static std::deque<BunqConnector> connectors;
// Registers a new key pair and device for `apiKey` (an API key or OAuth access token) and opens a session.
// `allowedIps` is a comma-separated list for the device, "*" for any address (a wildcard API key), or empty
// for the address this call comes from. A connector of the same kind for the same bunq user is replaced (that
// is how a key is renewed); one of the other kind (API key against OAuth) is refused, as every account would
// then be listed twice.
static BunqConnector& Create(std::string&& apiKey, std::string_view allowedIps, BunqEnvironment environment);
// Forgets a connector: deletes its stored transactions and takes it out of `connectors`, keeping the other
// connectors' accounts pointing at their connector. Does not log out; call Logout first.
static void Remove(BunqConnector& connector);
static BunqEnvironment EnvironmentOfKey(std::string_view apiKey);
// OAuth: send the user to this URL, where they approve with the bunq app; bunq then redirects to
// `redirectUri` with `code` and `state` in the query. `redirectUri` must be registered with the OAuth client.
static std::string OAuthAuthorizationUrl(BunqEnvironment environment, std::string_view clientId, std::string_view redirectUri, std::string_view state);
// Exchanges the code from that redirect for an access token, which Create takes in place of an API key.
static std::string OAuthExchangeCode(BunqEnvironment environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code);
// Where API calls for `environment` go: bunq's own host, or wherever RedirectTo sent them.
static BunqEndpoint Endpoint(BunqEnvironment environment);
// Sends every API and OAuth token call, whatever the connector's environment, to `endpoint` from now on.
// For tests against a local server; nostro itself never calls it.
static void RedirectTo(BunqEndpoint endpoint);
using Account = BunqAccount;
private:
enum class Auth : std::uint8_t { None, Installation, Session };
nlohmann::json Call(std::string_view method, std::string_view path, const nlohmann::json* body, Auth auth, bool renew = true);
void ReadUser(const nlohmann::json& response);
void EnsureServerPublicKey();
bool fetchingServerKey = false;
};
void to_json(nlohmann::json& j, const BunqConnector& connector);
void from_json(const nlohmann::json& j, BunqConnector& connector);
// Shared by the implementation units; not exported.
namespace BunqJson {
// The object under `key` in a response's "Response" array.
nlohmann::json Item(const nlohmann::json& response, std::string_view key);
// The single object inside an item, such as the MonetaryAccountBank in {"MonetaryAccountBank": {...}}, with its key.
std::pair<std::string, const nlohmann::json*> Only(const nlohmann::json& item);
nlohmann::json Amount(std::int64_t amount, Currency currency);
nlohmann::json Pointer(const BunqCounterparty& counterparty);
std::pair<Currency, std::int64_t> ReadAmount(const nlohmann::json& amount);
BunqLabel ReadLabel(const nlohmann::json& label);
std::string String(const nlohmann::json& object, std::string_view key);
}
}
template<>
@ -62,4 +281,74 @@ struct std::formatter<Nostro::BunqConnector> : std::formatter<std::string> {
}
};
#endif
template<>
struct std::formatter<Nostro::BunqLabel> : std::formatter<std::string> {
auto format(const Nostro::BunqLabel& obj, std::format_context& ctx) const {
return std::formatter<std::string>::format(obj.iban.empty() ? obj.name : std::format("{} {}", obj.name, obj.iban), ctx);
}
};
template<>
struct std::formatter<Nostro::BunqPaymentRequest> : std::formatter<std::string> {
auto format(const Nostro::BunqPaymentRequest& obj, std::format_context& ctx) const {
std::string out = std::format("{}\t{}\t{}\t{}\t{}", obj.id, Nostro::FormatLocalTime(obj.created), obj.status, obj.counterparty, Nostro::FormatMoney(obj.amount, obj.currency));
if(obj.amountPaid && *obj.amountPaid != obj.amount) {
out += std::format(" (paid {})", Nostro::FormatMoney(*obj.amountPaid, obj.currency));
}
out += std::format("\t{}", obj.description);
if(!obj.shareUrl.empty()) {
out += std::format("\t{}", obj.shareUrl);
}
return std::formatter<std::string>::format(out, ctx);
}
};
template<>
struct std::formatter<Nostro::BunqIncomingRequest> : std::formatter<std::string> {
auto format(const Nostro::BunqIncomingRequest& obj, std::format_context& ctx) const {
return std::formatter<std::string>::format(std::format("{}\t{}\t{}\t{}\t{}\t{}\t{}", obj.id, Nostro::FormatLocalTime(obj.created), obj.status, obj.type, obj.counterparty, Nostro::FormatMoney(obj.amount, obj.currency), obj.description), ctx);
}
};
template<>
struct std::formatter<Nostro::BunqScheduledPayment> : std::formatter<std::string> {
auto format(const Nostro::BunqScheduledPayment& obj, std::format_context& ctx) const {
const Nostro::BunqSchedule& schedule = obj.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, Nostro::FormatLocalTime(schedule.start)) : std::format("every {} {} from {}", schedule.every, unit->second.second, Nostro::FormatLocalTime(schedule.start));
} else {
when = std::format("once on {}", Nostro::FormatLocalTime(schedule.start));
}
if(schedule.end) {
when += std::format(" until {}", Nostro::FormatLocalTime(*schedule.end));
}
if(schedule.next && schedule.status == "ACTIVE") {
when += std::format(", next {}", Nostro::FormatLocalTime(*schedule.next));
}
return std::formatter<std::string>::format(std::format("{}\t{}\t{}\t{}\t{}\t{}", obj.id, schedule.status, when, obj.counterparty, Nostro::FormatMoney(obj.amount, obj.currency), obj.description), ctx);
}
};
template<>
struct std::formatter<Nostro::BunqDraftPayment> : std::formatter<std::string> {
auto format(const Nostro::BunqDraftPayment& obj, std::format_context& ctx) const {
std::string out = std::format("{}\t{}\t{}", obj.id, obj.status, obj.createdBy);
for(const Nostro::BunqDraftPayment::Entry& entry : obj.entries) {
out += std::format("\n\t{}\t{}\t{}", entry.counterparty, Nostro::FormatMoney(entry.amount, entry.currency), entry.description);
}
return std::formatter<std::string>::format(out, ctx);
}
};
template<>
struct std::formatter<Nostro::BunqCard> : std::formatter<std::string> {
auto format(const Nostro::BunqCard& obj, std::format_context& ctx) const {
return std::formatter<std::string>::format(std::format("{}\t{}\t{}\t**** {}\t{}\t{}\t{}\texpires {}", obj.id, obj.status, obj.productType, obj.lastFour, obj.nameOnCard, obj.secondLine, obj.iban, obj.expiry), ctx);
}
};
#endif

295
interfaces/Nostro-Bus.cppm Normal file
View file

@ -0,0 +1,295 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#ifdef NOSTRO_DBUS_ENABLED
#include <systemd/sd-bus.h>
#endif
export module Nostro:Bus;
#ifdef NOSTRO_DBUS_ENABLED
import std;
import Nostro.Checkout;
import :Account;
import :Bunq;
import :Currency;
import :Transaction;
// The wire between nostrod and its clients: the names, the methods and their signatures, the errors, the polkit
// actions, and how each type travels. The daemon and the client both build on it, so the two cannot disagree.
namespace Nostro {
// What Connectors() reports of one connector.
export struct ConnectorSummary {
std::string name;
std::string bank; // its connectorId: "bunq"
std::string environment; // "production" or "sandbox"
std::string auth; // "api key" or "oauth"
bool working = false; // whether a call to the bank worked just now
};
// What AddBunq() and AddBunqOAuth() report of the connector they added.
export struct AddedConnector {
std::string name;
std::string environment;
std::uint32_t accounts = 0;
};
// One connector's accounts, as Accounts() lists them.
export struct ConnectorAccounts {
std::string name;
std::string bank;
std::vector<Account> accounts;
};
// One connector's cards, as Cards() lists them.
export struct ConnectorCards {
std::string name;
std::string bank;
std::vector<BunqCard> cards;
};
// What Send(), Schedule() and Draft() made: bunq's id for it, and the currency its amount was in.
export struct Created {
std::uint64_t id = 0;
Currency currency = Currency::Euro;
};
}
export namespace Nostro::Bus {
// String views of literals, so `.data()` is NUL-terminated as sd-bus wants it.
inline constexpr std::string_view busName = "net.catcrafts.Nostro1";
inline constexpr std::string_view objectPath = "/net/catcrafts/Nostro1";
inline constexpr std::string_view interfaceName = "net.catcrafts.Nostro1";
// What nostrod answers with besides the standard AccessDenied and InteractiveAuthorizationRequired. The ones an app
// at checkout tells apart too are Nostro.Checkout's.
inline constexpr std::string_view errorInvalidArgument = Checkout::errorInvalidArgument; // refused before anything was sent
inline constexpr std::string_view errorBank = Checkout::errorBank; // the bank answered with an error
inline constexpr std::string_view errorOAuthCannotPay = "net.catcrafts.Nostro1.Error.OAuthCannotPay"; // bunq refused to pay through an OAuth connector
inline constexpr std::string_view errorCancelled = Checkout::errorCancelled; // the user did not authenticate at the prompt
inline constexpr std::string_view errorNoCheckoutAccount = Checkout::errorNoCheckoutAccount; // a checkout, and no account chosen to pay it
inline constexpr std::string_view errorFailed = Checkout::errorFailed; // anything else
// The polkit actions, declared in packaging/system/net.catcrafts.Nostro1.policy.
inline constexpr std::string_view actionView = "net.catcrafts.Nostro1.View";
inline constexpr std::string_view actionChange = "net.catcrafts.Nostro1.Change";
inline constexpr std::string_view actionPay = "net.catcrafts.Nostro1.Pay";
inline constexpr std::string_view actionUnfreezeCard = "net.catcrafts.Nostro1.UnfreezeCard";
inline constexpr std::string_view actionBlockCard = "net.catcrafts.Nostro1.BlockCard";
inline constexpr std::string_view actionConnectors = "net.catcrafts.Nostro1.Connectors";
inline constexpr std::string_view actionCheckout = "net.catcrafts.Nostro1.Checkout";
}
using namespace std::string_view_literals;
namespace Nostro::Bus {
// One method of the interface. Every reply ends with `as notes`: the library's warnings during the call.
struct Method {
std::string_view member;
std::string_view in; // the arguments' signature
std::string_view out; // the reply's
std::string_view names; // the arguments' names, then the reply's, each ended by a NUL
bool sensitive = false; // carries a secret: sd-bus wipes the message when it frees it
};
// The interface, in the order introspection lists it. The front and the workers build their vtables from it.
inline constexpr std::array methods = {
Method{"Connectors", "", "a(ssssb)as", "connectors\0notes\0"sv},
Method{"AddBunq", "sss", "ssuas", "apiKey\0allowedIps\0environment\0name\0addedEnvironment\0accounts\0notes\0"sv, true},
Method{"AddBunqOAuth", "sssss", "ssuas", "environment\0clientId\0clientSecret\0redirectUri\0code\0name\0addedEnvironment\0accounts\0notes\0"sv, true},
Method{"RemoveConnector", "s", "sas", "connector\0name\0notes\0"sv},
Method{"Accounts", "", "a(ssa(ssssx))as", "connectors\0notes\0"sv},
Method{"Transactions", "sa{sv}", "a(sssssxxss)as", "account\0query\0transactions\0notes\0"sv},
Method{"Send", "sssxs", "tsas", "account\0to\0name\0amount\0description\0id\0currency\0notes\0"sv},
Method{"Schedule", "sssxs(xaxsusax)", "tsas", "account\0to\0name\0amount\0description\0schedule\0id\0currency\0notes\0"sv},
Method{"Request", "sssxs", "(ts(ss)sxaxsxs)as", "account\0from\0name\0amount\0description\0request\0notes\0"sv},
Method{"Requests", "s", "a(ts(ss)sxaxsxs)as", "account\0requests\0notes\0"sv},
Method{"RevokeRequest", "st", "as", "account\0id\0notes\0"sv},
Method{"IncomingRequests", "s", "a(tss(ss)sxsx)as", "account\0requests\0notes\0"sv},
Method{"RespondToRequest", "stb", "as", "account\0id\0accept\0notes\0"sv},
Method{"ScheduledPayments", "s", "a(t(ss)sxs(xaxsusax))as", "account\0scheduled\0notes\0"sv},
Method{"CancelScheduledPayment", "st", "as", "account\0id\0notes\0"sv},
Method{"Draft", "sssxs", "tsas", "account\0to\0name\0amount\0description\0id\0currency\0notes\0"sv},
Method{"DraftPayments", "s", "a(tssa((ss)sxs)s)as", "account\0drafts\0notes\0"sv},
Method{"RespondToDraftPayment", "stb", "as", "account\0id\0accept\0notes\0"sv},
Method{"Cards", "", "a(ssa(tsssssssss))as", "connectors\0notes\0"sv},
Method{"SetCardStatus", "ts", "(tsssssssss)as", "card\0status\0updated\0notes\0"sv},
Method{"DefaultCheckoutAccount", "", "a(ssssx)as", "account\0notes\0"sv},
Method{"SetDefaultCheckoutAccount", "s", "(ssssx)as", "account\0chosen\0notes\0"sv},
};
// net.catcrafts.Nostro1.Checkout, which nostrod serves under a bus name of its own (Checkout::busName). Its reply
// carries no notes: they are the user's, and the app that asks is someone else.
inline constexpr std::array checkoutMethods = {
Method{"Pay", Checkout::payArguments, Checkout::payReply, Checkout::payNames},
};
// Throws a std::system_error naming `what` when an sd-bus call returned a negative errno; returns the result.
std::int32_t ThrowOnSdBus(std::int32_t result, std::string_view what);
// The header fields and error texts sd-bus hands out as C strings, as strings: empty when there are none.
std::string Sender(sd_bus_message* message);
std::string Interface(sd_bus_message* message);
std::string Member(sd_bus_message* message);
std::string ErrorName(const sd_bus_error& error);
std::string ErrorMessage(const sd_bus_error& error);
// Whether `member` carries a secret (Method::sensitive).
bool IsSensitive(std::string_view member);
// A string, or an object path ('o'), read as text.
std::string ReadText(sd_bus_message* message, char type);
struct BusUnref {
void operator()(sd_bus* bus) const;
};
using BusPtr = std::unique_ptr<sd_bus, BusUnref>;
struct MessageUnref {
void operator()(sd_bus_message* message) const;
};
using MessagePtr = std::unique_ptr<sd_bus_message, MessageUnref>;
// An sd_bus_error that frees itself.
struct Error {
sd_bus_error error = SD_BUS_ERROR_NULL;
Error() = default;
Error(const Error&) = delete;
Error& operator=(const Error&) = delete;
~Error();
};
// A vtable of every method of `table` (methods or checkoutMethods), all of them unprivileged (polkit decides, not
// sd-bus), each handled by `handler(member)`. It must outlive the object it is registered for.
std::vector<sd_bus_vtable> Vtable(std::span<const Method> table, const std::function<sd_bus_message_handler_t(std::string_view member)>& handler);
// Enters a container, or throws when the message holds something else there.
void Enter(sd_bus_message* message, char type, std::string_view contents);
void Leave(sd_bus_message* message);
// Opens and closes a container to append to.
void Open(sd_bus_message* message, char type, std::string_view contents);
void Close(sd_bus_message* message);
// How a type travels: its signature, and how it is appended to a message and read from one. A struct also has
// its `contents`, the signature without the parentheses.
template<typename T> struct Wire;
template<> struct Wire<std::string> {
static constexpr std::string_view signature = "s";
static void Append(sd_bus_message* message, const std::string& value);
static std::string Read(sd_bus_message* message);
};
template<> struct Wire<bool> {
static constexpr std::string_view signature = "b";
static void Append(sd_bus_message* message, bool value);
static bool Read(sd_bus_message* message);
};
template<> struct Wire<std::uint32_t> {
static constexpr std::string_view signature = "u";
static void Append(sd_bus_message* message, std::uint32_t value);
static std::uint32_t Read(sd_bus_message* message);
};
template<> struct Wire<std::int64_t> {
static constexpr std::string_view signature = "x";
static void Append(sd_bus_message* message, std::int64_t value);
static std::int64_t Read(sd_bus_message* message);
};
template<> struct Wire<std::uint64_t> {
static constexpr std::string_view signature = "t";
static void Append(sd_bus_message* message, std::uint64_t value);
static std::uint64_t Read(sd_bus_message* message);
};
// Microseconds since the epoch, UTC.
template<> struct Wire<std::chrono::system_clock::time_point> {
static constexpr std::string_view signature = "x";
static void Append(sd_bus_message* message, std::chrono::system_clock::time_point value);
static std::chrono::system_clock::time_point Read(sd_bus_message* message);
};
// Its ISO code.
template<> struct Wire<Currency> {
static constexpr std::string_view signature = "s";
static void Append(sd_bus_message* message, Currency value);
static Currency Read(sd_bus_message* message);
};
// An array.
template<typename T> struct Wire<std::vector<T>> {
static void Append(sd_bus_message* message, const std::vector<T>& values) {
Open(message, 'a', Wire<T>::signature);
for(const T& value : values) {
Wire<T>::Append(message, value);
}
Close(message);
}
static std::vector<T> Read(sd_bus_message* message) {
Enter(message, 'a', Wire<T>::signature);
std::vector<T> values;
while(ThrowOnSdBus(sd_bus_message_at_end(message, 0), "read an array") == 0) {
values.push_back(Wire<T>::Read(message));
}
Leave(message);
return values;
}
};
// An array of zero or one: D-Bus has no optional type.
template<typename T> struct Wire<std::optional<T>> {
static void Append(sd_bus_message* message, const std::optional<T>& value) {
Open(message, 'a', Wire<T>::signature);
if(value) {
Wire<T>::Append(message, *value);
}
Close(message);
}
static std::optional<T> Read(sd_bus_message* message) {
Enter(message, 'a', Wire<T>::signature);
std::optional<T> value;
if(ThrowOnSdBus(sd_bus_message_at_end(message, 0), "read an optional value") == 0) {
value = Wire<T>::Read(message);
}
if(ThrowOnSdBus(sd_bus_message_at_end(message, 0), "read an optional value") == 0) {
throw std::runtime_error("an optional value with more than one element");
}
Leave(message);
return value;
}
};
// The structs. Each is declared here and defined in the implementation unit.
#define NOSTRO_BUS_STRUCT(Type, Contents) \
template<> struct Wire<Type> { \
static constexpr std::string_view contents = Contents; \
static constexpr std::string_view signature = "(" Contents ")"; \
static void Append(sd_bus_message* message, const Type& value); \
static Type Read(sd_bus_message* message); \
}
NOSTRO_BUS_STRUCT(Account, "ssssx");
NOSTRO_BUS_STRUCT(Transaction, "sssssxxss");
NOSTRO_BUS_STRUCT(BunqLabel, "ss");
NOSTRO_BUS_STRUCT(BunqPaymentRequest, "ts(ss)sxaxsxs");
NOSTRO_BUS_STRUCT(BunqIncomingRequest, "tss(ss)sxsx");
NOSTRO_BUS_STRUCT(BunqSchedule, "xaxsusax");
NOSTRO_BUS_STRUCT(BunqScheduledPayment, "t(ss)sxs(xaxsusax)");
NOSTRO_BUS_STRUCT(BunqDraftPayment::Entry, "(ss)sxs");
NOSTRO_BUS_STRUCT(BunqDraftPayment, "tssa((ss)sxs)s");
NOSTRO_BUS_STRUCT(BunqCard, "tsssssssss");
NOSTRO_BUS_STRUCT(ConnectorSummary, "ssssb");
NOSTRO_BUS_STRUCT(ConnectorAccounts, "ssa(ssssx)");
NOSTRO_BUS_STRUCT(ConnectorCards, "ssa(tsssssssss)");
#undef NOSTRO_BUS_STRUCT
template<typename T> void Append(sd_bus_message* message, const T& value) {
Wire<T>::Append(message, value);
}
template<typename T> T Read(sd_bus_message* message) {
return Wire<T>::Read(message);
}
// A transaction query, as `a{sv}`: search, amount, from, to and limit, each only when it narrows anything.
// Unknown keys are skipped, so a newer client can ask an older daemon.
void AppendQuery(sd_bus_message* message, const TransactionQuery& query);
TransactionQuery ReadQuery(sd_bus_message* message);
}
#endif

View file

@ -0,0 +1,74 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:Client;
#ifdef NOSTRO_DBUS_ENABLED
import std;
import :Account;
import :Bunq;
import :Bus;
import :Transaction;
namespace Nostro {
// An error nostrod answered with, by its D-Bus name, for the errors a client tells apart: Bus::errorBank,
// Bus::errorOAuthCannotPay, Bus::errorCancelled, org.freedesktop.DBus.Error.AccessDenied and the like. Input
// nostrod refused before doing anything comes as std::invalid_argument instead.
export struct DaemonError : std::runtime_error {
std::string name;
DaemonError(std::string name, const std::string& message);
};
// nostrod over the system bus: each method of its interface (Bus::methods), with nostro's own types. `account` is
// an account's name or IBAN. A call may wait for a password dialog, which nostrod has polkit show, and for the
// bank. The library's warnings during the calls come out of TakeNotes().
export class Client {
public:
// Connects to the system bus; D-Bus starts nostrod with the first call. A call waits up to `timeout` for its
// answer: long enough for the user to type a password, and for the bank's rate limits. Throws when there is
// no system bus.
static Client System(std::chrono::seconds timeout = std::chrono::minutes(10));
std::vector<ConnectorSummary> Connectors();
// `environment` is "production", "sandbox", or empty for the one the key's prefix says.
AddedConnector AddBunq(std::string_view apiKey, std::string_view allowedIps, std::string_view environment);
AddedConnector AddBunqOAuth(std::string_view environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code);
// By name, or by its number in Connectors(); returns the name.
std::string RemoveConnector(std::string_view connector);
std::vector<ConnectorAccounts> Accounts();
// Fetches what is new first, then answers from the stored history.
std::vector<Transaction> Transactions(std::string_view account, const TransactionQuery& query);
Created Send(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description);
Created Schedule(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, const BunqSchedule& schedule);
Created Draft(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description);
BunqPaymentRequest Request(std::string_view account, std::string_view from, std::string_view name, std::int64_t amount, std::string_view description);
std::vector<BunqPaymentRequest> Requests(std::string_view account);
void RevokeRequest(std::string_view account, std::uint64_t id);
std::vector<BunqIncomingRequest> IncomingRequests(std::string_view account);
void RespondToRequest(std::string_view account, std::uint64_t id, bool accept);
std::vector<BunqScheduledPayment> ScheduledPayments(std::string_view account);
void CancelScheduledPayment(std::string_view account, std::uint64_t id);
std::vector<BunqDraftPayment> DraftPayments(std::string_view account);
void RespondToDraftPayment(std::string_view account, std::uint64_t id, bool accept);
std::vector<ConnectorCards> Cards();
// "ACTIVE", "DEACTIVATED", "LOST" or "STOLEN"; returns the card as bunq has it afterwards.
BunqCard SetCardStatus(std::uint64_t card, std::string_view status);
// The account apps' checkouts (Nostro.Checkout) pay from: none until one is chosen, or once it is gone.
std::optional<Account> DefaultCheckoutAccount();
// Chooses it, and returns it. An account reached through OAuth cannot pay a shop, and is refused.
Account SetDefaultCheckoutAccount(std::string_view account);
// The library's warnings from the calls so far, taken out.
std::vector<std::string> TakeNotes();
private:
explicit Client(Bus::BusPtr bus);
Bus::BusPtr bus;
std::vector<std::string> notes;
};
}
#endif

View file

@ -1,14 +1,19 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:Connector;
import std;
namespace Nostro {
// Both take an exclusive lock on connectors.lock in the config directory and hold it until the process ends, so
// a second nostro process waits (saying so through Note) instead of overwriting the first one's changes.
export struct Connector {
// Writes every bank's connectors to connectors.json in the config directory: synced to the disk, then
// renamed over the old file.
static void SaveConnectors();
// Reads connectors.json (a missing file is no connectors yet) and refreshes each connector's accounts. A
// connector whose refresh fails keeps no accounts and is reported through Note, so the others stay usable.
static void LoadConnectors();
};
}

View file

@ -1,5 +1,5 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
@ -14,7 +14,7 @@ export module Nostro:Crypto;
import std;
export namespace Nostro::Crypto {
long ThrowOnOpenssl(long status);
std::int64_t ThrowOnOpenssl(std::int64_t status);
template <typename T>
T* ThrowOnOpenssl(T* pointer) {
@ -25,9 +25,22 @@ export namespace Nostro::Crypto {
return pointer;
}
// A key that frees itself; copies share it.
using Key = std::shared_ptr<EVP_PKEY>;
Key OwnKey(EVP_PKEY* key);
// RSA PKCS#1 v1.5 over SHA-256, base64: what bunq expects in X-Bunq-Client-Signature.
std::string SignBody(EVP_PKEY* privateKey, std::string_view body);
// Checks a base64 signature made as SignBody makes one, with the signer's public key.
bool VerifyBody(EVP_PKEY* publicKey, std::string_view body, std::string_view signature);
// A new 2048-bit RSA key pair and its public half in PEM.
std::tuple<EVP_PKEY*, std::string> CreateKey();
EVP_PKEY* LoadKeyFromPem(std::string_view pem);
EVP_PKEY* LoadPublicKeyFromPem(std::string_view pem);
std::string PrivateKeyToPem(EVP_PKEY* key);
std::string PublicKeyToPem(EVP_PKEY* key);
// `bytes` random bytes from the system's CSPRNG, as lower-case hex.
std::string RandomHex(std::size_t bytes);
};
#endif
#endif

View file

@ -1,5 +1,5 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:Currency;
@ -9,7 +9,27 @@ export namespace Nostro {
enum class Currency : std::uint16_t {
Euro
};
}
namespace Nostro {
struct CurrencyInfo {
std::string_view code;
std::string_view symbol;
std::uint8_t decimals;
};
// What nostro knows of each currency, in the order of Currency's values: a new currency is a value there and a
// row here.
constexpr std::array<CurrencyInfo, 1> currencies = {{
{"EUR", "€", 2},
}};
constexpr const CurrencyInfo& Info(Currency currency) {
return currencies[std::to_underlying(currency)];
}
}
export namespace Nostro {
constexpr Currency GetCurrency(std::string_view name) {
if(name == "EUR" || name == "eur") {
return Currency::Euro;
@ -19,24 +39,15 @@ export namespace Nostro {
}
constexpr std::string_view GetCurrencyCode(Currency code) {
switch(code) {
case Currency::Euro: return "EUR";
}
std::unreachable();
return Info(code).code;
}
constexpr std::string_view GetCurrencySymbol(Currency code) {
switch(code) {
case Currency::Euro: return "€";
}
std::unreachable();
return Info(code).symbol;
}
constexpr std::uint8_t GetCurrencyDecimals(Currency code) {
switch(code) {
case Currency::Euro: return 2;
}
std::unreachable();
return Info(code).decimals;
}
constexpr std::int64_t ParseAmount(std::string_view value, Currency currency) {
@ -91,6 +102,12 @@ export namespace Nostro {
}
return digits;
}
// The amount with its currency's symbol, the sign in front: "-€1.02".
constexpr std::string FormatMoney(std::int64_t minor, Currency currency) {
const std::string amount = FormatAmount(minor, currency);
return amount.starts_with('-') ? std::format("-{}{}", GetCurrencySymbol(currency), amount.substr(1)) : std::format("{}{}", GetCurrencySymbol(currency), amount);
}
}
template<>

View file

@ -0,0 +1,31 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:Daemon;
#ifdef NOSTRO_DBUS_ENABLED
import std;
namespace Nostro {
// How nostrod runs: where it keeps each user's connectors and transactions, and when it lets go.
export struct DaemonOptions {
// Each user's directory is users/<uid> below it.
std::filesystem::path state;
// A worker exits after this long without a call, and the front once no worker is left; the next call starts
// them again, D-Bus activation the front.
std::chrono::seconds idle{300};
// How long a call waits for polkit, the user's password prompt included, before it is refused.
std::chrono::seconds promptTimeout{300};
};
// The front: owns net.catcrafts.Nostro1 on the system bus, works out each caller's uid, and hands every call to
// that uid's worker, started on demand as a process of its own. It holds no connector itself. Returns 0 once it
// was idle with no worker left or the bus went away, after it ended its workers. Throws when it cannot start.
export std::int32_t RunDaemon(const DaemonOptions& options);
// A worker: the library for one user, `uid`, whom logind calls `name`, serving the front over the connected socket
// `fd`. Every call is authorised with polkit before it runs. Returns 0 when it was idle or the front went away.
export std::int32_t RunWorker(std::int32_t fd, std::uint32_t uid, std::string_view name, const DaemonOptions& options);
}
#endif

View file

@ -1,5 +1,5 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:File;
@ -13,7 +13,7 @@ export namespace Nostro {
fs::path configPath = GetConfigPath();
fs::path cachePath = GetCachePath();
void CreatePrivateFile(const fs::path& path);
void WriteString(std::ofstream& file, std::string_view str);
void ReadString(std::ifstream& file, std::string& str);
std::uint16_t SeekString(std::ifstream& file);
// A line from stdin, trimmed. On a terminal the prompt goes to stderr and what is typed is not echoed, so a key
// never sits in the shell's history or in the process's command line. Throws when stdin ends first.
std::string ReadSecret(std::string_view prompt);
}

View file

@ -1,13 +1,15 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:Transaction;
import std;
import :Currency;
import :Utils;
namespace Nostro {
export struct Transaction {
// Version 1 of Transaction, kept so tables written by it migrate when opened. Do not change it.
struct TransactionV1 {
std::string name;
std::string bic;
std::string iban;
@ -16,8 +18,37 @@ namespace Nostro {
std::int64_t amount;
std::chrono::system_clock::time_point timePoint;
Transaction();
Transaction(std::string&& name, std::string&& bic, std::string&& iban, std::string&& description, Currency currency, std::int64_t amount, std::chrono::system_clock::time_point timePoint);
static constexpr std::uint32_t version = 1;
static constexpr auto orderedBy = &TransactionV1::timePoint;
};
// Also the row type of the Crafter.DB transaction tables, so it has to stay an aggregate. The members are the
// on-disk schema: changing them needs a `version` bump (with the old struct as `using Previous`), or existing
// tables are refused when opened.
export struct Transaction {
std::string name;
std::string bic;
std::string iban;
std::string description;
Currency currency;
std::int64_t amount;
std::chrono::system_clock::time_point timePoint;
// The bank's own id for it, so a sync that overlaps the last stored timestamp stores nothing twice.
// Empty for rows stored by version 1.
std::string id;
// The bank's own classification, e.g. bunq's "MASTERCARD/PAYMENT" or "EBA_SDD/SDD". Empty for rows stored by version 1.
std::string kind;
static constexpr std::uint32_t version = 2;
static constexpr auto orderedBy = &Transaction::timePoint;
using Previous = TransactionV1;
};
}
// One line of a transaction list: local time, amount, counterparty, IBAN and description, tab separated.
template<>
struct std::formatter<Nostro::Transaction> : std::formatter<std::string> {
auto format(const Nostro::Transaction& obj, std::format_context& ctx) const {
return std::formatter<std::string>::format(std::format("{}\t{}\t{}\t{}\t{}", Nostro::FormatLocalTime(obj.timePoint), Nostro::FormatMoney(obj.amount, obj.currency), obj.name, obj.iban, obj.description), ctx);
}
};

View file

@ -1,5 +1,5 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro:Utils;
@ -19,8 +19,8 @@ export namespace Nostro {
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (static_cast<unsigned char>(c) < 0x20) {
out += std::format("\\u{:04x}", static_cast<unsigned char>(c));
if (static_cast<std::uint8_t>(c) < 0x20) {
out += std::format("\\u{:04x}", static_cast<std::uint8_t>(c));
} else {
out += c;
}
@ -31,13 +31,11 @@ export namespace Nostro {
constexpr std::chrono::system_clock::time_point ParseTimestamp(std::string_view text) {
const auto field = [text](std::size_t offset, std::size_t length) {
// substr cuts a field that would run past the end short, and the size check refuses it.
const std::string_view digits = text.substr(offset, length);
std::uint32_t value = 0;
const char* const first = text.data() + offset;
if(offset + length > text.size()) {
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
const std::from_chars_result result = std::from_chars(first, first + length, value);
if(result.ec != std::errc() || result.ptr != first + length) {
const std::from_chars_result result = std::from_chars(digits.data(), digits.data() + digits.size(), value);
if(digits.size() != length || result.ec != std::errc() || result.ptr != digits.data() + digits.size()) {
throw std::runtime_error(std::format("malformed timestamp '{}'", text));
}
return value;
@ -66,4 +64,117 @@ export namespace Nostro {
return std::chrono::sys_days(date) + std::chrono::hours(field(11, 2)) + std::chrono::minutes(field(14, 2)) + std::chrono::seconds(field(17, 2)) + std::chrono::microseconds(micros);
}
// The inverse of ParseTimestamp: "YYYY-MM-DD hh:mm:ss.ffffff" in UTC, the format bunq reads and writes.
inline std::string FormatTimestamp(std::chrono::system_clock::time_point time) {
return std::format("{:%Y-%m-%d %H:%M:%S}", std::chrono::floor<std::chrono::microseconds>(time));
}
// "YYYY-MM-DD" or "YYYY-MM-DD hh:mm" in the local time zone, for dates typed by a person, moved `addDays` days on
// by the calendar: ParseLocalDate(day, 1) is the midnight that ends `day`, 23 or 25 hours on when the clocks change.
inline std::chrono::system_clock::time_point ParseLocalDate(std::string_view text, std::int32_t addDays = 0) {
const auto number = [text](std::size_t offset, std::size_t length) {
int value = 0;
const char* const first = text.data() + offset;
const std::from_chars_result result = std::from_chars(first, first + length, value);
if(result.ec != std::errc() || result.ptr != first + length) {
throw std::runtime_error(std::format("'{}' is not a date (YYYY-MM-DD or YYYY-MM-DD hh:mm)", text));
}
return value;
};
const bool hasTime = text.size() == 16;
if((text.size() != 10 && !hasTime) || text[4] != '-' || text[7] != '-' || (hasTime && (text[10] != ' ' || text[13] != ':'))) {
throw std::runtime_error(std::format("'{}' is not a date (YYYY-MM-DD or YYYY-MM-DD hh:mm)", text));
}
std::tm local{};
local.tm_year = number(0, 4) - 1900;
local.tm_mon = number(5, 2) - 1;
local.tm_mday = number(8, 2);
local.tm_hour = hasTime ? number(11, 2) : 0;
local.tm_min = hasTime ? number(14, 2) : 0;
local.tm_isdst = -1;
const std::chrono::year_month_day date(std::chrono::year(local.tm_year + 1900), std::chrono::month(local.tm_mon + 1), std::chrono::day(local.tm_mday));
if(!date.ok() || local.tm_hour > 23 || local.tm_min > 59) {
throw std::runtime_error(std::format("'{}' is not a date (YYYY-MM-DD or YYYY-MM-DD hh:mm)", text));
}
// mktime normalises a day past the month's end, and works out the offset of the day it lands on.
local.tm_mday += addDays;
return std::chrono::system_clock::from_time_t(std::mktime(&local));
}
// "YYYY-MM-DD hh:mm" in the local time zone.
inline std::string FormatLocalTime(std::chrono::system_clock::time_point time) {
const std::time_t seconds = std::chrono::system_clock::to_time_t(time);
const std::tm local = *std::localtime(&seconds);
return std::format("{:04}-{:02}-{:02} {:02}:{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday, local.tm_hour, local.tm_min);
}
// Percent-encodes everything but RFC 3986's unreserved characters, for a query parameter.
constexpr std::string UrlEncode(std::string_view text) {
constexpr std::string_view hex = "0123456789ABCDEF";
std::string out;
for(const char c : text) {
if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' || c == '~') {
out += c;
} else {
const std::uint8_t byte = static_cast<std::uint8_t>(c);
out += '%';
out += hex[byte >> 4];
out += hex[byte & 0xF];
}
}
return out;
}
// Decodes %XX and, as in a query string, '+' for a space. A '%' not followed by two hex digits stays as it is.
constexpr std::string UrlDecode(std::string_view text) {
const auto digit = [](char c) -> std::int32_t {
if(c >= '0' && c <= '9') return c - '0';
if(c >= 'a' && c <= 'f') return c - 'a' + 10;
if(c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
std::string out;
for(std::size_t i = 0; i < text.size(); i++) {
if(text[i] == '+') {
out += ' ';
} else if(text[i] == '%' && i + 2 < text.size() && digit(text[i + 1]) >= 0 && digit(text[i + 2]) >= 0) {
out += static_cast<char>(digit(text[i + 1]) * 16 + digit(text[i + 2]));
i += 2;
} else {
out += text[i];
}
}
return out;
}
// The decoded value of `name` in the query string of `url` (everything between '?' and '#'), if it is there.
constexpr std::optional<std::string> QueryParameter(std::string_view url, std::string_view name) {
const std::size_t question = url.find('?');
if(question == std::string_view::npos) {
return std::nullopt;
}
std::string_view query = url.substr(question + 1);
query = query.substr(0, query.find('#'));
for(const auto part : std::views::split(query, '&')) {
const std::string_view pair(part.begin(), part.end());
const std::size_t equals = pair.find('=');
if(UrlDecode(pair.substr(0, equals)) == name) {
return equals == std::string_view::npos ? std::string() : UrlDecode(pair.substr(equals + 1));
}
}
return std::nullopt;
}
// Where the library's warnings go: a connector that could not be refreshed, an account it skipped, a request made
// but not read back. A line on stderr unless the program replaces it; a daemon sends them to the client that made
// the call instead, as on stderr they would only reach its journal.
std::function<void(std::string_view)> noteSink = [](std::string_view note) {
std::println(std::cerr, "{}", note);
};
// Hands `note` to noteSink.
inline void Note(std::string_view note) {
noteSink(note);
}
}

View file

@ -0,0 +1,73 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro.Checkout;
import std;
// Checkout: how a shop app has the user's nostro pay an order, and nothing else of nostro. nostrod pays the order from
// the account the user chose for checkouts, once the user has confirmed it at a password prompt that shows the order and
// that account; the app never names nor sees an account, and learns only the payment's id. A module of its own, so
// `--product=checkout` builds it without nostro's bank code, OpenSSL, Crafter.Network or Crafter.DB: it needs libsystemd
// alone. Apps in other languages use packaging/dbus/net.catcrafts.Nostro1.Checkout.xml instead.
using namespace std::string_view_literals;
export namespace Nostro::Checkout {
// String views of literals, so `.data()` is NUL-terminated as sd-bus wants it.
inline constexpr std::string_view busName = "net.catcrafts.Nostro1.Checkout";
inline constexpr std::string_view objectPath = "/net/catcrafts/Nostro1";
inline constexpr std::string_view interfaceName = "net.catcrafts.Nostro1.Checkout";
// Pay(payeeIban, payeeName, amount, currency, reference, options) -> (paymentId, results): the arguments' signature,
// the reply's, and their names, each ended by a NUL.
inline constexpr std::string_view payArguments = "ssxssa{sv}";
inline constexpr std::string_view payReply = "ta{sv}";
inline constexpr std::string_view payNames = "payeeIban\0payeeName\0amount\0currency\0reference\0options\0paymentId\0results\0"sv;
// The errors an app tells apart, besides org.freedesktop.DBus.Error.AccessDenied (the system's policy refused),
// ServiceUnknown (no nostro) and InteractiveAuthorizationRequired. nostrod's other interface uses the same names.
inline constexpr std::string_view errorCancelled = "net.catcrafts.Nostro1.Error.Cancelled"; // the user did not confirm: nothing was paid
inline constexpr std::string_view errorNoCheckoutAccount = "net.catcrafts.Nostro1.Error.NoCheckoutAccount"; // the user has no account to pay checkouts from
inline constexpr std::string_view errorInvalidArgument = "net.catcrafts.Nostro1.Error.InvalidArgument"; // refused before anything was paid
inline constexpr std::string_view errorBank = "net.catcrafts.Nostro1.Error.Bank"; // the bank refused
inline constexpr std::string_view errorFailed = "net.catcrafts.Nostro1.Error.Failed"; // anything else
// An order to pay.
struct Order {
std::string payeeIban; // who is paid: an IBAN, the only kind of payee checkout pays
std::string payeeName; // their name, as the bank and the prompt show it
std::int64_t amount = 0; // in the currency's smallest unit: 1250 is 12.50
std::string currency = "EUR"; // ISO 4217
std::string reference; // the order's own number: the payment's description, and what tells orders apart
};
// What became of an order.
struct Paid {
std::uint64_t paymentId = 0; // the bank's id of the payment
bool repeated = false; // paid before, by an earlier call with the same order: nothing was paid now
};
// An error nostrod answered with, by its D-Bus name: errorBank, org.freedesktop.DBus.Error.AccessDenied, ...
struct Error : std::runtime_error {
std::string name;
Error(std::string name, const std::string& message);
};
// The user did not confirm the order: nothing was paid.
struct Cancelled : Error {
using Error::Error;
};
// The user has no account to pay checkouts from (`nostro checkout account <account>` chooses one): nothing was paid.
struct NoCheckoutAccount : Error {
using Error::Error;
};
// Has the user's nostro pay `order`, and waits for it: for nostrod to start, for the user to read the order and
// confirm it with their password, and for the bank, up to `timeout`; so call it off the UI thread. An order is paid
// once: the same payee and reference again, after a timeout or a crash, answers with the first payment
// (Paid::repeated), or waits for it while the user is still at the prompt, and the same reference with another
// amount is refused. Throws Cancelled, NoCheckoutAccount, std::invalid_argument for text that is not UTF-8, and
// Error for the rest; an Error named org.freedesktop.DBus.Error.ServiceUnknown means nostro is not installed.
Paid Pay(const Order& order, std::chrono::seconds timeout = std::chrono::minutes(10));
}

View file

@ -1,5 +1,5 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
export module Nostro;
@ -16,4 +16,9 @@ export import :Bunq;
#endif
#ifdef NOSTRO_OPENSSL_ENABLED
export import :Crypto;
#endif
#ifdef NOSTRO_DBUS_ENABLED
export import :Bus;
export import :Client;
export import :Daemon;
#endif

28
packaging/arch/PKGBUILD Normal file
View file

@ -0,0 +1,28 @@
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#
# The system half of nostro for Arch Linux: nostrod's user, its D-Bus and polkit policies, its systemd unit and the
# nostro command. nostrod and the CLI come from the net.catcrafts.Nostro Flatpak, installed system-wide
# (nostro-system.install says how). pacman's hooks create the user and reload systemd and D-Bus.
# Build in this directory: makepkg -si
pkgname=nostro-system
pkgver=0.1.0
pkgrel=1
pkgdesc="System files for nostro, a banking client for Linux whose daemon runs from a Flatpak"
arch=(any)
license=(LGPL-3.0-only)
depends=(dbus flatpak polkit systemd)
install=nostro-system.install
package() {
local system="$startdir/../system"
install -Dm644 "$system/nostro.sysusers" "$pkgdir/usr/lib/sysusers.d/nostro.conf"
install -Dm644 "$system/net.catcrafts.Nostro1.conf" "$pkgdir/usr/share/dbus-1/system.d/net.catcrafts.Nostro1.conf"
install -Dm644 "$system/net.catcrafts.Nostro1.service" "$pkgdir/usr/share/dbus-1/system-services/net.catcrafts.Nostro1.service"
install -Dm644 "$system/net.catcrafts.Nostro1.Checkout.service" "$pkgdir/usr/share/dbus-1/system-services/net.catcrafts.Nostro1.Checkout.service"
install -Dm644 "$system/net.catcrafts.Nostro1.policy" "$pkgdir/usr/share/polkit-1/actions/net.catcrafts.Nostro1.policy"
install -Dm644 "$system/nostrod.service" "$pkgdir/usr/lib/systemd/system/nostrod.service"
install -Dm755 "$system/nostro" "$pkgdir/usr/bin/nostro"
install -Dm644 "$startdir/../dbus/net.catcrafts.Nostro1.xml" "$pkgdir/usr/share/dbus-1/interfaces/net.catcrafts.Nostro1.xml"
install -Dm644 "$startdir/../dbus/net.catcrafts.Nostro1.Checkout.xml" "$pkgdir/usr/share/dbus-1/interfaces/net.catcrafts.Nostro1.Checkout.xml"
}

View file

@ -0,0 +1,21 @@
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
post_install() {
echo "nostrod and the nostro CLI come from a Flatpak; install it system-wide:"
echo " flatpak install --system net.catcrafts.Nostro.flatpakref"
echo "(packaging/flatpak/ in nostro's source), or from a local build: flatpak install --system <repo> net.catcrafts.Nostro"
}
post_upgrade() {
# A nostrod still running keeps the old files until it ends.
systemctl try-restart nostrod.service
}
pre_remove() {
systemctl stop nostrod.service
}
post_remove() {
echo "The bank connections stay in /var/lib/nostro; remove that directory to forget them, and revoke the API keys in the bank's app."
}

View file

@ -0,0 +1,54 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<!-- SPDX-License-Identifier: LGPL-3.0-only -->
<!-- SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® -->
<!-- nostro's checkout: how an app has the user's nostro pay an order. The bus name net.catcrafts.Nostro1.Checkout on
the system bus, at /net/catcrafts/Nostro1; a Flatpak app asks for it with the finish-arg
system-talk-name=net.catcrafts.Nostro1.Checkout. C++ programs can use the module Nostro.Checkout (nostro built with
product=checkout) instead. A test in nostro keeps this file the interface nostrod serves.
Pay(payeeIban, payeeName, amount, currency, reference, options) returns (paymentId, results)
payeeIban who is paid: an IBAN, the only payee checkout pays
payeeName their name, as the bank and the prompt show it
amount in the currency's smallest unit (1250 is 12.50), more than zero
currency an ISO code: "EUR"
reference the order's own number, not empty: the payment's description, and what tells orders apart
options none yet; keys nostrod does not know are ignored
paymentId the paying bank's id of the payment
results repeated (b): the order was paid by an earlier call, and nothing was paid now. Later versions may
add keys: ignore the ones you do not know.
nostrod pays the order from the account the user chose for checkouts (nostro checkout account), once the user has
confirmed it at a password prompt that shows the amount, the payee, the reference and that account. The app never
names nor sees the account. Allow interactive authorization on the call, make it asynchronously, and give it a
timeout of minutes: the user may take a while.
An order is paid once. Pay with the same payeeIban and reference again, after a timeout or a crash, answers with
the first payment (repeated is true) without asking the user, or waits for the first call while the user is still
at the prompt; the same reference with another amount is refused. A payment id is not a receipt: confirm the money
arrived with your own bank.
Errors:
net.catcrafts.Nostro1.Error.Cancelled the user did not confirm: nothing was paid
net.catcrafts.Nostro1.Error.NoCheckoutAccount the user has no account chosen to pay checkouts from: nothing was paid
net.catcrafts.Nostro1.Error.InvalidArgument the order was refused before anything was paid
net.catcrafts.Nostro1.Error.Bank the bank refused; its message says when it may have paid all the same
net.catcrafts.Nostro1.Error.Failed anything else, such as an earlier call for this order whose outcome was
lost: it may have been paid
org.freedesktop.DBus.Error.AccessDenied the system's policy refused
org.freedesktop.DBus.Error.InteractiveAuthorizationRequired the call did not allow a password prompt
org.freedesktop.DBus.Error.ServiceUnknown nostro is not installed -->
<node>
<interface name="net.catcrafts.Nostro1.Checkout">
<method name="Pay">
<arg type="s" name="payeeIban" direction="in"/>
<arg type="s" name="payeeName" direction="in"/>
<arg type="x" name="amount" direction="in"/>
<arg type="s" name="currency" direction="in"/>
<arg type="s" name="reference" direction="in"/>
<arg type="a{sv}" name="options" direction="in"/>
<arg type="t" name="paymentId" direction="out"/>
<arg type="a{sv}" name="results" direction="out"/>
</method>
</interface>
</node>

View file

@ -0,0 +1,196 @@
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<!-- SPDX-License-Identifier: LGPL-3.0-only -->
<!-- SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® -->
<!-- nostrod's interface: net.catcrafts.Nostro1 on the system bus, at /net/catcrafts/Nostro1. Generate a proxy from
this file (gdbus-codegen, qdbusxml2cpp, zbus-xmlgen); C++ programs can use Nostro::Client instead. A test in nostro
keeps this file the interface nostrod serves.
Every call is answered for the calling user only, and authorised with polkit first
(packaging/system/net.catcrafts.Nostro1.policy): allow interactive authorization on your calls, so the user can be
asked for their password, and give them a timeout of minutes. Every reply ends with `notes`, the warnings the
library gave during the call, to show the user.
Conventions:
account an account's name or IBAN
to, from an IBAN, an e-mail address, or a phone number starting with +
amount in the currency's smallest unit (1250 is 12.50), positive; balances and transactions are negative
when money goes out
currency an ISO code: "EUR"
times x: microseconds since 1970-01-01 00:00 UTC
optionals an array of zero or one element (ax)
Types:
connectors (Connectors) a(ssssb): name, bank ("bunq"), environment ("production" or "sandbox"),
auth ("api key" or "oauth"), whether a call to the bank works now
connectors (Accounts) a(ssa(ssssx)): connector name, bank, accounts: name, BIC, IBAN, currency, balance
query (Transactions) a{sv}, each key optional: search s, amount x, from x, to x, limit t (100)
transactions a(sssssxxss): name, BIC, IBAN, description, currency, amount, time, the bank's
id, the bank's kind ("MASTERCARD/PAYMENT")
schedule (xaxsusax): start, end, unit (ONCE, HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY),
every n units, status (ACTIVE, FINISHED, CANCELLED), next run
request (sent) (ts(ss)sxaxsxs): id, status, counterparty (name, IBAN), currency, amount asked,
amount paid, description, created, bunq.me link
requests (incoming) a(tss(ss)sxsx): id, status, type (INTERNAL, DIRECT_DEBIT, ...), counterparty,
currency, amount, description, created
scheduled a(t(ss)sxs(xaxsusax)): id, counterparty, currency, amount, description, schedule
drafts a(tssa((ss)sxs)s): id, status, created by, entries (counterparty, currency,
amount, description), bunq's time of its last change
cards / updated (tsssssssss): id, kind, product type, status, order status, name on card,
second line, last four digits, expiry, IBAN it pays from
account / chosen (ssssx): the account apps' checkouts pay from (net.catcrafts.Nostro1.Checkout),
as in Accounts; DefaultCheckoutAccount has none until one is chosen, or once
it is gone. An account reached through OAuth cannot pay a shop, and is refused.
Errors, besides org.freedesktop.DBus.Error.AccessDenied (refused, or polkit did not answer) and
org.freedesktop.DBus.Error.InteractiveAuthorizationRequired:
net.catcrafts.Nostro1.Error.InvalidArgument refused before anything was sent
net.catcrafts.Nostro1.Error.Cancelled the user did not authenticate: nothing was done
net.catcrafts.Nostro1.Error.Bank the bank's own refusal
net.catcrafts.Nostro1.Error.OAuthCannotPay an OAuth connection may only pay the user's own accounts
net.catcrafts.Nostro1.Error.NoCheckoutAccount (checkout) no account is chosen to pay checkouts from
net.catcrafts.Nostro1.Error.Failed anything else; a payment that failed this way may have been made -->
<node>
<interface name="net.catcrafts.Nostro1">
<method name="Connectors">
<arg type="a(ssssb)" name="connectors" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="AddBunq">
<arg type="s" name="apiKey" direction="in"/>
<arg type="s" name="allowedIps" direction="in"/>
<arg type="s" name="environment" direction="in"/>
<arg type="s" name="name" direction="out"/>
<arg type="s" name="addedEnvironment" direction="out"/>
<arg type="u" name="accounts" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="AddBunqOAuth">
<arg type="s" name="environment" direction="in"/>
<arg type="s" name="clientId" direction="in"/>
<arg type="s" name="clientSecret" direction="in"/>
<arg type="s" name="redirectUri" direction="in"/>
<arg type="s" name="code" direction="in"/>
<arg type="s" name="name" direction="out"/>
<arg type="s" name="addedEnvironment" direction="out"/>
<arg type="u" name="accounts" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="RemoveConnector">
<arg type="s" name="connector" direction="in"/>
<arg type="s" name="name" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="Accounts">
<arg type="a(ssa(ssssx))" name="connectors" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="Transactions">
<arg type="s" name="account" direction="in"/>
<arg type="a{sv}" name="query" direction="in"/>
<arg type="a(sssssxxss)" name="transactions" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="Send">
<arg type="s" name="account" direction="in"/>
<arg type="s" name="to" direction="in"/>
<arg type="s" name="name" direction="in"/>
<arg type="x" name="amount" direction="in"/>
<arg type="s" name="description" direction="in"/>
<arg type="t" name="id" direction="out"/>
<arg type="s" name="currency" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="Schedule">
<arg type="s" name="account" direction="in"/>
<arg type="s" name="to" direction="in"/>
<arg type="s" name="name" direction="in"/>
<arg type="x" name="amount" direction="in"/>
<arg type="s" name="description" direction="in"/>
<arg type="(xaxsusax)" name="schedule" direction="in"/>
<arg type="t" name="id" direction="out"/>
<arg type="s" name="currency" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="Request">
<arg type="s" name="account" direction="in"/>
<arg type="s" name="from" direction="in"/>
<arg type="s" name="name" direction="in"/>
<arg type="x" name="amount" direction="in"/>
<arg type="s" name="description" direction="in"/>
<arg type="(ts(ss)sxaxsxs)" name="request" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="Requests">
<arg type="s" name="account" direction="in"/>
<arg type="a(ts(ss)sxaxsxs)" name="requests" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="RevokeRequest">
<arg type="s" name="account" direction="in"/>
<arg type="t" name="id" direction="in"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="IncomingRequests">
<arg type="s" name="account" direction="in"/>
<arg type="a(tss(ss)sxsx)" name="requests" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="RespondToRequest">
<arg type="s" name="account" direction="in"/>
<arg type="t" name="id" direction="in"/>
<arg type="b" name="accept" direction="in"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="ScheduledPayments">
<arg type="s" name="account" direction="in"/>
<arg type="a(t(ss)sxs(xaxsusax))" name="scheduled" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="CancelScheduledPayment">
<arg type="s" name="account" direction="in"/>
<arg type="t" name="id" direction="in"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="Draft">
<arg type="s" name="account" direction="in"/>
<arg type="s" name="to" direction="in"/>
<arg type="s" name="name" direction="in"/>
<arg type="x" name="amount" direction="in"/>
<arg type="s" name="description" direction="in"/>
<arg type="t" name="id" direction="out"/>
<arg type="s" name="currency" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="DraftPayments">
<arg type="s" name="account" direction="in"/>
<arg type="a(tssa((ss)sxs)s)" name="drafts" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="RespondToDraftPayment">
<arg type="s" name="account" direction="in"/>
<arg type="t" name="id" direction="in"/>
<arg type="b" name="accept" direction="in"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="Cards">
<arg type="a(ssa(tsssssssss))" name="connectors" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="SetCardStatus">
<arg type="t" name="card" direction="in"/>
<arg type="s" name="status" direction="in"/>
<arg type="(tsssssssss)" name="updated" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="DefaultCheckoutAccount">
<arg type="a(ssssx)" name="account" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
<method name="SetDefaultCheckoutAccount">
<arg type="s" name="account" direction="in"/>
<arg type="(ssssx)" name="chosen" direction="out"/>
<arg type="as" name="notes" direction="out"/>
</method>
</interface>
</node>

View file

@ -0,0 +1,13 @@
[Flatpak Ref]
Title=Nostro
Name=net.catcrafts.Nostro
Branch=stable
Url=https://flatpak.catcrafts.net/repo/
SuggestRemoteName=catcrafts
Homepage=https://catcrafts.net
Comment=Banking client for Linux
Description=nostro and nostrod, its daemon; install it system-wide with the system files from packaging/system
Icon=
RuntimeRepo=https://dl.flathub.org/repo/flathub.flatpakrepo
IsRuntime=false
GPGKey=GPG_KEY_BASE64_PLACEHOLDER

View file

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- SPDX-License-Identifier: CC0-1.0 -->
<component type="console-application">
<id>net.catcrafts.Nostro</id>
<name>Nostro</name>
<summary>Banking client for Linux</summary>
<metadata_license>CC0-1.0</metadata_license>
<project_license>LGPL-3.0-only</project_license>
<developer id="net.catcrafts">
<name>Catcrafts</name>
</developer>
<description>
<p>
Nostro talks to your bank's API directly: accounts, transactions, payments, requests, schedules, draft payments
and cards, for bunq so far. Its daemon, nostrod, runs as a system user of its own and keeps every local user's
bank connections where no program of theirs can read them; the nostro command asks it over the system bus, and
your password is asked for before anything moves money.
</p>
<p>
Apps can have Nostro pay an order at checkout, from an account you chose, once you have confirmed the payment.
</p>
</description>
<provides>
<binary>nostro</binary>
</provides>
<content_rating type="oars-1.1"/>
</component>

View file

@ -0,0 +1,63 @@
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#
# nostro as a Flatpak: the CLI, which is the command, and nostrod, which systemd runs from it as the system user nostro
# (packaging/system/nostrod.service). Install it system-wide, with the system files packaging/system/install.sh or
# packaging/arch/PKGBUILD put in place; a Flatpak cannot install those itself.
#
# Built with crafter-build's own Flatpak as the base app, for its clang 23 and libc++, then stripped back to the two
# binaries and the three C++ runtime libraries they link. libssl, libcrypto and libsystemd come from the Platform.
app-id: net.catcrafts.Nostro
runtime: org.freedesktop.Platform
runtime-version: '26.08'
sdk: org.freedesktop.Sdk
base: net.catcrafts.CrafterBuild
base-version: stable
branch: stable
command: nostro
finish-args:
# nostrod talks to the bank, and to the bus, logind and polkit on the system bus; the CLI talks to nostrod there.
# Nothing else: no files, no session bus. nostrod keeps its state in the service's home, which is its own.
- --share=network
- --socket=system-bus
modules:
- name: nostro
buildsystem: simple
build-options:
# crafter-build fetches Crafter.Network, Crafter.Thread, Crafter.DB and Crafter.LintRules from git, unpinned (see
# AGENTS.md).
build-args:
- --share=network
# A baseline CPU: crafter-build builds for the building machine's own (-march=native) unless told otherwise.
env:
NOSTRO_MARCH: x86-64-v2
arch:
aarch64:
env:
NOSTRO_MARCH: armv8-a
build-commands:
- HOME="$PWD/.home" crafter-build --banks=bunq --march=$NOSTRO_MARCH --mtune=generic
- HOME="$PWD/.home" crafter-build --banks=bunq --product=daemon --march=$NOSTRO_MARCH --mtune=generic
- install -Dm755 "$(ls -t bin/nostro-*/nostro | head -n1)" /app/bin/nostro
- install -Dm755 "$(ls -t bin/nostrod-*/nostrod | head -n1)" /app/bin/nostrod
- install -Dm644 packaging/flatpak/net.catcrafts.Nostro.metainfo.xml -t /app/share/metainfo/
sources:
- type: dir
path: ../..
skip:
- .git
- .home
- bin
- build
cleanup-commands:
# The base app's toolchain is in /app too: keep what nostro needs at run time, its metainfo, and the licenses of what
# it ships: its own, which flatpak-builder recorded, and LLVM's, for libc++, libc++abi and libunwind.
- mkdir -p /var/tmp/keep/bin /var/tmp/keep/lib /var/tmp/keep/share/metainfo /var/tmp/keep/share/licenses
- cp -a /app/bin/nostro /app/bin/nostrod /var/tmp/keep/bin/
- cp -a /app/lib/libc++.so.1* /app/lib/libc++abi.so.1* /app/lib/libunwind.so.1* /var/tmp/keep/lib/
- cp -a /app/share/metainfo/net.catcrafts.Nostro.metainfo.xml /var/tmp/keep/share/metainfo/
- cp -a /app/share/licenses/net.catcrafts.Nostro /var/tmp/keep/share/licenses/
- install -Dm644 /app/share/licenses/net.catcrafts.CrafterBuild/llvm/LICENSE.TXT /var/tmp/keep/share/licenses/net.catcrafts.Nostro/llvm/LICENSE.TXT
- find /app -mindepth 1 -maxdepth 1 -exec rm -rf {} +
- cp -a /var/tmp/keep/. /app/
- rm -rf /var/tmp/keep

42
packaging/system/install.sh Executable file
View file

@ -0,0 +1,42 @@
#!/bin/sh
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#
# Installs nostro for every user of this machine: the system files nostrod needs (its user, its D-Bus and polkit
# policies, its systemd unit, the nostro command) and the net.catcrafts.Nostro Flatpak, system-wide. Run as root.
#
# install.sh the Flatpak from the system remote "catcrafts" (packaging/flatpak/net.catcrafts.Nostro.flatpakref
# sets it up: flatpak install --system net.catcrafts.Nostro.flatpakref)
# install.sh --repo DIR the Flatpak from a local repository, as flatpak-builder --repo=DIR makes one, for testing
#
# Running it again updates. packaging/arch/PKGBUILD installs the same files from a package; uninstall.sh removes them.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
repo=
if [ "${1:-}" = --repo ]; then
repo=$(cd "${2:?--repo needs a directory}" && pwd)
fi
install -Dm644 "$here/nostro.sysusers" /usr/lib/sysusers.d/nostro.conf
systemd-sysusers /usr/lib/sysusers.d/nostro.conf
install -Dm644 "$here/net.catcrafts.Nostro1.conf" /usr/share/dbus-1/system.d/net.catcrafts.Nostro1.conf
install -Dm644 "$here/net.catcrafts.Nostro1.service" /usr/share/dbus-1/system-services/net.catcrafts.Nostro1.service
install -Dm644 "$here/net.catcrafts.Nostro1.Checkout.service" /usr/share/dbus-1/system-services/net.catcrafts.Nostro1.Checkout.service
install -Dm644 "$here/net.catcrafts.Nostro1.policy" /usr/share/polkit-1/actions/net.catcrafts.Nostro1.policy
install -Dm644 "$here/nostrod.service" /etc/systemd/system/nostrod.service
install -Dm755 "$here/nostro" /usr/local/bin/nostro
if [ -n "$repo" ]; then
# A local repository is unsigned: for a build of your own, never for one from elsewhere.
flatpak remote-add --system --if-not-exists --no-gpg-verify nostro-local "file://$repo"
flatpak install --system -y --noninteractive --or-update nostro-local net.catcrafts.Nostro//stable
else
flatpak install --system -y --noninteractive --or-update catcrafts net.catcrafts.Nostro//stable
fi
systemctl daemon-reload
busctl call org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus ReloadConfig
# A nostrod already running keeps the old files until it ends; stop it, and the next call starts the new one.
systemctl try-restart nostrod.service
echo "nostro is installed: nostrod starts with the first call, such as 'nostro connectors add bunq'"

View file

@ -0,0 +1,8 @@
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
# An app's first checkout starts nostrod, through systemd. Install: /usr/share/dbus-1/system-services/
[D-BUS Service]
Name=net.catcrafts.Nostro1.Checkout
Exec=/bin/false
User=nostro
SystemdService=nostrod.service

View file

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
<!-- SPDX-License-Identifier: LGPL-3.0-only -->
<!-- SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® -->
<!-- nostrod owns its two names as the user nostro, and anyone may call them: nostrod answers each caller for their own
bank connections alone, and asks polkit first (net.catcrafts.Nostro1.policy).
Install: /usr/share/dbus-1/system.d/net.catcrafts.Nostro1.conf -->
<busconfig>
<policy user="nostro">
<allow own="net.catcrafts.Nostro1"/>
<allow own="net.catcrafts.Nostro1.Checkout"/>
</policy>
<policy context="default">
<allow send_destination="net.catcrafts.Nostro1"/>
<allow send_destination="net.catcrafts.Nostro1.Checkout"/>
</policy>
</busconfig>

View file

@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?> <!--*-nxml-*-->
<!-- SPDX-License-Identifier: LGPL-3.0-only -->
<!-- SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® -->
<!DOCTYPE policyconfig PUBLIC "-//freedesktop//DTD PolicyKit Policy Configuration 1.0//EN"
"http://www.freedesktop.org/standards/PolicyKit/1/policyconfig.dtd">
<!-- What nostrod (net.catcrafts.Nostro1) asks polkit before it does anything for a caller.
Every action is owned by unix-user:nostro, the user nostrod runs as: polkit lets only root or an action's owner
check a call made by another user, or pass the details the dialog shows. $(summary) is what nostrod read for the
call itself, such as the amount, the payee and the account of a payment; the details amount_minor, currency,
counterparty, account_iban, environment and, at checkout, reference are there for rules (an amount above which an
administrator must approve, say).
No action keeps an authorization: polkit ties a kept one to the calling process, so the CLI would ask every time
anyway. Viewing and the changes that move no money are free in an active session; whatever moves money (an app's
checkout included), unfreezes or blocks a card, or changes the bank connections or the account checkouts pay from
asks for the user's password every time.
Install: /usr/share/polkit-1/actions/net.catcrafts.Nostro1.policy. Tune with rules in /etc/polkit-1/rules.d/. -->
<policyconfig>
<vendor>Catcrafts</vendor>
<action id="net.catcrafts.Nostro1.View">
<description>See your bank accounts, transactions, requests and cards</description>
<message>Authentication is required to $(summary)</message>
<defaults>
<allow_any>auth_self</allow_any>
<allow_inactive>auth_self</allow_inactive>
<allow_active>yes</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.owner">unix-user:nostro</annotate>
</action>
<action id="net.catcrafts.Nostro1.Change">
<description>Ask for money, make draft payments, cancel what is pending, or freeze a card</description>
<message>Authentication is required to $(summary)</message>
<defaults>
<allow_any>auth_self</allow_any>
<allow_inactive>auth_self</allow_inactive>
<allow_active>yes</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.owner">unix-user:nostro</annotate>
</action>
<action id="net.catcrafts.Nostro1.Pay">
<description>Make a payment, schedule one, or accept a request or a draft payment</description>
<message>Authentication is required to $(summary)</message>
<defaults>
<allow_any>auth_self</allow_any>
<allow_inactive>auth_self</allow_inactive>
<allow_active>auth_self</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.owner">unix-user:nostro</annotate>
</action>
<action id="net.catcrafts.Nostro1.UnfreezeCard">
<description>Let a frozen card pay again</description>
<message>Authentication is required to $(summary)</message>
<defaults>
<allow_any>auth_self</allow_any>
<allow_inactive>auth_self</allow_inactive>
<allow_active>auth_self</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.owner">unix-user:nostro</annotate>
</action>
<action id="net.catcrafts.Nostro1.BlockCard">
<description>Report a card lost or stolen, which blocks it for good</description>
<message>Authentication is required to $(summary)</message>
<defaults>
<allow_any>auth_self</allow_any>
<allow_inactive>auth_self</allow_inactive>
<allow_active>auth_self</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.owner">unix-user:nostro</annotate>
</action>
<action id="net.catcrafts.Nostro1.Connectors">
<description>Add or remove a bank connection, or choose the account apps may ask you to pay from</description>
<message>Authentication is required to $(summary)</message>
<defaults>
<allow_any>auth_self</allow_any>
<allow_inactive>auth_self</allow_inactive>
<allow_active>auth_self</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.owner">unix-user:nostro</annotate>
</action>
<action id="net.catcrafts.Nostro1.Checkout">
<description>Pay an order an app asks you to pay</description>
<message>Authentication is required to $(summary)</message>
<defaults>
<allow_any>auth_self</allow_any>
<allow_inactive>auth_self</allow_inactive>
<allow_active>auth_self</allow_active>
</defaults>
<annotate key="org.freedesktop.policykit.owner">unix-user:nostro</annotate>
</action>
</policyconfig>

View file

@ -0,0 +1,8 @@
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
# The first call to nostrod starts it, through systemd. Install: /usr/share/dbus-1/system-services/
[D-BUS Service]
Name=net.catcrafts.Nostro1
Exec=/bin/false
User=nostro
SystemdService=nostrod.service

19
packaging/system/nostro Executable file
View file

@ -0,0 +1,19 @@
#!/bin/sh
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#
# The nostro command: the CLI from the net.catcrafts.Nostro Flatpak, run as you. It asks nostrod over the system bus,
# and your session's polkit agent asks for your password before anything moves money. Install: /usr/bin/nostro (a
# package) or /usr/local/bin/nostro (install.sh).
# Before nostrod, nostro kept the bank's secrets in the user's own home, where every program they run can read them.
# (With XDG_CONFIG_HOME set, it looked in $XDG_CONFIG_HOME/.config/nostro.)
for old in "${XDG_CONFIG_HOME:-$HOME/.config}/nostro/connectors.json" "${XDG_CONFIG_HOME:-$HOME}/.config/nostro/connectors.json"; do
if [ -e "$old" ]; then
echo "nostro: $old is an older nostro's, and holds your bank's API key where any program you run can read it." \
"Revoke that key in the bunq app, add a new one with 'nostro connectors add bunq', and delete the file." >&2
break
fi
done
exec /usr/bin/flatpak run --system net.catcrafts.Nostro//stable "$@"

View file

@ -0,0 +1,5 @@
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
# The user nostrod runs as. A static user rather than systemd's DynamicUser=, which D-Bus policies and polkit's
# action owners could not name. Its home is nostrod's state directory. Install: /usr/lib/sysusers.d/nostro.conf
u nostro - "nostro banking daemon" /var/lib/nostro

View file

@ -0,0 +1,47 @@
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#
# nostrod: every local user's bank connections, one worker process per user, behind net.catcrafts.Nostro1 and
# net.catcrafts.Nostro1.Checkout on the system bus. The first call starts it (D-Bus activation), and it ends by itself
# once idle, so an updated Flatpak takes over at the next call. It runs from the net.catcrafts.Nostro Flatpak as the
# system user nostro, whose home, the state directory, holds the connections: no other user can read it.
#
# The hardening is what bubblewrap, which flatpak runs the daemon in, works under. Not here, because it breaks it:
# RestrictSUIDSGID= (systemd answers openat2() with ENOSYS for it, and bubblewrap 0.13 has no fallback; NoNewPrivileges=
# voids setuid bits anyway), RestrictNamespaces=, and ProtectKernelTunables=, ProtectKernelLogs=, ProtectProc= and
# ProcSubset=, which overmount the /proc bubblewrap mounts its own over.
#
# Install: /etc/systemd/system/nostrod.service (install.sh) or /usr/lib/systemd/system/nostrod.service (a package).
[Unit]
Description=nostro banking daemon
[Service]
Type=dbus
BusName=net.catcrafts.Nostro1
User=nostro
Group=nostro
ExecStart=/usr/bin/flatpak run --system --no-session-bus --die-with-parent --command=nostrod net.catcrafts.Nostro//stable
StateDirectory=nostro
StateDirectoryMode=0700
# flatpak run needs a runtime directory, which a system user does not have.
RuntimeDirectory=nostro
RuntimeDirectoryMode=0700
Environment=XDG_RUNTIME_DIR=/run/nostro
UMask=0077
# A core dump would hold every key the daemon had in memory; nostrod's workers also make themselves undumpable.
LimitCORE=0
NoNewPrivileges=yes
PrivateTmp=yes
PrivateDevices=yes
ProtectSystem=strict
ProtectHome=yes
ProtectClock=yes
ProtectControlGroups=yes
CapabilityBoundingSet=
MemoryDenyWriteExecute=yes
LockPersonality=yes
RestrictRealtime=yes
# AF_NETLINK: bubblewrap brings up loopback in the network namespace of the sandbox flatpak runs ldconfig in.
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
# @mount, unshare and setns: bubblewrap builds the sandbox with them.
SystemCallFilter=@system-service @mount unshare setns

29
packaging/system/uninstall.sh Executable file
View file

@ -0,0 +1,29 @@
#!/bin/sh
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
#
# Removes what install.sh installed. Run as root. Every user's bank connections stay in /var/lib/nostro, for a later
# install to find, unless --purge is given: then they go too, with the user nostro. Revoke the API keys in the bank's app
# as well, since the bank still accepts them.
set -u
systemctl stop nostrod.service 2>/dev/null
flatpak uninstall --system -y --noninteractive net.catcrafts.Nostro 2>/dev/null
flatpak remote-delete --system nostro-local 2>/dev/null
rm -f /usr/share/dbus-1/system.d/net.catcrafts.Nostro1.conf \
/usr/share/dbus-1/system-services/net.catcrafts.Nostro1.service \
/usr/share/dbus-1/system-services/net.catcrafts.Nostro1.Checkout.service \
/usr/share/polkit-1/actions/net.catcrafts.Nostro1.policy \
/etc/systemd/system/nostrod.service \
/usr/local/bin/nostro
systemctl daemon-reload
busctl call org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus ReloadConfig
if [ "${1:-}" = --purge ]; then
rm -rf /var/lib/nostro
rm -f /usr/lib/sysusers.d/nostro.conf
userdel nostro 2>/dev/null
echo "nostro is removed, with every user's bank connections"
else
echo "nostro is removed; the bank connections stay in /var/lib/nostro (uninstall.sh --purge removes them)"
fi

View file

@ -1,16 +1,44 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
import std;
import Crafter.Build;
#pragma crafter dependency "https://forgejo.catcrafts.net/Catcrafts/Crafter.LintRules.git"
import Crafter.LintRules;
namespace fs = std::filesystem;
using namespace Crafter;
// Nostro.Checkout: what a shop app links to have nostrod pay an order, as a library of its own that needs no bank code,
// OpenSSL, Crafter.Network or Crafter.DB, only libsystemd. `--product=checkout` builds it alone; nostrod takes its names
// from it.
static Configuration CheckoutLibrary(std::span<const std::string_view> args, const std::vector<std::string>& compileFlags) {
Configuration checkout;
checkout.path = "./";
checkout.name = "nostro-checkout";
checkout.outputName = "nostro-checkout";
checkout.type = ConfigurationType::LibraryStatic;
checkout.linkFlags.push_back("-lsystemd");
ApplyStandardArgs(checkout, args);
checkout.compileFlags.insert(checkout.compileFlags.end(), compileFlags.begin(), compileFlags.end());
std::array<fs::path, 1> interfaces = {"interfaces/Nostro.Checkout"};
std::array<fs::path, 1> implementations = {"implementations/Nostro.Checkout"};
checkout.GetInterfacesAndImplementations(interfaces, implementations);
LintRules::AddLiteRules(checkout);
return checkout;
}
extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> args) {
constexpr std::string_view bankArgName = "--banks=";
bool lib = false;
bool dbusRequested = false;
bool bunqEnabled = false;
bool coverage = false;
std::string profileRuntime;
constexpr std::string_view profileRuntimeArgName = "--profile-runtime=";
// What a build makes: the CLI by default, "daemon" for nostrod, or "checkout" for the checkout client library.
std::string product;
constexpr std::string_view productArgName = "--product=";
std::vector<std::string> depArgs;
@ -19,6 +47,14 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
for(std::string_view arg : args) {
if(arg == "--lib") {
lib = true;
} else if(arg == "--dbus") {
dbusRequested = true;
} else if(arg.starts_with(productArgName)) {
product = arg.substr(productArgName.size());
} else if(arg == "--coverage") {
coverage = true;
} else if(arg.starts_with(profileRuntimeArgName)) {
profileRuntime = arg.substr(profileRuntimeArgName.size());
} else if(arg.starts_with(bankArgName)) {
for(std::ranges::subrange<std::string_view::iterator> part : std::views::split(arg.substr(bankArgName.size()), ',')) {
std::string_view name(part.begin(), part.end());
@ -34,6 +70,27 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
}
}
// --coverage builds the library, the CLI and the tests with clang's source-based coverage, and every process writes
// its counts where LLVM_PROFILE_FILE says. The flags go to clang's front end so the driver does not link a profile
// runtime by itself: --profile-runtime= names compiler-rt's libclang_rt.profile archive for a toolchain without one.
std::vector<std::string> coverageCompileFlags;
std::vector<std::string> coverageLinkFlags;
if(coverage) {
coverageCompileFlags = {"-Xclang", "-fprofile-instrument=clang", "-Xclang", "-fcoverage-mapping"};
if(profileRuntime.empty()) {
coverageLinkFlags = {"-fprofile-instr-generate"};
} else {
coverageLinkFlags = {profileRuntime, "-Wl,-u,__llvm_profile_runtime"};
}
}
libcfg.compileFlags.insert(libcfg.compileFlags.end(), coverageCompileFlags.begin(), coverageCompileFlags.end());
if(product == "checkout") {
return CheckoutLibrary(args, coverageCompileFlags);
}
if(!product.empty() && product != "daemon") {
throw std::runtime_error(std::format("unknown product '{}' in {}", product, productArgName));
}
if(!bunqEnabled) {
throw std::runtime_error("must enable atleast one bank");
}
@ -44,8 +101,26 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
libcfg.defines.push_back({"NOSTRO_OPENSSL_ENABLED"});
}
// nostrod and the CLI talk over D-Bus (sd-bus, from libsystemd). A consumer building the library alone gets that part
// only when it asks with --dbus, so the library does not make every consumer depend on libsystemd. The wire carries
// bunq's listing types, so it needs bunq.
const bool dbusEnabled = (!lib || dbusRequested) && bunqEnabled;
if(dbusEnabled) {
libcfg.defines.push_back({"NOSTRO_DBUS_ENABLED"});
}
Configuration* checkout = new Configuration(CheckoutLibrary(args, coverageCompileFlags));
// nostro uses Crafter.Network's HTTP/1.1 client alone: --no-quic leaves out msquic, its CMake build, and the runpath
// into the building user's cache that a binary linked against it carries.
std::vector<std::string> networkArgs = depArgs;
networkArgs.emplace_back("--no-quic");
Configuration* network = GitProject({
.source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Crafter.Network.git" },
.args = networkArgs,
});
Configuration* db = GitProject({
.source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Crafter.DB.git" },
.args = depArgs,
});
@ -53,12 +128,18 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
libcfg.name = "nostro";
libcfg.outputName = "nostro";
libcfg.type = ConfigurationType::LibraryStatic;
libcfg.dependencies = {network};
libcfg.dependencies = {network, db};
if(dbusEnabled) {
libcfg.dependencies.push_back(checkout);
}
if(opensslEnabled) {
libcfg.linkFlags.push_back("-lssl");
libcfg.linkFlags.push_back("-lcrypto");
}
if(dbusEnabled) {
libcfg.linkFlags.push_back("-lsystemd");
}
ApplyStandardArgs(libcfg, args);
@ -73,34 +154,65 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
"interfaces/Nostro-Currency",
"interfaces/Nostro-File",
"interfaces/Nostro-Utils",
"interfaces/Nostro-Bus",
"interfaces/Nostro-Client",
"interfaces/Nostro-Daemon",
};
std::vector<fs::path> libImplementations = {
"implementations/Nostro-Account",
"implementations/Nostro-File",
"implementations/Nostro-Transaction",
"implementations/Nostro-Connector"
};
if(bunqEnabled) {
libImplementations.push_back("implementations/Nostro-Bunq");
libImplementations.push_back("implementations/Nostro-Bunq-Payments");
}
if(opensslEnabled) {
libImplementations.push_back("implementations/Nostro-Crypto");
}
if(dbusEnabled) {
libImplementations.push_back("implementations/Nostro-Bus");
libImplementations.push_back("implementations/Nostro-Client");
libImplementations.push_back("implementations/Nostro-Daemon");
libImplementations.push_back("implementations/Nostro-Daemon-Worker");
}
libcfg.GetInterfacesAndImplementations(libInterfaces, libImplementations);
LintRules::AddLiteRules(libcfg);
if(lib) {
return libcfg;
}
// Both executables switch on the same bank and D-Bus flags as the library, and share the one library: two
// configurations exporting the same module in one build are an error.
const auto defines = libcfg.defines;
Configuration* library = new Configuration(std::move(libcfg));
// nostrod: the daemon that holds the connectors and answers the CLI over the system bus.
if(product == "daemon") {
Configuration daemon;
daemon.path = "./";
daemon.name = "nostrod";
daemon.outputName = "nostrod";
daemon.defines = defines;
ApplyStandardArgs(daemon, args);
daemon.compileFlags.insert(daemon.compileFlags.end(), coverageCompileFlags.begin(), coverageCompileFlags.end());
daemon.linkFlags.insert(daemon.linkFlags.end(), coverageLinkFlags.begin(), coverageLinkFlags.end());
daemon.dependencies = { library };
std::array<fs::path, 0> daemonInterfaces = {};
std::array<fs::path, 1> daemonImplementations = {"implementations/nostrod"};
daemon.GetInterfacesAndImplementations(daemonInterfaces, daemonImplementations);
LintRules::AddLiteRules(daemon);
return daemon;
}
Configuration execfg;
execfg.path = "./";
execfg.name = "nostro";
execfg.outputName = "nostro";
// The CLI switches on the same bank flags as the library.
execfg.defines = libcfg.defines;
execfg.defines = defines;
ApplyStandardArgs(execfg, args);
std::array<fs::path, 0> exeInterfaces = {
@ -110,8 +222,36 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
"implementations/main"
};
execfg.dependencies = { new Configuration(std::move(libcfg)) };
execfg.compileFlags.insert(execfg.compileFlags.end(), coverageCompileFlags.begin(), coverageCompileFlags.end());
execfg.linkFlags.insert(execfg.linkFlags.end(), coverageLinkFlags.begin(), coverageLinkFlags.end());
execfg.dependencies = { library };
execfg.GetInterfacesAndImplementations(exeInterfaces, exeImplementations);
// `crafter-build test --banks=bunq`: each test is tests/<Name>/main.cpp, linked against the library. The ones that
// talk to bunq talk to a fake of it on 127.0.0.1 (tests/Support/FakeBunq.inc), never to bunq itself.
constexpr std::array<std::string_view, 9> tests = {
"ShouldHandleMoneyAndText",
"ShouldSignAndVerify",
"ShouldStoreTransactions",
"ShouldKeepFilesPrivate",
"ShouldSaveConnectors",
"ShouldTalkToBunq",
"ShouldMoveMoney",
"ShouldRunCommands",
"ShouldServeEveryUser",
};
for(const std::string_view name : tests) {
TestBuilder test = execfg.AddTest(name).Dependencies({ library, network, db, checkout }).Timeout(std::chrono::seconds(180));
for(const std::string& flag : coverageCompileFlags) {
test.CompileFlag(flag);
}
for(const std::string& flag : coverageLinkFlags) {
test.LinkFlag(flag);
}
}
LintRules::AddLiteRules(execfg);
return execfg;
}

View file

@ -0,0 +1,106 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Currencies and amounts (Nostro:Currency) and the text helpers (Nostro:Utils): every parse with what it refuses,
// every format, and the local-time helpers with a fixed time zone so the expectations hold anywhere.
#include <stdlib.h>
#include <time.h>
import std;
import Nostro;
#include "../Support/Check.inc"
using namespace Nostro;
using Test::Check;
using Test::Equal;
using Test::Throws;
namespace {
void Currencies() {
Check(GetCurrency("EUR") == Currency::Euro, "EUR is the euro");
Check(GetCurrency("eur") == Currency::Euro, "eur is the euro");
Throws([] { GetCurrency("USD"); }, "unsupported currency 'USD'", "an unknown currency is refused");
Equal(GetCurrencyCode(Currency::Euro), std::string_view("EUR"), "code");
Equal(GetCurrencySymbol(Currency::Euro), std::string_view("€"), "symbol");
Equal(GetCurrencyDecimals(Currency::Euro), std::uint8_t{2}, "decimals");
Equal(std::format("{}", Currency::Euro), std::string("€"), "a currency formats as its symbol");
}
void Amounts() {
Equal(ParseAmount("12.50", Currency::Euro), std::int64_t{1250}, "a whole amount with cents");
Equal(ParseAmount("12", Currency::Euro), std::int64_t{1200}, "an amount without a fraction");
Equal(ParseAmount("12.5", Currency::Euro), std::int64_t{1250}, "a fraction shorter than the decimals");
Equal(ParseAmount("-0.05", Currency::Euro), std::int64_t{-5}, "a negative amount");
for(const std::string_view bad : {"", ".5", "-", "1.234", "1a.00", "1.0x", "+1"}) {
Throws([bad] { ParseAmount(bad, Currency::Euro); }, "malformed amount", std::format("'{}' is refused", bad));
}
Equal(FormatAmount(1250, Currency::Euro), std::string("12.50"), "cents format with a point");
Equal(FormatAmount(5, Currency::Euro), std::string("0.05"), "less than a unit gets its leading zeros");
Equal(FormatAmount(0, Currency::Euro), std::string("0.00"), "zero");
Equal(FormatAmount(-5, Currency::Euro), std::string("-0.05"), "a negative amount");
Equal(FormatAmount(std::numeric_limits<std::int64_t>::min(), Currency::Euro), std::string("-92233720368547758.08"), "the most negative amount");
Equal(FormatMoney(-102, Currency::Euro), std::string("-€1.02"), "money puts the sign before the symbol");
Equal(FormatMoney(102, Currency::Euro), std::string("€1.02"), "and no sign when positive");
}
void Escaping() {
Equal(EscB("a\"b\\c\nd\re\tf\x01g"), std::string("a\\\"b\\\\c\\nd\\re\\tf\\u0001g"), "JSON escaping of every kind of character");
}
void Timestamps() {
using namespace std::chrono;
const system_clock::time_point time = sys_days(year(2026) / 10 / 31) + hours(12) + minutes(34) + seconds(56) + microseconds(123456);
Check(ParseTimestamp("2026-10-31 12:34:56.123456") == time, "a timestamp with microseconds");
Check(ParseTimestamp("2026-10-31 12:34:56.1") == time - microseconds(23456), "a short fraction counts in tenths");
Check(ParseTimestamp("2026-10-31 12:34:56") == time - microseconds(123456), "a timestamp without a fraction");
for(const std::string_view bad : {"2026-10-31", "2026/10-31 12:34:56", "2026-10/31 12:34:56", "2026-10-31T12:34:56", "2026-10-31 12-34:56", "2026-10-31 12:34-56", "20x6-10-31 12:34:56", "2026-10-31 12:34:56.", "2026-10-31 12:34:56.1234567", "2026-10-31 12:34:56x1", "2026-02-30 12:34:56", "2026-10-31 12:34:5x"}) {
Throws([bad] { ParseTimestamp(bad); }, "malformed timestamp", std::format("'{}' is refused", bad));
}
Equal(FormatTimestamp(time), std::string("2026-10-31 12:34:56.123456"), "FormatTimestamp is ParseTimestamp's inverse");
}
void LocalTime() {
// Amsterdam: the clocks went back on 2026-10-25, so that day lasted 25 hours.
setenv("TZ", "Europe/Amsterdam", 1);
tzset();
using namespace std::chrono;
Check(ParseLocalDate("2026-10-31") == sys_days(year(2026) / 10 / 30) + hours(23), "a date is local midnight");
Check(ParseLocalDate("2026-10-31 09:30") == sys_days(year(2026) / 10 / 31) + hours(8) + minutes(30), "a date and time is local");
Check(ParseLocalDate("2026-10-25", 1) - ParseLocalDate("2026-10-25") == hours(25), "a day of the clock change counts by the calendar");
Check(ParseLocalDate("2026-10-31", 1) == ParseLocalDate("2026-11-01"), "a day on crosses the month");
for(const std::string_view bad : {"2026-10-3", "2026/10/31", "2026-10-31T09:30", "2026-10-31 09-30", "2026-1x-31", "2026-02-30", "2026-10-31 24:00", "2026-10-31 23:60"}) {
Throws([bad] { ParseLocalDate(bad); }, "is not a date", std::format("'{}' is refused", bad));
}
Equal(FormatLocalTime(sys_days(year(2026) / 10 / 31) + hours(8) + minutes(30)), std::string("2026-10-31 09:30"), "local time format");
}
void Urls() {
Equal(UrlEncode("a-b_c.d~e f/g?h=i&j"), std::string("a-b_c.d~e%20f%2Fg%3Fh%3Di%26j"), "everything but the unreserved characters is encoded");
Equal(UrlEncode("é"), std::string("%C3%A9"), "bytes above 0x7F are encoded one by one");
Equal(UrlDecode("a%20b+c%2Fd%2f"), std::string("a b c/d/"), "percent escapes and a plus decode");
Equal(UrlDecode("100%"), std::string("100%"), "a bare percent stays");
Equal(UrlDecode("%zz%2"), std::string("%zz%2"), "an escape without two hex digits stays");
Equal(UrlDecode("%Aa"), std::string("\xaa"), "hex digits of either case");
const std::string_view url = "https://example.com/cb?code=a%2Bb&state=x+y&empty=&flag#state=fragment";
Equal(QueryParameter(url, "code").value_or("none"), std::string("a+b"), "a parameter is decoded");
Equal(QueryParameter(url, "state").value_or("none"), std::string("x y"), "the fragment is not part of the query");
Equal(QueryParameter(url, "empty").value_or("none"), std::string(""), "an empty value");
Equal(QueryParameter(url, "flag").value_or("none"), std::string(""), "a name without a value");
Check(!QueryParameter(url, "missing"), "a parameter that is not there");
Check(!QueryParameter("https://example.com/cb", "code"), "a URL without a query");
}
}
int main() {
Currencies();
Amounts();
Escaping();
Timestamps();
LocalTime();
Urls();
return Test::Result();
}

View file

@ -0,0 +1,123 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// The file layer (Nostro:File): where the config and cache live, private files and what CreatePrivateFile refuses,
// and ReadSecret from a pipe and from a terminal, where it must not echo.
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <termios.h>
#include <unistd.h>
import std;
import Nostro;
#include "../Support/Check.inc"
using namespace Nostro;
using Test::Check;
using Test::Equal;
using Test::Throws;
namespace fs = std::filesystem;
namespace {
void Paths() {
const std::string home = std::getenv("HOME") ? std::string(std::getenv("HOME")) : std::string();
setenv("XDG_CONFIG_HOME", "/xdg/config", 1);
setenv("XDG_CACHE_HOME", "/xdg/cache", 1);
Equal(GetConfigPath().string(), std::string("/xdg/config/.config/nostro"), "the config path under XDG_CONFIG_HOME");
Equal(GetCachePath().string(), std::string("/xdg/cache/nostro"), "the cache path under XDG_CACHE_HOME");
unsetenv("XDG_CONFIG_HOME");
unsetenv("XDG_CACHE_HOME");
setenv("HOME", "/home/tester", 1);
Equal(GetConfigPath().string(), std::string("/home/tester/.config/nostro"), "the config path under HOME");
Equal(GetCachePath().string(), std::string("/home/tester/.cache/nostro"), "the cache path under HOME");
unsetenv("HOME");
Throws([] { GetConfigPath(); }, "XDG_CONFIG_HOME and HOME not set", "no config path without either variable");
Throws([] { GetCachePath(); }, "XDG_CACHE_HOME and HOME not set", "no cache path without either variable");
setenv("HOME", home.c_str(), 1);
}
std::uint32_t Mode(const fs::path& path) {
struct stat info{};
stat(path.c_str(), &info);
return info.st_mode & 0777;
}
void PrivateFiles(const fs::path& root) {
const fs::path file = root / "a" / "b" / "secret.json";
CreatePrivateFile(file);
Check(fs::is_regular_file(file), "the file is made, with the directories above it");
Equal(Mode(file), std::uint32_t{0600}, "the file is private");
Equal(Mode(file.parent_path()), std::uint32_t{0700}, "and so is its directory");
CreatePrivateFile(file);
Check(fs::is_regular_file(file), "making it again changes nothing");
// Neither the directory nor the file can be made inside a directory that is not writable.
const fs::path locked = root / "locked";
fs::create_directory(locked);
chmod(locked.c_str(), 0500);
Throws<std::system_error>([&locked] { CreatePrivateFile(locked / "inner" / "file"); }, "cannot create", "a directory that cannot be made");
Throws<std::system_error>([&locked] { CreatePrivateFile(locked / "file"); }, "cannot create", "a file that cannot be made");
chmod(locked.c_str(), 0700);
}
// Runs ReadSecret with `input` behind std::cin and something that is no terminal as stdin.
std::string SecretFrom(std::string_view input) {
std::istringstream in{std::string(input)};
std::streambuf* const original = std::cin.rdbuf(in.rdbuf());
std::string secret;
try {
secret = ReadSecret("Key: ");
} catch(...) {
std::cin.rdbuf(original);
throw;
}
std::cin.rdbuf(original);
return secret;
}
void Secrets() {
const std::int32_t saved = dup(STDIN_FILENO);
const std::int32_t null = open("/dev/null", O_RDONLY);
dup2(null, STDIN_FILENO);
Equal(SecretFrom(" my key \r\n"), std::string("my key"), "a secret is trimmed");
Equal(SecretFrom(" \t \n"), std::string(""), "a line of spaces is no secret");
Throws([] { SecretFrom(""); }, "nothing given for 'Key: '", "stdin ending before a line");
// On a terminal the typing is not echoed while it is read, and echoing is back afterwards.
const std::int32_t master = posix_openpt(O_RDWR | O_NOCTTY);
grantpt(master);
unlockpt(master);
std::array<char, 128> name{};
ptsname_r(master, name.data(), name.size());
const std::int32_t terminal = open(name.data(), O_RDWR | O_NOCTTY);
dup2(terminal, STDIN_FILENO);
clearerr(stdin);
std::cin.clear();
const std::string typed = "typed secret\n";
write(master, typed.data(), typed.size());
Equal(ReadSecret("Key: "), std::string("typed secret"), "a secret typed on a terminal");
termios after{};
tcgetattr(STDIN_FILENO, &after);
Check((after.c_lflag & ECHO) != 0, "echoing is back on after reading");
dup2(saved, STDIN_FILENO);
close(terminal);
close(master);
close(null);
close(saved);
clearerr(stdin);
std::cin.clear();
}
}
int main() {
const Test::Directory directory("files");
Paths();
PrivateFiles(directory.path);
Secrets();
return Test::Result();
}

View file

@ -0,0 +1,251 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// Moving money through the bunq connector, against a fake bunq (tests/Support/FakeBunq.inc): counterparties and what
// they refuse, payments, draft payments, scheduled payments, requests both ways, and how each lists and formats.
#include "../../lib/json.hpp"
#include <stdlib.h>
#include <time.h>
import std;
import Nostro;
import Crafter.Network;
#include "../Support/Check.inc"
#include "../Support/FakeBunq.inc"
using namespace Nostro;
using namespace std::chrono;
using Test::Check;
using Test::Equal;
using Test::Throws;
using json = nlohmann::json;
using Fault = Fake::Fault;
namespace {
constexpr std::uint16_t port = 47303;
constexpr std::string_view payerIban = "NL23BUNQ2025123456";
constexpr std::string_view payeeIban = "NL67BUNQ2025654321";
json LastBody(Fake::Bunq& bunq, std::string_view method) {
const std::vector<Fake::Logged> log = bunq.Log();
const auto last = std::ranges::find_if(log.rbegin(), log.rend(), [method](const Fake::Logged& entry) { return entry.method == method; });
return json::parse(last->body);
}
void Counterparties() {
const BunqCounterparty email = BunqCounterparty::Parse(" someone@example.com ", "Someone");
Check(email.type == "EMAIL" && email.value == "someone@example.com" && email.name == "Someone", "an e-mail address, trimmed");
const BunqCounterparty phone = BunqCounterparty::Parse("+31 6-1234 (5678)", "");
Check(phone.type == "PHONE_NUMBER" && phone.value == "+31612345678", "a phone number without its spaces, dashes and brackets");
Throws<std::invalid_argument>([] { BunqCounterparty::Parse("+31x6", ""); }, "is not a phone number", "a phone number with a letter");
Throws<std::invalid_argument>([] { BunqCounterparty::Parse("+3161", ""); }, "is not a phone number", "a phone number too short");
const BunqCounterparty iban = BunqCounterparty::Parse(" nl23 bunq 2025 1234 56 ", "Payer");
Check(iban.type == "IBAN" && iban.value == payerIban, "an IBAN, upper case and without spaces");
for(const std::string_view bad : {"NL23BUNQ2025123457", "NL23BUNQ", "1L23BUNQ2025123456", "N123BUNQ2025123456", "NLX3BUNQ2025123456", "NL2XBUNQ2025123456", "NL23BUNQ2025-23456", "NL23BUNQ20251234561234567890123456"}) {
Throws<std::invalid_argument>([bad] { BunqCounterparty::Parse(bad, ""); }, "is not a valid IBAN", std::format("'{}' is refused", bad));
}
}
void Payments(Fake::Bunq& bunq, BunqAccount& payer, BunqAccount& payee) {
const std::uint64_t id = payer.Send(payeeIban, "Payee", 1250, Currency::Euro, "lunch \"together\"");
Check(id != 0, "a payment gets an id");
const json sent = LastBody(bunq, "POST");
Check(sent.at("amount") == json{{"value", "12.50"}, {"currency", "EUR"}}, "the amount goes as a decimal string");
Check(sent.at("counterparty_alias") == json{{"type", "IBAN"}, {"value", payeeIban}, {"name", "Payee"}}, "the counterparty, with its name");
Equal(sent.at("description").get<std::string>(), std::string("lunch \"together\""), "the description, quotes and all");
Check(bunq.Log().back().signed_ && bunq.Log().back().signatureValid, "a signed payment");
payee.connector->GetNewTransactions(payee);
Equal(payee.FindTransactions(payee.StorageKey(), {}).at(0).amount, std::int64_t{1250}, "the payee gets it");
payer.Send("someone@example.com", "", 100, Currency::Euro, "");
Check(!LastBody(bunq, "POST").at("counterparty_alias").contains("name"), "no name, no name field");
Throws<std::invalid_argument>([&payer] { payer.Send(payeeIban, "Payee", 0, Currency::Euro, ""); }, "more than zero", "nothing to send");
Throws<std::invalid_argument>([&payer] { payer.Send(payeeIban, "Payee", -5, Currency::Euro, ""); }, "more than zero", "a negative amount");
}
void Drafts(Fake::Bunq& bunq, BunqAccount& payer) {
const std::uint64_t accepted = payer.Draft(payeeIban, "Payee", 200, Currency::Euro, "to accept");
const std::uint64_t rejected = payer.Draft(payeeIban, "Payee", 300, Currency::Euro, "to reject");
Check(LastBody(bunq, "POST").at("number_of_required_accepts") == 1, "one accept makes a draft a payment");
std::vector<BunqDraftPayment> drafts = payer.DraftPayments();
Equal(drafts.size(), std::size_t{2}, "both drafts list");
Check(drafts.at(0).id == rejected && drafts.at(0).status == "PENDING" && drafts.at(0).createdBy == "Payer", "newest first, pending, with who made it");
Check(drafts.at(0).entries.size() == 1 && drafts.at(0).entries.at(0).amount == 300 && drafts.at(0).entries.at(0).counterparty.iban == payeeIban, "its entry");
Equal(std::format("{}", drafts.at(0)), std::format("{}\tPENDING\tPayer\n\tPayee {}\t€3.00\tto reject", rejected, payeeIban), "a draft formats with a line per entry");
const std::size_t paid = bunq.Count("POST", "/");
const BunqDraftPayment shown = payer.DraftPayment(accepted);
Check(shown.id == accepted && shown.entries.at(0).amount == 200 && !shown.updated.empty(), "one draft, as bunq has it, with when it last changed");
payer.RespondToDraftPayment(shown, true);
Check(LastBody(bunq, "PUT").at("status") == "ACCEPTED" && LastBody(bunq, "PUT").at("previous_updated_timestamp") == shown.updated, "accepting names the draft as it was shown");
payer.RespondToDraftPayment(payer.DraftPayment(rejected), false);
Equal(LastBody(bunq, "PUT").at("status").get<std::string>(), std::string("REJECTED"), "rejecting");
drafts = payer.DraftPayments();
Check(drafts.at(0).status == "REJECTED" && drafts.at(1).status == "ACCEPTED", "the drafts' new states");
Equal(bunq.Count("POST", "/"), paid, "a response is a PUT, not a new payment");
// A draft bunq lists without an updated time, a creator or entries.
{
std::lock_guard lock(bunq.mutex);
json& draft = bunq.drafts[payer.id].at(0).at("DraftPayment");
draft.erase("updated");
bunq.drafts[payer.id].push_back(json{{"DraftPayment", json{{"id", 1}, {"status", "PENDING"}, {"entries", "none"}}}});
bunq.drafts[payer.id].push_back(json{{"DraftPayment", json{{"id", 3}, {"status", "PENDING"}, {"entries", json::array({json{{"amount", Fake::Amount(250)}, {"counterparty_alias", json{{"display_name", "Positive"}}}}})}}}});
bunq.drafts[payer.id].push_back(json{{"SomethingElse", json{{"id", 2}}}});
}
payer.RespondToDraftPayment(payer.DraftPayment(rejected), false);
Check(!LastBody(bunq, "PUT").contains("previous_updated_timestamp"), "a draft without an updated time is answered without one");
drafts = payer.DraftPayments();
Equal(drafts.size(), std::size_t{4}, "an object that is no draft is skipped");
Check(drafts.at(2).createdBy.empty() && drafts.at(2).entries.empty(), "a draft without a creator or entries");
Check(drafts.at(3).entries.at(0).amount == 250, "an entry bunq lists as positive stays positive");
// A draft that changed after it was shown is refused, not accepted unseen.
const BunqDraftPayment before = payer.DraftPayment(payer.Draft(payeeIban, "Payee", 400, Currency::Euro, "to change"));
{
std::lock_guard lock(bunq.mutex);
json& draft = bunq.drafts[payer.id].at(0).at("DraftPayment");
draft.at("entries").at(0)["amount"] = Fake::Amount(-40000);
draft["updated"] = Fake::Time(999);
}
Throws<BunqError>([&payer, &before] { payer.RespondToDraftPayment(before, true); }, "changed in the meantime", "accepting a draft that changed since it was shown");
}
void Schedules(Fake::Bunq& bunq, BunqAccount& payer) {
const system_clock::time_point start = sys_days(year(2027) / 1 / 1);
const std::uint64_t monthly = payer.Schedule(payeeIban, "Payee", 300, Currency::Euro, "rent", BunqSchedule{.start = start, .end = start + days(365), .unit = "MONTHLY", .every = 1});
const json body = LastBody(bunq, "POST");
Check(body.at("schedule") == json{{"time_start", "2027-01-01 00:00:00.000000"}, {"time_end", "2028-01-01 00:00:00.000000"}, {"recurrence_unit", "MONTHLY"}, {"recurrence_size", 1}}, "the schedule in UTC");
Check(body.at("payment").at("amount") == json{{"value", "3.00"}, {"currency", "EUR"}}, "the payment it makes");
const std::uint64_t weekly = payer.Schedule(payeeIban, "Payee", 400, Currency::Euro, "allowance", BunqSchedule{.start = start, .unit = "WEEKLY", .every = 2});
Check(!LastBody(bunq, "POST").at("schedule").contains("time_end"), "no end, no end time");
Throws<std::invalid_argument>([&] { payer.Schedule(payeeIban, "Payee", 1, Currency::Euro, "", BunqSchedule{.start = start, .unit = "FORTNIGHTLY"}); }, "is not a schedule", "an unknown recurrence");
Throws<std::invalid_argument>([&] { payer.Schedule(payeeIban, "Payee", 1, Currency::Euro, "", BunqSchedule{.start = start, .unit = "DAILY", .every = 0}); }, "at least every 1", "every 0");
std::vector<BunqScheduledPayment> scheduled = payer.ScheduledPayments();
Equal(scheduled.size(), std::size_t{2}, "both schedules list");
Check(scheduled.at(0).id == weekly && scheduled.at(0).amount == 400 && scheduled.at(0).schedule.unit == "WEEKLY" && scheduled.at(0).schedule.every == 2 && !scheduled.at(0).schedule.end, "the weekly one, its amount positive");
Check(scheduled.at(1).id == monthly && scheduled.at(1).schedule.end == start + days(365) && scheduled.at(1).schedule.next == start && scheduled.at(1).schedule.status == "ACTIVE", "the monthly one, with its end and next run");
{
std::lock_guard lock(bunq.mutex);
bunq.scheduledName = "SchedulePayment";
bunq.schedules[payer.id].push_back(json{{"ScheduledPayment", json{{"id", 3}, {"payment", json{{"amount", Fake::Amount(100)}, {"counterparty_alias", json{{"display_name", "Old"}}}}}, {"schedule", json{{"time_start", "2026-01-01 00:00:00"}, {"recurrence_unit", "ONCE"}, {"status", "FINISHED"}}}}}});
}
scheduled = payer.ScheduledPayments();
Equal(scheduled.size(), std::size_t{3}, "listed under the spec's name too");
Check(scheduled.back().schedule.status == "FINISHED" && !scheduled.back().schedule.next && scheduled.back().schedule.every == 1, "a status inside the schedule, no next run, every 1 by default");
Equal(scheduled.back().amount, std::int64_t{100}, "an amount bunq lists as positive stays positive");
payer.CancelScheduledPayment(weekly);
Equal(payer.ScheduledPayments().size(), std::size_t{2}, "a cancelled schedule is gone");
}
void Requests(Fake::Bunq& bunq, BunqAccount& payer, BunqAccount& payee) {
const BunqPaymentRequest asked = payee.Request(payerIban, "Payer", 500, Currency::Euro, "pay me back");
Check(asked.status == "PENDING" && asked.amount == 500 && !asked.amountPaid && asked.shareUrl.starts_with("https://bunq.me/"), "a request, with a bunq.me link");
Check(LastBody(bunq, "POST").at("allow_bunqme") == true, "bunq.me is allowed");
std::vector<BunqIncomingRequest> incoming = payer.IncomingRequests();
Equal(incoming.size(), std::size_t{1}, "the payer sees it");
Check(incoming.at(0).type == "INTERNAL" && incoming.at(0).status == "PENDING" && incoming.at(0).counterparty.iban == payeeIban, "who asks, and how");
const BunqIncomingRequest one = payer.IncomingRequest(incoming.at(0).id);
Check(one.id == incoming.at(0).id && one.amount == 500 && one.counterparty.iban == payeeIban, "one request, as bunq has it");
payer.RespondToRequest(incoming.at(0), true);
Check(LastBody(bunq, "PUT").at("amount_responded") == json{{"value", "5.00"}, {"currency", "EUR"}}, "accepting pays the amount asked");
const BunqPaymentRequest paid = payee.Requests().at(0);
Check(paid.status == "ACCEPTED" && paid.amountPaid == 500, "the asker sees it paid");
payee.Request(payerIban, "Payer", 600, Currency::Euro, "again");
payer.RespondToRequest(payer.IncomingRequests().at(0), false);
Equal(LastBody(bunq, "PUT"), json{{"status", "REJECTED"}}, "rejecting");
const BunqPaymentRequest revoked = payee.Request(payerIban, "Payer", 700, Currency::Euro, "never mind");
payee.RevokeRequest(revoked.id);
Equal(LastBody(bunq, "PUT"), json{{"status", "REVOKED"}}, "revoking");
const std::vector<BunqPaymentRequest> requests = payee.Requests();
Check(requests.at(0).status == "REVOKED" && requests.at(1).status == "REJECTED", "the requests' states");
// A request whose amount changes after it was shown is paid as shown.
payee.Request(payerIban, "Payer", 1000, Currency::Euro, "changes");
const BunqIncomingRequest shown = payer.IncomingRequests().at(0);
{
std::lock_guard lock(bunq.mutex);
bunq.responses[payer.id].at(0).at("RequestResponse")["amount_inquired"] = Fake::Amount(99900);
}
payer.RespondToRequest(shown, true);
Check(LastBody(bunq, "PUT").at("amount_responded") == json{{"value", "10.00"}, {"currency", "EUR"}}, "accepting pays the amount shown, not the one asked since");
// A request that was made but cannot be read back is still the request it is, and says so in a note.
std::vector<std::string> notes;
const std::function<void(std::string_view)> stderrSink = noteSink;
noteSink = [&notes](std::string_view note) { notes.emplace_back(note); };
bunq.Fail(Fault{.method = "GET", .path = std::format("/user/{}/monetary-account/{}/request-inquiry/", payee.connector->id, payee.id), .status = 500, .body = "{}"});
const BunqPaymentRequest unread = payee.Request(payerIban, "Payer", 800, Currency::Euro, "unread");
noteSink = stderrSink;
Check(unread.id != 0 && unread.status == "PENDING" && unread.counterparty.iban == payerIban && unread.shareUrl.empty(), "made, pending, without a link");
Check(notes.size() == 1 && notes.at(0).contains("was made, but reading it back failed"), "the failed read-back goes to the note sink");
bunq.Fail(Fault{.method = "GET", .path = std::format("/user/{}/monetary-account/{}/request-inquiry/", payee.connector->id, payee.id), .status = 500, .body = "{}"});
Check(payee.Request("someone@example.com", "Someone", 900, Currency::Euro, "").counterparty.iban.empty(), "one asked by e-mail has no IBAN");
Throws<std::invalid_argument>([&payee] { payee.Request(payerIban, "Payer", 0, Currency::Euro, ""); }, "more than zero", "asking for nothing");
{
std::lock_guard lock(bunq.mutex);
bunq.inquiries[payee.id].push_back(json{{"RequestInquiry", json{{"id", 1}, {"amount_inquired", Fake::Amount(100)}, {"counterparty_alias", json::object()}}}});
bunq.inquiries[payee.id].push_back(json{{"Other", json{{"id", 2}}}});
}
const BunqPaymentRequest bare = payee.Requests().back();
Check(bare.created == system_clock::time_point() && bare.status.empty(), "a request without a time or status");
}
void Formats() {
const system_clock::time_point at = sys_days(year(2026) / 10 / 31) + hours(9);
Equal(std::format("{}", BunqLabel{"Name", "NL01"}), std::string("Name NL01"), "a label with an IBAN");
Equal(std::format("{}", BunqLabel{"Name", ""}), std::string("Name"), "a label without one");
BunqPaymentRequest request{.id = 1, .status = "ACCEPTED", .counterparty = {"Payer", ""}, .currency = Currency::Euro, .amount = 500, .amountPaid = 500, .description = "pay", .created = at, .shareUrl = ""};
Equal(std::format("{}", request), std::string("1\t2026-10-31 09:00\tACCEPTED\tPayer\t€5.00\tpay"), "a request paid in full");
request.amountPaid = 400;
request.shareUrl = "https://bunq.me/x";
Equal(std::format("{}", request), std::string("1\t2026-10-31 09:00\tACCEPTED\tPayer\t€5.00 (paid €4.00)\tpay\thttps://bunq.me/x"), "a request paid in part, with its link");
const BunqIncomingRequest incoming{.id = 2, .status = "PENDING", .type = "DIRECT_DEBIT", .counterparty = {"Utility", "NL02"}, .currency = Currency::Euro, .amount = 3000, .description = "energy", .created = at};
Equal(std::format("{}", incoming), std::string("2\t2026-10-31 09:00\tPENDING\tDIRECT_DEBIT\tUtility NL02\t€30.00\tenergy"), "an incoming request");
BunqScheduledPayment scheduled{.id = 3, .counterparty = {"Landlord", ""}, .currency = Currency::Euro, .amount = 90000, .description = "rent", .schedule = BunqSchedule{.start = at, .end = std::nullopt, .unit = "ONCE", .every = 1, .status = "ACTIVE", .next = at}};
Equal(std::format("{}", scheduled), std::string("3\tACTIVE\tonce on 2026-10-31 09:00, next 2026-10-31 09:00\tLandlord\t€900.00\trent"), "a payment scheduled once");
scheduled.schedule.unit = "MONTHLY";
scheduled.schedule.end = at + days(1);
scheduled.schedule.status = "FINISHED";
Equal(std::format("{}", scheduled), std::string("3\tFINISHED\tmonthly from 2026-10-31 09:00 until 2026-11-01 09:00\tLandlord\t€900.00\trent"), "a finished monthly one, without its next run");
for(const auto& [unit, words] : std::map<std::string, std::string>{{"HOURLY", "every 3 hours"}, {"DAILY", "every 3 days"}, {"WEEKLY", "every 3 weeks"}, {"MONTHLY", "every 3 months"}, {"YEARLY", "every 3 years"}}) {
scheduled.schedule.unit = unit;
scheduled.schedule.every = 3;
Check(std::format("{}", scheduled).contains(words), std::format("{} every 3 is '{}'", unit, words));
}
}
}
int main() {
const Test::Directory directory("money");
configPath = directory.path / "config";
cachePath = directory.path / "cache";
setenv("TZ", "UTC", 1);
tzset();
Fake::Bunq bunq(port);
bunq.Redirect();
bunq.AddAccount(bunq.AddPerson("Payer", "key-payer"), payerIban, "Payer", 100000);
bunq.AddAccount(bunq.AddPerson("Payee", "key-payee"), payeeIban, "Payee", 0);
BunqConnector::Create("key-payer", "*", BunqEnvironment::Sandbox);
BunqConnector::Create("key-payee", "*", BunqEnvironment::Sandbox);
BunqAccount& payer = BunqConnector::connectors.at(0).accounts.at(0);
BunqAccount& payee = BunqConnector::connectors.at(1).accounts.at(0);
Counterparties();
Payments(bunq, payer, payee);
Drafts(bunq, payer);
Schedules(bunq, payer);
Requests(bunq, payer, payee);
Formats();
return Test::Result();
}

View file

@ -0,0 +1,336 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// The CLI (implementations/main.cpp), compiled into this test with its main renamed and run in-process, against
// nostrod: this executable again, started as a process of its own (nostrod's main is compiled in too), on a fake
// system bus (tests/Support/FakeBus.inc) and a fake bunq (tests/Support/FakeBunq.inc). Every command, with stdin fed in
// and stdout and stderr read back. The OAuth state comes from RAND_bytes, which this test defines over OpenSSL's so it
// can know the state to paste back.
#include "../../lib/json.hpp"
#include <dlfcn.h>
#include <fcntl.h>
#include <poll.h>
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <systemd/sd-bus.h>
#include <systemd/sd-id128.h>
#include <time.h>
#include <unistd.h>
import std;
import Nostro;
import Crafter.Network;
#define main NostroMain
#include "../../implementations/main.cpp"
#undef main
#define main NostrodMain
#include "../../implementations/nostrod.cpp"
#undef main
#include "../Support/Check.inc"
#include "../Support/FakeBunq.inc"
#include "../Support/FakeBus.inc"
namespace {
// The byte the next RAND_bytes call fills its buffer with, once.
std::optional<std::uint8_t> nextRandom;
}
extern "C" int RAND_bytes(unsigned char* buffer, int count) {
if(nextRandom) {
std::fill_n(buffer, count, *nextRandom);
nextRandom.reset();
return 1;
}
static const auto real = reinterpret_cast<int (*)(unsigned char*, int)>(dlsym(RTLD_NEXT, "RAND_bytes"));
return real(buffer, count);
}
using Test::Check;
using Test::Equal;
using json = nlohmann::json;
using Fault = Fake::Fault;
namespace fs = std::filesystem;
namespace {
constexpr std::uint16_t port = 47304;
const std::string annIban = "NL23BUNQ2025123456";
const std::string savingsIban = "NL46BUNQ2025111111";
const std::string bobIban = "NL67BUNQ2025654321";
const std::string carolIban = "NL65BUNQ2025222222";
struct Outcome {
std::int32_t code;
std::string out;
std::string err;
};
fs::path outputs;
std::string Slurp(const fs::path& file) {
std::ifstream in(file, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
// Runs `nostro <args>` with `input` on stdin, and returns its exit status and what it printed.
Outcome Cli(std::vector<std::string> args, std::string_view input = "") {
args.insert(args.begin(), "nostro");
// main's arguments are C strings.
// lint-disable-next-line no-char-pointer
std::vector<char*> argv;
for(std::string& arg : args) {
argv.push_back(arg.data());
}
argv.push_back(nullptr);
std::istringstream in{std::string(input)};
std::streambuf* const original = std::cin.rdbuf(in.rdbuf());
std::cin.clear();
std::fflush(stdout);
const std::int32_t savedOut = dup(STDOUT_FILENO);
const std::int32_t savedErr = dup(STDERR_FILENO);
const std::int32_t out = open((outputs / "out").c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
const std::int32_t err = open((outputs / "err").c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
dup2(out, STDOUT_FILENO);
dup2(err, STDERR_FILENO);
const std::int32_t code = NostroMain(static_cast<std::int32_t>(args.size()), argv.data());
std::fflush(stdout);
dup2(savedOut, STDOUT_FILENO);
dup2(savedErr, STDERR_FILENO);
close(out);
close(err);
close(savedOut);
close(savedErr);
std::cin.rdbuf(original);
return Outcome{code, Slurp(outputs / "out"), Slurp(outputs / "err")};
}
// `nostro <args>` succeeds and prints `part`.
void Works(std::vector<std::string> args, std::string_view part, std::string_view input = "", std::source_location where = std::source_location::current()) {
const std::string command = std::format("nostro {}", args | std::views::join_with(' ') | std::ranges::to<std::string>());
const Outcome outcome = Cli(std::move(args), input);
Test::Check(outcome.code == 0, std::format("{} exits 0, not {}: {}", command, outcome.code, outcome.err), where);
Test::Check(outcome.out.contains(part), std::format("{} prints '{}', not:\n{}", command, part, outcome.out), where);
}
// `nostro <args>` fails and says `part` on stderr.
void Fails(std::vector<std::string> args, std::string_view part, std::string_view input = "", std::source_location where = std::source_location::current()) {
const std::string command = std::format("nostro {}", args | std::views::join_with(' ') | std::ranges::to<std::string>());
const Outcome outcome = Cli(std::move(args), input);
Test::Check(outcome.code == 1, std::format("{} exits 1, not {}", command, outcome.code), where);
Test::Check(outcome.err.contains(part), std::format("{} says '{}', not:\n{}", command, part, outcome.err), where);
}
// The first number in what a command printed after `after`, such as an id.
std::string IdAfter(std::string_view text, std::string_view after) {
const std::size_t at = text.find(after);
std::string id;
for(std::size_t i = at == std::string_view::npos ? text.size() : at + after.size(); i < text.size() && text[i] >= '0' && text[i] <= '9'; i++) {
id += text[i];
}
return id;
}
void Basics() {
const Outcome none = Cli({});
Check(none.code == 1 && none.out.contains("usage:"), "no command prints the usage and fails");
Works({"help"}, "usage:");
Works({"--help"}, "usage:");
const Outcome unknown = Cli({"frobnicate"});
Check(unknown.code == 1 && unknown.err.contains("unknown command 'frobnicate'") && unknown.err.contains("usage:"), "an unknown command");
Fails({"accounts", "--limit"}, "--limit needs a value");
Works({"connectors"}, "");
Works({"accounts"}, "");
}
void Connecting(Fake::Bunq& bunq) {
// The key comes from the prompt, here stdin, never from the command line.
Works({"connectors", "add", "bunq", "--sandbox"}, "added Ann (sandbox, 2 accounts)", "key-ann\n");
Works({"connectors", "add", "bunq", "*"}, "added Bob (production, 1 accounts)", "key-bob\n");
Fails({"connectors", "add", "bunq"}, "nothing given for 'bunq API key: '");
Fails({"connectors", "add"}, "connector type not provided");
Fails({"connectors", "add", "unknown"}, "unknown connector type 'unknown'");
Fails({"connectors", "frob"}, "unknown connectors command 'frob'");
// OAuth: the address the browser lands on is pasted back, and its state must be this run's.
const std::string state(32, '1');
const std::string redirect = "http://127.0.0.1/cb";
Fails({"connectors", "add", "bunq-oauth", bunq.clientId}, "redirect uri not provided");
Fails({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, "no address given", "fake-secret\n");
Fails({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, "bunq did not authorize: access_denied No", std::format("fake-secret\n{}?error=access_denied&error_description=No\n", redirect));
Fails({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, "bunq did not authorize: access_denied", std::format("fake-secret\n{}?error=access_denied\n", redirect));
Fails({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, "has no code= in it", std::format("fake-secret\n{}?state={}\n", redirect, state));
Fails({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, "its state differs", std::format("fake-secret\n{}?code=code-cli&state=other\n", redirect));
nextRandom = 0x11;
const Outcome added = Cli({"connectors", "add", "bunq-oauth", bunq.clientId, redirect, "--sandbox"}, std::format("fake-secret\n{}?code=code-cli&state={}\n", redirect, state));
Check(added.code == 0 && added.out.contains("added Carol through OAuth (sandbox, 1 accounts)"), std::format("an OAuth connection: {}", added.err));
Check(added.out.contains(std::format("https://oauth.sandbox.bunq.com/auth?response_type=code&client_id={}&redirect_uri=http%3A%2F%2F127.0.0.1%2Fcb&state={}", bunq.clientId, state)), "the address to approve at");
Works({"connectors"}, "1\tAnn\tbunq\tsandbox\tapi key\tok");
Works({"connectors"}, "2\tBob\tbunq\tproduction\tapi key\tok");
Works({"connectors"}, "3\tCarol\tbunq\tsandbox\toauth\tok");
Works({"accounts"}, std::format("Ann\tbunq\n\tSavings\tBUNQNL2A {}\t€1.00\n\tMain\tBUNQNL2A {}\t€1000.00", savingsIban, annIban));
}
void History(Fake::Bunq& bunq, std::uint64_t main) {
bunq.AddPayment(main, -250, "Cafe", "", "coffee");
bunq.AddPayment(main, -1000, "Grocer", "", "food");
Works({"transactions", annIban}, "-€10.00\tGrocer\t\tfood");
Works({"transactions", annIban, "--search", "COFFEE", "--amount", "-250", "--from", "2026-10-01", "--to", "2026-10-01", "--limit", "5"}, "-€2.50\tCafe\t\tcoffee");
const Outcome late = Cli({"transactions", annIban, "--to", "2026-10-01 09:00"});
Check(late.code == 0 && late.out.empty(), "a time of day is when the range ends");
Fails({"transactions", annIban, "--limit", "x"}, "limit 'x' is not a whole number");
Fails({"transactions", annIban, "--from", "soon"}, "is not a date");
Fails({"transactions", "Main"}, "2 accounts are called 'Main': use the IBAN");
Fails({"transactions", "Nope"}, "no account is called or has IBAN 'Nope'");
Fails({"transactions"}, "account not provided");
}
void Paying(Fake::Bunq& bunq) {
Works({"send", annIban, std::string(bobIban), "Bob", "1250", "lunch"}, "sent €12.50 to Bob (payment ");
Works({"send", "Savings", std::string(annIban), "Ann", "100"}, "sent €1.00 to Ann");
Fails({"send", annIban, std::string(bobIban), "Bob", "12.50"}, "give it in the smallest unit, 1250 for 12.50");
Fails({"send", annIban, std::string(bobIban), "Bob", "12,50"}, "give it in the smallest unit");
Fails({"send", annIban, std::string(bobIban), "Bob", "lots"}, "amount 'lots' is not a whole number");
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 400, .body = R"({"Error":[{"error_description":"Not enough money."}]})"});
const Outcome refused = Cli({"send", annIban, std::string(bobIban), "Bob", "100"});
Check(refused.code == 1 && refused.err.contains("Not enough money.") && !refused.err.contains("OAuth"), "bunq's refusal, as it is");
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 403, .body = R"({"Error":[{"error_description":"Not allowed for this user."}]})"});
Fails({"send", std::string(carolIban), std::string(bobIban), "Bob", "100"}, "added through OAuth, which can only pay your own accounts");
Works({"draft", annIban, std::string(bobIban), "Bob", "200", "to accept"}, "drafted €2.00 to Bob (draft ");
const std::string draft = IdAfter(Cli({"drafts", annIban}).out, "");
Works({"drafts", annIban}, "PENDING\tAnn");
Works({"drafts", annIban, "accept", draft}, std::format("accepted draft {}", draft));
Works({"draft", annIban, std::string(bobIban), "Bob", "300"}, "drafted €3.00");
Works({"drafts", annIban, "reject", IdAfter(Cli({"drafts", annIban}).out, "")}, "rejected draft");
Fails({"drafts", annIban, "accept"}, "draft id not provided");
Works({"schedule", annIban, std::string(bobIban), "Bob", "300", "2027-01-01", "monthly", "rent", "--every", "2", "--until", "2027-12-31"}, "scheduled €3.00 to Bob (schedule ");
Works({"schedule", annIban, std::string(bobIban), "Bob", "400", "2027-01-01 08:00", "Weekly"}, "scheduled €4.00");
Fails({"schedule", annIban, std::string(bobIban), "Bob", "400", "2027-01-01", "fortnightly"}, "'FORTNIGHTLY' is not a schedule");
Fails({"schedule", annIban, std::string(bobIban), "Bob", "400", "2027-01-01", "daily", "--every", "-1"}, "--every '-1' is not a whole number");
Works({"scheduled", annIban}, "every 2 months from");
const std::string schedule = IdAfter(Cli({"scheduled", annIban}).out, "");
Works({"scheduled", annIban, "cancel", schedule}, std::format("cancelled schedule {}", schedule));
}
void Requesting() {
Works({"request", std::string(bobIban), annIban, "Ann", "500", "pay me back"}, "PENDING\tAnn");
Works({"requests", std::string(bobIban)}, "€5.00\tpay me back\thttps://bunq.me/");
Works({"incoming", annIban}, "PENDING\tINTERNAL\tBob");
const std::string incoming = IdAfter(Cli({"incoming", annIban}).out, "");
Works({"incoming", annIban, "accept", incoming}, std::format("paid request {}", incoming));
Works({"request", std::string(bobIban), annIban, "Ann", "600", "again"}, "PENDING");
Works({"incoming", annIban, "reject", IdAfter(Cli({"incoming", annIban}).out, "")}, "rejected request");
Works({"request", std::string(bobIban), annIban, "Ann", "700"}, "PENDING");
const std::string request = IdAfter(Cli({"requests", std::string(bobIban)}).out, "");
Works({"requests", std::string(bobIban), "revoke", request}, std::format("revoked request {}", request));
Fails({"requests", std::string(bobIban), "revoke", "x"}, "request id 'x' is not a whole number");
}
void Cards(Fake::Bunq& bunq, std::uint64_t ann) {
const std::string card = std::to_string(bunq.AddCard(ann, "ACTIVE"));
Works({"cards"}, std::format("Ann\tbunq\n\t{}\tACTIVE", card));
Works({"cards", "freeze", card}, std::format("card {} is now DEACTIVATED", card));
{
std::lock_guard lock(bunq.mutex);
bunq.cardsActivate = false;
}
Fails({"cards", "unfreeze", card}, std::format("bunq kept card {} DEACTIVATED (its order status is VIRTUAL_DELIVERY)", card));
Works({"cards", "lost", card}, std::format("card {} is now LOST", card));
Fails({"cards", "melt", card}, "unknown card action 'melt'");
Fails({"cards", "freeze", "1"}, "no card has id 1");
Fails({"cards", "freeze"}, "card id not provided");
}
void Checkouts() {
Works({"checkout", "account"}, "no account pays at checkout: `nostro checkout account <account>` chooses one");
Works({"checkout", "account", annIban}, std::format("checkouts pay from Main\tBUNQNL2A {}\t€", annIban));
Works({"checkout", "account"}, std::format("Main\tBUNQNL2A {}", annIban));
Fails({"checkout", "account", std::string(carolIban)}, "is reached through OAuth, which pays only your own accounts");
Fails({"checkout", "accounts"}, "unknown checkout command 'accounts'");
Fails({"checkout"}, "checkout command not provided");
}
void Removing(Fake::Bunq& bunq) {
bunq.AddAccount(bunq.AddPerson("Ann", "key-ann2"), "NL84BUNQ2025333333", "Other", 0);
Works({"connectors", "add", "bunq"}, "added Ann (production", "key-ann2\n");
Fails({"connectors", "remove", "Ann"}, "2 connectors are called 'Ann': use the number");
Fails({"connectors", "remove", "Nobody"}, "no connector is called or numbered 'Nobody'");
Works({"connectors", "remove", "4"}, "removed Ann");
{
std::lock_guard lock(bunq.mutex);
bunq.keys.erase("key-bob");
}
bunq.ExpireSessions();
Works({"connectors"}, "2\tBob\tbunq\tproduction\tapi key\tfailing");
const Outcome listed = Cli({"accounts"});
Check(listed.code == 0 && listed.err.contains("bunq connector 'Bob' is unavailable"), std::format("a connector that does not work is a note: {}", listed.err));
Works({"connectors", "remove", "Bob"}, "removed Bob");
bunq.Fail(Fault{.method = "DELETE", .path = "/session/", .status = 500, .body = "{}"});
const Outcome forced = Cli({"connectors", "remove", "Carol"});
Check(forced.code == 0 && forced.out.contains("removed Carol") && forced.err.contains("could not log out, forgetting the connector anyway"), std::format("a connector that cannot log out is removed anyway: {}", forced.err));
const Outcome left = Cli({"connectors"});
Check(left.out.contains("1\tAnn") && !left.out.contains("Bob") && !left.out.contains("Carol"), "what is left");
}
}
// main's signature is C's.
// lint-disable-next-line no-char-pointer
int main(int argc, char* argv[]) {
// nostrod, and each of its workers, is this executable again.
if(Fake::IsNostrod()) {
Fake::Bunq::RedirectFromEnvironment();
return NostrodMain(argc, argv);
}
const Test::Directory directory("cli");
outputs = directory.path;
setenv("TZ", "UTC", 1);
tzset();
// What nostrod reads from the environment is set before any thread starts.
Fake::Bunq::ExportRedirect(port, directory.path / "bunq.pem");
setenv("DBUS_SYSTEM_BUS_ADDRESS", Fake::Bus::Address(directory.path / "bus").c_str(), 1);
Fake::Bus bus(directory.path / "bus");
{
std::lock_guard lock(bus.mutex);
bus.logindNames[bus.clientUid] = "tester";
}
Fake::Bunq bunq(port);
const std::uint64_t ann = bunq.AddPerson("Ann", "key-ann");
const std::uint64_t annMain = bunq.AddAccount(ann, annIban, "Main", 100000);
bunq.AddAccount(ann, savingsIban, "Savings", 100);
bunq.AddAccount(bunq.AddPerson("Bob", "key-bob"), bobIban, "Main", 0);
const std::uint64_t carol = bunq.AddPerson("Carol", "key-carol");
bunq.AddAccount(carol, carolIban, "Shared", 500);
bunq.AddGrant(carol, "code-cli", "token-carol");
const pid_t nostrod = Fake::StartNostrod({"--state", (directory.path / "state").string()});
Check(bus.WaitForName("net.catcrafts.Nostro1"), "nostrod is on the bus");
Basics();
Connecting(bunq);
History(bunq, annMain);
Paying(bunq);
Requesting();
Cards(bunq, ann);
Checkouts();
Removing(bunq);
bus.Disconnect("net.catcrafts.Nostro1");
Equal(Fake::Wait(nostrod), 0, "nostrod ends when the bus goes");
Check(bus.WaitForName("net.catcrafts.Nostro1.Checkout", false), "and its checkout with it");
return Test::Result();
}

View file

@ -0,0 +1,178 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// connectors.json and its lock (Nostro:Connector), against a fake bunq (tests/Support/FakeBunq.inc): loading what is
// there, what is not and what is broken, saving through a synced rename, and every way the lock and the save can fail.
// A failing flock or fsync cannot be had on demand, so this test defines its own, which the linker takes over libc's:
// they do what the test scripts, and call libc's when there is no script.
#include "../../lib/json.hpp"
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/file.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <unistd.h>
import std;
import Nostro;
import Crafter.Network;
#include "../Support/Check.inc"
#include "../Support/FakeBunq.inc"
namespace {
// What the next calls answer, with the errno they leave, before libc's own calls take over again.
std::deque<std::pair<std::int32_t, std::int32_t>> flockScript;
std::deque<std::pair<std::int32_t, std::int32_t>> fsyncScript;
}
extern "C" int flock(int fd, int operation) {
if(!flockScript.empty()) {
const auto [result, error] = flockScript.front();
flockScript.pop_front();
errno = error;
return result;
}
static const auto real = reinterpret_cast<int (*)(int, int)>(dlsym(RTLD_NEXT, "flock"));
return real(fd, operation);
}
extern "C" int fsync(int fd) {
if(!fsyncScript.empty()) {
const auto [result, error] = fsyncScript.front();
fsyncScript.pop_front();
errno = error;
return result;
}
static const auto real = reinterpret_cast<int (*)(int)>(dlsym(RTLD_NEXT, "fsync"));
return real(fd);
}
using namespace Nostro;
using Test::Check;
using Test::Equal;
using Test::Throws;
using json = nlohmann::json;
namespace fs = std::filesystem;
namespace {
constexpr std::uint16_t port = 47301;
std::string Read(const fs::path& file) {
std::ifstream in(file, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
void Write(const fs::path& file, std::string_view text) {
std::ofstream out(file, std::ios::binary);
out << text;
}
void Locking() {
const fs::path lock = configPath / "connectors.lock";
fs::create_directories(lock);
Throws<std::system_error>([] { Connector::LoadConnectors(); }, "cannot open", "a lock file that cannot be opened");
fs::remove(lock);
flockScript = {{-1, ENOLCK}};
Throws<std::system_error>([] { Connector::LoadConnectors(); }, "cannot lock", "a lock that fails");
flockScript = {{-1, EWOULDBLOCK}, {-1, EINTR}, {-1, ENOLCK}};
Throws<std::system_error>([] { Connector::LoadConnectors(); }, "cannot lock", "a wait for the lock that fails");
Check(flockScript.empty(), "the wait goes on after a signal");
// Held by another process, then free: nostro waits, through a signal, and goes on.
flockScript = {{-1, EWOULDBLOCK}, {-1, EINTR}, {0, 0}};
Connector::LoadConnectors();
Check(flockScript.empty(), "the lock is taken after waiting");
Check(BunqConnector::connectors.empty(), "no file is no connectors");
Connector::LoadConnectors();
Check(flockScript.empty(), "and kept: the next load does not lock again");
}
void Loading(Fake::Bunq& bunq) {
const fs::path file = configPath / "connectors.json";
Write(file, "{ not json");
Throws<std::runtime_error>([] { Connector::LoadConnectors(); }, "is not valid JSON", "a broken file");
// Broken inside a key: the error says where, never what the file holds there.
Write(file, R"({"bunq": [{"privateKey": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADAN)");
std::string cutShort;
try {
Connector::LoadConnectors();
} catch(const std::runtime_error& e) {
cutShort = e.what();
}
Check(cutShort.contains("breaks at byte") && !cutShort.contains("MIIE") && !cutShort.contains("PRIVATE"), std::format("a key cut short is not quoted: {}", cutShort));
Write(file, "{}");
Connector::LoadConnectors();
Check(BunqConnector::connectors.empty(), "a file without bunq's key has no bunq connectors");
bunq.AddAccount(bunq.AddPerson("Saver", "key-saver"), "NL23BUNQ2025123456", "Savings", 100);
BunqConnector::Create("key-saver", "*", BunqEnvironment::Sandbox);
Connector::SaveConnectors();
struct stat info{};
stat(file.c_str(), &info);
Equal(info.st_mode & 0777, std::uint32_t{0600}, "the file is private");
Check(!fs::exists(configPath / std::format("connectors.json.tmp-{}", getpid())), "no temporary file is left");
// A connector whose key bunq no longer knows loads without accounts, beside one that works.
json saved = json::parse(Read(file));
json broken = saved.at("bunq").at(0);
broken["apiKey"] = "revoked";
broken["sessionToken"] = "ended";
saved.at("bunq").push_back(broken);
Write(file, saved.dump());
BunqConnector::connectors.clear();
Connector::LoadConnectors();
Equal(BunqConnector::connectors.size(), std::size_t{2}, "both connectors load");
Equal(BunqConnector::connectors.at(0).accounts.size(), std::size_t{1}, "the working one has its account");
Check(BunqConnector::connectors.at(1).accounts.empty(), "the broken one has none, and the load goes on");
BunqConnector::connectors.pop_back();
Connector::SaveConnectors();
}
void Saving() {
const fs::path file = configPath / "connectors.json";
const std::string before = Read(file);
const fs::path temporary = configPath / std::format("connectors.json.tmp-{}", getpid());
fs::create_directories(temporary);
Throws<std::system_error>([] { Connector::SaveConnectors(); }, "cannot open", "a temporary file that cannot be opened");
fs::remove(temporary);
// A file size limit makes the write fail part way.
signal(SIGXFSZ, SIG_IGN);
rlimit limit{};
getrlimit(RLIMIT_FSIZE, &limit);
const rlimit small{.rlim_cur = 16, .rlim_max = limit.rlim_max};
setrlimit(RLIMIT_FSIZE, &small);
Throws<std::system_error>([] { Connector::SaveConnectors(); }, "cannot write", "a write that fails");
setrlimit(RLIMIT_FSIZE, &limit);
Check(!fs::exists(temporary), "a failed write leaves no temporary file");
fsyncScript = {{-1, EIO}};
Throws<std::system_error>([] { Connector::SaveConnectors(); }, "cannot sync", "a sync that fails");
Check(!fs::exists(temporary), "nor does a failed sync");
Equal(Read(file), before, "and the old file is as it was");
Connector::SaveConnectors();
Check(Read(file) == before, "a save that works writes the same");
}
}
int main() {
const Test::Directory directory("connectors");
configPath = directory.path / "config";
cachePath = directory.path / "cache";
fs::create_directories(configPath);
Fake::Bunq bunq(port);
bunq.Redirect();
Locking();
Loading(bunq);
Saving();
return Test::Result();
}

View file

@ -0,0 +1,813 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// nostrod on a fake system bus (tests/Support/FakeBus.inc) in front of a fake bunq (tests/Support/FakeBunq.inc): the
// daemon and its workers are this executable again (nostrod's main is compiled in), every call goes through
// Nostro::Client or Nostro::Checkout, and the bus plays each user by the uid it gives a connection. Users kept apart, a
// uid handed to a new user, every polkit answer and what the dialog is told, calls that wait on each other or do not,
// checkouts and their retries, workers that die, idle exits, and how each error reaches the client.
#include "../../lib/json.hpp"
#include <poll.h>
#include <signal.h>
#include <spawn.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <systemd/sd-bus.h>
#include <systemd/sd-id128.h>
#include <unistd.h>
import std;
import Nostro;
import Nostro.Checkout;
import Crafter.Network;
#define main NostrodMain
#include "../../implementations/nostrod.cpp"
#undef main
#include "../Support/Check.inc"
#include "../Support/FakeBunq.inc"
#include "../Support/FakeBus.inc"
using namespace Nostro;
using Test::Check;
using Test::Equal;
using Test::Throws;
using json = nlohmann::json;
using Fault = Fake::Fault;
namespace fs = std::filesystem;
namespace {
constexpr std::uint16_t port = 47305;
constexpr std::uint32_t aliceUid = 4242;
constexpr std::uint32_t bobUid = 4343;
constexpr std::string_view name = "net.catcrafts.Nostro1";
constexpr std::string_view checkoutName = "net.catcrafts.Nostro1.Checkout";
const std::string aliceMain = "NL23BUNQ2025123456";
const std::string aliceOther = "NL46BUNQ2025111111";
const std::string closingIban = "NL09BUNQ2025999999";
const std::string lateIban = "NL08BUNQ2025888888";
const std::string bobIban = "NL67BUNQ2025654321";
const std::string carolIban = "NL65BUNQ2025222222";
const std::string daveIban = "NL84BUNQ2025333333";
const std::string briefIban = "NL06BUNQ2025444444";
const std::string shopIban = "NL91ABNA0417164300";
// The users and accounts at the fake bunq.
struct Bank {
std::uint64_t alice = 0;
std::uint64_t aliceMainId = 0;
std::uint64_t closingId = 0;
};
struct Failure {
std::string name;
std::string message;
};
// How `call` failed: the D-Bus name of nostrod's error, "exception" for any other, "none" when it did not fail.
template<typename Call>
Failure FailureOf(Call&& call) {
try {
call();
} catch(const DaemonError& e) {
return Failure{e.name, e.what()};
} catch(const Checkout::Error& e) {
return Failure{e.name, e.what()};
} catch(const std::exception& e) {
return Failure{"exception", e.what()};
}
return Failure{"none", ""};
}
// A client for user `uid`: the fake bus gives each new connection the uid it is set to.
Client As(Fake::Bus& bus, std::uint32_t uid) {
{
std::lock_guard lock(bus.mutex);
bus.clientUid = uid;
}
return Client::System();
}
void SetPolkit(Fake::Bus& bus, Fake::Polkit outcome, std::string_view action = {}) {
std::lock_guard lock(bus.mutex);
if(action.empty()) {
bus.polkit = outcome;
bus.polkitByAction.clear();
} else {
bus.polkitByAction[std::string(action)] = outcome;
}
}
std::string Summary(Fake::Bus& bus) {
const Fake::PolkitCheck check = bus.LastCheck();
return check.details.contains("summary") ? check.details.at("summary") : std::string();
}
std::string Slurp(const fs::path& file) {
std::ifstream in(file);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
// Stops every worker, as systemd stops a service, and waits until nostrod has seen them go.
void KillWorkers(Fake::Bus& bus, pid_t nostrod) {
for(const pid_t pid : bus.Peers()) {
if(pid != nostrod) {
kill(pid, SIGTERM);
}
}
for(std::size_t i = 0; i < 300 && std::ranges::any_of(bus.Peers(), [nostrod](pid_t pid) { return pid != nostrod; }); i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
// A call made by hand, as alice, for what Client never sends; the name of the error it got, or empty when it worked.
template<typename Build>
std::string Raw(Fake::Bus& bus, std::string_view destination, std::string_view interface, std::string_view member, bool interactive, Build&& build) {
{
std::lock_guard lock(bus.mutex);
bus.clientUid = aliceUid;
}
sd_bus* raw = nullptr;
sd_bus_open_system(&raw);
sd_bus_set_allow_interactive_authorization(raw, interactive ? 1 : 0);
sd_bus_message* call = nullptr;
sd_bus_message_new_method_call(raw, &call, std::string(destination).c_str(), "/net/catcrafts/Nostro1", std::string(interface).c_str(), std::string(member).c_str());
build(call);
sd_bus_error error = SD_BUS_ERROR_NULL;
sd_bus_message* reply = nullptr;
const std::int32_t result = sd_bus_call(raw, call, 0, &error, &reply);
const std::string failed = result < 0 ? std::string(error.name) : std::string();
sd_bus_error_free(&error);
sd_bus_message_unref(reply);
sd_bus_message_unref(call);
sd_bus_flush_close_unref(raw);
return failed;
}
// The element of interface `interface` in an introspection document, empty when it has none, with the whitespace
// between and inside tags brought down to what XML needs, so the published file and nostrod's own document compare.
std::string Interface(std::string_view xml, std::string_view interface) {
const std::size_t start = xml.find(std::format("<interface name=\"{}\">", interface));
if(start == std::string_view::npos) {
return {};
}
const std::string_view element = xml.substr(start, xml.find("</interface>", start) - start);
std::string out;
bool space = false;
for(const char c : element) {
if(c == ' ' || c == '\n' || c == '\t') {
space = true;
continue;
}
if(space && !out.empty() && out.back() != '>' && c != '<' && c != '/') {
out += ' ';
}
space = false;
out += c;
}
return out;
}
// The introspection document of nostrod's object under `destination`, asked as alice.
std::string Introspect(Fake::Bus& bus, std::string_view destination) {
{
std::lock_guard lock(bus.mutex);
bus.clientUid = aliceUid;
}
sd_bus* raw = nullptr;
sd_bus_open_system(&raw);
sd_bus_error error = SD_BUS_ERROR_NULL;
sd_bus_message* reply = nullptr;
sd_bus_call_method(raw, std::string(destination).c_str(), "/net/catcrafts/Nostro1", "org.freedesktop.DBus.Introspectable", "Introspect", &error, &reply, "");
// sd-bus hands strings out as C strings.
// lint-disable-next-line no-char-pointer
const char* document = nullptr;
sd_bus_message_read(reply, "s", &document);
std::string served(document ? document : "");
sd_bus_error_free(&error);
sd_bus_message_unref(reply);
sd_bus_flush_close_unref(raw);
return served;
}
// The published contract: packaging/dbus/net.catcrafts.Nostro1.xml and net.catcrafts.Nostro1.Checkout.xml are the
// interfaces nostrod serves, each under its own name alone, and the polkit policy declares every action nostrod asks
// about and no other, each owned by the user nostrod runs as, with a dialog that uses no detail nostrod does not set.
void Contract(Fake::Bus& bus) {
const std::string served = Introspect(bus, name);
Check(Interface(served, name) == Interface(Slurp("packaging/dbus/net.catcrafts.Nostro1.xml"), name), std::format("packaging/dbus/net.catcrafts.Nostro1.xml is the interface nostrod serves, which is:\n{}", served));
const std::string checkout = Introspect(bus, checkoutName);
Check(Interface(checkout, checkoutName) == Interface(Slurp("packaging/dbus/net.catcrafts.Nostro1.Checkout.xml"), checkoutName), std::format("packaging/dbus/net.catcrafts.Nostro1.Checkout.xml is the checkout nostrod serves, which is:\n{}", checkout));
// An app allowed to talk to the checkout's name reaches nothing else through it.
Check(Interface(served, checkoutName).empty() && Interface(checkout, name).empty(), "each name serves its own interface alone");
Check(!Raw(bus, checkoutName, name, "Connectors", true, [](sd_bus_message*) {}).empty(), "the checkout's name answers no other method");
const std::string payHere = Raw(bus, name, checkoutName, "Pay", true, [](sd_bus_message* call) {
sd_bus_message_append(call, "ssxssa{sv}", shopIban.c_str(), "Shop", std::int64_t{100}, "EUR", "1", 0u);
});
Check(!payHere.empty(), "and the other name pays no checkout");
const std::string policy = Slurp("packaging/system/net.catcrafts.Nostro1.policy");
std::vector<std::string> declared;
for(std::size_t at = policy.find("<action id=\""); at != std::string::npos; at = policy.find("<action id=\"", at + 1)) {
const std::string_view action = std::string_view(policy).substr(at, policy.find("</action>", at) - at);
const std::size_t id = action.find('"') + 1;
declared.emplace_back(action.substr(id, action.find('"', id) - id));
Check(action.contains("<annotate key=\"org.freedesktop.policykit.owner\">unix-user:nostro</annotate>"), std::format("{} is owned by the user nostrod runs as", declared.back()));
for(std::size_t key = action.find("$("); key != std::string_view::npos; key = action.find("$(", key + 1)) {
Check(action.substr(key).starts_with("$(summary)"), std::format("{} shows only details nostrod sets", declared.back()));
}
}
const std::vector<std::string> asked = {std::string(Bus::actionView), std::string(Bus::actionChange), std::string(Bus::actionPay), std::string(Bus::actionUnfreezeCard), std::string(Bus::actionBlockCard), std::string(Bus::actionConnectors), std::string(Bus::actionCheckout)};
Check(std::ranges::is_permutation(declared, asked), "the policy declares the actions nostrod asks about, and no other");
}
void NotRunning(Fake::Bus& bus) {
Throws<std::runtime_error>([&bus] { As(bus, aliceUid).Connectors(); }, "nostrod is not running", "a call without nostrod on the bus says so");
}
void Arguments(const fs::path& state) {
Equal(Fake::Wait(Fake::StartNostrod({"--state", state.string()})), 1, "a second nostrod cannot own the name, and ends");
Equal(Fake::Wait(Fake::StartNostrod({"--idle"}, {"XDG_DATA_HOME"})), 1, "an option without its value");
Equal(Fake::Wait(Fake::StartNostrod({"--idle", "soon"}, {"XDG_DATA_HOME", "HOME"})), 1, "a time that is no number");
Equal(Fake::Wait(Fake::StartNostrod({"--frob"})), 1, "an unknown argument");
}
void Users(Fake::Bus& bus, const fs::path& state) {
Client alice = As(bus, aliceUid);
Check(alice.Connectors().empty(), "a new user has no connectors");
const AddedConnector added = alice.AddBunq("key-alice", "*", "");
Check(added.name == "Alice" && added.environment == "production" && added.accounts == 3, "a connector, its environment from the key");
const Fake::PolkitCheck check = bus.LastCheck();
Check(check.action == "net.catcrafts.Nostro1.Connectors" && check.details.at("environment") == "production" && check.flags == 1, "adding one is the Connectors action, and the dialog may ask");
Equal(check.details.at("summary"), std::string("add a bunq connector (production)"), "what the dialog says");
Check(check.subject.starts_with(":1."), "polkit is asked about the caller's own connection");
Client bob = As(bus, bobUid);
Check(bob.Connectors().empty(), "another user sees none of them");
Equal(bob.AddBunq("key-bob", "", "sandbox").environment, std::string("sandbox"), "an environment named by the caller");
Equal(alice.Connectors().size(), std::size_t{1}, "each user sees their own connectors");
Equal(bob.Connectors().at(0).name, std::string("Bob"), "and only those");
Equal(Slurp(state / "users" / std::to_string(aliceUid) / "owner"), std::string("alice\n"), "a user's directory says whose it is");
Equal(Slurp(state / "users" / std::to_string(bobUid) / "owner"), std::string("bob\n"), "the other's too");
Check(fs::exists(state / "users" / std::to_string(aliceUid) / "connectors.json") && fs::exists(state / "users" / std::to_string(bobUid) / "connectors.json"), "each has their connectors in their own directory");
}
void Prompts(Fake::Bus& bus, Fake::Bunq& bunq, const Bank& bank) {
Client alice = As(bus, aliceUid);
const Created sent = alice.Send(aliceMain, bobIban, "Bob", 1250, "lunch");
Check(sent.id != 0 && sent.currency == Currency::Euro, "a payment, and the currency its amount was in");
Fake::PolkitCheck check = bus.LastCheck();
Equal(check.action, std::string("net.catcrafts.Nostro1.Pay"), "paying is the Pay action");
Equal(check.details.at("summary"), std::format("pay €12.50 to {} (Bob) from {} (Main)", bobIban, aliceMain), "the dialog names the amount, the payee and the account");
Check(check.details.at("amount_minor") == "1250" && check.details.at("currency") == "EUR" && check.details.at("counterparty") == bobIban && check.details.at("account_iban") == aliceMain && check.details.at("environment") == "production", "and gives polkit rules the details to test");
alice.Send(aliceMain, bobIban, "", 100, "");
Equal(Summary(bus), std::format("pay €1.00 to {} from {} (Main)", bobIban, aliceMain), "a payee without a name is its IBAN");
// What a caller writes is made fit for the dialog: no control, invisible or direction characters, nothing for
// markup or for polkit's $(…), at most 64 characters.
const std::string nasty = std::format("B\x01o\x7F" "b\xC2\x85\xE2\x80\x8B\xE2\x80\xAE\xE2\x81\xA6\xEF\xBB\xBF<i>$(amount_minor)</i>\xF0\x9F\x98\x80x{}", std::string(70, 'y'));
alice.Send(aliceMain, "x@y", nasty, 100, "");
Equal(Summary(bus), std::format("pay €1.00 to x@y (Bob‹i›$ (amount_minor)‹/i›😀x{}…) from {} (Main)", std::string(37, 'y'), aliceMain), "a name made safe to show");
// D-Bus carries UTF-8 alone, so text that is not cannot even be sent.
Throws<std::invalid_argument>([&alice] { alice.Send(aliceMain, bobIban, "\xFF", 100, ""); }, "not UTF-8", "a name that is not UTF-8");
alice.Accounts();
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.View" && Summary(bus) == "see your accounts and balances", "listing is the View action");
alice.Transactions(aliceMain, {});
Equal(Summary(bus), std::string("see your transactions"), "so are the transactions");
alice.Request(aliceMain, bobIban, "Bob", 500, "back");
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Change" && Summary(bus) == std::format("ask {} (Bob) for €5.00 into {} (Main)", bobIban, aliceMain), "asking for money is a Change");
const std::uint64_t asked = alice.Requests(aliceMain).at(0).id;
alice.RevokeRequest(aliceMain, asked);
Equal(Summary(bus), std::format("revoke request {} of {} (Main)", asked, aliceMain), "revoking one");
Client bob = As(bus, bobUid);
bob.Request(bobIban, aliceMain, "Alice", 700, "rent");
const BunqIncomingRequest owed = alice.IncomingRequests(aliceMain).at(0);
alice.RespondToRequest(aliceMain, owed.id, true);
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Pay" && Summary(bus) == std::format("pay €7.00 to {} ({}) from {} (Main), as asked in request {}", owed.counterparty.iban, owed.counterparty.name, aliceMain, owed.id), "accepting a request is a payment, shown as asked");
bob.Request(bobIban, aliceMain, "Alice", 800, "more");
const BunqIncomingRequest refused = alice.IncomingRequests(aliceMain).at(0);
alice.RespondToRequest(aliceMain, refused.id, false);
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Change" && Summary(bus) == std::format("reject request {} from {} ({})", refused.id, refused.counterparty.iban, refused.counterparty.name), "rejecting one is a Change");
const std::chrono::system_clock::time_point start = std::chrono::sys_days(std::chrono::year(2027) / 1 / 1);
alice.Schedule(aliceMain, bobIban, "Bob", 300, "rent", BunqSchedule{.start = start, .end = start + std::chrono::days(364), .unit = "MONTHLY", .every = 1});
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Pay" && Summary(bus) == std::format("schedule €3.00 to {} (Bob) from {} (Main), monthly from 2027-01-01 00:00 UTC until 2027-12-31 00:00 UTC", bobIban, aliceMain), "a schedule is a payment, with when it runs");
alice.Schedule(aliceMain, bobIban, "Bob", 300, "", BunqSchedule{.start = start, .unit = "ONCE"});
Check(Summary(bus).ends_with(", once on 2027-01-01 00:00 UTC"), "one that runs once");
const std::uint64_t scheduled = alice.ScheduledPayments(aliceMain).at(0).id;
alice.CancelScheduledPayment(aliceMain, scheduled);
Equal(Summary(bus), std::format("cancel scheduled payment {} of {} (Main)", scheduled, aliceMain), "cancelling one");
alice.Draft(aliceMain, bobIban, "Bob", 200, "");
Equal(Summary(bus), std::format("make a draft payment of €2.00 to {} (Bob) from {} (Main), paid once someone accepts it", bobIban, aliceMain), "a draft");
const BunqDraftPayment draft = alice.DraftPayments(aliceMain).at(0);
alice.RespondToDraftPayment(aliceMain, draft.id, true);
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Pay" && Summary(bus) == std::format("pay €2.00 to {} ({}) from {} (Main), as drafted in draft payment {}", draft.entries.at(0).counterparty.iban, draft.entries.at(0).counterparty.name, aliceMain, draft.id), "accepting a draft is a payment");
{
std::lock_guard lock(bunq.mutex);
json entries = json::array();
for(const std::string_view payee : {"One", "Two", "Three", "Four"}) {
entries.push_back(json{{"amount", Fake::Amount(-100)}, {"counterparty_alias", json{{"display_name", payee}, {"iban", bobIban}}}, {"pointer", json{{"type", "IBAN"}, {"value", bobIban}, {"name", payee}}}, {"description", ""}});
}
bunq.drafts[bank.aliceMainId].push_back(json{{"DraftPayment", json{{"id", 900001}, {"status", "PENDING"}, {"entries", entries}}}});
bunq.drafts[bank.aliceMainId].push_back(json{{"DraftPayment", json{{"id", 900002}, {"status", "PENDING"}, {"entries", json::array()}}}});
bunq.drafts[bank.aliceMainId].push_back(json{{"DraftPayment", json{{"id", 900003}, {"status", "PENDING"}, {"entries", json::array({json{{"amount", Fake::Amount(-250)}, {"counterparty_alias", json{{"iban", bobIban}}}}, json{{"amount", Fake::Amount(-50)}, {"counterparty_alias", json{{"display_name", "Mail"}}}}})}}}});
}
alice.RespondToDraftPayment(aliceMain, 900001, true);
Equal(Summary(bus), std::format("pay €4.00 to {0} (One), {0} (Two), {0} (Three) and 1 more from {1} (Main), as drafted in draft payment 900001", bobIban, aliceMain), "a draft to many payees names three");
alice.RespondToDraftPayment(aliceMain, 900002, false);
Equal(Summary(bus), std::string("reject draft payment 900002 of €0.00 to no one"), "a draft to nobody");
alice.RespondToDraftPayment(aliceMain, 900003, false);
Equal(Summary(bus), std::format("reject draft payment 900003 of €3.00 to {}, Mail", bobIban), "payees known by IBAN or by name alone");
const std::uint64_t card = bunq.AddCard(bank.alice, "ACTIVE");
Check(!alice.Cards().empty() && Summary(bus) == "see your cards", "the cards");
alice.SetCardStatus(card, "DEACTIVATED");
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Change" && Summary(bus) == "freeze card **** 1234", "freezing a card is a Change");
alice.SetCardStatus(card, "ACTIVE");
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.UnfreezeCard" && Summary(bus) == "unfreeze card **** 1234", "unfreezing one has an action of its own");
alice.SetCardStatus(card, "STOLEN");
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.BlockCard" && Summary(bus) == "report card **** 1234 stolen, which blocks it for good", "and so does blocking one for good");
}
void Outcomes(Fake::Bus& bus) {
Client alice = As(bus, aliceUid);
SetPolkit(bus, Fake::Polkit::Deny);
const Failure denied = FailureOf([&alice] { alice.Accounts(); });
Check(denied.name == SD_BUS_ERROR_ACCESS_DENIED && denied.message.contains("does not allow net.catcrafts.Nostro1.View"), std::format("a refusal by policy: {}", denied.message));
SetPolkit(bus, Fake::Polkit::Dismiss);
Equal(FailureOf([&alice] { alice.Send(aliceMain, bobIban, "Bob", 100, ""); }).name, std::string(Bus::errorCancelled), "a dialog closed without a password");
SetPolkit(bus, Fake::Polkit::Absent);
const Failure absent = FailureOf([&alice] { alice.Accounts(); });
Check(absent.name == SD_BUS_ERROR_ACCESS_DENIED && absent.message.contains("polkit did not decide"), "no polkit is no");
SetPolkit(bus, Fake::Polkit::Silent);
const Failure silent = FailureOf([&alice] { alice.Connectors(); });
Check(silent.name == SD_BUS_ERROR_ACCESS_DENIED && silent.message.contains("polkit did not decide"), "nor is no answer");
const std::string cancellation = bus.LastCheck().cancellation;
bool cancelled = false;
for(std::size_t i = 0; i < 100 && !cancelled; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::lock_guard lock(bus.mutex);
cancelled = std::ranges::contains(bus.cancelled, cancellation);
}
Check(cancelled, "and the dialog of a check given up on is cancelled");
// A call that may not ask for a password is told it would need one.
SetPolkit(bus, Fake::Polkit::Password);
Check(!alice.Connectors().empty(), "a password asked for, and given");
Equal(Raw(bus, name, name, "Connectors", false, [](sd_bus_message*) {}), std::string(SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED), "a call that does not allow a dialog");
// A client that stops waiting.
SetPolkit(bus, Fake::Polkit::Silent);
Client quick = As(bus, aliceUid);
Client hurried = Client::System(std::chrono::seconds(1));
const Failure lost = FailureOf([&hurried] { hurried.Send(aliceMain, bobIban, "Bob", 100, ""); });
Check(lost.name == "exception" && lost.message.contains("may have been carried out"), std::format("a payment without an answer may have been made: {}", lost.message));
Equal(FailureOf([&hurried] { hurried.Connectors(); }).name, std::string(SD_BUS_ERROR_TIMEOUT), "a listing without an answer is only that");
SetPolkit(bus, Fake::Polkit::Allow);
Check(!quick.Connectors().empty(), "and the next call is answered");
}
void Concurrency(Fake::Bus& bus, Fake::Bunq& bunq, const Bank& bank) {
Client alice = As(bus, aliceUid);
Client again = As(bus, aliceUid);
SetPolkit(bus, Fake::Polkit::Slow, Bus::actionPay);
std::thread paying([&alice] { alice.Send(aliceMain, bobIban, "Bob", 100, ""); });
std::this_thread::sleep_for(std::chrono::milliseconds(200));
const std::chrono::steady_clock::time_point asked = std::chrono::steady_clock::now();
again.Connectors();
Check(std::chrono::steady_clock::now() - asked < std::chrono::milliseconds(700), "a dialog left open holds up no other call");
paying.join();
// Gone while the dialog was open: the connector, then an account.
again.AddBunq("key-dave", "*", "");
std::string gone;
std::thread toDave([&alice, &gone] {
try {
alice.Send(daveIban, bobIban, "Bob", 100, "");
} catch(const std::invalid_argument& e) {
gone = e.what();
}
});
std::this_thread::sleep_for(std::chrono::milliseconds(200));
again.RemoveConnector("Dave");
Equal(Summary(bus), std::string("remove the bunq connector 'Dave' and its stored transactions"), "removing a connector");
toDave.join();
Check(gone.contains("that connector is no longer there"), std::format("a payment whose connector went: {}", gone));
std::thread fromClosing([&alice, &gone] {
try {
alice.Send(closingIban, bobIban, "Bob", 100, "");
} catch(const std::invalid_argument& e) {
gone = e.what();
}
});
std::this_thread::sleep_for(std::chrono::milliseconds(200));
bunq.ChangeAccount(bank.closingId, json{{"status", "CANCELLED"}});
again.Accounts();
fromClosing.join();
Check(gone.contains("that account is no longer there"), std::format("a payment whose account closed: {}", gone));
SetPolkit(bus, Fake::Polkit::Allow);
}
void Errors(Fake::Bus& bus, Fake::Bunq& bunq, const Bank& bank, const fs::path& state) {
Client alice = As(bus, aliceUid);
Throws<std::invalid_argument>([&alice] { alice.Send(aliceMain, "NL00BUNQ0000000000", "X", 100, ""); }, "is not a valid IBAN", "a payee refused before anything is asked");
Throws<std::invalid_argument>([&alice] { alice.Send(aliceMain, bobIban, "Bob", 0, ""); }, "more than zero", "nothing to pay");
Throws<std::invalid_argument>([&alice] { alice.Send("Main", bobIban, "Bob", 100, ""); }, "2 accounts are called 'Main': use the IBAN", "two accounts of one name");
Throws<std::invalid_argument>([&alice] { alice.Transactions("Nope", {}); }, "no account is called or has IBAN 'Nope'", "an account nobody has");
bunq.AddAccount(bank.alice, lateIban, "Late", 0);
Check(alice.Transactions(lateIban, {}).empty(), "an account opened since is found on a second look");
Throws<std::invalid_argument>([&alice] { alice.AddBunq("key", "*", "moon"); }, "unknown environment 'moon'", "an environment that is none");
Throws<std::invalid_argument>([&alice] { alice.SetCardStatus(1, "MELTED"); }, "unknown card status 'MELTED'", "a card status that is none");
Throws<std::invalid_argument>([&alice] { alice.SetCardStatus(1, "LOST"); }, "no card has id 1", "a card nobody has");
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 400, .body = R"({"Error":[{"error_description":"Not enough money."}]})"});
const Failure refused = FailureOf([&alice] { alice.Send(aliceMain, bobIban, "Bob", 100, ""); });
Check(refused.name == Bus::errorBank && refused.message.contains("Not enough money."), "bunq's refusal, as bunq said it");
const AddedConnector carol = alice.AddBunqOAuth("production", bunq.clientId, bunq.clientSecret, "http://127.0.0.1/cb", "code-carol");
Check(carol.name == "Carol" && Summary(bus) == "add a bunq connector through OAuth (production)", "a connector through OAuth");
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 403, .body = R"({"Error":[{"error_description":"Not allowed for this user."}]})"});
Equal(FailureOf([&alice] { alice.Send(carolIban, bobIban, "Bob", 100, ""); }).name, std::string(Bus::errorOAuthCannotPay), "an OAuth connector paying someone else");
// A user whose connectors.json cannot be read hears so, without what it holds.
const fs::path eve = state / "users" / "4444";
fs::create_directories(eve);
std::ofstream(eve / "owner") << "eve\n";
std::ofstream(eve / "connectors.json") << R"({"bunq": [{"privateKey": "-----BEGIN PRIVATE KEY-----\nMIIE)";
{
std::lock_guard lock(bus.mutex);
bus.logindNames[4444] = "eve";
}
const Failure unreadable = FailureOf([&bus] { As(bus, 4444).Connectors(); });
Check(unreadable.name == Bus::errorFailed && unreadable.message.contains("is not valid JSON") && !unreadable.message.contains("MIIE"), std::format("an unreadable connectors.json: {}", unreadable.message));
const Failure stranger = FailureOf([&bus] { As(bus, 4545).Connectors(); });
Check(stranger.name == SD_BUS_ERROR_ACCESS_DENIED && stranger.message.contains("logind knows no user 4545"), "a uid without a login session");
{
std::lock_guard lock(bus.mutex);
bus.omitUid = true;
}
const Failure nameless = FailureOf([&alice] { alice.Connectors(); });
Check(nameless.name == SD_BUS_ERROR_ACCESS_DENIED && nameless.message.contains("did not say which user"), "a caller the bus cannot name");
{
std::lock_guard lock(bus.mutex);
bus.omitUid = false;
}
// What Client never sends: an optional value of two, and a query key nostrod does not know, which it skips.
const std::string twoEnds = Raw(bus, name, name, "Schedule", true, [](sd_bus_message* call) {
sd_bus_message_append(call, "sssxs", aliceMain.c_str(), bobIban.c_str(), "Bob", std::int64_t{100}, "");
sd_bus_message_open_container(call, 'r', "xaxsusax");
sd_bus_message_append(call, "xaxsusax", std::int64_t{0}, 2, std::int64_t{1}, std::int64_t{2}, "ONCE", 1u, "", 0);
sd_bus_message_close_container(call);
});
Equal(twoEnds, std::string(Bus::errorFailed), "a schedule with two ends");
const std::string unknown = Raw(bus, name, name, "Transactions", true, [](sd_bus_message* call) {
sd_bus_message_append(call, "sa{sv}", aliceMain.c_str(), 1, "colour", "s", "blue");
});
Equal(unknown, std::string(), "a query key nostrod does not know");
}
// A stand-in for nostrod's checkout, for answers nostrod never gives, chosen by the order's reference: "extra", a
// result the client does not know; "shape", an answer of another shape; "odd", an error of another name; "bare", an
// error without a message; anything else, no answer at all. A plain object rather than a vtable, whose answers sd-bus would hold to its signature.
class FakeCheckout {
public:
FakeCheckout() {
sd_bus_open_system(&bus);
sd_bus_add_object(bus, nullptr, "/net/catcrafts/Nostro1", OnCall, nullptr);
sd_bus_request_name(bus, "net.catcrafts.Nostro1.Checkout", 0);
thread = std::thread([this] {
while(!stop) {
while(sd_bus_process(bus, nullptr) > 0) {
}
sd_bus_wait(bus, 20000);
}
});
}
FakeCheckout(const FakeCheckout&) = delete;
FakeCheckout& operator=(const FakeCheckout&) = delete;
~FakeCheckout() {
stop = true;
thread.join();
sd_bus_flush_close_unref(bus);
}
private:
static std::int32_t OnCall(sd_bus_message* call, void*, sd_bus_error*) {
if(!sd_bus_message_is_method_call(call, "net.catcrafts.Nostro1.Checkout", "Pay")) {
return 0;
}
sd_bus_message_skip(call, "ssxs");
// sd-bus hands strings out as C strings.
// lint-disable-next-line no-char-pointer
const char* reference = nullptr;
sd_bus_message_read_basic(call, 's', &reference);
const std::string_view kind(reference);
if(kind == "extra") {
return sd_bus_reply_method_return(call, "ta{sv}", std::uint64_t{7}, 2u, "colour", "s", "blue", "repeated", "b", 1);
}
if(kind == "shape") {
return sd_bus_reply_method_return(call, "s", "nonsense");
}
if(kind == "odd") {
return sd_bus_reply_method_errorf(call, "org.example.Odd", "an error of another name");
}
if(kind == "bare") {
const sd_bus_error bare = {"org.example.Bare", nullptr, 0};
return sd_bus_reply_method_error(call, &bare);
}
return 1;
}
sd_bus* bus = nullptr;
std::thread thread;
std::atomic<bool> stop{false};
};
// Nostro.Checkout's own side: with no nostro on the bus, and against a stand-in for nostrod's checkout.
void CheckoutClient(Fake::Bus& bus) {
Checkout::Order order{.payeeIban = shopIban, .payeeName = "Shop", .amount = 1250, .reference = "1"};
const Failure missing = FailureOf([&order] { Checkout::Pay(order); });
Check(missing.name == SD_BUS_ERROR_SERVICE_UNKNOWN && missing.message.contains("nostro is not installed"), std::format("a checkout without nostro: {}", missing.message));
Throws<std::invalid_argument>([] { Checkout::Pay({.payeeIban = "\xFF", .amount = 1, .reference = "1"}); }, "not UTF-8", "an order that is not UTF-8");
const auto pay = [&order](std::string_view reference, std::chrono::seconds timeout) {
order.reference = std::string(reference);
return Checkout::Pay(order, timeout);
};
{
const FakeCheckout stand;
Check(bus.WaitForName(checkoutName), "a stand-in for nostrod's checkout");
const Checkout::Paid extra = pay("extra", std::chrono::seconds(20));
Check(extra.paymentId == 7 && extra.repeated, "results the client does not know are skipped");
Throws<std::system_error>([&pay] { pay("shape", std::chrono::seconds(20)); }, "cannot read nostrod's answer", "an answer of another shape");
const Failure odd = FailureOf([&pay] { pay("odd", std::chrono::seconds(20)); });
Check(odd.name == "org.example.Odd" && odd.message == "an error of another name", "an error of another name, as it came");
const Failure bare = FailureOf([&pay] { pay("bare", std::chrono::seconds(20)); });
Check(bare.name == "org.example.Bare" && bare.message.empty(), "and one without a message");
const Failure late = FailureOf([&pay] { pay("silent", std::chrono::seconds(1)); });
Check(late.name == SD_BUS_ERROR_TIMEOUT && late.message.contains("the order may have been paid"), std::format("no answer in time: {}", late.message));
}
Check(bus.WaitForName(checkoutName, false), "and the stand-in gone");
}
// nostrod's side of a checkout: the account that pays, the prompt, the record that answers a retry, and every way an
// order is refused.
void Checkouts(Fake::Bus& bus, Fake::Bunq& bunq, const Bank& bank) {
Client alice = As(bus, aliceUid);
const auto pay = [&bus](const Checkout::Order& order) {
{
std::lock_guard lock(bus.mutex);
bus.clientUid = aliceUid;
}
return Checkout::Pay(order);
};
const auto checks = [&bus](std::string_view reference) {
std::lock_guard lock(bus.mutex);
return std::ranges::count_if(bus.checks, [reference](const Fake::PolkitCheck& check) { return check.details.contains("reference") && check.details.at("reference") == reference; });
};
const std::string payments = std::format("/user/{}/monetary-account/{}/payment", bank.alice, bank.aliceMainId);
const Checkout::Order order{.payeeIban = shopIban, .payeeName = "Shop", .amount = 1250, .reference = "order-1"};
Check(!alice.DefaultCheckoutAccount().has_value() && Summary(bus) == "see which account pays at checkout", "no account pays at checkout until one is chosen");
Throws<Checkout::NoCheckoutAccount>([&pay, &order] { pay(order); }, "no account is chosen to pay checkouts from", "a checkout before an account is chosen");
Throws<std::invalid_argument>([&alice] { alice.SetDefaultCheckoutAccount(carolIban); }, "is reached through OAuth, which pays only your own accounts", "an account that could pay no shop");
const Account chosen = alice.SetDefaultCheckoutAccount(aliceMain);
Check(chosen.iban == aliceMain && chosen.name == "Main", "an account chosen, and shown");
Check(bus.LastCheck().action == "net.catcrafts.Nostro1.Connectors" && Summary(bus) == std::format("let apps ask you to pay from {} (Main) at checkout", aliceMain), "choosing it is a change to the connections");
Equal(alice.DefaultCheckoutAccount().value_or(Account{}).iban, aliceMain, "the account checkouts pay from");
const std::size_t before = bunq.Count("POST", payments);
const Checkout::Paid paid = pay(order);
Check(paid.paymentId != 0 && !paid.repeated, "an order paid");
const Fake::PolkitCheck check = bus.LastCheck();
Equal(check.action, std::string("net.catcrafts.Nostro1.Checkout"), "paying at checkout is an action of its own");
Equal(check.details.at("summary"), std::format("pay €12.50 to {} (Shop) from {} (Main), as an app asks at checkout, reference order-1", shopIban, aliceMain), "the dialog shows the order, and the account that pays it");
Check(check.details.at("reference") == "order-1" && check.details.at("amount_minor") == "1250" && check.details.at("account_iban") == aliceMain && check.details.at("counterparty") == shopIban, "and gives polkit rules the details");
Equal(bunq.Count("POST", payments), before + 1, "one payment");
const Checkout::Paid again = pay(order);
Check(again.paymentId == paid.paymentId && again.repeated, "the same order again answers with its payment");
Check(checks("order-1") == 1 && bunq.Count("POST", payments) == before + 1, "without asking, or paying, again");
const auto refused = [&pay](Checkout::Order changed, std::string_view part, std::string_view what) {
const Failure failure = FailureOf([&pay, &changed] { pay(changed); });
Check(failure.name == Checkout::errorInvalidArgument && failure.message.contains(part), std::format("{}: {}", what, failure.message));
};
Checkout::Order changed = order;
changed.amount = 1300;
refused(changed, "reference order-1 to NL91ABNA0417164300 is an order of €12.50, not of €13.00", "a reference paid for another amount");
changed = order;
changed.payeeIban = "shop@example.com";
refused(changed, "checkout pays an IBAN, and 'shop@example.com' is none", "a payee that is no IBAN");
changed.payeeIban = "NL00BUNQ0000000000";
refused(changed, "is not a valid IBAN", "an IBAN with a typo");
changed = order;
changed.amount = 0;
refused(changed, "more than zero", "nothing to pay");
changed = order;
changed.currency = "USD";
refused(changed, "unsupported currency 'USD'", "a currency nostro does not pay in");
changed = order;
changed.reference = "";
refused(changed, "an order needs a reference", "an order without a reference");
// bunq refusing it before doing anything: the order was not paid, and is paid when asked again.
Checkout::Order refusedOrder = order;
refusedOrder.reference = "order-2";
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 400, .body = R"({"Error":[{"error_description":"Not enough money."}]})"});
const Failure poor = FailureOf([&pay, &refusedOrder] { pay(refusedOrder); });
Check(poor.name == Checkout::errorBank && poor.message.contains("Not enough money."), "bunq's refusal");
Check(!pay(refusedOrder).repeated, "and the order paid when asked again");
// bunq's answer lost: the order may have been paid, and is not paid again.
Checkout::Order lostOrder = order;
lostOrder.reference = "order-3";
bunq.Fail(Fault{.method = "POST", .path = "/user/", .status = 500, .body = R"({"Error":[{"error_description":"Hiccup."}]})"});
const Failure hiccup = FailureOf([&pay, &lostOrder] { pay(lostOrder); });
Check(hiccup.name == Checkout::errorBank && hiccup.message.contains("may have been carried out"), std::format("an answer that may hide a payment: {}", hiccup.message));
const Failure lost = FailureOf([&pay, &lostOrder] { pay(lostOrder); });
Check(lost.name == Checkout::errorFailed && lost.message.contains("order order-3 to NL91ABNA0417164300 may have been paid already") && !lost.message.contains(aliceMain), std::format("such an order asked again, without the account: {}", lost.message));
Checkout::Order unconfirmed = order;
unconfirmed.reference = "order-4";
SetPolkit(bus, Fake::Polkit::Dismiss, Bus::actionCheckout);
Throws<Checkout::Cancelled>([&pay, &unconfirmed] { pay(unconfirmed); }, "you did not authenticate", "an order the user did not confirm");
// Asked again while the user is still at the prompt: the second call waits for the first, and gets its answer.
SetPolkit(bus, Fake::Polkit::Slow, Bus::actionCheckout);
Checkout::Paid first;
std::thread paying([&pay, &unconfirmed, &first] { first = pay(unconfirmed); });
std::this_thread::sleep_for(std::chrono::milliseconds(300));
changed = unconfirmed;
changed.amount = 99;
refused(changed, "is an order of €12.50, not of €0.99", "another amount while the order is being paid");
const Checkout::Paid waited = pay(unconfirmed);
paying.join();
Check(first.paymentId != 0 && waited.paymentId == first.paymentId && !first.repeated && waited.repeated, "a retry while the first call is at the prompt gets the first call's payment");
Equal(checks("order-4"), std::ptrdiff_t{2}, "and the user is asked once for it, after the dismissed dialog");
SetPolkit(bus, Fake::Polkit::Silent, Bus::actionCheckout);
Checkout::Order unanswered = order;
unanswered.reference = "order-5";
Failure gaveUp;
std::thread asking([&pay, &unanswered, &gaveUp] { gaveUp = FailureOf([&pay, &unanswered] { pay(unanswered); }); });
std::this_thread::sleep_for(std::chrono::milliseconds(300));
const Failure alsoGaveUp = FailureOf([&pay, &unanswered] { pay(unanswered); });
asking.join();
Check(gaveUp.name == SD_BUS_ERROR_ACCESS_DENIED && alsoGaveUp.name == gaveUp.name && alsoGaveUp.message == gaveUp.message, "and the first call's refusal, when it is refused");
SetPolkit(bus, Fake::Polkit::Allow);
// An account chosen and since closed pays no checkout.
const std::uint64_t brief = bunq.AddAccount(bank.alice, briefIban, "Brief", 1000);
Equal(alice.SetDefaultCheckoutAccount(briefIban).iban, briefIban, "an account opened since");
bunq.ChangeAccount(brief, json{{"status", "CANCELLED"}});
alice.Accounts();
Check(!alice.DefaultCheckoutAccount().has_value(), "a closed account pays at checkout no more");
Checkout::Order orphan = order;
orphan.reference = "order-6";
Throws<Checkout::NoCheckoutAccount>([&pay, &orphan] { pay(orphan); }, "or it is gone", "nor does a checkout pay from it");
alice.SetDefaultCheckoutAccount(aliceMain);
}
void Workers(Fake::Bus& bus, pid_t nostrod) {
// A worker dying with a call under way: the caller hears it may have been carried out.
Client alice = As(bus, aliceUid);
SetPolkit(bus, Fake::Polkit::Silent, Bus::actionPay);
Failure lost;
std::thread paying([&alice, &lost] { lost = FailureOf([&alice] { alice.Send(aliceMain, bobIban, "Bob", 100, ""); }); });
std::this_thread::sleep_for(std::chrono::milliseconds(300));
KillWorkers(bus, nostrod);
paying.join();
Check(lost.name == Bus::errorFailed && lost.message.contains("stopped before it answered"), std::format("a call whose worker died: {}", lost.message));
SetPolkit(bus, Fake::Polkit::Allow);
Equal(As(bus, aliceUid).Connectors().size(), std::size_t{2}, "the next call starts a worker again, which reads the connectors again");
// A uid that logind gives another name now: the directory stays the first user's.
{
std::lock_guard lock(bus.mutex);
bus.logindNames[aliceUid] = "mallory";
}
KillWorkers(bus, nostrod);
const Failure reused = FailureOf([&bus] { As(bus, aliceUid).Connectors(); });
Check(reused.name == SD_BUS_ERROR_ACCESS_DENIED && reused.message.contains("holds the bank connections of 'alice'"), std::format("a uid handed to someone else: {}", reused.message));
{
std::lock_guard lock(bus.mutex);
bus.logindNames[aliceUid] = "alice";
}
KillWorkers(bus, nostrod);
Check(!As(bus, aliceUid).Connectors().empty(), "served again once the name is the one it was");
}
void Notes(Fake::Bus& bus, Fake::Bunq& bunq) {
Client bob = As(bus, bobUid);
{
std::lock_guard lock(bunq.mutex);
bunq.keys.erase("key-bob");
}
bunq.ExpireSessions();
bob.Accounts();
const std::vector<std::string> notes = bob.TakeNotes();
// The worker was started again for this call: its first read of the connectors notes it, and so does the refresh.
Check(!notes.empty() && std::ranges::all_of(notes, [](const std::string& note) { return note.contains("bunq connector 'Bob' is unavailable"); }), "a connector that cannot be reached comes back as a note");
Check(bob.TakeNotes().empty(), "taken once");
}
void SpawnFailure(Fake::Bus& bus, const fs::path& state) {
const pid_t limited = Fake::StartNostrod({"--state", state.string()});
Check(bus.WaitForName(name), "a nostrod that will run out of descriptors, then of processes");
// Descriptors 0 to 2 are taken, so no new one fits under 3; poll still takes one at a time.
const rlim_t files = Fake::Limit(limited, RLIMIT_NOFILE, 3);
const Failure noSocket = FailureOf([&bus] { As(bus, aliceUid).Connectors(); });
Check(noSocket.name == Bus::errorFailed && noSocket.message.contains("cannot make a socket for a worker"), std::format("no descriptor for a worker's socket: {}", noSocket.message));
Fake::Limit(limited, RLIMIT_NOFILE, files);
const rlim_t processes = Fake::Limit(limited, RLIMIT_NPROC, 0);
const Failure failed = FailureOf([&bus] { As(bus, aliceUid).Connectors(); });
Check(failed.name == Bus::errorFailed && failed.message.contains("cannot start a worker"), std::format("a worker that cannot be started: {}", failed.message));
Fake::Limit(limited, RLIMIT_NPROC, processes);
bus.Disconnect(name);
Equal(Fake::Wait(limited), 0, "it ends with the bus");
Check(bus.WaitForName(name, false) && bus.WaitForName(checkoutName, false), "and lets go of its names");
}
void Idle(Fake::Bus& bus, const fs::path& state) {
const pid_t idle = Fake::StartNostrod({"--state", state.string(), "--idle", "1", "--prompt-timeout", "3"});
Check(bus.WaitForName(name), "a nostrod that idles after a second");
Client alice = As(bus, aliceUid);
Check(!alice.Connectors().empty(), "it starts a worker");
// The worker and the front both pass an idle second while a dialog is open, and wait for it.
SetPolkit(bus, Fake::Polkit::Silent, Bus::actionView);
Equal(FailureOf([&alice] { alice.Accounts(); }).name, std::string(SD_BUS_ERROR_ACCESS_DENIED), "a dialog nobody answers");
SetPolkit(bus, Fake::Polkit::Allow);
Equal(Fake::Wait(idle), 0, "then the idle worker ends, and nostrod after it");
}
}
// main's signature is C's.
// lint-disable-next-line no-char-pointer
int main(int argc, char* argv[]) {
// nostrod, and each of its workers, is this executable again.
if(Fake::IsNostrod()) {
Fake::Bunq::RedirectFromEnvironment();
return NostrodMain(argc, argv);
}
const Test::Directory directory("daemon");
const fs::path state = directory.path / "state";
// What nostrod reads from the environment is set before any thread starts.
setenv("XDG_DATA_HOME", (directory.path / "data").c_str(), 1);
Fake::Bunq::ExportRedirect(port, directory.path / "bunq.pem");
setenv("DBUS_SYSTEM_BUS_ADDRESS", Fake::Bus::Address(directory.path / "bus").c_str(), 1);
Fake::Bus bus(directory.path / "bus");
{
std::lock_guard lock(bus.mutex);
bus.logindNames = {{aliceUid, "alice"}, {bobUid, "bob"}};
}
Fake::Bunq bunq(port);
Bank bank;
bank.alice = bunq.AddPerson("Alice", "key-alice");
bank.aliceMainId = bunq.AddAccount(bank.alice, aliceMain, "Main", 100000);
bunq.AddAccount(bank.alice, aliceOther, "Main", 500);
bank.closingId = bunq.AddAccount(bank.alice, closingIban, "Closing", 100);
bunq.AddAccount(bunq.AddPerson("Bob", "key-bob"), bobIban, "Bob's", 0);
const std::uint64_t carol = bunq.AddPerson("Carol", "key-carol");
bunq.AddAccount(carol, carolIban, "Shared", 500);
bunq.AddGrant(carol, "code-carol", "token-carol");
bunq.AddAccount(bunq.AddPerson("Dave", "key-dave"), daveIban, "Dave's", 100);
NotRunning(bus);
CheckoutClient(bus);
const pid_t nostrod = Fake::StartNostrod({"--state", state.string(), "--idle", "60", "--prompt-timeout", "2"});
Check(bus.WaitForName(name), "nostrod owns its name");
Contract(bus);
Arguments(state);
Users(bus, state);
Prompts(bus, bunq, bank);
Outcomes(bus);
Concurrency(bus, bunq, bank);
Errors(bus, bunq, bank, state);
Checkouts(bus, bunq, bank);
Workers(bus, nostrod);
Notes(bus, bunq);
bus.Disconnect(name);
Equal(Fake::Wait(nostrod), 0, "nostrod ends when the bus goes, after its workers");
Check(bus.WaitForName(name, false) && bus.WaitForName(checkoutName, false), "and lets go of its names");
SpawnFailure(bus, state);
Idle(bus, state);
return Test::Result();
}

View file

@ -0,0 +1,53 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// The OpenSSL helpers (Nostro:Crypto): keys made, written and read back, signatures made and checked, including every
// way a signature can fail to verify, and the error checks every OpenSSL call goes through.
import std;
import Nostro;
#include "../Support/Check.inc"
using namespace Nostro;
using Test::Check;
using Test::Equal;
using Test::Throws;
int main() {
const auto [made, publicPem] = Crypto::CreateKey();
const Crypto::Key key = Crypto::OwnKey(made);
const Crypto::Key other = Crypto::OwnKey(std::get<0>(Crypto::CreateKey()));
Check(publicPem.starts_with("-----BEGIN PUBLIC KEY-----"), "CreateKey gives the public half in PEM");
const std::string privatePem = Crypto::PrivateKeyToPem(key.get());
const Crypto::Key reread = Crypto::OwnKey(Crypto::LoadKeyFromPem(privatePem));
const Crypto::Key publicKey = Crypto::OwnKey(Crypto::LoadPublicKeyFromPem(publicPem));
Equal(Crypto::PublicKeyToPem(publicKey.get()), publicPem, "a public key reads back as it was written");
Equal(Crypto::PublicKeyToPem(reread.get()), publicPem, "a private key reads back to the same pair");
Throws([] { Crypto::LoadKeyFromPem("not a key"); }, "openssl error", "garbage is not a private key");
Throws([] { Crypto::LoadPublicKeyFromPem("not a key"); }, "openssl error", "garbage is not a public key");
const std::string body = R"({"amount":{"value":"12.50","currency":"EUR"}})";
const std::string signature = Crypto::SignBody(key.get(), body);
Check(Crypto::VerifyBody(publicKey.get(), body, signature), "a signature verifies against its key");
Check(Crypto::VerifyBody(reread.get(), body, Crypto::SignBody(reread.get(), body)), "and so does one from the key read back");
Check(!Crypto::VerifyBody(publicKey.get(), std::format("{} ", body), signature), "a changed body does not verify");
Check(!Crypto::VerifyBody(other.get(), body, signature), "another key does not verify");
Check(!Crypto::VerifyBody(publicKey.get(), body, ""), "an empty signature does not verify");
Check(!Crypto::VerifyBody(publicKey.get(), body, signature.substr(1)), "a signature that is not whole base64 does not verify");
Check(!Crypto::VerifyBody(publicKey.get(), body, "!!!!"), "a signature with characters outside base64 does not verify");
Check(!Crypto::VerifyBody(publicKey.get(), body, "QUI="), "one byte of padding decodes, and does not verify");
Check(!Crypto::VerifyBody(publicKey.get(), body, "QQ=="), "two bytes of padding decode, and do not verify");
Equal(Crypto::RandomHex(16).size(), std::size_t{32}, "16 random bytes are 32 hex digits");
Check(Crypto::RandomHex(8) != Crypto::RandomHex(8), "random bytes differ");
Check(std::ranges::all_of(Crypto::RandomHex(32), [](char c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); }), "lower-case hex");
Equal(Crypto::ThrowOnOpenssl(std::int64_t{1}), std::int64_t{1}, "a positive status passes");
Throws([] { Crypto::ThrowOnOpenssl(std::int64_t{0}); }, "openssl error", "zero is a failure");
std::int32_t value = 7;
Check(Crypto::ThrowOnOpenssl(&value) == &value, "a pointer passes");
Throws([] { Crypto::ThrowOnOpenssl(static_cast<std::int32_t*>(nullptr)); }, "openssl error", "a null pointer is a failure");
return Test::Result();
}

View file

@ -0,0 +1,100 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// The transaction store (Nostro:Account): what a sync stores and what it drops as already stored, the queries, the
// table's file name, a version 1 table migrating on its first open, and how transactions and accounts format.
#include <stdlib.h>
#include <time.h>
import std;
import Nostro;
import Crafter.DB;
#include "../Support/Check.inc"
using namespace Nostro;
using namespace std::chrono;
using Test::Check;
using Test::Equal;
namespace {
// Transaction version 1 as nostro wrote it; the same members give the same fingerprint, so it writes a real old table.
struct OldTransaction {
std::string name;
std::string bic;
std::string iban;
std::string description;
Currency currency;
std::int64_t amount;
system_clock::time_point timePoint;
static constexpr std::uint32_t version = 1;
static constexpr auto orderedBy = &OldTransaction::timePoint;
};
const system_clock::time_point start = sys_days(year(2026) / 10 / 1) + hours(10);
Transaction Made(std::string_view name, std::int32_t minute, std::string_view id, std::int64_t amount = -100, std::string_view description = "groceries", std::string_view iban = "NL02BUNQ0000000002") {
return Transaction{std::string(name), "BUNQNL2A", std::string(iban), std::string(description), Currency::Euro, amount, start + minutes(minute), std::string(id), "BUNQ/PAYMENT"};
}
std::vector<std::string> Names(const std::vector<Transaction>& rows) {
return rows | std::views::transform(&Transaction::name) | std::ranges::to<std::vector<std::string>>();
}
}
int main() {
const Test::Directory directory("transactions");
cachePath = directory.path;
setenv("TZ", "UTC", 1);
tzset();
const Account account{"Main/Spending", "BUNQNL2A", "NL01BUNQ0000000001", Currency::Euro, -1250};
Equal(std::format("{}", account), std::string("Main/Spending\tBUNQNL2A NL01BUNQ0000000001\t-€12.50"), "an account formats as name, BIC and IBAN, balance");
const std::string key = "test/sandbox/1/2";
Check(account.GetLastTransactionTime(key) == system_clock::time_point::min(), "a new table has no last transaction");
Account store = account;
store.SaveTransactions(key, {Made("Bob", 1, "1"), Made("Alice", 0, "0")});
Check(store.GetLastTransactionTime(key) == start + minutes(1), "rows arrive in any order and are stored sorted");
Check(std::filesystem::exists(directory.path / "transactions" / key / "Main_Spending.cdb"), "a '/' in the account name becomes '_' in the file name");
// At the last stored timestamp only a new id is new; a row without an id there cannot be told apart.
store.SaveTransactions(key, {Made("Bob again", 1, "1"), Made("Carol", 1, "2", -250, "rent", "NL03BUNQ0000000003"), Made("Nobody", 1, ""), Made("Old", 0, "9"), Made("Dave", 2, "3", 5000, "salary")});
Equal(Names(store.FindTransactions(key, {})).size(), std::size_t{4}, "a sync that overlaps the last one stores only what is new");
Check(Names(store.FindTransactions(key, {})) == std::vector<std::string>{"Dave", "Carol", "Bob", "Alice"}, "newest first, and the later of two at one time first");
Check(Names(store.FindTransactions(key, {.search = "CAROL"})) == std::vector<std::string>{"Carol"}, "search matches the name, whatever its case");
Check(Names(store.FindTransactions(key, {.search = "Salary"})) == std::vector<std::string>{"Dave"}, "search matches the description");
Check(Names(store.FindTransactions(key, {.search = "nl03"})) == std::vector<std::string>{"Carol"}, "search matches the IBAN");
Check(Names(store.FindTransactions(key, {.amount = -100})) == std::vector<std::string>{"Bob", "Alice"}, "an exact amount");
Check(Names(store.FindTransactions(key, {.from = start + minutes(1), .to = start + minutes(1)})) == std::vector<std::string>{"Carol", "Bob"}, "an inclusive time range");
Check(Names(store.FindTransactions(key, {.limit = 1})) == std::vector<std::string>{"Dave"}, "at most `limit`");
Check(store.FindTransactions(key, {.search = "nothing like it"}).empty(), "a search that matches nothing");
const Transaction alice = store.FindTransactions(key, {.search = "alice"}).at(0);
Equal(alice.id, std::string("0"), "the bank's id is stored");
Equal(alice.kind, std::string("BUNQ/PAYMENT"), "and its classification");
Equal(std::format("{}", alice), std::string("2026-10-01 10:00\t-€1.00\tAlice\tNL02BUNQ0000000002\tgroceries"), "a transaction formats as one line");
// A table written by version 1 migrates when it is first opened, and its rows come back without id or kind.
const std::filesystem::path oldFile = directory.path / "transactions" / "test" / "v1" / "Old.cdb";
{
Crafter::DB::Table<OldTransaction> old(oldFile);
const std::array rows = {
OldTransaction{"First", "", "NL04", "old", Currency::Euro, 100, start},
OldTransaction{"Second", "", "NL05", "old", Currency::Euro, 200, start + minutes(5)},
};
old.Append(std::span<const OldTransaction>(rows));
old.Close();
}
Account migrated{"Old", "", "", Currency::Euro, 0};
const std::vector<Transaction> rows = migrated.FindTransactions("test/v1", {});
Check(Names(rows) == std::vector<std::string>{"Second", "First"}, "a version 1 table reads after its migration");
Check(rows.size() == 2 && rows[0].id.empty() && rows[0].kind.empty(), "migrated rows have no id or kind");
Check(std::filesystem::exists(std::format("{}.v1.bak", oldFile.string())), "the migration keeps the old file");
migrated.SaveTransactions("test/v1", {Made("Second", 5, "55"), Made("Third", 6, "66")});
Check(Names(migrated.FindTransactions("test/v1", {})) == std::vector<std::string>{"Third", "Second", "First"}, "a migrated row at the last timestamp is not stored again under an id");
return Test::Result();
}

View file

@ -0,0 +1,403 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// The bunq connector against a fake bunq (tests/Support/FakeBunq.inc): connecting every kind of user, the protocol's
// checks (signatures, rate limits, session renewal, errors, a refused connection), accounts, the transaction sync,
// cards, OAuth, logging out, removing, and the connector's JSON, old and new.
#include "../../lib/json.hpp"
#include <stdlib.h>
#include <time.h>
import std;
import Nostro;
import Crafter.Network;
#include "../Support/Check.inc"
#include "../Support/FakeBunq.inc"
using namespace Nostro;
using Test::Check;
using Test::Equal;
using Test::Throws;
using json = nlohmann::json;
using Fault = Fake::Fault;
namespace {
constexpr std::uint16_t port = 47302;
// Nothing listens for nostro on HTTPS's own port here, which also makes a request's authority the host alone.
constexpr std::uint16_t closedPort = 443;
std::vector<std::string> AccountNames(const BunqConnector& connector) {
return connector.accounts | std::views::transform(&BunqAccount::name) | std::ranges::to<std::vector<std::string>>();
}
BunqAccount& AccountNamed(BunqConnector& connector, std::string_view name) {
return *std::ranges::find(connector.accounts, name, &BunqAccount::name);
}
void Connecting(Fake::Bunq& bunq) {
const std::uint64_t person = bunq.AddPerson("T. Tester", "key-person");
bunq.AddAccount(person, "NL69BUNQ2025123456", "Bank Account", 50000);
bunq.AddAccount(person, "NL17BUNQ2025654321", "Savings", 100, "MonetaryAccountSavings");
bunq.AddAccount(person, "NL45BUNQ2025111111", "Joint", 200, "MonetaryAccountJoint");
bunq.AddAccount(person, "NL91ABNA0417164300", "Elsewhere", 300, "MonetaryAccountExternal");
bunq.ChangeAccount(bunq.AddAccount(person, "NL02BUNQ2025222222", "Blocked", 400), {{"status", "BLOCKED"}});
bunq.ChangeAccount(bunq.AddAccount(person, "NL03BUNQ2025333333", "Closed", 0), {{"status", "CANCELLED"}});
bunq.ChangeAccount(bunq.AddAccount(person, "NL04BUNQ2025444444", "Dollars", 0), {{"currency", "USD"}});
bunq.ChangeAccount(bunq.AddAccount(person, "NL05BUNQ2025555555", "No balance", 0), {{"balance", nullptr}});
bunq.ChangeAccount(bunq.AddAccount(person, "NL06BUNQ2025666666", "No alias", 0), {{"alias", nullptr}});
{
std::lock_guard lock(bunq.mutex);
bunq.extraAccountItems = {json{{"Unknown", json{{"id", 1}}}}, json{{"A", json::object()}, {"B", json::object()}}, json(5)};
bunq.pageSize = 3;
}
BunqConnector& connector = BunqConnector::Create("key-person", "1.2.3.4, ,5.6.7.8 ", BunqEnvironment::Sandbox);
Equal(connector.name, std::string("T. Tester"), "a person's name is its display name");
Equal(std::format("{}", connector), std::string("T. Tester"), "a connector formats as its name");
Equal(connector.userType, std::string("UserPerson"), "the user type");
Equal(connector.id, person, "the user id");
Equal(connector.ownerId, person, "an API key's owner is its user");
Check(connector.environment == BunqEnvironment::Sandbox && !connector.IsOAuth(), "a sandbox API key connector");
Check(connector.sessionId != 0 && !connector.sessionToken.empty() && connector.serverPublicKey != nullptr, "a session and the server's key");
Check(AccountNames(connector) == std::vector<std::string>{"No alias", "No balance", "Blocked", "Elsewhere", "Joint", "Savings", "Bank Account"}, "open accounts of every kind, across pages, without closed or unknown-currency ones");
Equal(AccountNamed(connector, "Bank Account").bic, std::string("BUNQNL2A"), "a bunq IBAN gets bunq's BIC");
Equal(AccountNamed(connector, "Bank Account").balance, std::int64_t{50000}, "the balance");
Equal(AccountNamed(connector, "Savings").type, std::string("MonetaryAccountSavings"), "the account's kind");
Equal(AccountNamed(connector, "Elsewhere").bic, std::string(""), "an IBAN of another bank gets no BIC");
Equal(AccountNamed(connector, "No balance").balance, std::int64_t{0}, "no balance is zero");
Equal(AccountNamed(connector, "No alias").iban, std::string(""), "no IBAN alias is no IBAN");
Check(AccountNamed(connector, "Bank Account").connector == &connector, "an account points at its connector");
Equal(AccountNamed(connector, "Bank Account").Path(), std::format("/user/{}/monetary-account/{}", person, AccountNamed(connector, "Bank Account").id), "an account's API path");
Equal(AccountNamed(connector, "Bank Account").StorageKey(), std::format("bunq/sandbox/{}/{}", person, AccountNamed(connector, "Bank Account").id), "an account's storage key");
{
std::lock_guard lock(bunq.mutex);
Check(bunq.devices.at("key-person").at("permitted_ips") == json::array({"1.2.3.4", "5.6.7.8"}), "the allowed addresses, trimmed, without empty ones");
bunq.pageSize = 200;
}
for(const Fake::Logged& entry : bunq.Log()) {
Check(!entry.signed_ || entry.signatureValid, std::format("{} {} is signed with the installation's key", entry.method, entry.path));
}
Check(bunq.Count("POST", "/installation") == 1 && bunq.Log().front().signed_ == false, "the installation call is not signed");
// Adding the same user again replaces the connector and ends the old session, even when ending it fails.
const std::size_t logouts = bunq.Count("DELETE", "/session/");
BunqConnector& again = BunqConnector::Create("key-person", "", BunqEnvironment::Sandbox);
Equal(BunqConnector::connectors.size(), std::size_t{1}, "the same user replaces its connector");
Check(&again == &connector, "in place");
Equal(bunq.Count("DELETE", "/session/"), logouts + 1, "the old session is ended");
{
std::lock_guard lock(bunq.mutex);
Check(!bunq.devices.at("key-person").contains("permitted_ips"), "no addresses: the device is bound to the one it is added from");
}
bunq.Fail(Fault{.method = "DELETE", .path = "/session/", .status = 500, .body = "{}"});
BunqConnector::Create("key-person", "*", BunqEnvironment::Sandbox);
Equal(BunqConnector::connectors.size(), std::size_t{1}, "a failed logout of the old session does not stop the new one");
// Every kind of user, and the names bunq gives them.
bunq.AddUser("UserCompany", json{{"name", "Acme B.V."}, {"display_name", "Acme B.V."}}, "key-company");
Equal(BunqConnector::Create("key-company", "*", BunqEnvironment::Sandbox).userType, std::string("UserCompany"), "a company");
bunq.AddUser("UserPaymentServiceProvider", json{{"display_name", ""}, {"name", ""}, {"legal_name", "Legal Name"}}, "key-psp");
Equal(BunqConnector::Create("key-psp", "*", BunqEnvironment::Sandbox).name, std::string("Legal Name"), "the legal name when there is no display name or name");
bunq.AddUser("UserPerson", json{{"public_nick_name", "Nick"}}, "key-nick");
Equal(BunqConnector::Create("key-nick", "*", BunqEnvironment::Sandbox).name, std::string("Nick"), "the nick name last");
bunq.AddUser("UserPerson", json{{"display_name", 7}}, "key-nameless");
Equal(BunqConnector::Create("key-nameless", "*", BunqEnvironment::Sandbox).name, std::string(""), "no name at all");
bunq.Fail(Fault{.method = "POST", .path = "/session-server", .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"Response":[{"Id":{"id":1}},{"Token":{"token":"t"}},5,{"A":{},"B":{}}]})"});
Throws([] { BunqConnector::Create("key-person", "*", BunqEnvironment::Sandbox); }, "bunq session names no user", "a session without a user");
bunq.Fail(Fault{.method = "POST", .path = "/session-server", .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"Response":[{"Id":{"id":1}}]})"});
Throws([] { BunqConnector::Create("key-person", "*", BunqEnvironment::Sandbox); }, "bunq response has no 'Token' object", "a session without a token");
Throws<BunqError>([] { BunqConnector::Create("no such key", "*", BunqEnvironment::Sandbox); }, "User credentials are incorrect", "an unknown API key");
Check(BunqConnector::EnvironmentOfKey("sandbox_abc") == BunqEnvironment::Sandbox, "a sandbox key");
Check(BunqConnector::EnvironmentOfKey("abc") == BunqEnvironment::Production, "any other key is production");
}
void OAuth(Fake::Bunq& bunq) {
Equal(BunqConnector::OAuthAuthorizationUrl(BunqEnvironment::Production, "id x", "https://cb/?a=b", "s1"), std::string("https://oauth.bunq.com/auth?response_type=code&client_id=id%20x&redirect_uri=https%3A%2F%2Fcb%2F%3Fa%3Db&state=s1"), "the production authorization URL, encoded");
Equal(BunqConnector::OAuthAuthorizationUrl(BunqEnvironment::Sandbox, "id", "nostro://cb", "s2"), std::string("https://oauth.sandbox.bunq.com/auth?response_type=code&client_id=id&redirect_uri=nostro%3A%2F%2Fcb&state=s2"), "the sandbox one");
const std::uint64_t owner = bunq.AddPerson("O. Owner", "key-owner");
bunq.AddAccount(owner, "NL07BUNQ2025777777", "Shared", 1000);
const std::uint64_t grant = bunq.AddGrant(owner, "code-1", "token-1");
Equal(BunqConnector::OAuthExchangeCode(BunqEnvironment::Sandbox, bunq.clientId, bunq.clientSecret, "https://cb", "code-1"), std::string("token-1"), "a code gives its token");
Throws<BunqError>([&bunq] { BunqConnector::OAuthExchangeCode(BunqEnvironment::Production, bunq.clientId, bunq.clientSecret, "https://cb", "code-1"); }, "The authorization code is invalid or expired. (400)", "a code works once");
bunq.Fail(Fault{.method = "POST", .path = "/token", .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"token_type":"bearer"})"});
Throws<BunqError>([&bunq] { BunqConnector::OAuthExchangeCode(BunqEnvironment::Sandbox, bunq.clientId, bunq.clientSecret, "https://cb", "code-x"); }, "bunq OAuth token exchange", "an answer without a token");
BunqConnector& connector = BunqConnector::Create("token-1", "*", BunqEnvironment::Sandbox);
Check(connector.IsOAuth() && connector.userType == "UserApiKey", "an OAuth connection");
Equal(connector.id, grant, "its user id is the grant's own");
Equal(connector.ownerId, owner, "its owner is the user who granted access");
Equal(connector.name, std::string("O. Owner"), "and so is its name");
Check(AccountNames(connector) == std::vector<std::string>{"Shared"}, "the granted accounts");
// The same owner with an API key as well would list every account twice.
Throws([] { BunqConnector::Create("key-owner", "*", BunqEnvironment::Sandbox); }, "O. Owner is already connected through OAuth", "an API key for an owner connected through OAuth");
bunq.Fail(Fault{.method = "DELETE", .path = "/session/", .status = 500, .body = "{}"});
Throws([] { BunqConnector::Create("key-owner", "*", BunqEnvironment::Sandbox); }, "already connected through OAuth", "also when ending the refused session fails");
bunq.AddGrant(owner, "code-2", "token-2");
Equal(BunqConnector::Create("token-2", "*", BunqEnvironment::Sandbox).id, bunq.keys.at("token-2"), "a new grant for the owner replaces the old one");
// And the other way round: a grant for an owner connected with an API key.
const std::uint64_t keyed = bunq.AddPerson("K. Keyed", "key-keyed");
BunqConnector::Create("key-keyed", "*", BunqEnvironment::Sandbox);
bunq.AddGrant(keyed, "code-3", "token-3");
Throws([] { BunqConnector::Create("token-3", "*", BunqEnvironment::Sandbox); }, "K. Keyed is already connected with an API key", "a grant for an owner connected with an API key");
bunq.AddUser("UserApiKey", json{{"granted_by_user", json::object()}}, "token-empty");
BunqConnector& empty = BunqConnector::Create("token-empty", "*", BunqEnvironment::Sandbox);
Check(empty.name.empty() && empty.ownerId == empty.id, "a grant that names nobody");
}
void Protocol(Fake::Bunq& bunq, BunqConnector& connector) {
const std::string user = std::format("/user/{}", connector.id);
Check(connector.Get(user).contains("Response"), "a plain call");
Check(connector.Get(std::format("/v1{}", user)).contains("Response"), "a path that already has /v1, as pagination URLs do");
bunq.Fail(Fault{.method = "GET", .kind = Fault::Kind::Unsigned});
Throws([&] { connector.Get(user); }, "the response is not signed by bunq's server key", "an unsigned answer");
bunq.Fail(Fault{.method = "GET", .kind = Fault::Kind::BadSignature});
Throws([&] { connector.Get(user); }, "not signed by bunq's server key", "an answer signed by another key");
bunq.Fail(Fault{.method = "PUT", .kind = Fault::Kind::Reply, .status = 200, .body = "{}"});
Throws([&] { connector.Put(std::format("{}/card/1", user), json::object()); }, "not signed by bunq's server key; the request may have been carried out", "a write whose answer is not signed may have happened");
bunq.Fail(Fault{.method = "GET", .kind = Fault::Kind::SignedReply, .status = 200, .body = "not json"});
Throws([&] { connector.Get(user); }, "unreadable response", "an answer that is not JSON");
bunq.Fail(Fault{.method = "PUT", .kind = Fault::Kind::SignedReply, .status = 200, .body = "not json"});
Throws([&] { connector.Put(std::format("{}/card/1", user), json::object()); }, "may have been carried out", "an unreadable answer to a write");
bunq.Fail(Fault{.method = "DELETE", .kind = Fault::Kind::SignedReply, .status = 200, .body = ""});
Check(connector.Delete(std::format("{}/nothing", user)) == json::object(), "an empty answer is an empty object");
// A rate limit is waited out.
const std::size_t before = bunq.Count("GET", user);
bunq.Fail(Fault{.method = "GET", .status = 429, .body = R"({"Error":[{"error_description":"Too many requests."}]})"});
Check(connector.Get(user).contains("Response"), "a 429 is retried");
Equal(bunq.Count("GET", user), before + 2, "once");
// An ended session is opened again, once, and saved.
const std::string session = connector.sessionToken;
bunq.Fail(Fault{.method = "GET", .status = 401, .body = R"({"Error":[{"error_description":"Session expired."}]})"});
Check(connector.Get(user).contains("Response"), "a 401 opens a new session");
Check(connector.sessionToken != session, "with a new token");
Check(std::filesystem::exists(configPath / "connectors.json"), "which is saved");
bunq.ExpireSessions();
Check(connector.Get(user).contains("Response"), "a 403 Insufficient authentication. opens one too");
bunq.Fail(Fault{.method = "GET", .status = 403, .body = R"({"Error":[{"error_description":"Not allowed."}]})"});
Throws<BunqError>([&] { connector.Get(user); }, "Not allowed. (403)", "another 403 is an error");
bunq.Fail(Fault{.method = "GET", .status = 401, .body = "{}", .times = 2});
Throws<BunqError>([&] { connector.Get(user); }, "(401)", "a session is renewed once per call");
// Errors, and the ways bunq and its OAuth server describe them.
bunq.Fail(Fault{.method = "GET", .status = 500, .body = R"({"Error":[{"error_description":"one"},{"error_description":"two"},{"other":1}]})"});
Throws<BunqError>([&] { connector.Get(user); }, "bunq GET /user/", "a 5xx on a read");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = R"({"Error":[{"error_description":"one"},{"error_description":"two"},{"other":1}]})"});
Throws<BunqError>([&] { connector.Get(user); }, ": one; two (400)", "every error description, joined");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = R"({"error":"x","error_description":"y"})"});
Throws<BunqError>([&] { connector.Get(user); }, ": y (400)", "an OAuth-style description");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = R"({"error":"x"})"});
Throws<BunqError>([&] { connector.Get(user); }, ": x (400)", "an OAuth-style error alone");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = R"({"Error":"not a list"})"});
Throws<BunqError>([&] { connector.Get(user); }, R"({"Error":"not a list"} (400))", "an error body nostro cannot read is shown as it is");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = "plain text"});
Throws<BunqError>([&] { connector.Get(user); }, ": plain text (400)", "an error that is not JSON");
bunq.Fail(Fault{.method = "GET", .status = 400, .body = ""});
Throws<BunqError>([&] { connector.Get(user); }, ": no details (400)", "an empty error");
bunq.Fail(Fault{.method = "PUT", .status = 502, .body = ""});
Throws<BunqError>([&] { connector.Put(std::format("{}/card/1", user), json::object()); }, "(502); the request may have been carried out", "a 5xx leaves a write's outcome open");
try {
connector.Get(std::format("{}/nothing", user));
} catch(const BunqError& e) {
Equal(e.status, std::uint16_t{404}, "a BunqError carries the status");
}
// A connection that cannot be made: a read says so as it is, a write that its outcome is unknown.
BunqConnector::RedirectTo(BunqEndpoint{.host = "127.0.0.1", .port = closedPort, .caPem = ""});
Throws([&] { connector.Get(user); }, "", "a read that cannot connect throws");
Throws([&] { connector.Post(std::format("{}/card", user), json::object()); }, "may have been carried out", "a write that cannot connect may have happened");
bunq.Redirect();
// List follows a listing's pages, adding count to a path with or without a query.
connector.List(std::format("{}/monetary-account?status=ACTIVE", user));
Equal(bunq.Log().back().path, std::format("{}/monetary-account?status=ACTIVE&count=200", user), "count is added to a path with a query");
bunq.Fail(Fault{.method = "GET", .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"Response":[{"A":{}}]})"});
Equal(connector.List(std::format("{}/card", user)).size(), std::size_t{1}, "a listing without pagination is one page");
}
void Transactions(Fake::Bunq& bunq, BunqConnector& connector) {
BunqAccount& account = AccountNamed(connector, "Bank Account");
const std::uint64_t id = account.id;
bunq.AddPayment(id, 10000, "Employer", "NL91ABNA0417164300", "salary", json{{"counterparty_alias", json{{"iban", "NL91ABNA0417164300"}, {"display_name", "Employer"}, {"swift_bic", "ABNANL2A"}}}});
bunq.AddPayment(id, -250, "Shop", "", "coffee", json{{"type", "MASTERCARD"}, {"counterparty_alias", json{{"iban", nullptr}, {"display_name", "Shop"}}}});
bunq.AddPayment(id, -1000, "Friend", "NL17BUNQ2025654321", "dinner");
bunq.AddPayment(id, -500, "", "", "", json{{"counterparty_alias", json{{"iban", nullptr}, {"label_user", json{{"display_name", "Label User"}}}}}});
bunq.AddPayment(id, 700, "Refund", "NL69BUNQ2025123456", "refund", json{{"sub_type", "REVERSAL"}});
{
std::lock_guard lock(bunq.mutex);
bunq.payments[id].insert(bunq.payments[id].begin() + 2, json{{"Other", json{{"id", 1}}}});
bunq.pageSize = 2;
}
connector.GetNewTransactions(account);
const std::vector<Transaction> first = account.FindTransactions(account.StorageKey(), {});
Equal(first.size(), std::size_t{5}, "the first sync stores the whole history, across pages, skipping what is not a payment");
Equal(first.at(0).kind, std::string("BUNQ/REVERSAL"), "the type and sub type");
Equal(first.at(1).name, std::string("Label User"), "the user's name when the account has none");
Equal(first.at(3).bic, std::string(""), "no IBAN, no BIC");
Equal(first.at(3).kind, std::string("MASTERCARD/PAYMENT"), "a card payment");
Equal(first.at(4).bic, std::string("ABNANL2A"), "a BIC bunq gives");
Equal(first.at(2).bic, std::string("BUNQNL2A"), "bunq's BIC for a bunq IBAN without one");
Equal(first.at(4).amount, std::int64_t{10000}, "the amount");
// A later sync reads only to the last stored payment; one at the very same time with a new id is new.
const std::size_t pages = bunq.Count("GET", std::format("/user/{}/monetary-account/{}/payment", connector.id, id));
const std::string last = bunq.AccountObject(id).at("id").dump();
bunq.AddPayment(id, -100, "Same time", "", "same", json{{"created", Fake::Time(4)}});
bunq.AddPayment(id, -200, "Newest", "", "new");
connector.GetNewTransactions();
const std::vector<Transaction> second = account.FindTransactions(account.StorageKey(), {});
Equal(second.size(), std::size_t{7}, "a later sync adds what is new");
Equal(bunq.Count("GET", std::format("/user/{}/monetary-account/{}/payment", connector.id, id)) - pages, std::size_t{2}, "and stops at what it has");
Check(last.size() > 0, "the account exists");
bunq.Fail(Fault{.method = "GET", .path = std::format("/user/{}/monetary-account/{}/payment", connector.id, id), .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"Response":[]})"});
connector.GetNewTransactions(account);
Equal(account.FindTransactions(account.StorageKey(), {}).size(), std::size_t{7}, "a page without pagination ends the sync");
std::lock_guard lock(bunq.mutex);
bunq.pageSize = 200;
}
void Cards(Fake::Bunq& bunq, BunqConnector& connector) {
const std::uint64_t active = bunq.AddCard(connector.id, "ACTIVE");
bunq.AddCard(connector.id, "DEACTIVATED", json{{"primary_account_numbers", json::array()}, {"label_monetary_account_current", nullptr}});
{
std::lock_guard lock(bunq.mutex);
bunq.cards[connector.id].push_back(json{{"A", json::object()}, {"B", json::object()}});
}
const std::vector<BunqCard> cards = connector.Cards();
Equal(cards.size(), std::size_t{2}, "the cards, without what is not one");
Equal(cards.at(0).lastFour, std::string("1234"), "the last four digits");
Equal(cards.at(0).iban, std::string("NL01BUNQ0000000001"), "the account it pays from");
Equal(cards.at(0).kind, std::string("CardDebit"), "the kind of card");
Check(cards.at(1).lastFour.empty() && cards.at(1).iban.empty(), "a card without numbers or account");
Equal(std::format("{}", cards.at(0)), std::format("{}\tACTIVE\tMASTERCARD_DEBIT\t**** 1234\tJ. Tester\tNostro\tNL01BUNQ0000000001\texpires 2030-11-30", active), "a card formats as one line");
Equal(connector.SetCardStatus(active, "DEACTIVATED").status, std::string("DEACTIVATED"), "freezing a card");
{
std::lock_guard lock(bunq.mutex);
bunq.cardsActivate = false;
}
Equal(connector.SetCardStatus(active, "ACTIVE").status, std::string("DEACTIVATED"), "the card as bunq keeps it");
bunq.Fail(Fault{.method = "PUT", .kind = Fault::Kind::SignedReply, .status = 200, .body = R"({"Response":[{"Id":{"id":1}}]})"});
Throws([&] { connector.SetCardStatus(active, "ACTIVE"); }, "bunq did not return the card it updated", "an answer without the card");
}
void Sessions(Fake::Bunq& bunq, BunqConnector& connector) {
Check(connector.TestConnector(), "a working connector");
connector.Logout();
Check(connector.sessionToken.empty(), "logging out forgets the session");
connector.Logout();
Check(connector.sessionToken.empty(), "logging out of a session that is gone is fine");
Check(connector.TestConnector(), "a call after logging out opens a new session");
bunq.Fail(Fault{.method = "DELETE", .path = "/session/", .status = 500, .body = "{}"});
Throws<BunqError>([&] { connector.Logout(); }, "(500)", "a logout bunq fails is an error");
{
std::lock_guard lock(bunq.mutex);
bunq.keys.erase("key-company");
}
bunq.ExpireSessions();
BunqConnector& revoked = *std::ranges::find(BunqConnector::connectors, std::string("Acme B.V."), &BunqConnector::name);
Check(!revoked.TestConnector(), "a connector whose key is revoked does not work");
}
// The connector's JSON, through connectors.json as nostro reads and writes it.
void Json(Fake::Bunq& bunq) {
const std::filesystem::path file = configPath / "connectors.json";
// Saved with a live session, so loading needs no renewal.
BunqConnector::connectors.at(0).TestConnector();
Connector::SaveConnectors();
std::ifstream in(file);
json saved = json::parse(in);
const json first = saved.at("bunq").at(0);
Check(first.at("environment") == "sandbox" && first.contains("serverPublicKey") && first.contains("ownerId") && first.contains("sessionId") && first.contains("userType"), "a connector is saved with its environment, server key, owner, session and user type");
// A connector saved before 2026-10-31, and one for production without a server key.
json legacy = first;
for(const std::string field : {"environment", "serverPublicKey", "sessionId", "userType", "ownerId"}) {
legacy.erase(field);
}
json production = first;
production["environment"] = "production";
production.erase("serverPublicKey");
{
std::ofstream out(file);
out << json{{"bunq", json::array({legacy, production})}}.dump();
}
const std::size_t fetched = bunq.Count("GET", "/installation");
Connector::LoadConnectors();
Equal(BunqConnector::connectors.size(), std::size_t{2}, "both load");
const BunqConnector& old = BunqConnector::connectors.at(0);
Check(old.environment == BunqEnvironment::Sandbox && old.ownerId == old.id && old.sessionId == 0 && old.userType.empty(), "an old connector is a sandbox one, owned by its user");
Check(old.serverPublicKey != nullptr && !old.accounts.empty(), "and fetches the server key before its first call");
Check(BunqConnector::connectors.at(1).environment == BunqEnvironment::Production, "the environment reads back");
Equal(bunq.Count("GET", "/installation"), fetched + 4, "each fetches the installation and its key once");
std::ifstream reread(file);
Check(json::parse(reread).at("bunq").at(0).contains("serverPublicKey"), "and the file has it after");
}
void Removing(Fake::Bunq& bunq) {
BunqConnector::connectors.clear();
bunq.AddAccount(bunq.AddPerson("First", "key-first"), "NL08BUNQ2025888888", "First account", 0);
bunq.AddAccount(bunq.AddPerson("Second", "key-second"), "NL09BUNQ2025999999", "Second account", 0);
BunqConnector& first = BunqConnector::Create("key-first", "*", BunqEnvironment::Sandbox);
BunqConnector::Create("key-second", "*", BunqEnvironment::Sandbox);
const std::filesystem::path stored = cachePath / "transactions" / first.StorageKey();
std::filesystem::create_directories(stored);
BunqConnector::Remove(first);
Equal(BunqConnector::connectors.size(), std::size_t{1}, "a connector is removed");
Check(!std::filesystem::exists(stored), "with its stored transactions");
Check(BunqConnector::connectors.front().accounts.front().connector == &BunqConnector::connectors.front(), "the others' accounts point at where their connector is now");
// Removed while this process has its table open, then added again: the account syncs into a new table on
// disk, not into the deleted one.
BunqConnector& second = BunqConnector::connectors.front();
second.GetNewTransactions();
const std::filesystem::path table = cachePath / "transactions" / second.accounts.front().StorageKey() / "Second account.cdb";
Check(std::filesystem::exists(table), "a synced account has its table");
BunqConnector::Remove(second);
Check(!std::filesystem::exists(table), "removing deletes it");
BunqConnector::Create("key-second", "*", BunqEnvironment::Sandbox).GetNewTransactions();
Check(std::filesystem::exists(table), "added again, it syncs into a new table");
BunqConnector stray;
Throws<std::invalid_argument>([&stray] { BunqConnector::Remove(stray); }, "not in BunqConnector::connectors", "a connector that is not listed");
}
}
int main() {
const Test::Directory directory("bunq");
configPath = directory.path / "config";
cachePath = directory.path / "cache";
setenv("TZ", "UTC", 1);
tzset();
// Before anything is redirected: bunq's own hosts.
Equal(BunqConnector::Endpoint(BunqEnvironment::Production).host, std::string("api.bunq.com"), "production's host");
Equal(BunqConnector::Endpoint(BunqEnvironment::Sandbox).host, std::string("public-api.sandbox.bunq.com"), "the sandbox's host");
Equal(BunqConnector::Endpoint(BunqEnvironment::Sandbox).port, std::uint16_t{443}, "on HTTPS's port");
Fake::Bunq bunq(port);
bunq.Redirect();
Equal(BunqConnector::Endpoint(BunqEnvironment::Production).port, port, "a redirect replaces every environment's endpoint");
Connecting(bunq);
OAuth(bunq);
BunqConnector& person = *std::ranges::find(BunqConnector::connectors, std::string("T. Tester"), &BunqConnector::name);
Protocol(bunq, person);
Transactions(bunq, person);
Cards(bunq, person);
Sessions(bunq, person);
Json(bunq);
Removing(bunq);
return Test::Result();
}

67
tests/Support/Check.inc Normal file
View file

@ -0,0 +1,67 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// What every test checks with, included after `import std;`. A failed check prints where and why and makes the test
// exit 1; the test goes on, so one run lists every failure.
namespace Test {
std::int32_t failures = 0;
void Check(bool condition, std::string_view what, std::source_location where = std::source_location::current()) {
if(!condition) {
std::println("FAIL {}:{}: {}", where.file_name(), where.line(), what);
failures++;
}
}
template<typename Actual, typename Expected>
void Equal(const Actual& actual, const Expected& expected, std::string_view what, std::source_location where = std::source_location::current()) {
if(!(actual == expected)) {
std::println("FAIL {}:{}: {}: expected '{}', got '{}'", where.file_name(), where.line(), what, expected, actual);
failures++;
}
}
// `code` throws an E whose what() contains `part`.
template<typename E = std::exception, typename Code>
void Throws(Code&& code, std::string_view part, std::string_view what, std::source_location where = std::source_location::current()) {
try {
code();
} catch(const E& e) {
if(!std::string_view(e.what()).contains(part)) {
std::println("FAIL {}:{}: {}: the error '{}' does not say '{}'", where.file_name(), where.line(), what, e.what(), part);
failures++;
}
return;
} catch(...) {
std::println("FAIL {}:{}: {}: threw something else", where.file_name(), where.line(), what);
failures++;
return;
}
std::println("FAIL {}:{}: {}: did not throw", where.file_name(), where.line(), what);
failures++;
}
std::int32_t Result() {
if(failures == 0) {
std::println("all checks passed");
return 0;
}
std::println("{} check(s) failed", failures);
return 1;
}
// A fresh directory for one test's files, deleted with everything in it when the test ends.
struct Directory {
std::filesystem::path path;
explicit Directory(std::string_view name) : path(std::filesystem::temp_directory_path() / std::format("nostro-{}-{}", name, std::random_device()())) {
std::filesystem::create_directories(path);
}
~Directory() {
std::error_code ignored;
std::filesystem::remove_all(path, ignored);
}
};
}

694
tests/Support/FakeBunq.inc Normal file
View file

@ -0,0 +1,694 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// A bunq for tests, included after `#include "../../lib/json.hpp"`, `import std;`, `import Nostro;` and
// `import Crafter.Network;`. It serves HTTPS on 127.0.0.1 with Crafter.Network's self-signed certificate,
// answers the calls nostro makes from a small state of its own, signs every success with its own key as bunq does,
// checks the client's signatures, and fails on request. Point nostro at it with Fake::Bunq::Redirect().
namespace Fake {
using json = nlohmann::json;
// bunq's clock: every object made moves it on a minute, from 2026-10-01 10:00 UTC.
std::string Time(std::uint32_t minutes) {
return Nostro::FormatTimestamp(Nostro::ParseTimestamp("2026-10-01 10:00:00") + std::chrono::minutes(minutes));
}
// A value of `query` ("a=1&b=2"), decoded.
std::string Param(std::string_view query, std::string_view name) {
return Nostro::QueryParameter(std::format("?{}", query), name).value_or("");
}
std::int64_t Minor(const json& amount) {
return Nostro::ParseAmount(amount.at("value").get<std::string>(), Nostro::Currency::Euro);
}
json Amount(std::int64_t minor) {
return json{{"value", Nostro::FormatAmount(minor, Nostro::Currency::Euro)}, {"currency", "EUR"}};
}
// What the server does instead of answering, for the next `times` requests that match.
struct Fault {
enum class Kind : std::uint8_t {
Reply, // `status` and `body`, unsigned, as bunq sends an error
SignedReply, // `status` and `body`, signed: a success bunq would not send
Unsigned, // the real answer without its signature
BadSignature, // the real answer signed with another key
};
std::string method; // empty matches every method
std::string path; // a prefix of the path below /v1, without the query; empty matches every path
Kind kind = Kind::Reply;
std::uint16_t status = 500;
std::string body;
std::uint32_t times = 1;
};
// One request as the server saw it.
struct Logged {
std::string method;
std::string path; // below /v1, with the query
std::string body;
bool signed_ = false; // carried an X-Bunq-Client-Signature
bool signatureValid = false; // which verified against the installation's key
};
class Bunq {
public:
// The server answers on threads of its own: lock this around anything a test reads or changes while nostro
// could be calling.
std::mutex mutex;
std::uint16_t port;
Nostro::Crypto::Key key; // signs every success
Nostro::Crypto::Key otherKey; // signs for BadSignature
std::string publicKeyPem;
std::uint64_t nextId = 1000;
std::uint32_t clock = 0;
std::size_t pageSize = 200; // a listing sends at most this many per page, whatever its count asks
std::string scheduledName = "ScheduledPayment";
bool cardsActivate = true; // false: PUT card ACTIVE leaves the card as it is, as the sandbox does
struct Installation {
std::uint64_t id;
std::string clientKeyPem;
};
struct Session {
std::uint64_t id;
std::string key; // the API key or OAuth token the session was opened with
std::string installation; // its installation token
};
std::map<std::string, Installation> installations; // by token
std::map<std::string, Session> sessions; // by token
std::map<std::string, std::uint64_t> keys; // API key or OAuth token: the user it opens a session for
std::map<std::string, json> devices; // API key: the device-server body that registered it
std::map<std::uint64_t, std::pair<std::string, json>> users; // id: the object's type and the object
std::map<std::uint64_t, std::pair<std::string, json>> accounts; // id: the object's type and the object
std::vector<json> extraAccountItems; // listed first, as they are
std::map<std::uint64_t, std::vector<json>> payments; // account id: items, newest first
std::map<std::uint64_t, std::vector<json>> inquiries; // account id: RequestInquiry items, newest first
std::map<std::uint64_t, std::vector<json>> responses; // account id: RequestResponse items, newest first
std::map<std::uint64_t, std::vector<json>> schedules; // account id: items, newest first
std::map<std::uint64_t, std::vector<json>> drafts; // account id: DraftPayment items, newest first
std::map<std::uint64_t, std::vector<json>> cards; // user id: card items
std::map<std::string, std::string> codes; // OAuth authorization code: the token it gives
std::string clientId = "fake-client";
std::string clientSecret = "fake-secret";
std::vector<Fault> faults;
std::vector<Logged> log;
explicit Bunq(std::uint16_t port) : port(port), key(Nostro::Crypto::OwnKey(std::get<0>(Nostro::Crypto::CreateKey()))), otherKey(Nostro::Crypto::OwnKey(std::get<0>(Nostro::Crypto::CreateKey()))), publicKeyPem(Nostro::Crypto::PublicKeyToPem(key.get())), listener(port, {}, [this](const Crafter::HTTPRequest& request) { return Answer(request); }, Crafter::TLSServerCredentials{.selfSigned = true}) {
}
// Sends nostro's bunq calls here.
void Redirect() const {
Nostro::BunqConnector::RedirectTo(Nostro::BunqEndpoint{.host = "127.0.0.1", .port = port, .caPem = Crafter::GetSelfSignedCertificatePem().certificate});
}
// Points the processes this test starts (nostrod and its workers) at the bunq it will run on `port`: in
// NOSTRO_TEST_BUNQ, "<port> <file with this process's certificate>", read by RedirectFromEnvironment(). Called
// before any thread starts, as it sets the environment.
static void ExportRedirect(std::uint16_t port, const std::filesystem::path& certificate) {
std::ofstream(certificate) << Crafter::GetSelfSignedCertificatePem().certificate;
setenv("NOSTRO_TEST_BUNQ", std::format("{} {}", port, certificate.string()).c_str(), 1);
}
// In a process the test started: sends nostro to the test's bunq, as ExportRedirect() said.
static void RedirectFromEnvironment() {
std::istringstream variable(std::getenv("NOSTRO_TEST_BUNQ"));
std::uint16_t port = 0;
std::string certificate;
variable >> port >> certificate;
std::ifstream file(certificate);
Nostro::BunqConnector::RedirectTo(Nostro::BunqEndpoint{.host = "127.0.0.1", .port = port, .caPem = std::string(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>())});
}
// A user, its API key, and nothing else; `object` is what bunq says about it ("id" is filled in).
std::uint64_t AddUser(std::string_view type, json object, std::string_view apiKey) {
std::lock_guard lock(mutex);
const std::uint64_t id = nextId++;
object["id"] = id;
users[id] = {std::string(type), std::move(object)};
if(!apiKey.empty()) {
keys[std::string(apiKey)] = id;
}
return id;
}
std::uint64_t AddPerson(std::string_view name, std::string_view apiKey) {
return AddUser("UserPerson", json{{"display_name", name}, {"public_nick_name", name}}, apiKey);
}
// An OAuth grant of `granted`'s accounts: a UserApiKey of its own, and the code that gives its token.
std::uint64_t AddGrant(std::uint64_t granted, std::string_view code, std::string_view token) {
json grantedObject;
{
std::lock_guard lock(mutex);
grantedObject = json{{users.at(granted).first, users.at(granted).second}};
codes[std::string(code)] = std::string(token);
}
return AddUser("UserApiKey", json{{"requested_by_user", json{{"UserPerson", json{{"id", 1}, {"display_name", "Nostro"}}}}}, {"granted_by_user", grantedObject}}, token);
}
std::uint64_t AddAccount(std::uint64_t user, std::string_view iban, std::string_view description, std::int64_t balance, std::string_view type = "MonetaryAccountBank") {
std::lock_guard lock(mutex);
const std::uint64_t id = nextId++;
accounts[id] = {std::string(type), json{
{"id", id},
{"user_id", user},
{"description", description},
{"currency", "EUR"},
{"status", "ACTIVE"},
{"balance", Amount(balance)},
{"alias", json::array({json{{"type", "PHONE_NUMBER"}, {"value", "+31600000000"}}, json{{"type", "IBAN"}, {"value", iban}, {"name", description}}})},
}};
return id;
}
// A payment as bunq lists it, on `account`; `extra` overrides or adds fields.
std::uint64_t AddPayment(std::uint64_t account, std::int64_t amount, std::string_view counterparty, std::string_view iban, std::string_view description, json extra = json::object()) {
std::lock_guard lock(mutex);
return AddPaymentLocked(account, amount, counterparty, iban, description, std::move(extra));
}
std::uint64_t AddCard(std::uint64_t user, std::string_view status, json extra = json::object()) {
std::lock_guard lock(mutex);
const std::uint64_t id = nextId++;
json card = {
{"id", id},
{"status", status},
{"order_status", "VIRTUAL_DELIVERY"},
{"product_type", "MASTERCARD_DEBIT"},
{"name_on_card", "J. Tester"},
{"second_line", "Nostro"},
{"expiry_date", "2030-11-30"},
{"primary_account_numbers", json::array({json{{"four_digit", "1234"}}})},
{"label_monetary_account_current", json{{"iban", "NL01BUNQ0000000001"}}},
};
card.update(extra);
cards[user].push_back(json{{"CardDebit", card}});
return id;
}
void Fail(Fault fault) {
std::lock_guard lock(mutex);
faults.push_back(std::move(fault));
}
std::vector<Logged> Log() {
std::lock_guard lock(mutex);
return log;
}
std::size_t Count(std::string_view method, std::string_view pathPrefix) {
std::lock_guard lock(mutex);
return static_cast<std::size_t>(std::ranges::count_if(log, [method, pathPrefix](const Logged& entry) { return entry.method == method && entry.path.starts_with(pathPrefix); }));
}
// Ends every session, as an expiry would.
void ExpireSessions() {
std::lock_guard lock(mutex);
sessions.clear();
}
json AccountObject(std::uint64_t id) {
std::lock_guard lock(mutex);
return accounts.at(id).second;
}
void ChangeAccount(std::uint64_t id, const json& changes) {
std::lock_guard lock(mutex);
accounts.at(id).second.update(changes);
}
private:
// Last, so the rest is ready when it starts accepting.
Crafter::ListenerAsyncHTTP1 listener;
json Error(std::string_view description) {
return json{{"Error", json::array({json{{"error_description", description}, {"error_description_translated", description}}})}};
}
static json Response(json items) {
return json{{"Response", std::move(items)}};
}
static json Id(std::uint64_t id) {
return Response(json::array({json{{"Id", json{{"id", id}}}}}));
}
static std::uint64_t ItemId(const json& item) {
if(!item.is_object() || item.size() != 1 || !item.begin().value().is_object() || !item.begin().value().contains("id")) {
return std::numeric_limits<std::uint64_t>::max();
}
return item.begin().value().at("id").get<std::uint64_t>();
}
json Label(std::uint64_t account) {
const json& object = accounts.at(account).second;
std::string iban;
for(const json& alias : object.value("alias", json::array())) {
if(alias.value("type", "") == "IBAN") {
iban = alias.at("value").get<std::string>();
}
}
// bunq shows an account by its holder's name, as it did "Sugar Daddy" in the sandbox.
const std::uint64_t user = object.value("user_id", std::uint64_t{0});
const std::string holder = users.contains(user) ? users.at(user).second.value("display_name", "") : std::string();
return json{{"iban", iban}, {"display_name", holder.empty() ? object.value("description", "") : holder}, {"label_user", json{{"display_name", holder}}}};
}
std::optional<std::uint64_t> AccountOfIban(std::string_view iban) {
for(const auto& [id, account] : accounts) {
for(const json& alias : account.second.value("alias", json::array())) {
if(alias.value("type", "") == "IBAN" && alias.value("value", "") == iban) {
return id;
}
}
}
return std::nullopt;
}
// What a payment's counterparty looks like in a listing.
json CounterpartyLabel(const json& pointer) {
if(pointer.value("type", "") == "IBAN") {
return json{{"iban", pointer.at("value")}, {"display_name", pointer.value("name", "")}};
}
return json{{"iban", nullptr}, {"display_name", pointer.value("name", "")}, {"label_user", json{{"display_name", pointer.value("name", "")}}}};
}
std::uint64_t AddPaymentLocked(std::uint64_t account, std::int64_t amount, std::string_view counterparty, std::string_view iban, std::string_view description, json extra) {
const std::uint64_t id = nextId++;
json payment = {
{"id", id},
{"created", Time(clock++)},
{"monetary_account_id", account},
{"amount", Amount(amount)},
{"counterparty_alias", json{{"iban", iban.empty() ? json(nullptr) : json(iban)}, {"display_name", counterparty}}},
{"description", description},
{"type", "BUNQ"},
{"sub_type", "PAYMENT"},
};
payment.update(extra);
payments[account].insert(payments[account].begin(), json{{"Payment", payment}});
json& balance = accounts.at(account).second["balance"];
if(balance.is_object()) {
balance = Amount(Minor(balance) + amount);
}
return id;
}
// Moves money out of `from` to whoever `pointer` names, and into their account when it is one of ours.
std::uint64_t Pay(std::uint64_t from, const json& amount, const json& pointer, std::string_view description) {
const std::int64_t minor = Minor(amount);
const json label = CounterpartyLabel(pointer);
const std::uint64_t id = AddPaymentLocked(from, -minor, label.value("display_name", ""), label.at("iban").is_string() ? label.at("iban").get<std::string>() : std::string(), description, json::object());
if(pointer.value("type", "") == "IBAN") {
if(const std::optional<std::uint64_t> to = AccountOfIban(pointer.at("value").get<std::string>())) {
const json payer = Label(from);
AddPaymentLocked(*to, minor, payer.value("display_name", ""), payer.value("iban", ""), description, json::object());
}
}
return id;
}
// A listing page of `items` (newest first) by bunq's count and older_id.
json Page(const std::vector<json>& items, std::string_view path, std::string_view query) {
const std::string count = Param(query, "count");
const std::size_t limit = std::min<std::size_t>(count.empty() ? 10 : std::stoul(count), pageSize);
const std::string older = Param(query, "older_id");
const std::uint64_t olderId = older.empty() ? std::numeric_limits<std::uint64_t>::max() : std::stoull(older);
json page = json::array();
std::uint64_t last = 0;
bool more = false;
for(const json& item : items) {
const std::uint64_t id = ItemId(item);
if(id != std::numeric_limits<std::uint64_t>::max() && id >= olderId) {
continue;
}
if(page.size() == limit) {
more = true;
break;
}
page.push_back(item);
last = id;
}
return json{
{"Response", page},
{"Pagination", json{
{"future_url", std::format("/v1{}?newer_id={}", path, last)},
{"newer_url", nullptr},
{"older_url", more ? json(std::format("/v1{}?count={}&older_id={}", path, count.empty() ? "10" : count, last)) : json(nullptr)},
}},
};
}
json* FindItem(std::vector<json>& items, std::string_view type, std::uint64_t id) {
for(json& item : items) {
if(item.contains(type) && item.at(type).at("id").get<std::uint64_t>() == id) {
return &item.at(type);
}
}
return nullptr;
}
std::pair<std::uint16_t, json> Route(const std::string& method, const std::vector<std::string>& part, const std::string& path, const std::string& query, const json& body, const std::string& authentication) {
const auto is = [&part](std::initializer_list<std::string_view> pattern) {
if(part.size() != pattern.size()) {
return false;
}
std::size_t i = 0;
for(const std::string_view expected : pattern) {
if(expected != "*" && part[i] != expected) {
return false;
}
i++;
}
return true;
};
const auto number = [&part](std::size_t i) { return std::stoull(part[i]); };
if(method == "POST" && is({"installation"})) {
const std::string token = Nostro::Crypto::RandomHex(16);
const std::uint64_t id = nextId++;
installations[token] = Installation{id, body.at("client_public_key").get<std::string>()};
return {200, Response(json::array({json{{"Id", json{{"id", id}}}}, json{{"Token", json{{"id", id}, {"token", token}}}}, json{{"ServerPublicKey", json{{"server_public_key", publicKeyPem}}}}}))};
}
if(method == "POST" && is({"token"})) {
if(Param(query, "grant_type") != "authorization_code") {
return {400, json{{"error", "invalid_request"}, {"error_description", "Missing required GET parameter \"grant_type\"."}}};
}
const auto code = codes.find(Param(query, "code"));
if(code == codes.end() || Param(query, "client_id") != clientId || Param(query, "client_secret") != clientSecret) {
return {400, json{{"error", "invalid_grant"}, {"error_description", "The authorization code is invalid or expired."}}};
}
const std::string token = code->second;
codes.erase(code);
return {200, json{{"access_token", token}, {"token_type", "bearer"}, {"state", ""}}};
}
if(is({"device-server"}) || is({"session-server"})) {
if(!installations.contains(authentication)) {
return {401, Error("Insufficient authorisation.")};
}
const std::string secret = body.value("secret", "");
if(!keys.contains(secret)) {
return {400, Error("User credentials are incorrect. Incorrect API key or IP address.")};
}
if(is({"device-server"})) {
devices[secret] = body;
return {200, Id(nextId++)};
}
const std::uint64_t user = keys.at(secret);
const std::string token = Nostro::Crypto::RandomHex(16);
const std::uint64_t id = nextId++;
sessions[token] = Session{id, secret, authentication};
return {200, Response(json::array({json{{"Id", json{{"id", id}}}}, json{{"Token", json{{"id", id}, {"token", token}}}}, json{{users.at(user).first, users.at(user).second}}}))};
}
// Everything else needs a session, for the user in its path.
const auto session = sessions.find(authentication);
if(session == sessions.end()) {
return {403, Error("Insufficient authentication.")};
}
const std::uint64_t self = keys.at(session->second.key);
if(method == "GET" && is({"installation"})) {
return {200, Response(json::array({json{{"Id", json{{"id", installations.at(session->second.installation).id}}}}}))};
}
if(method == "GET" && is({"installation", "*", "server-public-key"})) {
return {200, Response(json::array({json{{"ServerPublicKey", json{{"server_public_key", publicKeyPem}}}}}))};
}
if(method == "DELETE" && is({"session", "*"})) {
sessions.erase(session);
return {200, Response(json::array())};
}
if(part.size() < 2 || part[0] != "user" || number(1) != self) {
return {403, Error("Insufficient authentication.")};
}
if(method == "GET" && is({"user", "*"})) {
return {200, Response(json::array({json{{users.at(self).first, users.at(self).second}}}))};
}
if(method == "GET" && is({"user", "*", "monetary-account"})) {
std::vector<json> items = Older(extraAccountItems, query);
// An OAuth grant lists the accounts of the user who granted it; one that names nobody lists none.
std::uint64_t granted = self;
if(users.at(self).first == "UserApiKey") {
const json& grantedBy = users.at(self).second.at("granted_by_user");
granted = grantedBy.empty() ? 0 : grantedBy.begin().value().at("id").get<std::uint64_t>();
}
for(auto account = accounts.rbegin(); account != accounts.rend(); account++) {
const std::uint64_t owner = account->second.second.value("user_id", std::uint64_t{0});
if(owner == granted) {
items.push_back(json{{account->second.first, account->second.second}});
}
}
return {200, Page(items, path, query)};
}
if(method == "GET" && is({"user", "*", "card"})) {
return {200, Page(cards[self], path, query)};
}
if(method == "PUT" && is({"user", "*", "card", "*"})) {
for(json& item : cards[self]) {
json& card = item.begin().value();
if(card.at("id").get<std::uint64_t>() == number(3)) {
const std::string status = body.at("status").get<std::string>();
if(status != "ACTIVE" || cardsActivate) {
card["status"] = status;
}
return {200, Response(json::array({item}))};
}
}
return {404, Error("Card not found.")};
}
if(part.size() < 5 || part[2] != "monetary-account" || !accounts.contains(number(3))) {
return {404, Error("Not found.")};
}
const std::uint64_t account = number(3);
const std::string what = part[4];
if(what == "payment" && part.size() == 5) {
if(method == "GET") {
return {200, Page(payments[account], path, query)};
}
return {200, Id(Pay(account, body.at("amount"), body.at("counterparty_alias"), body.value("description", "")))};
}
if(what == "request-inquiry") {
if(part.size() == 5 && method == "GET") {
return {200, Page(inquiries[account], path, query)};
}
if(part.size() == 5) {
const std::uint64_t id = nextId++;
const json& pointer = body.at("counterparty_alias");
json inquiry = {
{"id", id},
{"created", Time(clock++)},
{"status", "PENDING"},
{"amount_inquired", body.at("amount_inquired")},
{"amount_responded", nullptr},
{"counterparty_alias", CounterpartyLabel(pointer)},
{"description", body.value("description", "")},
{"bunqme_share_url", body.value("allow_bunqme", false) ? json(std::format("https://bunq.me/t/{}", id)) : json(nullptr)},
};
inquiries[account].insert(inquiries[account].begin(), json{{"RequestInquiry", inquiry}});
if(pointer.value("type", "") == "IBAN") {
if(const std::optional<std::uint64_t> payer = AccountOfIban(pointer.at("value").get<std::string>())) {
json response = {
{"id", nextId++},
{"created", inquiry.at("created")},
{"status", "PENDING"},
{"type", "INTERNAL"},
{"amount_inquired", body.at("amount_inquired")},
{"counterparty_alias", Label(account)},
{"description", body.value("description", "")},
{"inquiry", json{{"account", account}, {"id", id}}},
};
responses[*payer].insert(responses[*payer].begin(), json{{"RequestResponse", response}});
}
}
return {200, Id(id)};
}
json* inquiry = FindItem(inquiries[account], "RequestInquiry", number(5));
if(!inquiry) {
return {404, Error("Request not found.")};
}
if(method == "GET") {
return {200, Response(json::array({json{{"RequestInquiry", *inquiry}}}))};
}
(*inquiry)["status"] = body.at("status");
return {200, Id(number(5))};
}
if(what == "request-response") {
if(part.size() == 5) {
return {200, Page(responses[account], path, query)};
}
json* response = FindItem(responses[account], "RequestResponse", number(5));
if(!response) {
return {404, Error("Request not found.")};
}
if(method == "GET") {
return {200, Response(json::array({json{{"RequestResponse", *response}}}))};
}
const std::string status = body.at("status").get<std::string>();
(*response)["status"] = status;
json* inquiry = response->contains("inquiry") ? FindItem(inquiries[response->at("inquiry").at("account").get<std::uint64_t>()], "RequestInquiry", response->at("inquiry").at("id").get<std::uint64_t>()) : nullptr;
if(inquiry) {
(*inquiry)["status"] = status;
}
if(status == "ACCEPTED") {
const json requester = response->at("counterparty_alias");
Pay(account, body.at("amount_responded"), json{{"type", "IBAN"}, {"value", requester.at("iban")}, {"name", requester.value("display_name", "")}}, response->value("description", ""));
if(inquiry) {
(*inquiry)["amount_responded"] = body.at("amount_responded");
}
}
return {200, Id(number(5))};
}
if(what == "schedule-payment") {
if(part.size() == 5 && method == "GET") {
std::vector<json> items;
for(const json& item : schedules[account]) {
items.push_back(json{{scheduledName, item.begin().value()}});
}
return {200, Page(items, path, query)};
}
if(part.size() == 5) {
const std::uint64_t id = nextId++;
const json& payment = body.at("payment");
json schedule = body.at("schedule");
schedule["time_next"] = schedule.at("time_start");
json scheduled = {
{"id", id},
{"status", "ACTIVE"},
{"payment", json{{"amount", Amount(-Minor(payment.at("amount")))}, {"counterparty_alias", CounterpartyLabel(payment.at("counterparty_alias"))}, {"description", payment.value("description", "")}}},
{"schedule", schedule},
};
schedules[account].insert(schedules[account].begin(), json{{"ScheduledPayment", scheduled}});
return {200, Id(id)};
}
std::erase_if(schedules[account], [id = number(5)](const json& item) { return ItemId(item) == id; });
return {200, Response(json::array())};
}
if(what == "draft-payment") {
if(part.size() == 5 && method == "GET") {
return {200, Page(drafts[account], path, query)};
}
if(part.size() == 5) {
const std::uint64_t id = nextId++;
json entries = json::array();
for(const json& entry : body.at("entries")) {
entries.push_back(json{{"amount", Amount(-Minor(entry.at("amount")))}, {"counterparty_alias", CounterpartyLabel(entry.at("counterparty_alias"))}, {"pointer", entry.at("counterparty_alias")}, {"description", entry.value("description", "")}});
}
const std::string now = Time(clock++);
json draft = {{"id", id}, {"created", now}, {"updated", now}, {"status", "PENDING"}, {"user_alias_created", json{{"display_name", users.at(self).second.value("display_name", "")}}}, {"entries", entries}};
drafts[account].insert(drafts[account].begin(), json{{"DraftPayment", draft}});
return {200, Id(id)};
}
json* draft = FindItem(drafts[account], "DraftPayment", number(5));
if(!draft) {
return {404, Error("Draft not found.")};
}
if(method == "GET") {
return {200, Response(json::array({json{{"DraftPayment", *draft}}}))};
}
if(body.contains("previous_updated_timestamp") && body.at("previous_updated_timestamp") != draft->value("updated", "")) {
return {400, Error("The draft payment was changed in the meantime.")};
}
const std::string status = body.at("status").get<std::string>();
(*draft)["status"] = status;
(*draft)["updated"] = Time(clock++);
if(status == "ACCEPTED") {
for(const json& entry : draft->at("entries")) {
Pay(account, Amount(-Minor(entry.at("amount"))), entry.at("pointer"), entry.value("description", ""));
}
}
return {200, Id(number(5))};
}
return {404, Error("Not found.")};
}
// The extra account items, on the first page only.
std::vector<json> Older(const std::vector<json>& items, std::string_view query) {
return Param(query, "older_id").empty() ? items : std::vector<json>();
}
Crafter::HTTPResponse Reply(std::uint16_t status, const std::string& body, std::optional<std::reference_wrapper<const Nostro::Crypto::Key>> signer) {
std::unordered_map<std::string, std::string> headers = {{"Content-Type", "application/json"}};
if(signer) {
headers["X-Bunq-Server-Signature"] = Nostro::Crypto::SignBody(signer->get().get(), body);
}
return Crafter::CreateResponseHTTP(std::to_string(status), headers, body);
}
Crafter::HTTPResponse Answer(const Crafter::HTTPRequest& request) {
std::lock_guard lock(mutex);
std::string path = request.path.substr(0, request.path.find('?'));
const std::string query = request.path.contains('?') ? request.path.substr(request.path.find('?') + 1) : std::string();
if(path.starts_with("/v1")) {
path = path.substr(3);
}
const auto header = [&request](const std::string& name) {
const auto found = request.headers.find(name);
return found == request.headers.end() ? std::string() : found->second;
};
const std::string authentication = header("x-bunq-client-authentication");
Logged entry{request.method, query.empty() ? path : std::format("{}?{}", path, query), request.body, false, false};
const std::string signature = header("x-bunq-client-signature");
if(!signature.empty()) {
entry.signed_ = true;
const std::string installation = installations.contains(authentication) ? authentication : (sessions.contains(authentication) ? sessions.at(authentication).installation : std::string());
if(installations.contains(installation)) {
const Nostro::Crypto::Key client = Nostro::Crypto::OwnKey(Nostro::Crypto::LoadPublicKeyFromPem(installations.at(installation).clientKeyPem));
entry.signatureValid = Nostro::Crypto::VerifyBody(client.get(), request.body, signature);
}
}
log.push_back(entry);
// A session and a payment need a valid signature, as at bunq.
if((path == "/session-server" || (request.method == "POST" && path.ends_with("/payment"))) && !entry.signatureValid) {
return Reply(466, Error("Request signature required.").dump(), std::nullopt);
}
std::optional<Fault> fault;
for(auto it = faults.begin(); it != faults.end(); it++) {
if((it->method.empty() || it->method == request.method) && (it->path.empty() || path.starts_with(it->path))) {
fault = *it;
if(--it->times == 0) {
faults.erase(it);
}
break;
}
}
if(fault && fault->kind == Fault::Kind::Reply) {
return Reply(fault->status, fault->body, std::nullopt);
}
if(fault && fault->kind == Fault::Kind::SignedReply) {
return Reply(fault->status, fault->body, std::cref(key));
}
std::vector<std::string> part;
for(const auto piece : std::views::split(std::string_view(path).substr(1), '/')) {
part.emplace_back(std::string_view(piece.begin(), piece.end()));
}
const json body = request.body.empty() ? json::object() : json::parse(request.body, nullptr, false);
const auto [status, answer] = Route(request.method, part, path, query, body, authentication);
const bool success = status >= 200 && status < 300;
if(fault && fault->kind == Fault::Kind::Unsigned) {
return Reply(status, answer.dump(), std::nullopt);
}
if(fault && fault->kind == Fault::Kind::BadSignature) {
return Reply(status, answer.dump(), std::cref(otherKey));
}
return Reply(status, answer.dump(), success ? std::optional(std::cref(key)) : std::nullopt);
}
};
}

458
tests/Support/FakeBus.inc Normal file
View file

@ -0,0 +1,458 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// A system bus for tests, included after <systemd/sd-bus.h>, <systemd/sd-id128.h>, <poll.h>, <spawn.h>,
// <sys/resource.h>, <sys/socket.h>, <sys/un.h>, <sys/wait.h>, <unistd.h> and `import std;`. It listens on a unix socket and stands in
// for the bus driver, for logind and for polkit; every other call goes to the connection that owns the name it is sent
// to, from the caller's unique name, and every answer back to whoever it is for. Each connection has a uid: one from
// this test's own process gets Bus::clientUid as it is when the connection is made, so a test plays a user by setting
// it before Client::System(); one from another process (nostrod, its workers) keeps its own. Point sd-bus at it by
// setting DBUS_SYSTEM_BUS_ADDRESS to Address() before any thread starts, so before the Bus itself.
namespace Fake {
// What polkit answers a check with.
enum class Polkit : std::uint8_t {
Allow, // authorized
Password, // needs the user's password: authorized when the call lets a dialog ask for it, a challenge if not
Deny, // refused by policy (polkit.result=no)
Dismiss, // the dialog was closed: not authorized, polkit.result=auth_self, which is how Plasma's agent answers
Absent, // no polkit on the bus: ServiceUnknown, without a message
Silent, // never answers
Slow, // authorized, a second later
};
// One CheckAuthorization as polkit got it.
struct PolkitCheck {
std::string subject;
std::string action;
std::map<std::string, std::string> details;
std::uint32_t flags = 0;
std::string cancellation;
};
class Bus {
public:
// Lock this around anything a test reads or changes while the bus runs.
std::mutex mutex;
std::uint32_t clientUid = 4242;
std::map<std::uint32_t, std::string> logindNames;
Polkit polkit = Polkit::Allow;
std::map<std::string, Polkit, std::less<>> polkitByAction;
std::vector<PolkitCheck> checks;
std::vector<std::string> cancelled;
// Credentials without the uid, as no bus sends them.
bool omitUid = false;
explicit Bus(std::filesystem::path path) : path(std::move(path)) {
listener = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
sockaddr_un address{};
address.sun_family = AF_UNIX;
std::strncpy(address.sun_path, this->path.c_str(), sizeof(address.sun_path) - 1);
if(bind(listener, reinterpret_cast<sockaddr*>(&address), sizeof(address)) != 0 || listen(listener, 64) != 0) {
throw std::runtime_error(std::format("the fake bus cannot listen on {}", this->path.string()));
}
thread = std::thread([this] { Run(); });
}
Bus(const Bus&) = delete;
Bus& operator=(const Bus&) = delete;
~Bus() {
stop = true;
thread.join();
close(listener);
std::filesystem::remove(path);
}
static std::string Address(const std::filesystem::path& path) {
return std::format("unix:path={}", path.string());
}
// Waits until `name` is owned, or not: false when `owned` is not reached within `timeout`.
bool WaitForName(std::string_view name, bool owned = true, std::chrono::milliseconds timeout = std::chrono::seconds(20)) {
const std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now() + timeout;
while(std::chrono::steady_clock::now() < end) {
{
std::lock_guard lock(mutex);
if(names.contains(name) == owned) {
return true;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
return false;
}
// Ends the connection that owns `name`, as when the bus goes away under it.
void Disconnect(std::string_view name) {
std::lock_guard lock(mutex);
dropping.emplace_back(name);
}
// The other processes connected now: nostrod, and its workers.
std::vector<pid_t> Peers() {
std::lock_guard lock(mutex);
std::vector<pid_t> peers;
for(const Connection& connection : connections) {
if(!connection.dead && connection.pid != getpid()) {
peers.push_back(connection.pid);
}
}
return peers;
}
// The last check polkit got, or an empty one.
PolkitCheck LastCheck() {
std::lock_guard lock(mutex);
return checks.empty() ? PolkitCheck() : checks.back();
}
private:
struct Connection {
sd_bus* bus = nullptr;
std::string unique;
std::uint32_t uid = 0;
pid_t pid = 0;
bool dead = false;
};
// An answer kept for later (Polkit::Slow).
struct Later {
std::chrono::steady_clock::time_point at;
std::size_t connection = 0;
sd_bus_message* call = nullptr;
};
std::filesystem::path path;
std::int32_t listener = -1;
std::thread thread;
std::atomic<bool> stop{false};
std::vector<Connection> connections;
std::map<std::string, std::size_t, std::less<>> names;
std::vector<std::string> dropping;
std::vector<Later> later;
std::uint32_t nextUnique = 1;
// sd-bus hands strings out as C strings.
// lint-disable-next-line no-char-pointer
static std::string Text(const char* text) {
return text ? std::string(text) : std::string();
}
static std::string ReadString(sd_bus_message* message) {
// lint-disable-next-line no-char-pointer
const char* value = nullptr;
sd_bus_message_read_basic(message, 's', &value);
return Text(value);
}
void Run() {
while(!stop) {
std::vector<pollfd> fds;
{
std::lock_guard lock(mutex);
for(const std::string& name : std::exchange(dropping, {})) {
if(const auto owner = names.find(name); owner != names.end()) {
Drop(owner->second);
}
}
AnswerLater();
fds.push_back(pollfd{listener, POLLIN, 0});
for(const Connection& connection : connections) {
fds.push_back(pollfd{connection.dead ? -1 : sd_bus_get_fd(connection.bus), static_cast<std::int16_t>(connection.dead ? 0 : sd_bus_get_events(connection.bus)), 0});
}
}
poll(fds.data(), fds.size(), 10);
std::lock_guard lock(mutex);
if((fds[0].revents & POLLIN) != 0) {
Accept();
}
for(std::size_t i = 0; i < connections.size(); i++) {
while(!connections[i].dead) {
sd_bus_message* message = nullptr;
const std::int32_t result = sd_bus_process(connections[i].bus, &message);
if(result < 0) {
Drop(i);
break;
}
if(message) {
Route(i, message);
sd_bus_message_unref(message);
}
if(result == 0) {
break;
}
}
}
}
std::lock_guard lock(mutex);
for(Later& answer : later) {
sd_bus_message_unref(answer.call);
}
for(std::size_t i = 0; i < connections.size(); i++) {
Drop(i);
}
}
void Drop(std::size_t i) {
if(connections[i].dead) {
return;
}
connections[i].dead = true;
sd_bus_flush_close_unref(connections[i].bus);
connections[i].bus = nullptr;
std::erase_if(names, [i](const auto& owner) { return owner.second == i; });
}
void Accept() {
const std::int32_t fd = accept4(listener, nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK);
if(fd < 0) {
return;
}
ucred peer{};
socklen_t size = sizeof(peer);
getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &peer, &size);
Connection connection;
connection.pid = peer.pid;
connection.uid = peer.pid == getpid() ? clientUid : peer.uid;
sd_bus_new(&connection.bus);
sd_bus_set_fd(connection.bus, fd, fd);
sd_id128_t id{};
sd_id128_randomize(&id);
sd_bus_set_server(connection.bus, 1, id);
sd_bus_start(connection.bus);
connections.push_back(connection);
}
std::optional<std::size_t> Owner(std::string_view name) {
if(name.starts_with(':')) {
for(std::size_t i = 0; i < connections.size(); i++) {
if(!connections[i].dead && connections[i].unique == name) {
return i;
}
}
return std::nullopt;
}
const auto owner = names.find(name);
return owner == names.end() ? std::nullopt : std::optional<std::size_t>(owner->second);
}
template<typename... Args>
void Reply(std::size_t to, sd_bus_message* call, std::string_view types, Args... args) {
sd_bus_message* reply = nullptr;
sd_bus_message_new_method_return(call, &reply);
if(!types.empty()) {
sd_bus_message_append(reply, std::string(types).c_str(), args...);
}
sd_bus_send(connections[to].bus, reply, nullptr);
sd_bus_message_unref(reply);
}
void Fail(std::size_t to, sd_bus_message* call, std::string_view name, const std::optional<std::string>& message) {
sd_bus_message* reply = nullptr;
const std::string errorName(name);
const sd_bus_error error = {errorName.c_str(), message ? message->c_str() : nullptr, 0};
sd_bus_message_new_method_error(call, &reply, &error);
sd_bus_send(connections[to].bus, reply, nullptr);
sd_bus_message_unref(reply);
}
void Route(std::size_t from, sd_bus_message* message) {
std::uint8_t type = 0;
sd_bus_message_get_type(message, &type);
const std::string destination = Text(sd_bus_message_get_destination(message));
if(type == SD_BUS_MESSAGE_METHOD_CALL && destination == "org.freedesktop.DBus") {
Driver(from, message);
} else if(type == SD_BUS_MESSAGE_METHOD_CALL && destination == "org.freedesktop.login1") {
Logind(from, message);
} else if(type == SD_BUS_MESSAGE_METHOD_CALL && destination == "org.freedesktop.PolicyKit1") {
PolicyKit(from, message);
} else if(const std::optional<std::size_t> to = Owner(destination)) {
if(type == SD_BUS_MESSAGE_METHOD_CALL) {
// A call goes on from the caller's unique name, with its own cookie, so the answer finds it again.
std::uint64_t cookie = 0;
sd_bus_message_get_cookie(message, &cookie);
sd_bus_message* copy = nullptr;
sd_bus_message_new_method_call(connections[*to].bus, &copy, destination.c_str(), sd_bus_message_get_path(message), sd_bus_message_get_interface(message), sd_bus_message_get_member(message));
sd_bus_message_rewind(message, 1);
sd_bus_message_copy(copy, message, 1);
sd_bus_message_set_sender(copy, connections[from].unique.c_str());
sd_bus_message_set_allow_interactive_authorization(copy, sd_bus_message_get_allow_interactive_authorization(message));
sd_bus_message_seal(copy, cookie, 0);
sd_bus_send(connections[*to].bus, copy, nullptr);
sd_bus_message_unref(copy);
} else {
sd_bus_send(connections[*to].bus, message, nullptr);
}
} else if(type == SD_BUS_MESSAGE_METHOD_CALL) {
Fail(from, message, SD_BUS_ERROR_SERVICE_UNKNOWN, std::format("The name {} was not provided by any .service files", destination));
}
}
void Driver(std::size_t from, sd_bus_message* call) {
const std::string member = Text(sd_bus_message_get_member(call));
if(member == "Hello") {
connections[from].unique = std::format(":1.{}", nextUnique++);
Reply(from, call, "s", connections[from].unique.c_str());
} else if(member == "RequestName") {
const std::string name = ReadString(call);
const std::optional<std::size_t> owner = Owner(name);
if(owner && *owner != from) {
Reply(from, call, "u", 3u);
return;
}
names[name] = from;
Reply(from, call, "u", 1u);
} else if(member == "GetConnectionUnixUser" || member == "GetConnectionCredentials") {
const std::optional<std::size_t> owner = Owner(ReadString(call));
const std::uint32_t uid = owner ? connections[*owner].uid : 0;
const std::uint32_t pid = owner ? static_cast<std::uint32_t>(connections[*owner].pid) : 0;
if(member == "GetConnectionUnixUser") {
Reply(from, call, "u", uid);
} else if(omitUid) {
Reply(from, call, "a{sv}", 1, "ProcessID", "u", pid);
} else {
Reply(from, call, "a{sv}", 2, "UnixUserID", "u", uid, "ProcessID", "u", pid);
}
} else {
// AddMatch, RemoveMatch, ReleaseName: done.
Reply(from, call, "");
}
}
void Logind(std::size_t from, sd_bus_message* call) {
const std::string member = Text(sd_bus_message_get_member(call));
constexpr std::string_view prefix = "/org/freedesktop/login1/user/_";
if(member == "GetUser") {
std::uint32_t uid = 0;
sd_bus_message_read_basic(call, 'u', &uid);
if(!logindNames.contains(uid)) {
Fail(from, call, "org.freedesktop.login1.NoSuchUser", std::format("No user {} known or logged in", uid));
return;
}
Reply(from, call, "o", std::format("{}{}", prefix, uid).c_str());
} else {
// Properties.Get(interface, "Name") on a user's object.
const std::string userPath = Text(sd_bus_message_get_path(call));
std::uint32_t uid = 0;
std::from_chars(userPath.data() + prefix.size(), userPath.data() + userPath.size(), uid);
Reply(from, call, "v", "s", logindNames.at(uid).c_str());
}
}
void PolicyKit(std::size_t from, sd_bus_message* call) {
if(Text(sd_bus_message_get_member(call)) == "CancelCheckAuthorization") {
cancelled.push_back(ReadString(call));
Reply(from, call, "");
return;
}
PolkitCheck check;
sd_bus_message_enter_container(call, 'r', "sa{sv}");
ReadString(call);
sd_bus_message_enter_container(call, 'a', "{sv}");
while(sd_bus_message_enter_container(call, 'e', "sv") > 0) {
ReadString(call);
sd_bus_message_enter_container(call, 'v', "s");
check.subject = ReadString(call);
sd_bus_message_exit_container(call);
sd_bus_message_exit_container(call);
}
sd_bus_message_exit_container(call);
sd_bus_message_exit_container(call);
check.action = ReadString(call);
sd_bus_message_enter_container(call, 'a', "{ss}");
while(sd_bus_message_enter_container(call, 'e', "ss") > 0) {
std::string key = ReadString(call);
check.details[std::move(key)] = ReadString(call);
sd_bus_message_exit_container(call);
}
sd_bus_message_exit_container(call);
sd_bus_message_read_basic(call, 'u', &check.flags);
check.cancellation = ReadString(call);
checks.push_back(check);
const auto chosen = polkitByAction.find(check.action);
const Polkit outcome = chosen == polkitByAction.end() ? polkit : chosen->second;
const bool prompt = (check.flags & 1) != 0;
if(outcome == Polkit::Allow || (outcome == Polkit::Password && prompt)) {
Reply(from, call, "(bba{ss})", 1, 0, 1, "polkit.result", "auth_self");
} else if(outcome == Polkit::Password) {
Reply(from, call, "(bba{ss})", 0, 1, 1, "polkit.result", "auth_self");
} else if(outcome == Polkit::Deny) {
Reply(from, call, "(bba{ss})", 0, 0, 1, "polkit.result", "no");
} else if(outcome == Polkit::Dismiss) {
Reply(from, call, "(bba{ss})", 0, 0, 1, "polkit.result", "auth_self");
} else if(outcome == Polkit::Absent) {
Fail(from, call, SD_BUS_ERROR_SERVICE_UNKNOWN, std::nullopt);
} else if(outcome == Polkit::Slow) {
later.push_back(Later{std::chrono::steady_clock::now() + std::chrono::seconds(1), from, sd_bus_message_ref(call)});
}
}
void AnswerLater() {
const std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
std::erase_if(later, [this, now](const Later& answer) {
if(answer.at > now) {
return false;
}
if(!connections[answer.connection].dead) {
Reply(answer.connection, answer.call, "(bba{ss})", 1, 0, 1, "polkit.result", "auth_self");
}
sd_bus_message_unref(answer.call);
return true;
});
}
};
// Whether this process is nostrod, or one of its workers, started by a test from its own executable.
inline bool IsNostrod() {
return std::getenv("NOSTRO_TEST_ROLE") != nullptr;
}
// Starts this test's own executable as nostrod with `args`: its main runs nostrod's main when IsNostrod(). The
// variables in `unset` are left out of its environment.
inline pid_t StartNostrod(std::vector<std::string> args, std::vector<std::string_view> unset = {}) {
args.insert(args.begin(), "nostrod");
// posix_spawn takes C strings.
// lint-disable-next-line no-char-pointer
std::vector<char*> argv;
for(std::string& arg : args) {
argv.push_back(arg.data());
}
argv.push_back(nullptr);
std::vector<std::string> variables;
for(std::size_t i = 0; environ[i]; i++) {
const std::string_view variable(environ[i]);
if(std::ranges::none_of(unset, [variable](std::string_view name) { return variable.starts_with(std::format("{}=", name)); })) {
variables.emplace_back(variable);
}
}
variables.emplace_back("NOSTRO_TEST_ROLE=nostrod");
// lint-disable-next-line no-char-pointer
std::vector<char*> envp;
for(std::string& variable : variables) {
envp.push_back(variable.data());
}
envp.push_back(nullptr);
pid_t pid = -1;
posix_spawn(&pid, "/proc/self/exe", nullptr, nullptr, argv.data(), envp.data());
return pid;
}
// Sets the soft limit of `resource` for process `pid`, to see what it does when it reaches it, and returns the soft
// limit it had. The hard limit stays, so the old one can be set again.
inline rlim_t Limit(pid_t pid, decltype(RLIMIT_NOFILE) resource, rlim_t soft) {
rlimit old{};
prlimit(pid, resource, nullptr, &old);
const rlimit limit{.rlim_cur = soft, .rlim_max = old.rlim_max};
prlimit(pid, resource, &limit, nullptr);
return old.rlim_cur;
}
// Waits for a process this test started, and returns how it ended: its exit status, or 128 and the signal.
inline std::int32_t Wait(pid_t pid) {
std::int32_t status = 0;
waitpid(pid, &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}
}

42
tests/coverage.sh Executable file
View file

@ -0,0 +1,42 @@
#!/bin/sh
# SPDX-License-Identifier: LGPL-3.0-only
# SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
# Runs the tests built with clang's source-based coverage and reports it for nostro's own sources, then lists every
# line no test ran. Needs crafter-build, llvm-profdata, llvm-cov and llvm-readelf on PATH. A toolchain without compiler-rt's profile
# runtime takes its libclang_rt.profile archive as the first argument. Leaves the profiles and the annotated sources in
# build/coverage/.
set -eu
cd "$(dirname "$0")/.."
out=build/coverage
rm -rf "$out"
mkdir -p "$out"
if [ $# -gt 0 ]; then
LLVM_PROFILE_FILE="$PWD/$out/%p.profraw" crafter-build test --banks=bunq --coverage "--profile-runtime=$1"
else
LLVM_PROFILE_FILE="$PWD/$out/%p.profraw" crafter-build test --banks=bunq --coverage
fi
llvm-profdata merge -sparse "$out"/*.profraw -o "$out/nostro.profdata"
# Each test's newest build with coverage mappings in it: a plain build can be newer, and a test whose sources did not
# change is not linked again.
set --
for test in tests/Should*/; do
name=$(basename "$test")
for binary in $(ls -t bin/"$name"-*/"$name"); do
if llvm-readelf -S "$binary" | grep -q __llvm_covfun; then
if [ $# -eq 0 ]; then
set -- "$binary"
else
set -- "$@" -object "$binary"
fi
break
fi
done
done
ignore='(lib/json\.hpp|/tests/|/Crafter\.|/app/|/usr/)'
llvm-cov report "$@" -instr-profile="$out/nostro.profdata" -ignore-filename-regex="$ignore"
llvm-cov show "$@" -instr-profile="$out/nostro.profdata" -ignore-filename-regex="$ignore" -format=text > "$out/sources.txt"
awk '/^\/.*:$/ { file = $0 } /^ *[0-9]+\| *0\|/ { split($0, part, "|"); gsub(/ /, "", part[1]); print "not run: " file part[1] }' "$out/sources.txt"