46 KiB
AGENTS.md
Guidance for coding agents and contributors working on nostro itself. The README is the user-facing manual (what nostro is for, the CLI, how to contribute a bank), and AGENTS.consumer.md is what agents working in a consumer of the library read: crafter-build copies it into the dependency-notes section of the consumer's AGENTS.md on every build. When any of the three disagrees with the code, the code wins; the interfaces under interfaces/ are the contract, Transaction in interfaces/Nostro-Transaction.cppm is the contract for the bytes on disk, and packaging/dbus/*.xml with packaging/system/net.catcrafts.Nostro1.policy are the contract on the system bus, which a test holds to what nostrod serves. This file is written by crafter-build from AGENTS.template.md; the section at its end holds the notes of the libraries nostro builds against (Crafter.Network, Crafter.DB), straight from their repositories.
Project overview
nostro is a banking client for Linux, phones first: a library that talks to bank APIs directly; nostrod, a system daemon that runs it for every local user behind D-Bus and polkit, so no program of the user's can read the bank's secrets or move money without the user's password; and a small CLI that only talks to nostrod. Linux phones have no banking apps; nostro is the open-source answer, one connector per bank. One C++26 module, Nostro, with twelve partitions behind the umbrella and ten implementation units, and a second module, Nostro.Checkout, for apps that have nostrod pay an order. project.cpp makes one product per build: the static library nostro with the CLI nostro (implementations/main.cpp), nostrod (--product=daemon, implementations/nostrod.cpp), or the static library nostro-checkout (--product=checkout). The bunq connector is the only bank so far and the model for the next one. It depends on Crafter.Network (HTTPS to the bank), Crafter.DB (the local transaction tables and the checkout record), OpenSSL (request signing, response verification), libsystemd (sd-bus and sd-event, for nostrod and its clients) and a vendored nlohmann/json. It ships as a Flatpak, net.catcrafts.Nostro, that systemd runs nostrod from as the system user nostro.
| Path | What lives there |
|---|---|
interfaces/Nostro.cppm |
The umbrella: export imports every partition; :Bunq and :Crypto only under their defines, :Bus, :Client and :Daemon only under NOSTRO_DBUS_ENABLED. |
interfaces/Nostro-<Partition>.cppm |
One partition per file, Nostro:<Partition>. |
implementations/Nostro-<Partition>.cpp |
The implementation units, Nostro:<Partition>_impl: Account, File and Connector always; Bunq, BunqPayments (Nostro-Bunq-Payments.cpp: counterparties, payments, drafts, requests, schedules) and Crypto when their bank is enabled; Bus, Client, Daemon (nostrod's front) and DaemonWorker (Nostro-Daemon-Worker.cpp: a user's worker, the polkit gate, the checkout) under D-Bus. |
interfaces/Nostro.Checkout.cppm, implementations/Nostro.Checkout.cpp |
The module Nostro.Checkout: the checkout's names and wire, and a blocking Pay over sd-bus. A module of its own, so --product=checkout builds it without the rest. |
implementations/main.cpp |
The CLI, a client of nostrod: argv parsing (positional arguments, --name value options, --sandbox), one function per command over Client, output through the std::formatters, the notes on stderr, errors caught in main and printed with exit status 1. |
implementations/nostrod.cpp |
nostrod's main: --state, --idle, --prompt-timeout, and --worker <uid> <name> for the worker processes it starts itself. |
project.cpp |
The build description: reads --banks=, --lib, --dbus, --product=, --coverage and --profile-runtime=, forwards the other args to the dependencies (with --no-quic for Crafter.Network), returns the product. |
packaging/dbus/ |
The published D-Bus interfaces, net.catcrafts.Nostro1.xml and net.catcrafts.Nostro1.Checkout.xml. |
packaging/system/ |
What a Flatpak cannot install: the polkit policy, the D-Bus policy and activation files, nostrod.service, the sysusers entry, the nostro command, install.sh and uninstall.sh. |
packaging/flatpak/, packaging/arch/ |
The Flatpak manifest (on crafter-build's Flatpak as its base app), metainfo and .flatpakref; the Arch package of the system files, nostro-system. |
lib/json.hpp |
nlohmann/json 3.12.0 (MIT), included in the global module fragment of :Bunq and of the Connector, Bunq and BunqPayments implementation units. |
tests/<Name>/main.cpp, tests/Support/, tests/coverage.sh |
The tests, their checks, fake bunq and fake system bus, and the coverage run; see "Testing instructions". |
README.md, LICENSE, LICENSE.GPL |
The manual; LGPL-3.0-only and the GPL it incorporates. |
AGENTS.template.md, AGENTS.consumer.md |
The source of this file, and the notes for consumers. AGENTS.md is gitignored: edit the template. |
.vscode/ |
A build task and an lldb launch configuration, both stale; see "Gotchas". |
bin/, build/ |
Generated and gitignored. The library and the CLI are both named nostro, so one build leaves two bin/nostro-<target>-<march>-<mtune>-<hash>/ directories: the library's (libnostro.a, the PCMs, std.pcm) and the executable's (nostro). Glob for the one holding nostro. nostrod builds into bin/nostrod-…/, the checkout library into bin/nostro-checkout-…/. |
Partitions, from the bottom up (each imports only the ones above it):
:Currency:Currency(anenum class : std::uint16_twithEuroalone),GetCurrency(from"EUR"or"eur", throws for anything else),GetCurrencyCode,GetCurrencySymbol,GetCurrencyDecimals,ParseAmount(decimal string to minor units),FormatAmount(back) andFormatMoney(-€1.02), allconstexpr, andstd::formatter<Currency>, which prints the symbol.:Utils:ParseTimestampandFormatTimestamp(bunq'sYYYY-MM-DD HH:MM:SS[.ffffff], UTC),ParseLocalDateandFormatLocalTime(dates a person types and reads, local time throughmktime/localtime),UrlEncode,UrlDecodeandQueryParameter(for OAuth),EscB(JSON string escaping, no longer used by nostro itself), andNotewith its replaceablenoteSink, where every warning of the library goes (stderr by default).:Transaction: theTransactionaggregate, which is also the row type of the Crafter.DB tables:version = 2(idandkindadded on 2026-10-31),orderedBy = &Transaction::timePoint,using Previous = TransactionV1(unexported, kept for the migration), and itsstd::formatter(one tab-separated line).:Account:TransactionQueryandAccount(name,bic,iban,currency,balancein minor units) with the three methods over the transaction store and the staticForgetTransactions(which closes this process's open tables under a storage key before deleting them), and thestd::formatterforAccountand everything derived from it. The implementation unit owns the Crafter.DB tables and pins the schema with twostatic_asserts.:File:GetConfigPath,GetCachePath, the globalsconfigPathandcachePaththey initialise at static-init time,CreatePrivateFile(a0600file in a0700directory), andReadSecret(a line from stdin, not echoed on a terminal).:Crypto(underNOSTRO_OPENSSL_ENABLED; OpenSSL headers in the global module fragment), innamespace Nostro::Crypto:ThrowOnOpenssl,Key(std::shared_ptr<EVP_PKEY>freeing itself) andOwnKey,SignBody(RSA SHA-256, base64) andVerifyBody(its check against a public key),CreateKey(RSA 2048 and its public PEM),LoadKeyFromPem,LoadPublicKeyFromPem,PrivateKeyToPem,PublicKeyToPem,RandomHex(the OAuthstate).:Bunq(underNOSTRO_BUNQ_ENABLED;json.hppandopenssl/types.hin the global module fragment; the implementation units import Crafter.Network):BunqEnvironment,BunqError,BunqCounterparty, the listing types (BunqLabel,BunqPaymentRequest,BunqIncomingRequest,BunqSchedule,BunqScheduledPayment,BunqDraftPayment,BunqCard) and their formatters,BunqAccount : Account(id,type,connector, the payment calls),BunqConnector(environment, keys, tokens, user,accounts, the rawGet/Post/Put/Delete/List, the static dequeconnectors,Create,Remove, the OAuth helpers, andEndpoint/RedirectTowithBunqEndpoint),to_json/from_json, and the unexportedBunqJsonhelpers both implementation units share.:Banks:tuple_for<Tuple>(f)andEnabledBanks, thestd::tupleof enabled connector types; every generic loop in the CLI and in:Connectoris atuple_for<EnabledBanks>.:Connector:Connector::SaveConnectors()andLoadConnectors(),connectors.jsonout (synced, then renamed into place) and in, both under the process-wideconnectors.lock.:Bus(underNOSTRO_DBUS_ENABLED;sd-bus.hin the global module fragment): the wire nostrod and its clients share. The names, the error names (the checkout's fromNostro.Checkout), the polkit actions, the method tablesmethodsandcheckoutMethods(member, signatures, argument names, sensitive), the result structs (ConnectorSummary,AddedConnector,ConnectorAccounts,ConnectorCards,Created),Wire<T>withAppendandReadfor every type that travels (a struct as its members, a time as microseconds, a currency as its code, an optional as an array of zero or one),AppendQuery/ReadQuery,Vtable,ThrowOnSdBus, and theBusPtr/MessagePtr/Errorowners.:Client:Client::System(), one method per method ofnet.catcrafts.Nostro1,TakeNotes(), andDaemonError.:Daemon:DaemonOptions,RunDaemon(the front) andRunWorker(one user's worker).
Nostro.Checkout, a module of its own that imports nothing of Nostro: the checkout's bus name, interface, Pay's signatures and argument names, the error names apps tell apart, Order, Paid, Error with Cancelled and NoCheckoutAccount, and Pay. :Bus and the daemon take their names from it.
The bunq connector end to end:
- Requests (
implementations/Nostro-Bunq.cpp): every call goes through the privateBunqConnector::Call, behind the publicGet,Post,Put,DeleteandList. It talks toBunqConnector::Endpoint(environment):api.bunq.comorpublic-api.sandbox.bunq.comby the connector's environment, or whereverRedirectTosent everything (the tests' fake), with oneClientHTTP1per endpoint.- It signs every body except the installation's.
- It refuses a 2xx whose
x-bunq-server-signaturedoes not verify againstserverPublicKey, which an old connector fetches first (EnsureServerPublicKey). - It waits out a 429, and renews the session once on a 401 or a 403 "Insufficient authentication.", then saves.
- It sends a POST, PUT or DELETE over a fresh connection, because
ClientHTTP1replays a request on a reused connection that fails before any answer, even after a read timeout. A write whose outcome is unknown says it may have been carried out. - Every other error is a
BunqErrorwith bunq'serror_description.
- Connecting:
Create(apiKey, allowedIps, environment)makes an RSA key, thenPOST /installation(installation token and server key),POST /device-serverwithpermitted_ipsas a JSON array, andRefreshSession(). The session isPOST /session-server, signed: the token, the session id, and the user fromUserPerson,UserCompany,UserPaymentServiceProvideror, for OAuth,UserApiKey(its own id in paths,ownerIdand the name fromgranted_by_user). - Accounts and history:
RefreshAccounts()lists everyMonetaryAccount…type that isACTIVEorBLOCKED.GetNewTransactions(account)pages the payments newest first until one older than the last stored row, and hands them toAccount::SaveTransactionsunderaccount.StorageKey(). - Payments (
implementations/Nostro-Bunq-Payments.cpp):BunqCounterparty::Parsereads an IBAN (check digits verified), an e-mail address or a phone number.Send,Draft,ScheduleandRequestbuild their bodies from it, the listings read bunq's objects into the listing types, and the responses are PUTs or a DELETE. Accepting a request or a draft takes the object as it was read and shown (IncomingRequest(id),DraftPayment(id)), so what gets paid is what the user saw. - OAuth:
OAuthAuthorizationUrlandOAuthExchangeCode(the token endpoint reads query parameters only). The token then goes toCreatelike an API key.
nostrod end to end:
- The front (
implementations/Nostro-Daemon.cpp,RunDaemon) is one sd-event loop with two system bus connections. One ownsnet.catcrafts.Nostro1and serves that interface. The other ownsnet.catcrafts.Nostro1.Checkoutand serves the checkout alone: a Flatpak allowed to talk to that name can call its owner's unique name too, and on that connection there is nothing else. Every method of both is one forwarding handler. It asks the bus for the caller's uid (GetConnectionCredentials), and logind for that uid's name, starts the uid's worker if there is none (posix_spawnof/proc/self/exe --worker <uid> <name> …, a socketpair end as fd 3, D-Bus peer to peer over it), and passes a copy of the call on, from the caller's unique name and allowing a dialog only when the caller did. The answer is relayed when it comes, so one user's open dialog holds up nobody. A worker that dies under a call is answeredFailedwith "may have been carried out". It holds no connector and no secret. It ends once idle with no worker left, on SIGTERM, or when the bus goes; D-Bus activation starts it again. - A worker (
implementations/Nostro-Daemon-Worker.cpp,RunWorker) is one user's library:configPathandcachePathare<state>/users/<uid>, the connectors are read on the first call, and it is not dumpable. A directory records whose it is (owner): a uid that logind now names differently, after a user was deleted and another given their uid, is refused. Every handler reads and checks the call first (the account, the counterparty, what is to be paid, or for a request or a draft the object as bunq has it), builds aPrompt(the polkit action, a summary from its own data, and details for polkit rules), and hands it toGate.Gateasks polkit asynchronously (CheckAuthorizationabout the caller's bus name, cancelled if it does not answer in time) and runs the call's work only once polkit says yes. It fails closed: no polkit, an error or a timeout isAccessDenied. A dialog the user closed isCancelled, which polkit says withpolkit.dismissedor, from Plasma's agent,polkit.resultauth_…. A challenge to a call that allowed no dialog isInteractiveAuthorizationRequired. Every answer of the main interface ends with the notes. A summary's text from a caller or the bank goes throughShown()(no control, invisible or direction characters,<and>replaced,$(broken, 64 characters at most) and names the address before the name. The worker ends once idle with no dialog open, on SIGTERM, or when the front goes. - Checkout (the same file):
Order::Readrefuses a payee that is not an IBAN, an amount that is not positive, an unknown currency or an empty reference. An order already incheckouts.cdb(a Crafter.DB table,CheckoutRecord) is answered with its payment,repeated, without a dialog, or refused when its amount differs, or when its payment is still 0: a payment whose outcome was lost. An order being paid makes the next call for it wait, andSettlegives it the first call's answer.ChooseAccountpicks the account (the one incheckout-account, set bySetDefaultCheckoutAccount; an account of an OAuth connector is refused there) and answers through a continuation, so an account picker can take its place later. The dialog (net.catcrafts.Nostro1.Checkout) shows the order and that account.PayOrderrecords the order, with no payment, before it pays, and takes the record away again only when bunq refused before doing anything, below 500. - The client (
implementations/Nostro-Client.cpp) allows interactive authorization and waits 10 minutes by default; nostrod'sInvalidArgumentbecomesstd::invalid_argument,ServiceUnknowna "not running" message, a write without an answer "may have been carried out", and the rest aDaemonErrorwith its name.Nostro.Checkout'sPaydoes the same for the checkout with its own types.
Dev environment
crafter-build is the only build tool. It compiles with its clang 23 and libc++, -std=c++26 and import std;, and links -lssl -lcrypto, and -lsystemd for anything with D-Bus in it (libsystemd's sd-bus.h and sd-event.h; crafter-build's Flatpak SDK has them). Packaging uses flatpak-builder.
- Every build needs the network: Crafter.Network (with Crafter.Thread behind it; nostro builds it
--no-quic, so without msquic) and Crafter.DB areGitProjects on their default branches, and Crafter.LintRules a#pragma crafter dependencyofproject.cpp, so each buildgit pulls them fromforgejo.catcrafts.net, and the notes at the end of this file follow their HEAD. A.commit(in the pragma,commit "<sha>") would pin them. - Where the connectors live depends on who runs the library. nostrod's worker keeps each user's under
<state>/users/<uid>/:connectors.json, the transaction tables,checkouts.cdb,checkout-accountandowner, with<state>from--state, else$XDG_DATA_HOME, else$HOME/.local/share. Installed, that is/var/lib/nostro/.var/app/net.catcrafts.Nostro/data/, readable by the usernostroalone. The library used directly readsconnectors.jsonfrom$XDG_CONFIG_HOME/.config/nostro/(sic, see "Gotchas") or$HOME/.config/nostro/, and keeps the transaction tables under$XDG_CACHE_HOME/nostro/transactions/or$HOME/.cache/nostro/transactions/. A real connectors file holds a real API key: point every experiment elsewhere. - No test uses the system bus: they run on
tests/Support/FakeBus.inc. Running anything by hand that talks tonet.catcrafts.Nostro1reaches the installed nostrod, if there is one, and its dialogs. A Flatpak sandbox with the system bus (flatpak run,flatpak build) setsDBUS_SYSTEM_BUS_ADDRESSitself, over an--envof yours: keep a sandboxed experiment off the bus with--nosocket=system-bus. - To read a
constexprvalue such asDB::Layout<Transaction>::fingerprint,static_assert(x == 0)it and read "expression evaluates to" in the error.
Build, test and style commands
crafter-build --banks=bunq # the library, then the CLI: bin/nostro-<variant>/nostro
crafter-build --banks=bunq --product=daemon # nostrod: bin/nostrod-<variant>/nostrod
crafter-build --product=checkout # the Nostro.Checkout library alone; no bank needed
crafter-build --banks=bunq --lib # the library alone (what a consumer builds), without D-Bus
crafter-build --banks=bunq --lib --dbus # the library with :Bus, :Client and :Daemon
crafter-build --debug --banks=bunq # debug build
crafter-build -v --banks=bunq # with the compiler commands
crafter-build clean # delete bin/ and build/
crafter-build test --banks=bunq # the tests in tests/, against a fake bunq; none talks to bunq itself
tests/coverage.sh [profile runtime] # the tests with coverage: a report per file and every line no test ran
crafter-build lint --banks=bunq # the Crafter.LintRules lite rules project.cpp registers, report only
flatpak run --filesystem=<dir> org.flatpak.Builder --user --force-clean --repo=<dir>/repo --state-dir=<dir>/state <dir>/build packaging/flatpak/net.catcrafts.Nostro.yaml
--banks= is mandatory except for --product=checkout: without it project.cpp throws "must enable atleast one bank" and nothing is built; an unknown name throws "unknown connector", an unknown product "unknown product". flatpak-builder needs crafter-build's own Flatpak (net.catcrafts.CrafterBuild, stable) installed as its base app, the network during the build, and, run as a Flatpak itself, --filesystem= for a build directory outside your home, or the build commands cannot find it. Install the result for a test with sudo packaging/system/install.sh --repo <dir>/repo. There is no CI. The tests run every line, function and region of nostro's own sources (2026-11-01), and a change keeps them doing so; the README's rule for contributed connectors applies on top: not blind, also tried against the sandbox or the live API ("Testing instructions").
Testing instructions
crafter-build test --banks=bunq builds and runs tests/<Name>/main.cpp for each name in project.cpp's list, each linked against the library, in parallel; a test exits 0 when every check passed and prints each failed one with its line. They are:
| Test | What it covers |
|---|---|
ShouldHandleMoneyAndText |
:Currency and :Utils: every parse with what it refuses, every format, local dates in a fixed time zone |
ShouldSignAndVerify |
:Crypto: keys, PEM, signatures and each way one fails to verify |
ShouldStoreTransactions |
:Account: what a sync stores and drops, the queries, a version 1 table migrating |
ShouldKeepFilesPrivate |
:File: the paths, private files and their failures, ReadSecret from a pipe and from a pseudo-terminal |
ShouldSaveConnectors |
:Connector: loading, the synced save, and every way the lock and the save fail |
ShouldTalkToBunq |
the connector: every user type, signatures, rate limits, session renewal, errors, accounts, the sync, cards, OAuth, old connectors |
ShouldMoveMoney |
payments, drafts, schedules and requests, and their formatters |
ShouldRunCommands |
the CLI: implementations/main.cpp compiled in with its main renamed, every command run in-process against a real nostrod on the fake bus |
ShouldServeEveryUser |
nostrod: users kept apart, a uid handed to a new user, every polkit answer and what each dialog says, calls that wait on each other or do not, the checkout and its retries, the checkout client, workers that die, idle exits, every error as the client gets it, and the published contract (the XML and the polkit policy) |
How they are built:
tests/Support/Check.incholds the checks (Check,Equal,Throws) and a temporaryDirectory;tests/Support/FakeBunq.incis a bunq in the test's own process, HTTPS on 127.0.0.1 with Crafter.Network's self-signed certificate. It signs what it answers, checks the client's signatures, keeps users, accounts, payments, requests, schedules, drafts and cards, and fails on request (Fake::Fault).BunqConnector::RedirectTopoints nostro at it; each test has a port of its own (47301 to 47305), and port 443 on 127.0.0.1 stands for a host that refuses the connection.tests/Support/FakeBus.incis a system bus in the test's own process, an sd-bus server on a unix socket: it routes calls by name with the caller's unique name, and plays the bus driver (GetConnectionCredentialswith the uid the test chose for a connection of its own process, the real one for nostrod's), logind (GetUserand the user'sName) and polkit (each check recorded; allow, a password, deny, a closed dialog, absent, silent or slow, per action). The two nostrod tests start their own executable again as nostrod (Fake::StartNostrod, withNOSTRO_TEST_ROLEset; itsmainthen runsimplementations/nostrod.cpp's, compiled in withmainrenamed), which finds the fake bunq through the environment (Fake::Bunq::ExportRedirect,RedirectFromEnvironment). Everything a child reads from the environment is set before any thread starts. A worker that cannot be spawned is made withprlimiton nostrod (Fake::Limit), and workers are stopped with SIGTERM, which they handle, so their coverage counts are written.- What a disk or a kernel will not do on demand (
flockfailing or interrupted,fsyncfailing, a chosen OAuth state fromRAND_bytes) the test defines itself as anextern "C"function: the linker takes it over libc's or OpenSSL's, and it calls the real one throughdlsym(RTLD_NEXT, …)when nothing is scripted. A file size limit (RLIMIT_FSIZE) makes a write fail part way. - Each test sets
configPathandcachePathto a temporary directory first, andTZwhere it formats local time.
Coverage is clang's source-based coverage: tests/coverage.sh builds with --coverage, runs the tests with LLVM_PROFILE_FILE set (with %p, so nostrod and every worker write their own), merges the profiles and reports with llvm-cov, leaving build/coverage/sources.txt annotated. A toolchain without compiler-rt's profile library, which crafter-build's Flatpak lacks, takes one as the script's argument (--profile-runtime= to project.cpp). On 2026-11-01 lines, functions and regions were all at 100% and branches at 95%: what is left is mostly defensive checks no input can flip and per-instantiation counts in main.cpp's templates.
The bunq sandbox is still the check for what a fake cannot show. Since nostrod (2026-11-01) the CLI needs an installed nostrod: build the Flatpak, install it with sudo packaging/system/install.sh --repo <dir>/repo, and use the CLI as yourself; real polkit dialogs then ask for your password. A second local user shows the separation. The library alone still runs from an isolated config and cache, never from ~/.config/nostro. The recipe, as it worked on 2026-10-31 with the CLI of then, which held the connectors itself:
- Build (in place or in a scratch copy made with
rsync -a --exclude build/ --exclude bin/ --exclude .git/) and run the binary withXDG_CONFIG_HOMEandXDG_CACHE_HOMEpointing into a scratch directory. Noconnectors.jsonneeds seeding. - Throwaway users:
POST https://public-api.sandbox.bunq.com/v1/sandbox-user-person(or-company) with no authentication returnsResponse[0].ApiKey.api_key;nostro connectors add bunq, given the key on stdin, recognises the sandbox by its prefix. The response also holds the user's e-mail and phone aliases, for paying by those. Make two, so there is someone to pay; sandbox accounts are all called "Bank Account", so name them by IBAN. - The CLI reaches every bunq call (
nostro helplists them). Session renewal is tried by ending the session behind nostro's back (DELETE /v1/session/0with the storedsessionToken), signature checking by putting another public key inserverPublicKey. - A new sandbox account holds €0 and no payments. Fund it with
nostro request <iban> sugardaddy@bunq.com "Sugar Daddy" 50000: it is paid within seconds. A hundred rows at once:POST …/payment-batchwith{"payments": […]}(more than 200 exercises the paging).curlcan call as the same user with thesessionTokenfrom the scratch file, and sign withopenssl dgst -sha256 -signover the body using itsprivateKeyPEM, base64, inX-Bunq-Client-Signature. A sandbox virtual card (POST /v1/user/{id}/card-debitwithorder_status: VIRTUAL_DELIVERY) cannot be activated through the API, socards unfreezecan only show bunq keeping itDEACTIVATED. OAuth stops at the token exchange: approving needs a person and the bunq app. - bunq allows 3 GETs, 5 POSTs and 2 PUTs per three seconds per endpoint and one session per 30 seconds; nostro waits a 429 out, so a burst of runs is slow rather than failing. Concurrent nostro processes queue on
connectors.lock, so two never hold the same account's table.
A bug fix comes with a test that fails without it, and states in its commit how it was reproduced; a new bank comes with tests against a fake of it and with the same check against its sandbox or live API.
Code style
crafter-build lint --banks=bunqreports nothing. A finding at a C boundary (main'sargv, achar*an OpenSSL or POSIX call hands out) is suppressed with// lint-disable-next-line <rule>and a comment saying why; anything else is fixed. The rules that need an AST cannot parse a file that#includes a standard header beforeimport std;(the nine that includejson.hpp: four in the library, five tests), so lint exits 1 for those alone until Crafter.Build issue #46 is fixed: check them by hand, and prefer C headers (<errno.h>, not<cerrno>) elsewhere. Tests are linted like the rest.- The first two lines of every source are
// SPDX-License-Identifier: LGPL-3.0-onlyand// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®, then a blank line.project.cppcarries them too. - Four-space indentation, LF, K&R braces with
} else {, one declaration per statement.if(,for(,while(,switch(without a space in most files (:Utilshas the space; match the file). Lines run long rather than wrap. import std;everywhere;#includes only in a global module fragment (module;first), and only for OpenSSL, the vendoredjson.hpp, sd-bus and sd-event, and the POSIX calls of:File,:Connectorand nostrod.namespace fs = std::filesystem;where paths appear.- Interfaces are
export module Nostro:<P>;withexport namespace Nostro { … }when the partition is free functions (:Currency,:Utils,:File,:Crypto) andnamespace Nostro { export struct … }when it is types. Astd::formatterspecialisation sits after the namespace, unexported, which importers still find. Implementation units aremodule Nostro:<P>_impl;followed byimport :<P>;.Nostro.Checkoutis a module of its own (export module Nostro.Checkout;, implemented inmodule Nostro.Checkout;) because a shop app links it without the rest. - An sd-bus callback returns 0 or more and never throws: a negative result closes the connection it came on, and an exception would unwind through C. Every worker handler catches everything (
Handle) and answers with an error instead. PascalCasefor types, functions and member functions;camelCasefor variables, members and constants (sessionToken,connectorId,configPath);enum classonly; fixed-width integers (std::int64_tfor money,std::uint64_tfor bunq ids,std::uint16_tunderCurrency).tuple_for,to_jsonandfrom_jsonare the snake_case exceptions, the last two because nlohmann/json looks them up by that name.- Parameters are
std::string_view, orstd::string&&where the callee stores them (the account constructors,Create).std::formatandstd::printlnfor all text; iostreams only forconnectors.json. - Errors are exceptions with a
std::formatted message that names the thing:std::runtime_error("malformed amount '{}'"),BunqErrorwith the HTTP status for a bunq error response ("bunq {} {}: {} ({})", method, path, description, status),std::invalid_argumentfor input refused before anything is sent. Every OpenSSL return goes throughThrowOnOpenssl, which prints OpenSSL's error stack to stderr first. No error codes, nostd::expected. - Comments say why, and are kept: the table cache in
Nostro-Account.cpp, the schema warning onTransaction, theopensslEnabledline inproject.cpp. New non-obvious code gets the same.
Design rules
- Banks are chosen at build time.
--banks=lists them, each gets aNOSTRO_<BANK>_ENABLEDdefine, its partition and implementation unit exist only under it, andEnabledBanksis thestd::tupleof what is in. Generic code istuple_for<EnabledBanks>over duck-typed connector types; there is no virtual base, no registry, no runtime plug-in. A binary knows exactly the banks it was built with. - A connector is a struct with a known shape.
static constexpr std::string connectorId,static std::deque<Self> connectors(a deque, so an account'sconnectorpointer survives the nextCreate),using Account = <Bank>Account,std::vector<Account> accounts,name,TestConnector(),RefreshAccounts(),GetNewTransactions()andGetNewTransactions(account),Logout(),StorageKey(), staticCreate(…)andRemove(connector),to_json/from_jsonforconnectors.json, and astd::formatterthat prints its name; its account derives fromAccountand hasStorageKey()andSend(to, name, amount, currency, description).main.cppand:Connectorcompile against that shape; anything a bank offers beyond it (bunq's requests, schedules, drafts and cards) the CLI reaches throughif constexpr (requires { … }). (Revised 2026-10-31 for the MVP connector: the deque,Logout,Removeand the storage keys.) - Money is an integer. Amounts and balances are
std::int64_tin the currency's minor unit, outgoing negative, with theCurrencybeside them; decimal strings exist only at the API boundary and go throughParseAmountandFormatAmount. No floating point anywhere near an amount. - Secrets live in one private file, out of the user's reach.
connectors.jsonholds the API key or OAuth token, both tokens and the RSA private key,0600under a0700directory made byCreatePrivateFile; nothing prints them, nothing else persists them. Installed, the file is nostrod's, under the state directory of the system usernostro, so no program the user runs can read it; the CLI reads a key or a client secret at a prompt (ReadSecret), never fromargv, which every local user can read and polkit logs, and passes it to nostrod once, in a message marked sensitive. (Revised 2026-11-01 for nostrod.) - Transactions are a local, append-only cache in Crafter.DB. One table per account, under a storage key the connector chooses (bunq's: environment, user id, account id), ordered by
timePoint; a sync appends what is newer than the last stored row, and at that last timestamp what has anidnot stored yet; queries are answered from the table, never from the bank.Transactionis the on-disk schema: a change to its members bumpsversionand keeps the old struct asPrevious(see the Crafter.DB notes below), and thestatic_asserts onrowSize(120) andfingerprintinNostro-Account.cpp, and those pinning the previous version, are updated in the same commit. - Synchronous HTTPS, one client per bank host.
ClientHTTP1::Sendon the calling thread, a persistent connection for reads and a fresh one for every write, no thread pool, default TLS verification. A bank's own request function owns the protocol: signing, verifying, waiting out rate limits and renewing an expired session once. Every other error is an exception; whether to retry a write is the caller's decision, and an unknown outcome is reported as such. (Revised 2026-10-31: the retries moved from the transaction sync into the request function.) - Signing is opt-in per bank.
:Cryptoand-lssl -lcryptoare pulled in byopensslEnabled, the OR of the banks that sign; a bank that does not sign must not make the build depend on OpenSSL. - The library is the product, the CLI is a thin client.
--libreturns the library configuration; the CLI addsmain.cppalone, which parsesargv, calls nostrod throughClientand prints through the formatters, and nostrod addsnostrod.cppalone. Logic goes into a partition (the daemon's into:Daemon), not intomain.cpp. (Revised 2026-11-01: the CLI talks to nostrod, not to the bank.) - nostrod answers each caller for their own money, and asks polkit first. The front maps a caller's uid, asked of the bus, to that uid's own worker process; nothing of one user's is ever in another's process. Every method has one polkit action, decided by what the call does (
View,Change,Pay,UnfreezeCard,BlockCard,Connectors,Checkout), and the dialog's summary and details are built from the worker's own data after the call is read and checked, never from text the caller formatted: what the dialog shows is what gets paid. Every action is owned byunix-user:nostroin the policy, or polkit refuses nostrod's checks. Every method isSD_BUS_VTABLE_UNPRIVILEGED, since polkit decides, not sd-bus. It fails closed. No action keeps an authorization: polkit keeps one per process, so the CLI would ask every time anyway. - The wire is a published contract.
packaging/dbus/*.xmlis what nostrod serves (ShouldServeEveryUsercompares them with its introspection), and apps in other languages generate their proxies from it. A method may be added; changing a method's signature or meaning means a new interface (…Nostro2). The checkout'soptionsandresultsare dictionaries so that it can grow without one: unknown options are ignored, unknown results skipped.
Adding a bank
The checklist, from the bunq connector:
interfaces/Nostro-<Bank>.cppm:export module Nostro:<Bank>;with everything under#ifdef NOSTRO_<BANK>_ENABLED, defining<Bank>Account : Accountand<Bank>Connectorto design rule 2;implementations/Nostro-<Bank>.cppasmodule Nostro:<Bank>_impl;.interfaces/Nostro.cppm:export import :<Bank>;under the define.interfaces/Nostro-Banks.cppm:import :<Bank>;under the define and the type inEnabledBanks; with two optional entries the comma between them needs a condition of its own, or the tuple does not parse when only one bank is on.project.cpp: the name in the--banks=loop, its define, its implementation unit, andopensslEnabledif it signs. Both configurations get the defines (execfg.defines = libcfg.defines).implementations/main.cpp: theconnectors add <bank> …branch, plus any command for what the bank offers beyond design rule 2, behindif constexpr (requires { … }).README.md: the CLI lines and the supported-banks list.AGENTS.consumer.md: what consumers need to know about the bank.- A fake of the bank in
tests/Support/and tests that run every line of its connector, asFakeBunq.incand the bunq tests do; then try it against the bank's sandbox or live API, and say in the commit how. The README refuses blind connector submissions.
Commit and PR guidelines
- Patches go by mail to jorijnvdgraaf@catcrafts.net, as the README says. Branch off
master. - Take the commit voice from the sibling Crafter repositories:
type(scope): imperative summarywithfeat,fix,refactor,docsorbuild, and the partition or the CLI as the scope (bunq,account,currency,connector,file,bus,client,daemon,checkout,cli,build,packaging). The body says what was wrong, why, and how it was verified against the sandbox. Add aCo-Authored-By:trailer when an agent wrote it. - The README is the manual: keep its CLI section true to
main.cpp. UpdateAGENTS.consumer.mdin the same change when a signature, a path, a default, a file format or an error behaviour consumers lean on changes; consumers pick it up on their next build. - A change to
Transactionis a schema change (design rule 5), and the commit message says so. - A change to the D-Bus interfaces or the polkit policy changes the published contract (design rule 10); the XML, the policy and the test that holds them change together.
- Never commit
bin/,build/,AGENTS.md, or aconnectors.json.
Security considerations
connectors.jsonis the crown jewels: the bunq API key or OAuth token, the installation and session tokens and the unencrypted RSA private key, as plain text. Its protection is0600in a0700directory, and installed, the directory of a system user of its own (/var/lib/nostro) under a service that keeps the rest of the system read-only to it; it is replaced by a synced rename, never rewritten in place. There is no encryption at rest: root, and a disk taken out of the machine, read it. Never print it, never log a token or a signature, never copy a real one into a scratch directory or a commit. The transaction tables are the user's financial history, kept private the same way by Crafter.DB.- What nostrod does not stop: a program running as the user can still draw a dialog that looks like polkit's and ask for the password; only the system's own agent is the real one. On a session without a polkit agent (SSH, a TTY without one) nothing can confirm, so every call that needs a password is
Cancelled. polkit logs the calling process's command line, which is why no secret is ever an argument. - A worker makes itself undumpable, and the service sets
LimitCORE=0: a core dump would hold the keys. A text that reaches a dialog goes throughShown(), so neither a payee's name nor a description can fake another amount or payee in it. - The checkout answers a repeated order with its payment id without a dialog, so any app with access to the checkout can learn whether the user paid an order whose IBAN, reference and amount it knows (README, "Checkout for apps").
- A connector's
environmentdecides betweenapi.bunq.com, wheresendmoves real money, and the sandbox. Sandbox API keys are recognised by theirsandbox_prefix; anything else is production. Only the sandbox has been exercised; test production with small amounts first. - Request bodies are
nlohmann::jsonvalues serialised once (dumpwith invalid UTF-8 replaced), and the signature covers those exact bytes; nothing is spliced into JSON text by hand. Responses are used only after their server signature verifies. - A write is never replayed by the transport (fresh connection) and only resent by nostro after a 429, which bunq refuses before acting. An IBAN's check digits are verified before anything is sent.
- TLS is Crafter.Network's default
TLSClientCredentials{}: the chain against the system store and the hostname. Do not reach forinsecureNoServerValidation. - The private key signs every request body (
SignBody, RSA SHA-256). Key material lives inCrypto::Keys (freed with the last copy) for the process's life; there is no zeroisation. project.cppexecutes theproject.cppof three unpinned dependencies (Crafter.Network, Crafter.DB, Crafter.LintRules) on every build, fetched from the Catcrafts Forgejo at HEAD, and the Flatpak build does the same with the network on. Pin a commit on each for a build that is reproducible and offline after the first fetch.install.sh --repoinstalls from an unsigned local repository, for a build of your own. A published Flatpak comes from the GPG-signed Catcrafts remote;packaging/flatpak/net.catcrafts.Nostro.flatpakrefcarries the same placeholder for the key as Crafter.Build's, for the publishing side to fill in.- Input from the bank is parsed with nlohmann/json's
at()andget(), which throw on a missing key or a wrong type: a malformed response is an exception, not undefined behaviour.ParseAmountandParseTimestampreject anything outside their grammar.
Gotchas
The state of the code on 2026-11-01; each is a fact to work with.
-
crafter-build makes one configuration per run, so nostrod and the checkout library are products chosen with
--product=, as in imsd. The library is one sharedConfiguration*: two configurations exporting the same module in one build are an error. -
systemd's hardening and bubblewrap, which flatpak runs nostrod in, disagree in places, found on 2026-11-01 under
systemd-run --user: bubblewrap needsAF_NETLINK(it brings up loopback),@mount,unshareandsetns, and a/procof its own;RestrictSUIDSGID=makes systemd answeropenat2()with ENOSYS, which bubblewrap 0.13 does not fall back from.nostrod.servicesays which options are left out and why. -
polkit as seen on that day (polkit 127, Plasma): closing Plasma's dialog sends no
polkit.dismissed, onlypolkit.resultauth_self, soCancelledis read from either; a kept authorization is the calling process's alone; the command line of the process asking is logged. -
sd-bus holds a vtable method's answer to the signature the vtable declares: an answer of another shape becomes
System.Error.ENOMSG. A test that must send a malformed answer (FakeCheckoutinShouldServeEveryUser) registers a plain object (sd_bus_add_object) instead. -
A worker or nostrod killed with SIGKILL writes no coverage counts; both handle SIGTERM (systemd's stop signal too) by ending the loop, and the tests stop them that way.
-
--product=checkoutreturns before the bank check, so it needs no--banks=; every other product does. -
GetConfigPath()withXDG_CONFIG_HOMEset returns$XDG_CONFIG_HOME/.config/nostro, not$XDG_CONFIG_HOME/nostro; the cache path has no such insertion. An open bug, kept as is so existing files are still found; the sandbox recipe above accounts for it. -
bunq's spec is not always what the API does. Verified in the sandbox:
- The scheduled payment listing names its objects
ScheduledPayment, notSchedulePayment. - An ended session answers 403 "Insufficient authentication.", unsigned, not 401.
- The OAuth token endpoint ignores a form body: its parameters go in the query string.
UserPersonhas noname; every user type hasdisplay_name.PUT …/card/{id}answers with the card as it is, even when it ignored the status asked for.- Check a listing's object name against a real response before relying on it.
- The scheduled payment listing names its objects
-
The transaction cache moved on 2026-10-31 to
<cache>/transactions/bunq/<environment>/<user id>/<account id>/<name>.cdb. Tables from before sit attransactions/bunq/<name>.cdb, are no longer read, and stay on disk until deleted by hand; a connector re-syncs its history on first use. -
connectors.lockis held for the whole process. Under nostrod that is the user's worker, which lives until it is idle; a program using the library directly on the same directory waits for it, and before nostrod a command waiting at a prompt held up the next one. -
A sandbox virtual card cannot be activated through the API:
cards unfreezereports bunq keeping itDEACTIVATED, which is the real answer, not a bug. -
RespondToDraftPaymentsends the shown draft'supdatedasprevious_updated_timestamp; bunq refuses a response to a draft that changed since it was read.RespondToRequestpays the shown request's amount, not what bunq holds by the time it runs. -
The
std::formatterfor accounts is a constrained partial specialisation (template<std::derived_from<Nostro::Account> T>) because an explicitstd::formatter<Account>does not apply toBunqAccount; every new account type is covered by it. Non-exported formatter specialisations in a partition are found by importers. -
.vscode/tasks.jsonrunscrafter-build build --debug --banks=bunq:buildis not a crafter-build verb, it passes through as a project arg, nostro forwards it to its dependencies, and everything builds into variant directories of its own..vscode/launch.jsonnames a variant directory and abalancecommand that no longer exist. -
connectorIdis astatic constexpr std::string, which compiles only because"bunq"is short enough for libc++'s inline buffer; a long id needs astd::string_view. -
tuple_fortakes a template lambda,[&]<typename Bank>() { … }, and callsfunc.template operator()<Ts>()for each tuple element; a lambda that captures by reference what it mutates is the pattern throughoutmain.cpp.