Nostro/AGENTS.template.md
2026-11-01 18:35:23 +01:00

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 (an enum class : std::uint16_t with Euro alone), GetCurrency (from "EUR" or "eur", throws for anything else), GetCurrencyCode, GetCurrencySymbol, GetCurrencyDecimals, ParseAmount (decimal string to minor units), FormatAmount (back) and FormatMoney (-€1.02), all constexpr, and std::formatter<Currency>, which prints the symbol.
  • :Utils: ParseTimestamp and FormatTimestamp (bunq's YYYY-MM-DD HH:MM:SS[.ffffff], UTC), ParseLocalDate and FormatLocalTime (dates a person types and reads, local time through mktime/localtime), UrlEncode, UrlDecode and QueryParameter (for OAuth), EscB (JSON string escaping, no longer used by nostro itself), and Note with its replaceable noteSink, where every warning of the library goes (stderr by default).
  • :Transaction: the Transaction aggregate, which is also the row type of the Crafter.DB tables: version = 2 (id and kind added on 2026-10-31), orderedBy = &Transaction::timePoint, using Previous = TransactionV1 (unexported, kept for the migration), and its std::formatter (one tab-separated line).
  • :Account: TransactionQuery and Account (name, bic, iban, currency, balance in minor units) with the three methods over the transaction store and the static ForgetTransactions (which closes this process's open tables under a storage key before deleting them), and the std::formatter for Account and everything derived from it. The implementation unit owns the Crafter.DB tables and pins the schema with two static_asserts.
  • :File: GetConfigPath, GetCachePath, the globals configPath and cachePath they initialise at static-init time, CreatePrivateFile (a 0600 file in a 0700 directory), and ReadSecret (a line from stdin, not echoed on a terminal).
  • :Crypto (under NOSTRO_OPENSSL_ENABLED; OpenSSL headers in the global module fragment), in namespace Nostro::Crypto: ThrowOnOpenssl, Key (std::shared_ptr<EVP_PKEY> freeing itself) and OwnKey, SignBody (RSA SHA-256, base64) and VerifyBody (its check against a public key), CreateKey (RSA 2048 and its public PEM), LoadKeyFromPem, LoadPublicKeyFromPem, PrivateKeyToPem, PublicKeyToPem, RandomHex (the OAuth state).
  • :Bunq (under NOSTRO_BUNQ_ENABLED; json.hpp and openssl/types.h in the global module fragment; the implementation units import Crafter.Network): BunqEnvironment, BunqError, BunqCounterparty, the listing types (BunqLabel, BunqPaymentRequest, BunqIncomingRequest, BunqSchedule, BunqScheduledPayment, BunqDraftPayment, BunqCard) and their formatters, BunqAccount : Account (id, type, connector, the payment calls), BunqConnector (environment, keys, tokens, user, accounts, the raw Get/Post/Put/Delete/List, the static deque connectors, Create, Remove, the OAuth helpers, and Endpoint/RedirectTo with BunqEndpoint), to_json/from_json, and the unexported BunqJson helpers both implementation units share.
  • :Banks: tuple_for<Tuple>(f) and EnabledBanks, the std::tuple of enabled connector types; every generic loop in the CLI and in :Connector is a tuple_for<EnabledBanks>.
  • :Connector: Connector::SaveConnectors() and LoadConnectors(), connectors.json out (synced, then renamed into place) and in, both under the process-wide connectors.lock.
  • :Bus (under NOSTRO_DBUS_ENABLED; sd-bus.h in the global module fragment): the wire nostrod and its clients share. The names, the error names (the checkout's from Nostro.Checkout), the polkit actions, the method tables methods and checkoutMethods (member, signatures, argument names, sensitive), the result structs (ConnectorSummary, AddedConnector, ConnectorAccounts, ConnectorCards, Created), Wire<T> with Append and Read for every type that travels (a struct as its members, a time as microseconds, a currency as its code, an optional as an array of zero or one), AppendQuery/ReadQuery, Vtable, ThrowOnSdBus, and the BusPtr/MessagePtr/Error owners.
  • :Client: Client::System(), one method per method of net.catcrafts.Nostro1, TakeNotes(), and DaemonError.
  • :Daemon: DaemonOptions, RunDaemon (the front) and RunWorker (one user's worker).

Nostro.Checkout, a module of its own that imports nothing of Nostro: the checkout's bus name, interface, Pay's signatures and argument names, the error names apps tell apart, Order, Paid, Error with Cancelled and NoCheckoutAccount, and Pay. :Bus and the daemon take their names from it.

The bunq connector end to end:

  • Requests (implementations/Nostro-Bunq.cpp): every call goes through the private BunqConnector::Call, behind the public Get, Post, Put, Delete and List. It talks to BunqConnector::Endpoint(environment): api.bunq.com or public-api.sandbox.bunq.com by the connector's environment, or wherever RedirectTo sent everything (the tests' fake), with one ClientHTTP1 per endpoint.
    • It signs every body except the installation's.
    • It refuses a 2xx whose x-bunq-server-signature does not verify against serverPublicKey, which an old connector fetches first (EnsureServerPublicKey).
    • It waits out a 429, and renews the session once on a 401 or a 403 "Insufficient authentication.", then saves.
    • It sends a POST, PUT or DELETE over a fresh connection, because ClientHTTP1 replays a request on a reused connection that fails before any answer, even after a read timeout. A write whose outcome is unknown says it may have been carried out.
    • Every other error is a BunqError with bunq's error_description.
  • Connecting: Create(apiKey, allowedIps, environment) makes an RSA key, then POST /installation (installation token and server key), POST /device-server with permitted_ips as a JSON array, and RefreshSession(). The session is POST /session-server, signed: the token, the session id, and the user from UserPerson, UserCompany, UserPaymentServiceProvider or, for OAuth, UserApiKey (its own id in paths, ownerId and the name from granted_by_user).
  • Accounts and history: RefreshAccounts() lists every MonetaryAccount… type that is ACTIVE or BLOCKED. GetNewTransactions(account) pages the payments newest first until one older than the last stored row, and hands them to Account::SaveTransactions under account.StorageKey().
  • Payments (implementations/Nostro-Bunq-Payments.cpp): BunqCounterparty::Parse reads an IBAN (check digits verified), an e-mail address or a phone number. Send, Draft, Schedule and Request build their bodies from it, the listings read bunq's objects into the listing types, and the responses are PUTs or a DELETE. Accepting a request or a draft takes the object as it was read and shown (IncomingRequest(id), DraftPayment(id)), so what gets paid is what the user saw.
  • OAuth: OAuthAuthorizationUrl and OAuthExchangeCode (the token endpoint reads query parameters only). The token then goes to Create like an API key.

nostrod end to end:

  • The front (implementations/Nostro-Daemon.cpp, RunDaemon) is one sd-event loop with two system bus connections. One owns net.catcrafts.Nostro1 and serves that interface. The other owns net.catcrafts.Nostro1.Checkout and serves the checkout alone: a Flatpak allowed to talk to that name can call its owner's unique name too, and on that connection there is nothing else. Every method of both is one forwarding handler. It asks the bus for the caller's uid (GetConnectionCredentials), and logind for that uid's name, starts the uid's worker if there is none (posix_spawn of /proc/self/exe --worker <uid> <name> …, a socketpair end as fd 3, D-Bus peer to peer over it), and passes a copy of the call on, from the caller's unique name and allowing a dialog only when the caller did. The answer is relayed when it comes, so one user's open dialog holds up nobody. A worker that dies under a call is answered Failed with "may have been carried out". It holds no connector and no secret. It ends once idle with no worker left, on SIGTERM, or when the bus goes; D-Bus activation starts it again.
  • A worker (implementations/Nostro-Daemon-Worker.cpp, RunWorker) is one user's library: configPath and cachePath are <state>/users/<uid>, the connectors are read on the first call, and it is not dumpable. A directory records whose it is (owner): a uid that logind now names differently, after a user was deleted and another given their uid, is refused. Every handler reads and checks the call first (the account, the counterparty, what is to be paid, or for a request or a draft the object as bunq has it), builds a Prompt (the polkit action, a summary from its own data, and details for polkit rules), and hands it to Gate. Gate asks polkit asynchronously (CheckAuthorization about the caller's bus name, cancelled if it does not answer in time) and runs the call's work only once polkit says yes. It fails closed: no polkit, an error or a timeout is AccessDenied. A dialog the user closed is Cancelled, which polkit says with polkit.dismissed or, from Plasma's agent, polkit.result auth_…. A challenge to a call that allowed no dialog is InteractiveAuthorizationRequired. Every answer of the main interface ends with the notes. A summary's text from a caller or the bank goes through Shown() (no control, invisible or direction characters, < and > replaced, $( broken, 64 characters at most) and names the address before the name. The worker ends once idle with no dialog open, on SIGTERM, or when the front goes.
  • Checkout (the same file): Order::Read refuses a payee that is not an IBAN, an amount that is not positive, an unknown currency or an empty reference. An order already in checkouts.cdb (a Crafter.DB table, CheckoutRecord) is answered with its payment, repeated, without a dialog, or refused when its amount differs, or when its payment is still 0: a payment whose outcome was lost. An order being paid makes the next call for it wait, and Settle gives it the first call's answer. ChooseAccount picks the account (the one in checkout-account, set by SetDefaultCheckoutAccount; an account of an OAuth connector is refused there) and answers through a continuation, so an account picker can take its place later. The dialog (net.catcrafts.Nostro1.Checkout) shows the order and that account. PayOrder records the order, with no payment, before it pays, and takes the record away again only when bunq refused before doing anything, below 500.
  • The client (implementations/Nostro-Client.cpp) allows interactive authorization and waits 10 minutes by default; nostrod's InvalidArgument becomes std::invalid_argument, ServiceUnknown a "not running" message, a write without an answer "may have been carried out", and the rest a DaemonError with its name. Nostro.Checkout's Pay does the same for the checkout with its own types.

Dev environment

crafter-build is the only build tool. It compiles with its clang 23 and libc++, -std=c++26 and import std;, and links -lssl -lcrypto, and -lsystemd for anything with D-Bus in it (libsystemd's sd-bus.h and sd-event.h; crafter-build's Flatpak SDK has them). Packaging uses flatpak-builder.

  • Every build needs the network: Crafter.Network (with Crafter.Thread behind it; nostro builds it --no-quic, so without msquic) and Crafter.DB are GitProjects on their default branches, and Crafter.LintRules a #pragma crafter dependency of project.cpp, so each build git pulls them from forgejo.catcrafts.net, and the notes at the end of this file follow their HEAD. A .commit (in the pragma, commit "<sha>") would pin them.
  • Where the connectors live depends on who runs the library. nostrod's worker keeps each user's under <state>/users/<uid>/: connectors.json, the transaction tables, checkouts.cdb, checkout-account and owner, with <state> from --state, else $XDG_DATA_HOME, else $HOME/.local/share. Installed, that is /var/lib/nostro/.var/app/net.catcrafts.Nostro/data/, readable by the user nostro alone. The library used directly reads connectors.json from $XDG_CONFIG_HOME/.config/nostro/ (sic, see "Gotchas") or $HOME/.config/nostro/, and keeps the transaction tables under $XDG_CACHE_HOME/nostro/transactions/ or $HOME/.cache/nostro/transactions/. A real connectors file holds a real API key: point every experiment elsewhere.
  • No test uses the system bus: they run on tests/Support/FakeBus.inc. Running anything by hand that talks to net.catcrafts.Nostro1 reaches the installed nostrod, if there is one, and its dialogs. A Flatpak sandbox with the system bus (flatpak run, flatpak build) sets DBUS_SYSTEM_BUS_ADDRESS itself, over an --env of yours: keep a sandboxed experiment off the bus with --nosocket=system-bus.
  • To read a constexpr value such as DB::Layout<Transaction>::fingerprint, static_assert(x == 0) it and read "expression evaluates to" in the error.

Build, test and style commands

crafter-build --banks=bunq            # the library, then the CLI: bin/nostro-<variant>/nostro
crafter-build --banks=bunq --product=daemon   # nostrod: bin/nostrod-<variant>/nostrod
crafter-build --product=checkout      # the Nostro.Checkout library alone; no bank needed
crafter-build --banks=bunq --lib      # the library alone (what a consumer builds), without D-Bus
crafter-build --banks=bunq --lib --dbus   # the library with :Bus, :Client and :Daemon
crafter-build --debug --banks=bunq    # debug build
crafter-build -v --banks=bunq         # with the compiler commands
crafter-build clean                   # delete bin/ and build/
crafter-build test --banks=bunq       # the tests in tests/, against a fake bunq; none talks to bunq itself
tests/coverage.sh [profile runtime]   # the tests with coverage: a report per file and every line no test ran
crafter-build lint --banks=bunq       # the Crafter.LintRules lite rules project.cpp registers, report only
flatpak run --filesystem=<dir> org.flatpak.Builder --user --force-clean --repo=<dir>/repo --state-dir=<dir>/state <dir>/build packaging/flatpak/net.catcrafts.Nostro.yaml

--banks= is mandatory except for --product=checkout: without it project.cpp throws "must enable atleast one bank" and nothing is built; an unknown name throws "unknown connector", an unknown product "unknown product". flatpak-builder needs crafter-build's own Flatpak (net.catcrafts.CrafterBuild, stable) installed as its base app, the network during the build, and, run as a Flatpak itself, --filesystem= for a build directory outside your home, or the build commands cannot find it. Install the result for a test with sudo packaging/system/install.sh --repo <dir>/repo. There is no CI. The tests run every line, function and region of nostro's own sources (2026-11-01), and a change keeps them doing so; the README's rule for contributed connectors applies on top: not blind, also tried against the sandbox or the live API ("Testing instructions").

Testing instructions

crafter-build test --banks=bunq builds and runs tests/<Name>/main.cpp for each name in project.cpp's list, each linked against the library, in parallel; a test exits 0 when every check passed and prints each failed one with its line. They are:

Test What it covers
ShouldHandleMoneyAndText :Currency and :Utils: every parse with what it refuses, every format, local dates in a fixed time zone
ShouldSignAndVerify :Crypto: keys, PEM, signatures and each way one fails to verify
ShouldStoreTransactions :Account: what a sync stores and drops, the queries, a version 1 table migrating
ShouldKeepFilesPrivate :File: the paths, private files and their failures, ReadSecret from a pipe and from a pseudo-terminal
ShouldSaveConnectors :Connector: loading, the synced save, and every way the lock and the save fail
ShouldTalkToBunq the connector: every user type, signatures, rate limits, session renewal, errors, accounts, the sync, cards, OAuth, old connectors
ShouldMoveMoney payments, drafts, schedules and requests, and their formatters
ShouldRunCommands the CLI: implementations/main.cpp compiled in with its main renamed, every command run in-process against a real nostrod on the fake bus
ShouldServeEveryUser nostrod: users kept apart, a uid handed to a new user, every polkit answer and what each dialog says, calls that wait on each other or do not, the checkout and its retries, the checkout client, workers that die, idle exits, every error as the client gets it, and the published contract (the XML and the polkit policy)

How they are built:

  • tests/Support/Check.inc holds the checks (Check, Equal, Throws) and a temporary Directory; tests/Support/FakeBunq.inc is a bunq in the test's own process, HTTPS on 127.0.0.1 with Crafter.Network's self-signed certificate. It signs what it answers, checks the client's signatures, keeps users, accounts, payments, requests, schedules, drafts and cards, and fails on request (Fake::Fault). BunqConnector::RedirectTo points nostro at it; each test has a port of its own (47301 to 47305), and port 443 on 127.0.0.1 stands for a host that refuses the connection.
  • tests/Support/FakeBus.inc is a system bus in the test's own process, an sd-bus server on a unix socket: it routes calls by name with the caller's unique name, and plays the bus driver (GetConnectionCredentials with the uid the test chose for a connection of its own process, the real one for nostrod's), logind (GetUser and the user's Name) and polkit (each check recorded; allow, a password, deny, a closed dialog, absent, silent or slow, per action). The two nostrod tests start their own executable again as nostrod (Fake::StartNostrod, with NOSTRO_TEST_ROLE set; its main then runs implementations/nostrod.cpp's, compiled in with main renamed), which finds the fake bunq through the environment (Fake::Bunq::ExportRedirect, RedirectFromEnvironment). Everything a child reads from the environment is set before any thread starts. A worker that cannot be spawned is made with prlimit on nostrod (Fake::Limit), and workers are stopped with SIGTERM, which they handle, so their coverage counts are written.
  • What a disk or a kernel will not do on demand (flock failing or interrupted, fsync failing, a chosen OAuth state from RAND_bytes) the test defines itself as an extern "C" function: the linker takes it over libc's or OpenSSL's, and it calls the real one through dlsym(RTLD_NEXT, …) when nothing is scripted. A file size limit (RLIMIT_FSIZE) makes a write fail part way.
  • Each test sets configPath and cachePath to a temporary directory first, and TZ where it formats local time.

Coverage is clang's source-based coverage: tests/coverage.sh builds with --coverage, runs the tests with LLVM_PROFILE_FILE set (with %p, so nostrod and every worker write their own), merges the profiles and reports with llvm-cov, leaving build/coverage/sources.txt annotated. A toolchain without compiler-rt's profile library, which crafter-build's Flatpak lacks, takes one as the script's argument (--profile-runtime= to project.cpp). On 2026-11-01 lines, functions and regions were all at 100% and branches at 95%: what is left is mostly defensive checks no input can flip and per-instantiation counts in main.cpp's templates.

The bunq sandbox is still the check for what a fake cannot show. Since nostrod (2026-11-01) the CLI needs an installed nostrod: build the Flatpak, install it with sudo packaging/system/install.sh --repo <dir>/repo, and use the CLI as yourself; real polkit dialogs then ask for your password. A second local user shows the separation. The library alone still runs from an isolated config and cache, never from ~/.config/nostro. The recipe, as it worked on 2026-10-31 with the CLI of then, which held the connectors itself:

  1. Build (in place or in a scratch copy made with rsync -a --exclude build/ --exclude bin/ --exclude .git/) and run the binary with XDG_CONFIG_HOME and XDG_CACHE_HOME pointing into a scratch directory. No connectors.json needs seeding.
  2. Throwaway users: POST https://public-api.sandbox.bunq.com/v1/sandbox-user-person (or -company) with no authentication returns Response[0].ApiKey.api_key; nostro connectors add bunq, given the key on stdin, recognises the sandbox by its prefix. The response also holds the user's e-mail and phone aliases, for paying by those. Make two, so there is someone to pay; sandbox accounts are all called "Bank Account", so name them by IBAN.
  3. The CLI reaches every bunq call (nostro help lists them). Session renewal is tried by ending the session behind nostro's back (DELETE /v1/session/0 with the stored sessionToken), signature checking by putting another public key in serverPublicKey.
  4. A new sandbox account holds €0 and no payments. Fund it with nostro request <iban> sugardaddy@bunq.com "Sugar Daddy" 50000: it is paid within seconds. A hundred rows at once: POST …/payment-batch with {"payments": […]} (more than 200 exercises the paging). curl can call as the same user with the sessionToken from the scratch file, and sign with openssl dgst -sha256 -sign over the body using its privateKey PEM, base64, in X-Bunq-Client-Signature. A sandbox virtual card (POST /v1/user/{id}/card-debit with order_status: VIRTUAL_DELIVERY) cannot be activated through the API, so cards unfreeze can only show bunq keeping it DEACTIVATED. OAuth stops at the token exchange: approving needs a person and the bunq app.
  5. bunq allows 3 GETs, 5 POSTs and 2 PUTs per three seconds per endpoint and one session per 30 seconds; nostro waits a 429 out, so a burst of runs is slow rather than failing. Concurrent nostro processes queue on connectors.lock, so two never hold the same account's table.

A bug fix comes with a test that fails without it, and states in its commit how it was reproduced; a new bank comes with tests against a fake of it and with the same check against its sandbox or live API.

Code style

  • crafter-build lint --banks=bunq reports nothing. A finding at a C boundary (main's argv, a char* an OpenSSL or POSIX call hands out) is suppressed with // lint-disable-next-line <rule> and a comment saying why; anything else is fixed. The rules that need an AST cannot parse a file that #includes a standard header before import std; (the nine that include json.hpp: four in the library, five tests), so lint exits 1 for those alone until Crafter.Build issue #46 is fixed: check them by hand, and prefer C headers (<errno.h>, not <cerrno>) elsewhere. Tests are linted like the rest.
  • The first two lines of every source are // SPDX-License-Identifier: LGPL-3.0-only and // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®, then a blank line. project.cpp carries them too.
  • Four-space indentation, LF, K&R braces with } else {, one declaration per statement. if(, for(, while(, switch( without a space in most files (:Utils has the space; match the file). Lines run long rather than wrap.
  • import std; everywhere; #includes only in a global module fragment (module; first), and only for OpenSSL, the vendored json.hpp, sd-bus and sd-event, and the POSIX calls of :File, :Connector and nostrod. namespace fs = std::filesystem; where paths appear.
  • Interfaces are export module Nostro:<P>; with export namespace Nostro { … } when the partition is free functions (:Currency, :Utils, :File, :Crypto) and namespace Nostro { export struct … } when it is types. A std::formatter specialisation sits after the namespace, unexported, which importers still find. Implementation units are module Nostro:<P>_impl; followed by import :<P>;. Nostro.Checkout is a module of its own (export module Nostro.Checkout;, implemented in module Nostro.Checkout;) because a shop app links it without the rest.
  • An sd-bus callback returns 0 or more and never throws: a negative result closes the connection it came on, and an exception would unwind through C. Every worker handler catches everything (Handle) and answers with an error instead.
  • PascalCase for types, functions and member functions; camelCase for variables, members and constants (sessionToken, connectorId, configPath); enum class only; fixed-width integers (std::int64_t for money, std::uint64_t for bunq ids, std::uint16_t under Currency). tuple_for, to_json and from_json are the snake_case exceptions, the last two because nlohmann/json looks them up by that name.
  • Parameters are std::string_view, or std::string&& where the callee stores them (the account constructors, Create). std::format and std::println for all text; iostreams only for connectors.json.
  • Errors are exceptions with a std::formatted message that names the thing: std::runtime_error ("malformed amount '{}'"), BunqError with the HTTP status for a bunq error response ("bunq {} {}: {} ({})", method, path, description, status), std::invalid_argument for input refused before anything is sent. Every OpenSSL return goes through ThrowOnOpenssl, which prints OpenSSL's error stack to stderr first. No error codes, no std::expected.
  • Comments say why, and are kept: the table cache in Nostro-Account.cpp, the schema warning on Transaction, the opensslEnabled line in project.cpp. New non-obvious code gets the same.

Design rules

  1. Banks are chosen at build time. --banks= lists them, each gets a NOSTRO_<BANK>_ENABLED define, its partition and implementation unit exist only under it, and EnabledBanks is the std::tuple of what is in. Generic code is tuple_for<EnabledBanks> over duck-typed connector types; there is no virtual base, no registry, no runtime plug-in. A binary knows exactly the banks it was built with.
  2. A connector is a struct with a known shape. static constexpr std::string connectorId, static std::deque<Self> connectors (a deque, so an account's connector pointer survives the next Create), using Account = <Bank>Account, std::vector<Account> accounts, name, TestConnector(), RefreshAccounts(), GetNewTransactions() and GetNewTransactions(account), Logout(), StorageKey(), static Create(…) and Remove(connector), to_json/from_json for connectors.json, and a std::formatter that prints its name; its account derives from Account and has StorageKey() and Send(to, name, amount, currency, description). main.cpp and :Connector compile against that shape; anything a bank offers beyond it (bunq's requests, schedules, drafts and cards) the CLI reaches through if constexpr (requires { … }). (Revised 2026-10-31 for the MVP connector: the deque, Logout, Remove and the storage keys.)
  3. Money is an integer. Amounts and balances are std::int64_t in the currency's minor unit, outgoing negative, with the Currency beside them; decimal strings exist only at the API boundary and go through ParseAmount and FormatAmount. No floating point anywhere near an amount.
  4. Secrets live in one private file, out of the user's reach. connectors.json holds the API key or OAuth token, both tokens and the RSA private key, 0600 under a 0700 directory made by CreatePrivateFile; nothing prints them, nothing else persists them. Installed, the file is nostrod's, under the state directory of the system user nostro, so no program the user runs can read it; the CLI reads a key or a client secret at a prompt (ReadSecret), never from argv, which every local user can read and polkit logs, and passes it to nostrod once, in a message marked sensitive. (Revised 2026-11-01 for nostrod.)
  5. Transactions are a local, append-only cache in Crafter.DB. One table per account, under a storage key the connector chooses (bunq's: environment, user id, account id), ordered by timePoint; a sync appends what is newer than the last stored row, and at that last timestamp what has an id not stored yet; queries are answered from the table, never from the bank. Transaction is the on-disk schema: a change to its members bumps version and keeps the old struct as Previous (see the Crafter.DB notes below), and the static_asserts on rowSize (120) and fingerprint in Nostro-Account.cpp, and those pinning the previous version, are updated in the same commit.
  6. Synchronous HTTPS, one client per bank host. ClientHTTP1::Send on the calling thread, a persistent connection for reads and a fresh one for every write, no thread pool, default TLS verification. A bank's own request function owns the protocol: signing, verifying, waiting out rate limits and renewing an expired session once. Every other error is an exception; whether to retry a write is the caller's decision, and an unknown outcome is reported as such. (Revised 2026-10-31: the retries moved from the transaction sync into the request function.)
  7. Signing is opt-in per bank. :Crypto and -lssl -lcrypto are pulled in by opensslEnabled, the OR of the banks that sign; a bank that does not sign must not make the build depend on OpenSSL.
  8. The library is the product, the CLI is a thin client. --lib returns the library configuration; the CLI adds main.cpp alone, which parses argv, calls nostrod through Client and prints through the formatters, and nostrod adds nostrod.cpp alone. Logic goes into a partition (the daemon's into :Daemon), not into main.cpp. (Revised 2026-11-01: the CLI talks to nostrod, not to the bank.)
  9. nostrod answers each caller for their own money, and asks polkit first. The front maps a caller's uid, asked of the bus, to that uid's own worker process; nothing of one user's is ever in another's process. Every method has one polkit action, decided by what the call does (View, Change, Pay, UnfreezeCard, BlockCard, Connectors, Checkout), and the dialog's summary and details are built from the worker's own data after the call is read and checked, never from text the caller formatted: what the dialog shows is what gets paid. Every action is owned by unix-user:nostro in the policy, or polkit refuses nostrod's checks. Every method is SD_BUS_VTABLE_UNPRIVILEGED, since polkit decides, not sd-bus. It fails closed. No action keeps an authorization: polkit keeps one per process, so the CLI would ask every time anyway.
  10. The wire is a published contract. packaging/dbus/*.xml is what nostrod serves (ShouldServeEveryUser compares them with its introspection), and apps in other languages generate their proxies from it. A method may be added; changing a method's signature or meaning means a new interface (…Nostro2). The checkout's options and results are dictionaries so that it can grow without one: unknown options are ignored, unknown results skipped.

Adding a bank

The checklist, from the bunq connector:

  1. interfaces/Nostro-<Bank>.cppm: export module Nostro:<Bank>; with everything under #ifdef NOSTRO_<BANK>_ENABLED, defining <Bank>Account : Account and <Bank>Connector to design rule 2; implementations/Nostro-<Bank>.cpp as module Nostro:<Bank>_impl;.
  2. interfaces/Nostro.cppm: export import :<Bank>; under the define. interfaces/Nostro-Banks.cppm: import :<Bank>; under the define and the type in EnabledBanks; with two optional entries the comma between them needs a condition of its own, or the tuple does not parse when only one bank is on.
  3. project.cpp: the name in the --banks= loop, its define, its implementation unit, and opensslEnabled if it signs. Both configurations get the defines (execfg.defines = libcfg.defines).
  4. implementations/main.cpp: the connectors add <bank> … branch, plus any command for what the bank offers beyond design rule 2, behind if constexpr (requires { … }). README.md: the CLI lines and the supported-banks list. AGENTS.consumer.md: what consumers need to know about the bank.
  5. A fake of the bank in tests/Support/ and tests that run every line of its connector, as FakeBunq.inc and the bunq tests do; then try it against the bank's sandbox or live API, and say in the commit how. The README refuses blind connector submissions.

Commit and PR guidelines

  • Patches go by mail to jorijnvdgraaf@catcrafts.net, as the README says. Branch off master.
  • Take the commit voice from the sibling Crafter repositories: type(scope): imperative summary with feat, fix, refactor, docs or build, and the partition or the CLI as the scope (bunq, account, currency, connector, file, bus, client, daemon, checkout, cli, build, packaging). The body says what was wrong, why, and how it was verified against the sandbox. Add a Co-Authored-By: trailer when an agent wrote it.
  • The README is the manual: keep its CLI section true to main.cpp. Update AGENTS.consumer.md in the same change when a signature, a path, a default, a file format or an error behaviour consumers lean on changes; consumers pick it up on their next build.
  • A change to Transaction is a schema change (design rule 5), and the commit message says so.
  • A change to the D-Bus interfaces or the polkit policy changes the published contract (design rule 10); the XML, the policy and the test that holds them change together.
  • Never commit bin/, build/, AGENTS.md, or a connectors.json.

Security considerations

  • connectors.json is the crown jewels: the bunq API key or OAuth token, the installation and session tokens and the unencrypted RSA private key, as plain text. Its protection is 0600 in a 0700 directory, and installed, the directory of a system user of its own (/var/lib/nostro) under a service that keeps the rest of the system read-only to it; it is replaced by a synced rename, never rewritten in place. There is no encryption at rest: root, and a disk taken out of the machine, read it. Never print it, never log a token or a signature, never copy a real one into a scratch directory or a commit. The transaction tables are the user's financial history, kept private the same way by Crafter.DB.
  • What nostrod does not stop: a program running as the user can still draw a dialog that looks like polkit's and ask for the password; only the system's own agent is the real one. On a session without a polkit agent (SSH, a TTY without one) nothing can confirm, so every call that needs a password is Cancelled. polkit logs the calling process's command line, which is why no secret is ever an argument.
  • A worker makes itself undumpable, and the service sets LimitCORE=0: a core dump would hold the keys. A text that reaches a dialog goes through Shown(), so neither a payee's name nor a description can fake another amount or payee in it.
  • The checkout answers a repeated order with its payment id without a dialog, so any app with access to the checkout can learn whether the user paid an order whose IBAN, reference and amount it knows (README, "Checkout for apps").
  • A connector's environment decides between api.bunq.com, where send moves real money, and the sandbox. Sandbox API keys are recognised by their sandbox_ prefix; anything else is production. Only the sandbox has been exercised; test production with small amounts first.
  • Request bodies are nlohmann::json values serialised once (dump with invalid UTF-8 replaced), and the signature covers those exact bytes; nothing is spliced into JSON text by hand. Responses are used only after their server signature verifies.
  • A write is never replayed by the transport (fresh connection) and only resent by nostro after a 429, which bunq refuses before acting. An IBAN's check digits are verified before anything is sent.
  • TLS is Crafter.Network's default TLSClientCredentials{}: the chain against the system store and the hostname. Do not reach for insecureNoServerValidation.
  • The private key signs every request body (SignBody, RSA SHA-256). Key material lives in Crypto::Keys (freed with the last copy) for the process's life; there is no zeroisation.
  • project.cpp executes the project.cpp of three unpinned dependencies (Crafter.Network, Crafter.DB, Crafter.LintRules) on every build, fetched from the Catcrafts Forgejo at HEAD, and the Flatpak build does the same with the network on. Pin a commit on each for a build that is reproducible and offline after the first fetch.
  • install.sh --repo installs from an unsigned local repository, for a build of your own. A published Flatpak comes from the GPG-signed Catcrafts remote; packaging/flatpak/net.catcrafts.Nostro.flatpakref carries the same placeholder for the key as Crafter.Build's, for the publishing side to fill in.
  • Input from the bank is parsed with nlohmann/json's at() and get(), which throw on a missing key or a wrong type: a malformed response is an exception, not undefined behaviour. ParseAmount and ParseTimestamp reject anything outside their grammar.

Gotchas

The state of the code on 2026-11-01; each is a fact to work with.

  • crafter-build makes one configuration per run, so nostrod and the checkout library are products chosen with --product=, as in imsd. The library is one shared Configuration*: two configurations exporting the same module in one build are an error.

  • systemd's hardening and bubblewrap, which flatpak runs nostrod in, disagree in places, found on 2026-11-01 under systemd-run --user: bubblewrap needs AF_NETLINK (it brings up loopback), @mount, unshare and setns, and a /proc of its own; RestrictSUIDSGID= makes systemd answer openat2() with ENOSYS, which bubblewrap 0.13 does not fall back from. nostrod.service says which options are left out and why.

  • polkit as seen on that day (polkit 127, Plasma): closing Plasma's dialog sends no polkit.dismissed, only polkit.result auth_self, so Cancelled is read from either; a kept authorization is the calling process's alone; the command line of the process asking is logged.

  • sd-bus holds a vtable method's answer to the signature the vtable declares: an answer of another shape becomes System.Error.ENOMSG. A test that must send a malformed answer (FakeCheckout in ShouldServeEveryUser) registers a plain object (sd_bus_add_object) instead.

  • A worker or nostrod killed with SIGKILL writes no coverage counts; both handle SIGTERM (systemd's stop signal too) by ending the loop, and the tests stop them that way.

  • --product=checkout returns before the bank check, so it needs no --banks=; every other product does.

  • GetConfigPath() with XDG_CONFIG_HOME set returns $XDG_CONFIG_HOME/.config/nostro, not $XDG_CONFIG_HOME/nostro; the cache path has no such insertion. An open bug, kept as is so existing files are still found; the sandbox recipe above accounts for it.

  • bunq's spec is not always what the API does. Verified in the sandbox:

    • The scheduled payment listing names its objects ScheduledPayment, not SchedulePayment.
    • An ended session answers 403 "Insufficient authentication.", unsigned, not 401.
    • The OAuth token endpoint ignores a form body: its parameters go in the query string.
    • UserPerson has no name; every user type has display_name.
    • PUT …/card/{id} answers with the card as it is, even when it ignored the status asked for.
    • Check a listing's object name against a real response before relying on it.
  • The transaction cache moved on 2026-10-31 to <cache>/transactions/bunq/<environment>/<user id>/<account id>/<name>.cdb. Tables from before sit at transactions/bunq/<name>.cdb, are no longer read, and stay on disk until deleted by hand; a connector re-syncs its history on first use.

  • connectors.lock is held for the whole process. Under nostrod that is the user's worker, which lives until it is idle; a program using the library directly on the same directory waits for it, and before nostrod a command waiting at a prompt held up the next one.

  • A sandbox virtual card cannot be activated through the API: cards unfreeze reports bunq keeping it DEACTIVATED, which is the real answer, not a bug.

  • RespondToDraftPayment sends the shown draft's updated as previous_updated_timestamp; bunq refuses a response to a draft that changed since it was read. RespondToRequest pays the shown request's amount, not what bunq holds by the time it runs.

  • The std::formatter for accounts is a constrained partial specialisation (template<std::derived_from<Nostro::Account> T>) because an explicit std::formatter<Account> does not apply to BunqAccount; every new account type is covered by it. Non-exported formatter specialisations in a partition are found by importers.

  • .vscode/tasks.json runs crafter-build build --debug --banks=bunq: build is not a crafter-build verb, it passes through as a project arg, nostro forwards it to its dependencies, and everything builds into variant directories of its own. .vscode/launch.json names a variant directory and a balance command that no longer exist.

  • connectorId is a static constexpr std::string, which compiles only because "bunq" is short enough for libc++'s inline buffer; a long id needs a std::string_view.

  • tuple_for takes a template lambda, [&]<typename Bank>() { … }, and calls func.template operator()<Ts>() for each tuple element; a lambda that captures by reference what it mutates is the pattern throughout main.cpp.