An app could have nostrod pay an order: it called Pay of net.catcrafts.Nostro1.Checkout on the system bus, and nostrod paid from an account the user had chosen, after a dialog of its own. On 2026-11-22 the owner decided that a link takes its place. The app registers for payto links (RFC 8905), so that an app or a website can hand one to the desktop, and shows a link as its pay form filled in. The link: - The app's desktop entry takes the scheme (Exec=nostro-app %u, MimeType=x-scheme-handler/payto), and nostro-app takes an argument that is no option as a link: it overwrites it in argv and hands it to App::Open once the app has started. - ReadPaymentLink (Nostro.App:Forms) reads payto://iban/<IBAN> with the options amount, receiver-name and message, and refuses a link rather than guess at it, in a sentence of the app's own with nothing of the link in it. Among what it refuses: an IBAN whose check digits do not hold, one of the three options given twice, instruction, a comma in the amount, and a name or a message with a code point that is Unshown, or Blank and no plain space. - A link that is read waits until the accounts are read and DefaultCheckoutAccount has answered or failed, with a line on the accounts' page. Then App::TakeLink fills in the pay form, which says in a banner that a link filled it in, and with more than one account opens it under the choice of accounts that the form's From row has. A link pays nothing: the form's button sends, and polkit's dialog confirms as for any payment (design rule 12, and 14, which is new). - Unshown and Blank are the two tables the worker's Shown() works from. They move into Nostro:Utils, where the app's reader asks them too. The move is within the library. The reader holds a link's name to those two and to no more of Shown(): a name with an & is read, and the dialog shows it with a + as it does any name. The checkout: - nostrod serves one interface under one bus name. Gone are net.catcrafts.Nostro1.Checkout with its XML and its activation file, the polkit action Checkout, the module Nostro.Checkout with --product=checkout, and the worker's record of orders. That changes the published contract after a release, 0.0.0, and design rule 10 records it as the owner's decision. - DefaultCheckoutAccount and SetDefaultCheckoutAccount keep their names and signatures. The account they keep is where a link's pay form starts: nostrod's dialog for choosing it says "have pay links start from", the app's setting reads "Pay links start from", and `nostro checkout account` prints "pay links start from". - The D-Bus policy still lets nostrod own the old name: the nostrod of 0.0.0 asks for it when it starts, and the system files can be newer than the Flatpak it runs from. install.sh removes the old name's activation file. A user's checkouts.cdb is read by nothing any more, and is left where it is. - The Arch package stops installing the checkout's two files, and its pkgrel goes up to 2. Where makepkg -si finds a package of the version already built it installs that one again, which would bring the activation file back. The guide now says that pkgrel goes up with a change to what the package installs. - Bus::Interface goes too: the worker called it in two places, to tell a call to the checkout from one to the main interface. The review's own files follow. gate0 loses the build of --product=checkout, and the three lens sections that named the checkout no longer do, and ask about a link. The README has "Pay links" in place of "Checkout for apps", and AGENTS.consumer.md says what the app reads of a link. Its line on lib/json.hpp no longer gives a release: the file is of none, and the guide names its commit. The pay form and the accounts' page change only by a banner each, shown while a link is in play, which docs/screenshots/take.sh never has: the README's pictures stand. Tests: ShouldValidateForms reads and refuses links and fills the form from one. ShouldDriveTheApp opens links against a real nostrod on the fake bus: before the accounts are known, with no account, with one and with several, with the accounts known and the system bus gone, for a second user whose first connection pays their own accounts only, one that cannot be read, one whose name has an &, and through polkit's dialog to the payment. It now counts nostrod's answers to hold that the account pay links start from is read again once a connection is removed: the check it had there passed without that. ShouldHandleMoneyAndText holds the two tables at the ends of their ranges. ShouldServeEveryUser holds that nostrod serves no checkout, that the bus's policy lets an older nostrod own the old name, and the account pay links start from. ShouldRunCommands holds the CLI's wording. The review's gate0 passes at this commit: the version check, 17 tests, the builds of the CLI, the library, nostrod, the fake system, the app and its --debug-api build, and five lint runs that report nothing. tests/coverage.sh reports lines, functions and regions at 100.00%. Looked at on 2026-11-22 on the made-up system (run fake), on a desktop (KWin at a scale of 1.85). At 420x760, at --scale 3 --size 360x760 and at 1100x720 in the light look: a link's pay form under the choice of accounts, the form after a tap beside that choice, and the accounts' page while a link waits, its line above the rows that stand in for the accounts (--bank-delay 10000). At 420x760: that line above what the page says when the accounts cannot be read (--polkit deny) and above the accounts themselves (--polkit slow, the link opened in the running app), the settings' row and page for the account pay links start from, the sheet for a link that cannot be read, and with --empty the sheet for no account.
35 KiB
nostro
nostro is a banking client for Linux in four 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 and the Nostro app, a window for a phone or a desktop, are clients of nostrod. The app's own modules (Nostro.Ui, Nostro.App, Nostro.Ui.Shell) are built for the app and its tests alone, and are GPL-3.0-only where the library is LGPL-3.0-only: --lib does not hand them to a consumer. A consumer does one of two things:
- links the library and holds the credentials itself, in its own process (
--lib --banks=bunq); - or talks to nostrod through
Nostro::Client(--lib --banks=bunq --dbus), as the CLI does.
An app that only wants a customer to pay an order links nothing of nostro: it opens a link, see "Having a customer pay".
Everything is in namespace Nostro: the OpenSSL helpers in Nostro::Crypto, the D-Bus names and wire in Nostro::Bus. 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 (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
GitProjectwith nostro's repository, orLocalProject({ .projectFile = "<checkout>/project.cpp", .args = nostroArgs })for a checkout, intocfg.dependencies.nostroArgsis your ownProjectArgs()plus--liband--banks=bunq, built once insideCrafterBuildProject: without--libnostro'sproject.cppreturns 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 andbunqis the only name it accepts.--dbuswith--libadds the partitions that talk to nostrod,:Bus,:Clientand: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.- nostro strips its own args (
--lib,--banks=,--dbus,--product=,--debug-api,--coverage,--profile-runtime=) from what it hands its dependencies and forwards the rest, adding--no-quicfor 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-quicincluded, and Crafter.DB the list without it, or the build stops with two loads that disagree on their args. - nostro's
project.cpploads two build helpers by#pragma crafter dependency, Crafter.LintRules and, at a pinned commit, Crafter.Debug's: loading nostro fetches and builds both for the host, whatever is built of it. Crafter.Debug's library itself is only in nostro's own app, under--debug-api. - 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, soThreadPool::Start()is not needed for it. - Defines do not cross a dependency. nostro compiles with
NOSTRO_BUNQ_ENABLED,NOSTRO_OPENSSL_ENABLEDand, under--dbus,NOSTRO_DBUS_ENABLED, and the PCMs carry the result:import Nostro;exportsBunqConnectorandClient, andEnabledBankslists bunq, whatever your configuration defines (nostro's own CLI compiles without them). Your own#ifdef NOSTRO_BUNQ_ENABLEDsees it only when you push the sameDefineinto yourcfg.defines, as nostro's CLI configuration does withexecfg.defines = libcfg.defines. import Nostro;is enough for everything below; nothing exposed needsimport Crafter.Network;orimport Crafter.DB;. The raw bunq calls (Get,Post,Put,Delete,List) take and returnnlohmann::json: hold the result inauto, and includelib/json.hppwhere you have to name or build one.- Static initialisers run at load:
Nostro::configPathandcachePathreadXDG_CONFIG_HOMEandXDG_CACHE_HOME, elseHOME, and throw (sostd::terminate) when neither is set. The HTTPS clients are function-local statics, made on the first bunq call.
Money, currencies and time
Currencyis anenum classwithEuroalone.GetCurrency("EUR")(or"eur") is the only parse; anything else throwsstd::runtime_error("unsupported currency '…'").RefreshAccountsskips a bank account in another currency with aNoteinstead.GetCurrencyCodegives"EUR",GetCurrencySymbol"€",GetCurrencyDecimals2;std::format("{}", Currency::Euro)is the symbol. Allconstexpr.- Amounts and balances are
std::int64_tin the minor unit, so1250is €12.50, outgoing negative.ParseAmount("12.50", Currency::Euro)is1250: an optional leading-, digits, an optional.with at mostdecimalsdigits, nothing else, orstd::runtime_error("malformed amount '…'").FormatAmount(1250, Currency::Euro)is"12.50",FormatAmount(-5, …)"-0.05", andFormatMoney(-102, …)"-€1.02", the sign before the symbol. Allconstexpr. ParseTimestamp("2026-10-31 12:34:56.123456")is astd::chrono::system_clock::time_point, read as UTC: exactlyYYYY-MM-DD HH:MM:SS, optionally.and one to six fraction digits, no zone, orstd::runtime_error("malformed timestamp '…'").FormatTimestampis its inverse, bunq's format. libc++'ssystem_clockticks in microseconds, which is also what the tables store.- For dates a person types:
ParseLocalDate("2026-10-31")orParseLocalDate("2026-10-31 09:30")in the local time zone (throughmktime), orstd::runtime_errornaming the format;ParseLocalDate(day, 1)is the midnight that endsday, counted by the calendar, so a day the clocks change is 23 or 25 hours, andParseLocalDateEnd(text)the last moment a range ending attextincludes (the end of that day for a date alone).FormatLocalTime(time)is"YYYY-MM-DD hh:mm"in local time. UrlEncodepercent-encodes all but RFC 3986's unreserved characters;UrlDecodeundoes it and reads+as a space;QueryParameter(url, name)is the decoded value from the query string, orstd::nullopt.EscB(text)escapes text for inside a JSON string literal; nostro itself no longer builds JSON by hand.Unshown(codePoint)is whether a Unicode code point draws nothing or tells text where to go, andBlank(codePoint)whether it is a space of any width, U+0020 among them, or U+2800, the Braille pattern without a dot. Both areconstexprandnoexceptand take astd::uint32_t; decoding UTF-8 is yours. nostrod's worker drops the first from what it puts into a password dialog, and turns a run of the second into one plain space, none leading or trailing.
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'sconnectorsfirst and then callsRefreshAccounts()on each, a network round trip per connector. A connector whose refresh throws keeps no accounts and is reported throughNote(bunq connector '<name>' is unavailable: …), so the others stay usable. A file that is not JSON throwsstd::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 anlohmann::json::parse_error). Valid JSON with a missing or mistyped key still throws nlohmann'sjson::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: toconnectors.json.tmp-<pid>(0600in a0700directory, throughCreatePrivateFile),fsync, rename over the old file,fsyncof the directory. A crash or power cut leaves one whole file.Createdoes 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 inBunqConnector::connectors. The file holds the API key or OAuth token, both tokens and the unencrypted RSA private key PEM, per connectorenvironment,apiKey,installationToken,sessionToken,sessionId,privateKey,serverPublicKey,userType,name,id,ownerId; treat it accordingly and never commit one. Files from before 2026-10-31 lackenvironment,sessionId,serverPublicKey,userTypeandownerId; they load as sandbox connectors, the only host then.- Both take an exclusive
flockon<config>/connectors.lockand hold it until the process ends. A second nostro process blocks in its first load or save, after theNotewaiting 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 globalnoteSink, astd::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>isGetConfigPath():$XDG_CONFIG_HOME/.config/nostrowhenXDG_CONFIG_HOMEis set (the.configis inserted, as of 2026-10-31), else$HOME/.config/nostro.<cache>isGetCachePath():$XDG_CACHE_HOME/nostro, else$HOME/.cache/nostro. The globalsconfigPathandcachePathare 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 throwsstd::runtime_errorwhen stdin ends first.- Generic code over the enabled banks is
tuple_for<EnabledBanks>([&]<typename Bank>() { for (Bank& bank : Bank::connectors) { … } });, a template lambda. EveryBankhasstatic constexpr std::string connectorId("bunq"),static std::deque<Bank> connectors,using Account,std::vector<Account> accounts,std::string name,TestConnector(),RefreshAccounts(),RefreshSession(),GetNewTransactions()andGetNewTransactions(account),Logout(),StorageKey(), a staticCreate(…)andRemove(bank), and formats as its name. Its accounts haveStorageKey()and format asname<TAB>bic iban<TAB>€12.50(std::formatworks onAccountand 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 theconnectorargument. For bunq that isaccount.StorageKey(),bunq/<production|sandbox>/<user id>/<account id>.GetLastTransactionTime(key): the newest storedtimePoint,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 and flushes; a call that brings nothing new writes nothing. At the last stored timestamp a row is appended when itsidis 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 mostlimit.TransactionQuerytakes 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),.fromand.to(inclusivetime_points, the whole range by default),.limit(100), and.stored(false), which is for nostrod and whichFindTransactionsdoes not look at: it never asks a bank. The time range is a binary search on the ordered table; the rest is a backwards scan that stops atlimit: measured at 1.5 µs over 20 rows and 4 ms over 100 000 when nothing matches.- 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 untilAccount::ForgetTransactions(key)closes and deletes every table underkey(a connector's storage key covers all its accounts;Removecalls it). A renamed account starts a new table and syncs again. Tables written before 2026-10-31 sit at<cache>/transactions/bunq/<account name>.cdband 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).idis the bank's own id as text andkindits 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::environmentisBunqEnvironment::Production(api.bunq.com, real money) orSandbox(public-api.sandbox.bunq.com).BunqConnector::EnvironmentOfKey(key)isSandboxfor a key startingsandbox_; an OAuth token does not say, so the caller decides. Production has been used to connect and to read since 2026-11-19; before that only the sandbox was.BunqConnector::Endpoint(environment)is theBunqEndpoint(host,port,caPem) its calls go to. Each endpoint has oneClientHTTP1, 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 attests/Support/FakeBunq.inc, an in-process bunq that a consumer's test can include as well (afterlib/json.hpp,import std;,import Nostro;andimport 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.allowedIpsis 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 intoBunqConnector::connectors, astd::deque, so a laterCreateleaves earlier references and every account'sconnectorpointer 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),Createlogs the new session out and throws, because every account would otherwise be listed twice. Follow it withConnector::SaveConnectors()or the connector is gone at exit.BunqConnector::Remove(connector)deletes its stored transactions (throughAccount::ForgetTransactions, which first closes the tables this process has open, so the same user added again syncs into new files) and erases it fromconnectors, re-pointing the remaining accounts; references to other connectors you held are invalidated, as with anydeque::erasein the middle. It does not log out: callLogout()first (DELETE /v1/session/{sessionId}, not renewed; a session already gone counts as logged out). ThenSaveConnectors().- After
LoadConnectorsorCreatea connector hasenvironment,name(bunq'sdisplay_nameof the user; for OAuth of the user who granted access),id(the user id in API paths; for OAuth theUserApiKey's own),ownerId,userType(UserPerson,UserCompany,UserApiKeyorUserPaymentServiceProvider;IsOAuth()isUserApiKey),sessionToken,sessionId,installationToken,privateKeyandserverPublicKey(Crypto::Key, astd::shared_ptr<EVP_PKEY>),apiKey, andaccountsofBunqAccount(Accountplusid, bunq's objecttypesuch asMonetaryAccountSavings, and aconnectorback-pointer). - Every call goes through
Get,Post,PutorDelete(a path below/v1, or a pagination URL) andList(every item of a listing, pages of 200 followed througholder_url, newest first). Bodies are signed. Every 2xx must carry a validx-bunq-server-signaturefor 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 forsession-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, becauseClientHTTP1would 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, which isBunqError::maybeCarriedOut. Any other error response is aBunqError. RefreshAccounts()rebuildsaccountsfrom scratch (references into it go stale): everyMonetaryAccount…type whose status isACTIVEorBLOCKED, the IBAN alias asiban,BUNQNL2Aasbicfor a bunq IBAN.TestConnector()isGET /v1/user/{id}and returnsfalseon any exception rather than throwing.GetNewTransactions(account)(andGetNewTransactions()for all) pages the payments newest first until one older than the last stored row, fillsidandkind("<type>/<sub_type>"), and callsSaveTransactions(account.StorageKey(), …); the first sync walks the whole history, 200 a call.- On a
BunqAccount, amounts are positive minor units, orstd::invalid_argument. Counterparties go throughBunqCounterparty::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 throwsstd::invalid_argumentbefore anything is sent. bunq needsnamefor an IBAN outside bunq.Send,Draft(one-entry draft payment, paid once someone accepts it) andSchedule(…, BunqSchedule)return bunq's id.BunqSchedule { start, end, unit ("ONCE", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"), every }is UTC; an unknown unit orevery == 0throwsstd::invalid_argument.BunqSchedule::UnitFromWord("monthly")is"MONTHLY", for a unit a person typed.Request(from, name, amount, currency, description)asks for money with bunq.me allowed and returns aBunqPaymentRequest, whoseshareUrlanyone can pay through. When reading it back fails, the request still exists: it comes backPENDINGwithout a share URL, with aNote.- The listings, newest first:
Requests()(sent,BunqPaymentRequest),IncomingRequests()(BunqIncomingRequest, incoming SEPA direct debits included asDIRECT_DEBIT),ScheduledPayments(),DraftPayments(). One of each, as bunq has it now:IncomingRequest(id)andDraftPayment(id). The answers:RevokeRequest(id),CancelScheduledPayment(id), and two that take the object you showed the user:RespondToRequest(shown, accept)paysshown.amountandshown.currency, whatever the request asks by then, andRespondToDraftPayment(shown, accept)sendsshown.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,orderStatus,productType,lastFour,expiry, the payingiban, …).statusis bunq's, and is about the plastic:card.State()is how the card stands in one word, which isstatusexcept for a virtual card (card.Virtual(): itsorderStatusisVIRTUAL_DELIVERY), which isVIRTUALuntil it is gone for good. bunq has a virtual card asDEACTIVATEDhowever well it pays, and nothing says whether one is frozen. Thestd::formatterprintsState().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 staysDEACTIVATED, and a virtual card is left as it is when asked to freeze or unfreeze.card.ExpectStatus(asked)throwsstd::runtime_errorsaying so in either case. Through nostrod,Client::SetCardStatusrefuses to freeze or unfreeze a virtual card withstd::invalid_argument, before anyone is asked for a password.- OAuth instead of an API key:
OAuthAuthorizationUrl(environment, clientId, redirectUri, state)is where the user approves with the bunq app. bunq then redirects toredirectUriwithcodeandstate:OAuthCodeFromRedirect(redirectedAddress, state)returns the code, or throwsstd::runtime_errorwhen bunq did not authorize (error=), the address has no code, or itsstateis another.OAuthExchangeCode(environment, clientId, clientSecret, redirectUri, code)returns the access token, whichCreatetakes 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::formatas 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: as shipped only viewing passes in an active session, and everything else asks for the user's password each time, a draft saved, a request for money and a card frozen as much as a payment. An administrator's rule may ask for less. A call that names an account, a card, a request, a draft or a connector, and is not a call to see it, is checked twice: for viewing, before nostrod looks up what it names, and then for what it does. So a caller polkit does not let see the accounts gets AccessDenied for it, whether what it named is there or not. 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 oneClientper 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)andAddBunqOAuth(environment, clientId, clientSecret, redirectUri, code)(AddedConnector; forAddBunqleave the environment empty: nostrod takes the one the key is of, and naming one only has a key of the other refused withstd::invalid_argument, before anything is sent),RemoveConnector(name or number),Accounts()(ConnectorAccounts),Transactions(account, TransactionQuery)(nostrod asks the bank for what is new first, a call to the bank that takes its time and that the bank counts; with.stored = trueit answers from what it has stored alone, in milliseconds: for a search in a list just read, or more of it. A nostrod from before 2026-11-19 ignoresstoredand asks the bank),Send,Schedule,Draft(Created: bunq'sidand thecurrency),Request(BunqPaymentRequest), the listings,RevokeRequest,RespondToRequest(account, id, accept),CancelScheduledPayment,RespondToDraftPayment(account, id, accept),Cards()(ConnectorCards),SetCardStatus(card, status),DefaultCheckoutAccount()(std::optional<Account>) andSetDefaultCheckoutAccount(account).accountis 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.- Every method also has an asynchronous form, for a program with an event loop that must not wait minutes on a password dialog:
client.Attach(sd_event*)once (a secondAttachthrows), then call the method with a last argumentThen<T>(std::function<void(Answer<T>)>;std::monostatefor a method that answers nothing). It returns a[[nodiscard]] Client::Pendingat once and callsthenfrom the loop when nostrod answers.Answer<T>holds theresultor thestd::exception_ptrthe blocking call would have thrown (Get()returns the one or rethrows the other,Failed(),Error()), and that call'snotes; an error answer carries none, and notes are collected per user by nostrod's worker, so they can be another call's of the same user. Destroying thePending, orCancel(), drops the answer (thenis not called) without undoing the call, which nostrod and bunq carry on with;Active()says whetherthenis still to come. Athenthat throws is reported throughNote. Calling one withoutAttachthrowsstd::logic_error. Once the connection is gone (Connected()false), make a new client: a closed connection answers nothing it still awaited. - Errors:
std::invalid_argumentfor what nostrod refused before doing anything (it names the problem, as the library's own messages do). That includes an e-mail address to pay or ask that the password dialog could not show exactly as it is: one with an&, a<or a>in it, with a character that draws nothing, or longer than 254 characters. A name is never refused for that: the dialog shows it without what draws nothing, with&,<and>replaced, and cut at 64 characters.DaemonError, astd::runtime_errorwith the D-Bus errorname, for the rest:Bus::errorBank(bunq's refusal, as bunq said it),Bus::errorOAuthCannotPay,Bus::errorCancelled(the user closed the password dialog),Bus::errorFailed,org.freedesktop.DBus.Error.AccessDenied(the system's policy, or polkit not answering) andInteractiveAuthorizationRequired. A missing nostrod isDaemonMissing, astd::runtime_errorsaying it is not running. A call that moves money or changes something and gets no answer in time, or that bunq answered with an error ending inBunqError::maybeCarriedOut(a 5xx: the payment may have been made), isOutcomeUnknown, astd::runtime_errorsaying it may have been carried out: check before trying again. Text that is not UTF-8 is astd::invalid_argumentbefore anything is sent. - The API key and the OAuth client secret travel once, in messages marked sensitive. Read them with
ReadSecret, never fromargv, which every local user can read and polkit logs.
Having a customer pay
An app that wants a customer to pay an order links nothing of nostro and calls nothing of nostrod: it opens a payto://iban/… link (RFC 8905), and the Nostro app shows it as its pay form filled in, for the user to check, change and confirm with their password. What the app reads of a link:
payto://iban/<IBAN>?amount=EUR:12.50&receiver-name=<name>&message=<what it is for>, the values percent-encoded, whichUrlEncodedoes. A BIC and a/may come before the IBAN, and are left out. The amount isEUR, a colon and digits, with a point and one or two more digits or without, asFormatAmount(1250, Currency::Euro)writes one (12.50); withoutamountthe user fills it in. The name is at most 70 code points, the message 140, and the link 4096 bytes.- A link the app refuses gets a sentence of the app's own, with nothing of the link in it. Among what it refuses: an IBAN whose check digits do not hold;
amount,receiver-nameormessagegiven twice, where an option's name counts with its escapes undone and in small letters;instruction; a#; a%that is no escape in one of those values; a name or a message that is not UTF-8, or has a code point in it that isUnshown, a noncharacter (the last two of a plane), orBlankand no plain space; a currency other than EUR; an amount that is zero, or has a sign, a space or a comma in it. Other options are passed over. - A
+in a value is read as a space (UrlDecode): write%20for a space and%2Bfor a plus. - The app tells whoever opened the link nothing. See the payment arrive at your own bank.
- The checkout over D-Bus that 0.0.0 has is gone:
net.catcrafts.Nostro1.Checkout, the moduleNostro.Checkoutand--product=checkout, which is now an unknown product, and with themBus::actionCheckout,Bus::checkoutMethodsandBus::errorNoCheckoutAccount.Client::DefaultCheckoutAccountandSetDefaultCheckoutAccountstayed: the account they keep is where the app's pay form starts for a link.
Errors
BunqErroris astd::runtime_errorwith the HTTPstatus(bunq also uses 466, 490 and 491), its messagebunq <METHOD> <path>: <error_description> (<status>).std::invalid_argumentis 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"(afterERR_print_errors_fp(stderr)),"XDG_CONFIG_HOME and HOME not set". - Around it come:
nlohmann::json::exceptions from aconnectors.jsonor a bank response with a missing key or a wrong type (astd::exception, not aruntime_error).std::system_errorfrom the file layer and the lock.- Crafter.Network's
SocketErrorException,SocketTimeoutException,TLSExceptionandHTTP1::HTTP1ProtocolErrorfrom a GET (a write wraps them as above). - Crafter.DB's
Errorfamily from the tables.
- Catch
std::exceptionat the top of a command, as nostro'smaindoes.
Testing a consumer
- Point
XDG_CONFIG_HOMEandXDG_CACHE_HOMEat a scratch directory before the process starts, or setNostro::configPathandcachePathfirst thing inmain. Noconnectors.jsonneeds seeding. - A consumer of
Clientneeds nostrod on a system bus, and a build sandbox has none. nostro'stests/Support/FakeBus.incis one in the test's own process: the bus driver, logind and polkit (with scripted answers: allow, a password, deny, a closed dialog, absent, silent or slow), giving each connection of the test's own process a uid of the test's choosing (nostrod's keep their own). SetDBUS_SYSTEM_BUS_ADDRESStoFake::Bus::Address(path)before any thread starts, and start nostrod as a process of its own:tests/ShouldServeEveryUsercompilesimplementations/nostrod.cppin with itsmainrenamed and runs its own executable again as nostrod (Fake::StartNostrod), pointed at a fake bunq through the environment (Fake::Bunq::ExportRedirect,RedirectFromEnvironment). - Without bunq:
RedirectToa 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 returnsResponse[0].ApiKey.api_key. Pass it toCreatewith"*"andEnvironmentOfKey(key), thenSaveConnectors(). 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 nextGetNewTransactions(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.cppexercises 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, OAuthCodeFromRedirect 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; EnabledBanksandtuple_forin:Banks;ParseAmount,FormatAmount,FormatMoney,GetCurrency,GetCurrencyCode,GetCurrencySymbolandGetCurrencyDecimals;- in
:Utils:ParseTimestamp,FormatTimestamp,ParseLocalDate,ParseLocalDateEnd,FormatLocalTime,UrlEncode,UrlDecode,QueryParameter,Unshown,BlankandEscB; FindTransactions(not Query, Load or List),SaveTransactionsandGetLastTransactionTime;TransactionQuerywithsearch,amount,from,to,limitandstored;- in
Nostro::Crypto:Key,OwnKey,SignBody,VerifyBody,CreateKey(astd::tuple<EVP_PKEY*, std::string>, the public PEM second),LoadKeyFromPem,LoadPublicKeyFromPem,PrivateKeyToPem,PublicKeyToPem,RandomHexandThrowOnOpenssl; configPath,cachePath,CreatePrivateFileandReadSecret;- for nostrod:
Client(System,Attach,Connected,TakeNotes,DefaultCheckoutAccount,SetDefaultCheckoutAccount, andClient::PendingandClient::Then),Answer,DaemonError,DaemonMissing,OutcomeUnknown,ConnectorSummary,AddedConnector,ConnectorAccounts,ConnectorCards,Created, andBus::busName,Bus::errorBankand the otherBus::error…names.