The app was built against a checkout of Crafter.Graphics given with --graphics=, because the text-input purposes it asks the input method for were uncommitted work in one checkout. They are on Crafter.Graphics' master since a9ce1a0, so project.cpp names the library as a GitProject at that commit, as it names Crafter.Network and Crafter.DB. --graphics= is gone, and with it $NOSTRO_GRAPHICS in build-aarch64.sh and the workflow's step that cloned the branch claude/nostro-app, which the forge never had: neither job of the workflow could have built the app. That master also has 89111e0, which the window was not written against. A size the compositor configures is no longer taken in the configure's listener. The listener keeps it and fires onFrameOwed, and the next Render() makes the swapchain again, fires onResize from inside itself, and answers the configure with that frame's buffer. The window draws on demand, so: - Shell::Window asks for a frame from onFrameOwed. Without it nothing draws the frame that answers the configure, and the window keeps its old size until something else changes on it. - Canvas::Reconcile no longer turns the compositor's sizes into Resize(pixels). The library takes the size asked for last, whoever asked, so that call took the configured size's place, and with it came back the surface a dp larger than configured that 89111e0 had ended (Crafter.Graphics #201). It now sizes the window only where the library does not: the app's own size (--size, SetSize, --scale); the size that comes with a new window (#166), handed over in deferredLogicalWidth, where the library's listener keeps every later one; and a scale the display changes to by itself (#165), through RebuildSwapchain. The last two reach into the library's own state, and go once the library does them. The text-input API on master is the one the app was written against: nothing changed there. Looked at on 2026-11-20 on the made-up system, on a desktop (KWin at a scale of 1.85), with WAYLAND_DEBUG=1 on the app: - The accounts at 420x760: the start, and resize:600,800 from --poke, the app's own size. Each size reaches the surface once, with the first buffer drawn for it. - The same window given 760x532 by the compositor (a KWin script that sets its frameGeometry): the configure is kept, a frame is asked for, and set_destination(760, 532), the acknowledgement and the first buffer of 1406x985 go out together. A temporary probe had that frame's draw list reach 1406x985: it is laid out for the new size. - 421x761, whose pixels at 1.85 are no whole number: it opens as 422x762, since the app's own size goes through Resize in pixels. The notes say so. - --scale 2 --size 360x760, the cards and the pay form filled in from --poke, with resize:400,700: the compositor's sizes are passed over. - The --debug-api build driven with crafter-debug: Window_Resize, Ui_Tap, ui.texts and a screenshot. The two paths that are a phone's, a size in the first configure and a scale named after the first frames, were tried only with the values put in by hand in a temporary probe. Nothing was looked at on a phone, and what the input method is told was not read off the wire: the test window never had the keyboard. 17 tests pass and the four lint passes report nothing. The app, its --debug-api build, the fake system, the x86_64 Flatpak bundle and both aarch64 Flatpaks (build-aarch64.sh) build. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
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 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.Checkoutmodule 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
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.--product=checkoutinstead returns thenostro-checkoutlibrary alone: the moduleNostro.Checkout, needing neither--libnor--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=,--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.
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::errorNoCheckoutAccount,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.
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)returnsPaid{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:
Payagain with the same IBAN and reference, after a timeout or a crash, answers with the first payment andrepeatedset, 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, without a word on which amount the order has. 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) andCheckout::NoCheckoutAccount(none chosen, or the chosen one is gone), bothCheckout::Error, which every other refusal is, with the D-Busname:Checkout::errorInvalidArgument,errorBank(its message isbunq:and what bunq said, without the call it answered, which would name the user's account; it 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, andServiceUnknown, which means nostro is not installed. No answer withintimeoutis anErrorsaying the order may have been paid, and asking again is safe. Text that is not UTF-8 is astd::invalid_argument; a failure of the bus itself astd::system_error. - On the wire it is
net.catcrafts.Nostro1.Checkout, its own bus name, with one method,Pay(ssxssa{sv}) -> (ta{sv}), published aspackaging/dbus/net.catcrafts.Nostro1.Checkout.xmlfor 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
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
Clientor ofNostro.Checkoutneeds 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, none, slow), giving each connection a uid of the test's choosing. 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,QueryParameterandEscB; 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; - for checkout:
Nostro::Checkout::Pay,Order,Paid,Error,Cancelled,NoCheckoutAccount, and the moduleNostro.Checkout, with a dot.