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

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.