bank: Nostro reads the bank's callback, and the shop's bunq code is gone
All checks were successful
Deploy / build-deploy (push) Successful in 7m20s

The shadow run of 36a635f had Nostro's ReadCallback read a real
callback beside our own parser on 2026-11-25, for order CC-BCD155: the
same id, amount and reference, on the shop's own account. So the reader
takes over, and what this repo carried of bunq goes: the callback
parser, the payment-type table, the API client with its RSA signing,
`--pull-credits`, the mode that read the bank from the server with an
API key, and tools/register-bunq-webhook.sh.

The server now knows no bank. Catcrafts.Server-BankCallback.cpp is the
one unit that imports Nostro.Money: ReadBankCallback has a body read
and says what it comes to, CreditMethodFor says how a payment arrived.
Which bank it is is configuration: --banks= in project.cpp for what the
build can read, BANK_CALLBACK_BANK on the server for what arrives.

What changes for a running shop:

- The endpoint is configured with BANK_CALLBACK_PATH and
  BANK_CALLBACK_BANK; BUNQ_WEBHOOK_PATH is no longer read. Without the
  bank's name, or without TRANSFER_IBAN, the endpoint stays off and the
  startup log says so: one that answered 200 and credited nothing would
  look like working. Production's payments.env got both names before
  this was pushed.
- Only a payment on TRANSFER_IBAN is credited. A bank posts to whatever
  address any of its customers registered, so a callback about someone
  else's account can be the bank's own. Until now a payment in a
  callback was credited whichever account it was on.
- `via` says `internal` for a payment from another account at the bank
  itself, where it said `bunq`, and `card` where it would have said
  `MASTERCARD`. A kind without a word is still passed on as the bank
  wrote it, now only where that is a plain word.
- Every callback leaves one line in the log, `bank callback: credited
  ...` or `bank callback: nothing credited: <why>`, with nothing of the
  body in it beyond the credit.
- A line of the credits file may carry the bank's kind and the bank
  (`"bank":"bunq","kind":"EBA_SCT/SCT"`) in place of `method`, put into
  the ledger's words when the file is read. The pull script ships those
  and takes the bank's name from nostrod, so it holds no table of a
  bank's words either.

Also gone, with their last user: ParseAmountToMinor, PullCreditsInto
and the explicit -lcrypto (Crafter.Network names what it needs).

ShouldReadBankCallbacks replaces ShouldParseBunqPayments and
ShouldCompareCallbackReaders: what a callback comes to for each shape,
each method, the account and the sign, and that no note repeats
anything a body carried. ShouldReceiveBankCallbacks posts to the real
endpoint: an order settles from a callback, one from another account
quoting the same order does not pay for it, and a server without the
bank's name has no endpoint.

Built from scratch and run in a copy of this tree with crafter-build
6.4.1: the server and the wasm bundle build, and every suite passes but
ShouldServePostPages, which fails there for want of mirrored post media
and passed in CI on the commit before this. A dry run of the pull
script against nostrod gave 19 credits with their kinds.

Not tried: a real callback through the new handler, and `nostro
callbacks` against the registration that is in place, which was made
with the script this removes. deploy/README.md has the new setup.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Jorijn van der Graaf 2026-11-25 15:08:42 +01:00
commit 33ce8f45d8
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
24 changed files with 1218 additions and 2385 deletions

View file

@ -0,0 +1,206 @@
/*
catcrafts.net
Copyright (C) 2026 Catcrafts
The source code of this website is made available for viewing purposes only.
No permission is granted to copy, modify, distribute, or create derivative works.
*/
// Reading what the bank posts to the callback endpoint, and saying how a
// payment arrived. This is the ONE unit that knows a bank library exists: it
// imports Nostro.Money (https://forgejo.catcrafts.net/Catcrafts/Nostro), the
// part of Nostro that holds no credential, and turns what that reads into this
// shop's own terms before anything leaves the file. No line here, or anywhere
// else in the server, knows how a bank writes a callback or what it calls a
// kind of payment: which bank is a word of configuration, handed through.
//
// History worth keeping: until 2026-11-25 the shop carried its own reader of
// bunq's callbacks and its own table of bunq's payment types. Nostro's reader
// ran beside it as a shadow on a real payment first, agreed, and took over.
//
// Two rules the code below is written to:
//
// * NOTHING OF THE BODY IS SAID BACK. A body holds the payer's name and
// IBAN, and may repeat the address it was posted to, which is the
// endpoint's only secret. So a note is made of fixed words, of the
// reader's own sentence for a refusal, and of a bank's word for an event,
// which is checked to be a plain word before it is passed on.
// * A PAYMENT MUST BE ON THE SHOP'S OWN ACCOUNT. A bank posts to whatever
// address any of its customers registered. Someone with an account at the
// same bank could register this endpoint for an account of their own and
// pay themselves, and the callback that follows would be the bank's own,
// from the bank's own address range. The account it names is what tells
// that payment from one to the shop.
module;
module Catcrafts.Server;
import std;
import Catcrafts.Shared;
import Nostro.Money;
namespace Catcrafts::Server {
namespace {
// A bank's own word, as one may be passed on: letters, digits and the marks
// such a word is made with, and not many of them. Anything else is no word of
// a bank's, whoever wrote it.
bool PlainWord(std::string_view s) {
constexpr std::size_t most = 48;
if (s.empty() || s.size() > most) return false;
for (const char c : s) {
const bool plain = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9') || c == '_' || c == ':'
|| c == '-';
if (!plain) return false;
}
return true;
}
// The sentence the reader refused a body with. By its contract that sentence
// is its own and holds nothing of the body, which is what makes it the one
// piece of text from outside that is passed on. Still held to printable ASCII
// and a length, so a contract that was broken cannot put a control character
// or a page of text into the journal.
std::string Sentence(std::string_view s) {
constexpr std::size_t most = 200;
std::string out;
out.reserve(std::min(s.size(), most));
for (const char c : s.substr(0, most)) {
out += (c >= 0x20 && c < 0x7F) ? c : '?';
}
return out;
}
// IBANs compared as a person writes one down and as a bank sends one: spacing
// and case are not part of it.
std::string FoldIban(std::string_view s) {
std::string out;
out.reserve(s.size());
for (const char c : s) {
if (c == ' ' || c == '\t') continue;
out += static_cast<char>(c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c);
}
return out;
}
// The ledger's word for each way a payment can arrive. Empty for Unknown: the
// caller then says what the bank itself called it, and never guesses.
std::string_view ViaOf(Nostro::PaymentMethod method) {
switch (method) {
case Nostro::PaymentMethod::CreditTransfer: return "sepa";
case Nostro::PaymentMethod::DirectDebit: return "directdebit";
case Nostro::PaymentMethod::Card: return "card";
case Nostro::PaymentMethod::Ideal: return "ideal";
case Nostro::PaymentMethod::Internal: return "internal";
case Nostro::PaymentMethod::Swift: return "swift";
case Nostro::PaymentMethod::Unknown: break;
}
return {};
}
} // namespace
std::string CreditMethodFor(std::string_view bank, std::string_view kind) {
try {
Nostro::PaymentMethod method = Nostro::PaymentMethod::Unknown;
try {
method = Nostro::PaymentMethodOf(bank, kind);
} catch (...) {
// A bank this build was not made with. Its kinds are then words
// nobody here can place, which is what Unknown already means.
}
if (const std::string_view via = ViaOf(method); !via.empty()) {
return std::string(via);
}
// A kind is the bank's "<type>/<sub type>". The type alone is what
// an operator recognises, and it is passed on only where it is a
// plain word: on a callback it is a stranger's to write.
const std::string_view type = kind.substr(0, kind.find('/'));
return PlainWord(type) ? std::string(type) : std::string("bank");
} catch (...) {
return "bank";
}
}
BankCallbackResult ReadBankCallback(std::string_view bank, std::string_view body,
std::string_view ownIban) {
BankCallbackResult out;
try {
Nostro::CallbackEvent event;
try {
event = Nostro::ReadCallback(bank, body);
} catch (const std::runtime_error& e) {
// What the reader promises to throw, and the only thing whose
// words are passed on.
out.note = std::format("the body was refused: {}", Sentence(e.what()));
return out;
} catch (...) {
// Anything else is not in its contract, and its words could be
// the body's: a JSON library quotes what it choked on.
out.note = "the body was refused: the reader threw something it does "
"not promise to";
return out;
}
// Only the event that says the account's payments changed carries
// money to count. A bank's other events (a request, a card being
// blocked) are word of something else, payment in them or not.
const std::string eventWord = PlainWord(event.event) ? event.event
: std::string("?");
if (!event.transaction) {
out.note = std::format("no payment in it (event={})", eventWord);
return out;
}
if (event.event != Nostro::transactionsEvent) {
out.note = std::format("not the event payments are counted from (event={})",
eventWord);
return out;
}
const Nostro::Transaction& payment = *event.transaction;
// Whose account, before anything else about the payment: see the
// second rule at the top of this file.
if (ownIban.empty() || event.account.empty()
|| FoldIban(event.account) != FoldIban(ownIban)) {
out.note = "the payment is on another account than the shop's";
return out;
}
// Money going out cannot pay for an order. The matcher would ignore
// it anyway, and the shop's own spending has no business in a file on
// a public-facing host.
if (payment.amount <= 0) {
out.note = "the payment is not money coming in";
return out;
}
// Orders are in euro, and a credit is counted at its face value.
if (Nostro::GetCurrencyCode(payment.currency) != "EUR") {
out.note = "the payment is not in euro";
return out;
}
// The id is what a retried callback, and the pull delivering the same
// payment later, are told apart by. Without one the same money could
// be counted twice.
if (payment.id.empty()) {
out.note = "the payment has no id of the bank's";
return out;
}
BankCredit credit;
credit.id = payment.id;
credit.reference = payment.description;
credit.amountMinor = payment.amount;
credit.method = CreditMethodFor(bank, payment.kind);
out.credit = std::move(credit);
return out;
} catch (...) {
// Out of memory while building a note, in practice. Reading a
// callback must never be what takes the endpoint down.
out.credit.reset();
out.note = "the callback could not be read: reading it failed";
return out;
}
}
} // namespace Catcrafts::Server

View file

@ -1,629 +0,0 @@
/*
catcrafts.net
Copyright (C) 2026 Catcrafts
The source code of this website is made available for viewing purposes only.
No permission is granted to copy, modify, distribute, or create derivative works.
*/
// The bunq credit source: reads the shop's OWN bank account and reports the
// incoming credits, which is all the transfer rail needs to settle an order.
//
// This is a READER. It never moves money, and that asymmetry is the only
// reason it can exist at all — see the key-policy note below, which is the
// most important thing in this file.
//
// Descended from the bunq PAYMENT rail this repo carried until 2026-08-14
// (deleted in 70668af): the four-call onboarding dance, the RSA body signing
// and the context file are that code, kept because they were already proven
// against the live API. What changed is the question asked at the end. The old
// rail created bunq.me tabs and polled them; that route is closed to a webshop
// on volume grounds (a €1,500/week ceiling across all of bunq.me, and no way
// to disable its 2.5% card path), so this one reads the account's payment list
// instead and lets the reference do the matching.
//
// installation (once, ever) -> installation token
// device-server (once, ever) -> binds the API key to this "device"
// session-server (per session) -> session token + user id
// monetary-account (once) -> which account to read
// payment (per poll) -> the credits
//
// State persists in ONE json file so the first four never repeat: bunq allows
// as few as TEN calls PER DAY to the setup endpoints, so a client that
// re-onboarded on every start would lock itself out by lunchtime. Delete the
// file and it re-onboards from the API key.
//
// ── THE KEY POLICY, which this file cannot enforce on its own ─────────
//
// A bunq API key can INITIATE PAYMENTS. bunq offers no read-only scope, so
// there is no such thing as a key that can only do what this file does. The
// standing rule for this project is therefore that the bunq key does NOT live
// on the internet-facing box.
//
// That rule and this code are compatible, but only in one deployment shape:
// run this as `catcrafts-server --pull-credits` on a trusted machine, on a
// timer, and ship the resulting credits file to the server, which reads it
// with the file source and holds no key at all. The server then cannot be made
// to move money even if it is fully compromised.
//
// Configuring BUNQ_API_KEY on the server itself also works and is one less
// moving part, but it puts a payment-capable credential on a public host. The
// startup path says so out loud rather than letting it pass unnoticed.
module;
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
module Catcrafts.Server;
import std;
import Catcrafts.Shared;
import Crafter.Network;
namespace Catcrafts::Server {
namespace {
std::string Base64B(std::span<const unsigned char> in) {
static constexpr char tbl[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string out;
out.reserve(((in.size() + 2) / 3) * 4);
std::size_t i = 0;
for (; i + 2 < in.size(); i += 3) {
const std::uint32_t n = (in[i] << 16) | (in[i + 1] << 8) | in[i + 2];
out += tbl[(n >> 18) & 63]; out += tbl[(n >> 12) & 63];
out += tbl[(n >> 6) & 63]; out += tbl[n & 63];
}
if (i + 1 == in.size()) {
const std::uint32_t n = in[i] << 16;
out += tbl[(n >> 18) & 63]; out += tbl[(n >> 12) & 63];
out += "==";
} else if (i + 2 == in.size()) {
const std::uint32_t n = (in[i] << 16) | (in[i + 1] << 8);
out += tbl[(n >> 18) & 63]; out += tbl[(n >> 12) & 63];
out += tbl[(n >> 6) & 63]; out += '=';
}
return out;
}
std::string EscB(std::string_view s) {
std::string out;
out.reserve(s.size() + 8);
for (const char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (static_cast<unsigned char>(c) < 0x20) {
out += std::format("\\u{:04x}", static_cast<unsigned char>(c));
} else {
out += c;
}
}
}
return out;
}
std::string RandomHexB(std::size_t words) {
std::random_device rd;
std::string out;
for (std::size_t i = 0; i < words; ++i) out += std::format("{:08x}", rd());
return out;
}
// bunq wraps everything: {"Response":[{"Id":{…}},{"Token":{…}}]}. Find the
// first object under `key` anywhere in that array.
const Json::Value* InResponse(const Json::Value& doc, std::string_view key) {
const Json::Value* resp = doc.Find("Response");
if (!resp || !resp->IsArray()) return nullptr;
for (const Json::Value& item : resp->array) {
if (!item.IsObject()) continue;
if (const Json::Value* v = item.Find(key)) return v;
}
return nullptr;
}
} // namespace
std::optional<std::int64_t> ParseSignedAmountToMinor(std::string_view s) {
// bunq quotes an OUTGOING payment as a negative value ("-25.00"), and the
// shared money parser rejects a sign by design — it guards amounts we
// choose, where a minus would be nonsense. Here the sign is information:
// it is what separates a customer paying us from us paying a supplier, and
// dropping it would let a refund look like income. So the sign is peeled
// off here and the magnitude goes through the strict parser unchanged.
bool negative = false;
if (!s.empty() && (s.front() == '-' || s.front() == '+')) {
negative = s.front() == '-';
s.remove_prefix(1);
}
const std::optional<std::int64_t> magnitude = ParseAmountToMinor(s);
if (!magnitude) return std::nullopt;
return negative ? -*magnitude : *magnitude;
}
std::string_view BunqMethodFor(std::string_view paymentType) {
// bunq's Payment.type, mapped to the ledger's `via` vocabulary. The
// distinction earns its keep at dispatch time: a SEPA credit transfer is
// final, while a card payment can be reversed for months, so these are not
// interchangeable labels for "money arrived".
if (paymentType == "EBA_SCT") return "sepa";
if (paymentType == "IDEAL") return "ideal";
if (paymentType == "FIS") return "card";
if (paymentType == "BUNQ") return "bunq";
if (paymentType == "SWIFT") return "swift";
if (paymentType == "EBA_SDD") return "directdebit";
// An unknown type still settles — the money is on the account either way —
// but it reaches the ledger verbatim so the `via` column shows what bunq
// actually said instead of a comfortable guess.
return paymentType.empty() ? std::string_view("bank") : paymentType;
}
std::vector<BankCredit> ParseBunqPayments(std::string_view json) {
std::vector<BankCredit> out;
const auto doc = Json::Parse(json);
if (!doc || !doc->IsObject()) return out;
const Json::Value* resp = doc->Find("Response");
if (!resp || !resp->IsArray()) return out;
for (const Json::Value& item : resp->array) {
if (!item.IsObject()) continue;
const Json::Value* p = item.Find("Payment");
if (!p || !p->IsObject()) continue;
const Json::Value* amount = p->Find("amount");
if (!amount || !amount->IsObject()) continue;
// Only euro amounts can pay a euro order. A foreign-currency credit is
// skipped rather than counted at face value, which would silently
// treat 25 of something else as 25 euro.
if (amount->Str("currency") != "EUR") continue;
const std::optional<std::int64_t> minor =
ParseSignedAmountToMinor(amount->Str("value"));
if (!minor) continue;
BankCredit c;
c.id = std::format("{}", p->Int("id"));
c.reference = std::string(p->Str("description"));
c.amountMinor = *minor;
c.method = std::string(BunqMethodFor(p->Str("type")));
out.push_back(std::move(c));
}
return out;
}
std::optional<BankCredit> ParseBunqCallback(std::string_view json) {
const auto doc = Json::Parse(json);
if (!doc || !doc->IsObject()) return std::nullopt;
const Json::Value* note = doc->Find("NotificationUrl");
if (!note || !note->IsObject()) return std::nullopt;
const Json::Value* object = note->Find("object");
if (!object || !object->IsObject()) return std::nullopt;
const Json::Value* p = object->Find("Payment");
if (!p || !p->IsObject()) return std::nullopt;
const Json::Value* amount = p->Find("amount");
if (!amount || !amount->IsObject()) return std::nullopt;
// Only euro can pay a euro order; see ParseBunqPayments for why a
// foreign-currency credit is skipped rather than counted at face value.
if (amount->Str("currency") != "EUR") return std::nullopt;
const std::optional<std::int64_t> minor =
ParseSignedAmountToMinor(amount->Str("value"));
if (!minor) return std::nullopt;
BankCredit c;
c.id = std::format("{}", p->Int("id"));
c.reference = std::string(p->Str("description"));
c.amountMinor = *minor;
c.method = std::string(BunqMethodFor(p->Str("type")));
// An id is what deduplication rests on. A callback without one cannot be
// deduplicated, so accepting it would let a retry credit the same money
// twice — refuse instead.
if (c.id.empty() || c.id == "0") return std::nullopt;
return c;
}
namespace {
class BunqCreditSource final : public CreditSource {
public:
BunqCreditSource(std::string apiKey, std::filesystem::path statePath,
std::string permittedIps, int count, std::string wantIban)
: apiKey_(std::move(apiKey)), statePath_(std::move(statePath)),
permittedIps_(std::move(permittedIps)), count_(count),
wantIban_(std::move(wantIban)) {}
std::optional<std::vector<BankCredit>> Recent() override {
std::lock_guard lock(mutex_);
if (!EnsureSession()) return std::nullopt;
// One page is enough and more would be worse: the reconciler only ever
// asks about orders inside their payment window, so a credit old enough
// to fall off this page is old enough to be settled by hand anyway.
// Paging the whole account history every minute would also spend the
// per-method rate limit on data nothing reads.
const auto doc = Call("GET", std::format(
"/v1/user/{}/monetary-account/{}/payment?count={}", userId_, accountId_,
count_), {});
if (!doc) return std::nullopt;
return ParseBunqPayments(raw_);
}
std::string_view Name() const override { return "bunq"; }
private:
// ── state, so onboarding happens once ─────────────────────────────
void LoadState() {
std::ifstream in(statePath_, std::ios::binary);
if (!in) return;
std::ostringstream buf;
buf << in.rdbuf();
const auto doc = Json::Parse(buf.str());
if (!doc || !doc->IsObject()) return;
privateKeyPem_ = std::string(doc->Str("private_key_pem"));
installationToken_ = std::string(doc->Str("installation_token"));
deviceRegistered_ = doc->Bool("device_registered");
sessionToken_ = std::string(doc->Str("session_token"));
userId_ = doc->Int("user_id");
accountId_ = doc->Int("account_id");
}
bool SaveState() {
std::ofstream out(statePath_, std::ios::trunc | std::ios::binary);
if (!out) {
std::println(std::cerr, "bunq: cannot write context {}", statePath_.string());
return false;
}
out << std::format(
R"({{"private_key_pem":"{}","installation_token":"{}",)"
R"("device_registered":{},"session_token":"{}","user_id":{},)"
R"("account_id":{}}})",
EscB(privateKeyPem_), EscB(installationToken_), deviceRegistered_,
EscB(sessionToken_), userId_, accountId_);
out.flush();
// The file holds a private key. Narrow it even though the directory
// should already be private: defence in depth costs one syscall.
std::error_code ec;
std::filesystem::permissions(statePath_,
std::filesystem::perms::owner_read
| std::filesystem::perms::owner_write,
ec);
return static_cast<bool>(out);
}
// ── the keypair bunq's installation call demands ──────────────────
bool EnsureKeypair() {
if (!privateKeyPem_.empty()) return LoadKey();
EVP_PKEY* raw = EVP_RSA_gen(2048);
if (!raw) return false;
key_.reset(raw);
BIO* bio = BIO_new(BIO_s_mem());
if (!bio) return false;
if (PEM_write_bio_PrivateKey(bio, key_.get(), nullptr, nullptr, 0,
nullptr, nullptr) != 1) {
BIO_free(bio);
return false;
}
char* data = nullptr;
const long len = BIO_get_mem_data(bio, &data);
privateKeyPem_.assign(data, static_cast<std::size_t>(len));
BIO_free(bio);
return SaveState();
}
bool LoadKey() {
if (key_) return true;
BIO* bio = BIO_new_mem_buf(privateKeyPem_.data(),
static_cast<int>(privateKeyPem_.size()));
if (!bio) return false;
EVP_PKEY* raw = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
if (!raw) return false;
key_.reset(raw);
return true;
}
std::string PublicKeyPem() {
if (!LoadKey()) return {};
BIO* bio = BIO_new(BIO_s_mem());
if (!bio) return {};
if (PEM_write_bio_PUBKEY(bio, key_.get()) != 1) {
BIO_free(bio);
return {};
}
char* data = nullptr;
const long len = BIO_get_mem_data(bio, &data);
std::string pem(data, static_cast<std::size_t>(len));
BIO_free(bio);
return pem;
}
// bunq stopped REQUIRING body signatures years ago, but the keypair has to
// exist for installation anyway and a signed request is valid whether or
// not the server checks, so every body is signed.
std::string SignBody(std::string_view body) {
if (!LoadKey()) return {};
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
if (!ctx) return {};
std::string out;
do {
if (EVP_DigestSignInit(ctx, nullptr, EVP_sha256(), nullptr,
key_.get()) != 1) break;
std::size_t len = 0;
if (EVP_DigestSign(ctx, nullptr, &len,
reinterpret_cast<const unsigned char*>(body.data()),
body.size()) != 1) break;
std::vector<unsigned char> sig(len);
if (EVP_DigestSign(ctx, sig.data(), &len,
reinterpret_cast<const unsigned char*>(body.data()),
body.size()) != 1) break;
sig.resize(len);
out = Base64B(sig);
} while (false);
EVP_MD_CTX_free(ctx);
return out;
}
// ── transport ─────────────────────────────────────────────────────
std::optional<Json::Value> DoCall(std::string_view method, const std::string& path,
const std::string& body,
const std::string& authToken,
std::string* statusOut = nullptr) {
try {
if (!client_) {
client_ = std::make_unique<Crafter::ClientHTTP1>(
kHost, static_cast<std::uint16_t>(443),
Crafter::TLSClientCredentials{});
}
Crafter::HTTPRequest req;
req.method = std::string(method);
req.path = path;
req.authority = kHost;
req.body = body;
req.headers["user-agent"] = "catcrafts.net-server/1.0 (+https://catcrafts.net)";
req.headers["cache-control"] = "no-cache";
req.headers["x-bunq-client-request-id"] = RandomHexB(4);
req.headers["x-bunq-geolocation"] = "0 0 0 0 000";
req.headers["x-bunq-language"] = "en_US";
req.headers["x-bunq-region"] = "nl_NL";
if (!body.empty()) {
req.headers["content-type"] = "application/json";
const std::string sig = SignBody(body);
if (!sig.empty()) req.headers["x-bunq-client-signature"] = sig;
}
if (!authToken.empty()) {
req.headers["x-bunq-client-authentication"] = authToken;
}
const Crafter::HTTPResponse res = client_->Send(req);
if (statusOut) *statusOut = res.status;
if (res.status.size() != 3 || res.status[0] != '2') {
// 429 gets named, because the cure is different from every
// other failure: bunq allows only a few reads per second per
// method, and setup endpoints as few as ten per DAY.
if (res.status == "429") {
std::println(std::cerr,
"bunq: {} {} -> 429 rate limited; reads are capped at "
"a few per second and setup calls at ~10/day, so back "
"off rather than retrying in a loop", method, path);
} else {
std::println(std::cerr, "bunq: {} {} -> {} {}", method, path,
res.status, res.body.substr(0, 200));
}
return std::nullopt;
}
// Kept so the caller can re-parse into domain types without this
// layer knowing about them.
raw_ = res.body;
auto doc = Json::Parse(res.body);
if (!doc) return std::nullopt;
return std::move(*doc);
} catch (const std::exception& e) {
std::println(std::cerr, "bunq: {} {} failed: {}", method, path, e.what());
client_.reset(); // dial fresh next time
return std::nullopt;
}
}
// A session call, with ONE automatic re-session on 401. Sessions expire
// server-side on a schedule the bunq app controls, so expiry is routine
// and must not surface as a payment failure.
std::optional<Json::Value> Call(std::string_view method, const std::string& path,
const std::string& body) {
std::string status;
auto doc = DoCall(method, path, body, sessionToken_, &status);
if (!doc && status == "401") {
sessionToken_.clear();
if (!EnsureSession()) return std::nullopt;
doc = DoCall(method, path, body, sessionToken_, &status);
}
return doc;
}
// ── onboarding, each step at most once ────────────────────────────
bool EnsureSession() {
if (!loaded_) { LoadState(); loaded_ = true; }
if (apiKey_.empty()) {
std::println(std::cerr, "bunq: no API key configured");
return false;
}
if (!EnsureKeypair()) return false;
if (installationToken_.empty()) {
const std::string body = std::format(R"({{"client_public_key":"{}"}})",
EscB(PublicKeyPem()));
const auto doc = DoCall("POST", "/v1/installation", body, {});
if (!doc) return false;
const Json::Value* token = InResponse(*doc, "Token");
if (!token) return false;
installationToken_ = std::string(token->Str("token"));
if (installationToken_.empty()) return false;
SaveState();
}
if (!deviceRegistered_) {
// permitted_ips decides what a leaked key is worth. bunq has no
// read-only scope, so this key can move money: pinning it to the
// one address that should ever use it is the difference between a
// leak being survivable and being catastrophic. "*" is accepted
// but announced, because silently unpinning a payment-capable
// credential is exactly the kind of default nobody revisits.
if (permittedIps_ == "*") {
std::println(std::cerr,
"bunq: registering this device with permitted_ips=* — a "
"leaked key would then work from anywhere. Set "
"BUNQ_PERMITTED_IPS to this machine's egress address to "
"pin it (the registration is once-only, so changing it "
"later means deleting the context file).");
}
std::string ipList;
for (const auto part : std::views::split(permittedIps_, ',')) {
const std::string_view ip(part.begin(), part.end());
if (ip.empty()) continue;
if (!ipList.empty()) ipList += ",";
ipList += std::format("\"{}\"", EscB(ip));
}
if (ipList.empty()) ipList = "\"*\"";
const std::string body = std::format(
R"({{"description":"catcrafts.net credit reader","secret":"{}",)"
R"("permitted_ips":[{}]}})", EscB(apiKey_), ipList);
const auto doc = DoCall("POST", "/v1/device-server", body,
installationToken_);
if (!doc) return false;
deviceRegistered_ = true;
SaveState();
}
if (sessionToken_.empty() || userId_ == 0) {
const std::string body = std::format(R"({{"secret":"{}"}})", EscB(apiKey_));
const auto doc = DoCall("POST", "/v1/session-server", body,
installationToken_);
if (!doc) return false;
const Json::Value* token = InResponse(*doc, "Token");
if (!token) return false;
sessionToken_ = std::string(token->Str("token"));
// Which user object comes back depends on the account type, so try
// each rather than assuming this is a company account.
for (const std::string_view k : { "UserPerson", "UserCompany", "UserApiKey" }) {
if (const Json::Value* u = InResponse(*doc, k)) {
userId_ = u->Int("id");
break;
}
}
if (sessionToken_.empty() || userId_ == 0) return false;
SaveState();
}
if (accountId_ == 0) {
const auto doc = Call("GET", std::format(
"/v1/user/{}/monetary-account?count=25", userId_), {});
if (!doc) return false;
const Json::Value* resp = doc->Find("Response");
if (!resp || !resp->IsArray()) return false;
// With more than one account, guessing is how the shop ends up
// reconciling against savings. Name the wanted one by IBAN when
// there is a choice, and refuse rather than pick.
std::vector<std::pair<std::int64_t, std::string>> active;
for (const Json::Value& item : resp->array) {
const Json::Value* acc = item.Find("MonetaryAccountBank");
if (!acc || !acc->IsObject()) continue;
if (acc->Str("status") != "ACTIVE") continue;
std::string iban;
if (const Json::Value* aliases = acc->Find("alias");
aliases && aliases->IsArray()) {
for (const Json::Value& a : aliases->array) {
if (a.IsObject() && a.Str("type") == "IBAN") {
iban = std::string(a.Str("value"));
break;
}
}
}
active.emplace_back(acc->Int("id"), std::move(iban));
}
if (active.empty()) {
std::println(std::cerr, "bunq: no active account found");
return false;
}
if (!wantIban_.empty()) {
for (const auto& [id, iban] : active) {
if (Matches(iban, wantIban_)) { accountId_ = id; break; }
}
if (accountId_ == 0) {
std::println(std::cerr,
"bunq: no active account matches TRANSFER_IBAN; the "
"key sees {} account(s)", active.size());
return false;
}
} else if (active.size() == 1) {
accountId_ = active.front().first;
} else {
std::println(std::cerr,
"bunq: this key sees {} active accounts and no "
"TRANSFER_IBAN was given to choose between them — "
"refusing to guess which one the shop is paid into",
active.size());
return false;
}
SaveState();
}
return true;
}
// IBANs are compared ignoring spacing and case: what a human pastes into
// configuration and what the API returns differ cosmetically far more
// often than they differ in substance.
static bool Matches(std::string_view a, std::string_view b) {
const auto fold = [](std::string_view s) {
std::string out;
for (const char c : s) {
if (c == ' ' || c == '\t') continue;
out += static_cast<char>(c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c);
}
return out;
};
return !a.empty() && fold(a) == fold(b);
}
struct PkeyDeleter {
void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); }
};
static constexpr const char* kHost = "api.bunq.com";
std::string apiKey_;
std::filesystem::path statePath_;
std::string permittedIps_;
int count_ = 50;
std::string wantIban_;
std::mutex mutex_;
std::unique_ptr<Crafter::ClientHTTP1> client_;
std::unique_ptr<EVP_PKEY, PkeyDeleter> key_;
std::string raw_;
bool loaded_ = false;
std::string privateKeyPem_;
std::string installationToken_;
bool deviceRegistered_ = false;
std::string sessionToken_;
std::int64_t userId_ = 0;
std::int64_t accountId_ = 0;
};
} // namespace
std::unique_ptr<CreditSource> MakeBunqCreditSource(const BunqConfig& config) {
if (config.apiKey.empty()) return nullptr;
if (config.statePath.empty()) {
std::println(std::cerr, "bunq: no context path given");
return nullptr;
}
return std::make_unique<BunqCreditSource>(
config.apiKey, config.statePath,
config.permittedIps.empty() ? std::string("*") : config.permittedIps,
config.count > 0 ? config.count : 50, config.iban);
}
} // namespace Catcrafts::Server

View file

@ -1,179 +0,0 @@
/*
catcrafts.net
Copyright (C) 2026 Catcrafts
The source code of this website is made available for viewing purposes only.
No permission is granted to copy, modify, distribute, or create derivative works.
*/
// The callback shadow: what Nostro's reader makes of a bank callback, set
// beside what this shop's own parser made of it. TEMPORARY, and it decides
// nothing. The interface (ShadowCallbackVerdict) says why it exists and when
// it goes.
//
// This is the one unit that imports Nostro.Money. Everything it takes from
// there is read here and turned into this shop's own words before it leaves,
// so nothing else in the server knows the module is there.
//
// The rule every line below is written to: NOTHING OF THE BODY COMES OUT. The
// verdict is built from fixed words, from whether two values are equal, and
// from the few words a bank has for a category or a type of payment, each
// checked to be such a word before it is printed. An id, an amount, a name, an
// IBAN or a description is compared and never quoted.
module;
module Catcrafts.Server;
import std;
import Catcrafts.Shared;
import Nostro.Money;
namespace Catcrafts::Server {
namespace {
// A word that is safe to print whoever wrote the body: letters, digits and
// the three marks a bank's own word or ours is made with, and not many of
// them. Anything else is not printed at all. Nostro already holds a bank's
// category to capitals, digits and underscores; this does not lean on that.
std::string Word(std::string_view s) {
constexpr std::size_t most = 48;
if (s.empty() || s.size() > most) return "?";
for (const char c : s) {
const bool plain = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9') || c == '_' || c == ':'
|| c == '-';
if (!plain) return "?";
}
return std::string(s);
}
// The sentence Nostro refused a body with. By its contract that sentence is
// Nostro's own and holds nothing of the body, which is what makes it the one
// piece of text here that is passed on. Still held to printable ASCII and a
// length, so a contract that was broken cannot put a control character or a
// page of text into the journal.
std::string Sentence(std::string_view s) {
constexpr std::size_t most = 200;
std::string out;
out.reserve(std::min(s.size(), most));
for (const char c : s.substr(0, most)) {
out += (c >= 0x20 && c < 0x7F) ? c : '?';
}
return out;
}
// IBANs compared as the rest of the server compares them: spacing and case
// are how a person wrote one down, not part of it.
std::string FoldIban(std::string_view s) {
std::string out;
out.reserve(s.size());
for (const char c : s) {
if (c == ' ' || c == '\t') continue;
out += static_cast<char>(c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c);
}
return out;
}
// Nostro's answer to how a payment arrived, in the ledger's `via` words, so
// it can be set beside what BunqMethodFor said. Empty for Unknown: the caller
// then falls back to the bank's own word, as BunqMethodFor does.
std::string_view ViaOf(Nostro::PaymentMethod method) {
switch (method) {
case Nostro::PaymentMethod::CreditTransfer: return "sepa";
case Nostro::PaymentMethod::DirectDebit: return "directdebit";
case Nostro::PaymentMethod::Card: return "card";
case Nostro::PaymentMethod::Ideal: return "ideal";
case Nostro::PaymentMethod::Internal: return "bunq";
case Nostro::PaymentMethod::Swift: return "swift";
case Nostro::PaymentMethod::Unknown: break;
}
return {};
}
// The `via` word Nostro's reading leads to for a payment of this kind.
std::string NostroVia(std::string_view bank, std::string_view kind) {
Nostro::PaymentMethod method = Nostro::PaymentMethod::Unknown;
try {
method = Nostro::PaymentMethodOf(bank, kind);
} catch (...) {
return "?";
}
if (const std::string_view via = ViaOf(method); !via.empty()) {
return std::string(via);
}
// A kind Nostro's table has not. A kind is "<type>/<sub type>", and the
// type alone is what BunqMethodFor passes through for one IT does not
// know, with "bank" where the bank sent none.
const std::string_view type = kind.substr(0, kind.find('/'));
return type.empty() ? std::string("bank") : std::string(type);
}
std::string_view Same(bool same) { return same ? "same" : "DIFFERENT"; }
} // namespace
std::string ShadowCallbackVerdict(std::string_view bank, std::string_view body,
const std::optional<BankCredit>& ours,
std::string_view ownIban) {
try {
Nostro::CallbackEvent event;
try {
event = Nostro::ReadCallback(bank, body);
} catch (const std::runtime_error& e) {
// What Nostro promises to throw, and the only thing whose words
// are passed on.
const std::string why = Sentence(e.what());
return ours
? std::format("DIFFER nostro refused what ours reads as a payment: {}", why)
: std::format("AGREE neither reads a payment (nostro: {})", why);
} catch (...) {
// Anything else is not in its contract, and its words could be
// the body's: a JSON library quotes what it choked on.
return "DIFFER nostro threw something other than it promises";
}
const std::string eventWord = Word(event.event);
if (!event.transaction) {
return ours
? std::format("DIFFER nostro reads no payment in it (event={}), ours does",
eventWord)
: std::format("AGREE no payment in it (event={})", eventWord);
}
const Nostro::Transaction& theirs = *event.transaction;
const std::string_view direction =
theirs.amount > 0 ? "in" : theirs.amount < 0 ? "out" : "zero";
const std::string_view account =
ownIban.empty() ? "unknown"
: FoldIban(event.account) == FoldIban(ownIban) ? "ours" : "other";
if (!ours) {
return std::format(
"DIFFER nostro reads a payment, ours does not ({} account={} event={})",
direction, account, eventWord);
}
const std::string theirVia = NostroVia(bank, theirs.kind);
const std::string method = theirVia == ours->method
? std::format("method={}", Word(theirVia))
: std::format("method ours={} nostro={}", Word(ours->method), Word(theirVia));
const std::string rest = std::format("{} {} account={} event={}", direction,
method, account, eventWord);
const bool sameId = theirs.id == ours->id;
const bool sameAmount = theirs.amount == ours->amountMinor;
const bool sameReference = theirs.description == ours->reference;
if (sameId && sameAmount && sameReference) {
return std::format("AGREE {}", rest);
}
return std::format("DIFFER id={} amount={} reference={} {}", Same(sameId),
Same(sameAmount), Same(sameReference), rest);
} catch (...) {
// Out of memory while building a line, in practice. The comparison
// must never be the thing that fails a callback.
return "FAILED the comparison itself threw";
}
}
} // namespace Catcrafts::Server

View file

@ -28,7 +28,8 @@ No permission is granted to copy, modify, distribute, or create derivative works
// arrive here as a plain list. This process can therefore only ever LEARN an
// address it was given — it cannot derive the next one, cannot recognise a
// sibling, and has nothing on disk that is worth stealing. It is the same rule
// the bunq key follows, taken one step further.
// the bank side follows, where this box holds no key to the account either,
// taken one step further.
//
// Why balanceOf and not log scanning. One eth_call answers "how much EURC does
// this address hold", which is the entire question. Asking it AT A FINALIZED
@ -203,7 +204,7 @@ std::optional<std::int64_t> Pow10(int n) {
// so anything bigger is a broken or hostile node rather than a large balance,
// and the one thing it must not do is satisfy the covering comparison.
// Exported so the self-test can drive it with canned RPC bodies, the same way
// ParseBunqPayments is driven — the HTTP around it is thin, the decoding is
// ReadBankCallback is driven — the HTTP around it is thin, the decoding is
// where a mistake would cost money.
// True when the reply carries exactly the numeric id we sent. Absent or
// non-numeric is false: an answer that will not say which question it belongs

View file

@ -14,7 +14,7 @@ No permission is granted to copy, modify, distribute, or create derivative works
// written by the owner's own tooling, off this box, and re-read per request so
// updating the file is all it takes to update the page.
//
// This unit once also held the bunq mutation callback that moved those numbers
// This unit once also held a bank callback of its own that moved those numbers
// live (parser, default-deny classifier, dedup ledger, signature check). That
// integration was retired 2026-08-17 — the webhook is deregistered and the
// endpoint is gone — and the file is in git history if a bank feed ever comes

View file

@ -75,17 +75,15 @@ std::string gCssHref = "/styles.css";
PaymentRails gRails;
std::string gRedirectBase = "https://catcrafts.net";
// Where the bunq callback writes, and the secret path that authorises it.
// Both empty means the endpoint does not exist at all — an unconfigured
// Where the bank's callback writes, the secret path that authorises it, which
// bank's callbacks arrive there, and the account a payment has to be on. An
// empty path means the endpoint does not exist at all — an unconfigured
// webhook must not answer, or the shop would carry a public write-ish endpoint
// nobody asked for.
std::filesystem::path gCreditsPath;
std::string gWebhookPath;
// The callback shadow (temporary, see ShadowCallbackVerdict): off until
// ConfigureCallbackShadow says which account is the shop's own.
bool gCallbackShadow = false;
std::string gShadowIban;
std::string gCallbackBank;
std::string gCallbackIban;
// The bank-derived aggregates for /financials live in Catcrafts.Server-
// Financials.cpp, which owns their file. They are read through
@ -649,16 +647,20 @@ std::string NowRfc2822() {
// the POST/redirect/GET pattern, and it matters for a real form: a rendered
// POST response means reloading re-submits, and the back button re-posts. The
// redirect leaves the browser on a GET it can safely repeat.
// The bunq callback. See ParseBunqCallback for the security model; the short
// version is that bunq does NOT sign these, so this endpoint's only defences
// are the ones around it: a secret path segment, a source-IP allowlist in
// Caddy for bunq's published range, and the fact that no parcel leaves without
// a human. It therefore does the least it possibly can — decode one payment
// and append it to the credits file — and makes no settlement decision at all.
// The reconciler settles from that file exactly as it does from a pulled one,
// so a forged callback can at worst manufacture a credit line, never bypass
// the reference match or the covering-amount rule.
HTTPResponse HandleBunqCallback(const HTTPRequest& req) {
// The bank's callback. See ReadBankCallback in the interface for the security
// model; the short version is that a bank need not sign these and ours does
// not, so this endpoint's defences are the ones around it: a secret path
// segment, a source-IP allowlist in Caddy for the bank's published range, the
// check that a payment is on the shop's own account, and the fact that no
// parcel leaves without a human. It therefore does the least it possibly can —
// have one payment read and append it to the credits file — and makes no
// settlement decision at all. The reconciler settles from that file exactly as
// it does from a pulled one, so a forged callback can at worst manufacture a
// credit line, never bypass the reference match or the covering-amount rule.
//
// Every callback leaves exactly one line in the log, and none of them says
// anything the body carried beyond what a credit line already holds.
HTTPResponse HandleBankCallback(const HTTPRequest& req) {
HTTPResponse res;
res.headers["content-type"] = "text/plain; charset=utf-8";
// Never cache, never index, and say nothing useful in the body: this URL
@ -673,65 +675,32 @@ HTTPResponse HandleBunqCallback(const HTTPRequest& req) {
return res;
}
const std::optional<BankCredit> credit = ParseBunqCallback(req.body);
if (!credit) {
// A callback shape this cannot decode is NOT an error to shout about
// with a 4xx: bunq sends several notification categories, and only
// some carry a Payment. Answer 200 so bunq stops retrying something
// that will never decode, and log it so a genuinely new shape is
// visible rather than silently dropped.
std::println(std::cerr, "bunq callback: no usable payment in body ({} bytes)",
req.body.size());
res.status = "200";
res.body = "ok\n";
return res;
}
// Outgoing money cannot pay for an order, and the matcher ignores it
// anyway — so refuse to write the shop's own supplier payments into a file
// that lives on a public-facing host.
if (credit->amountMinor <= 0) {
res.status = "200";
res.body = "ok\n";
return res;
}
if (AppendCreditTo(gCreditsPath, *credit)) {
std::println(std::cerr, "bunq callback: credited {} via {} (id {})",
Money::FormatMinor(credit->amountMinor), credit->method,
credit->id);
}
// 200 even on a duplicate or a write we skipped: a duplicate IS success
// from bunq's side, and making it retry would achieve nothing.
// 200 whatever comes of it. A body that carries no payment for us is NOT
// an error to answer with a 4xx: a bank sends several kinds of event, and
// one it gets an error for it sends again, which achieves nothing. A
// duplicate IS success from the bank's side for the same reason.
res.status = "200";
res.body = "ok\n";
return res;
}
// The shadow run (temporary, see ShadowCallbackVerdict): what Nostro's reader
// makes of the body HandleBunqCallback has just dealt with, logged beside what
// ours made of it.
//
// It is called AFTER the handler has returned its answer and written its
// credit, on purpose. The handler above is not touched by it and cannot be
// changed by it: the body is parsed a second time here rather than handed
// over, so that the code which settles money stays exactly the code that has
// been settling it. If this ever took the process down, the credit would be on
// disk already, and the bank's retry of a callback it got no answer to is
// refused as a duplicate by the id.
void ShadowBunqCallback(const HTTPRequest& req) {
if (!gCallbackShadow) return;
try {
const std::optional<BankCredit> ours = ParseBunqCallback(req.body);
std::println(std::cerr, "bank callback shadow: {}",
ShadowCallbackVerdict("bunq", req.body, ours, gShadowIban));
} catch (...) {
// Nothing here may fail a callback that was already answered.
try {
std::println(std::cerr, "bank callback shadow: FAILED before a verdict");
} catch (...) {
}
const BankCallbackResult read = ReadBankCallback(gCallbackBank, req.body, gCallbackIban);
if (!read.credit) {
// Said aloud, so that a shape the reader does not take, or a payment
// on an account that is not ours, is visible rather than silently
// dropped. The note holds nothing of the body.
std::println(std::cerr, "bank callback: nothing credited: {}", read.note);
return res;
}
if (AppendCreditTo(gCreditsPath, *read.credit)) {
std::println(std::cerr, "bank callback: credited {} via {} (id {})",
Money::FormatMinor(read.credit->amountMinor), read.credit->method,
read.credit->id);
} else {
std::println(std::cerr, "bank callback: nothing credited: the payment was "
"credited before, or the credits file could not be "
"written");
}
return res;
}
HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) {
@ -1161,38 +1130,43 @@ void ConfigurePayments(PaymentRails rails, std::string redirectBase) {
if (!redirectBase.empty()) gRedirectBase = std::move(redirectBase);
}
void ConfigureBunqCallback(std::filesystem::path creditsPath, std::string secretPath) {
// Both or neither. A secret with nowhere to write, or a path to write with
// no secret guarding it, are each worse than not having the endpoint: the
// first answers requests it cannot act on, the second answers everyone.
void ConfigureBankCallback(std::filesystem::path creditsPath, std::string secretPath,
std::string bank, std::string ownIban) {
// All of it or none. A secret with nowhere to write, or a path to write
// with no secret guarding it, are each worse than not having the endpoint:
// the first answers requests it cannot act on, the second answers everyone.
if (creditsPath.empty() || secretPath.empty()) return;
// A short secret is not a secret. Refuse rather than serve a guessable
// write endpoint just because someone set the variable to "hook".
if (secretPath.size() < 24) {
std::println(std::cerr,
"bunq callback: BUNQ_WEBHOOK_PATH is too short to be secret "
"bank callback: BANK_CALLBACK_PATH is too short to be secret "
"({} chars, want 24+) — the endpoint is NOT enabled",
secretPath.size());
return;
}
// Which bank posts there decides how a body is read, and the account is
// what a payment has to be on to count. Without either the endpoint would
// answer the bank 200 and credit nothing, which looks like working.
if (bank.empty() || ownIban.empty()) {
std::println(std::cerr,
"bank callback: {} is not set — the endpoint is NOT enabled",
bank.empty() ? "BANK_CALLBACK_BANK (whose callbacks arrive there)"
: "TRANSFER_IBAN (the account a payment must be on)");
return;
}
if (secretPath.front() != '/') secretPath.insert(secretPath.begin(), '/');
gCreditsPath = std::move(creditsPath);
gWebhookPath = std::move(secretPath);
// Deliberately does NOT log the path: it would land in the journal, and
// from there in any log shipping or analytics that reads it.
std::println(std::cerr, "bunq callback: enabled on a secret path ({} chars)",
gWebhookPath.size());
}
void ConfigureCallbackShadow(std::string ownIban) {
gShadowIban = std::move(ownIban);
gCallbackShadow = true;
// The account is not printed: whether one was named is what a reader of
// the log needs, to know what "account=unknown" on a verdict means.
gCallbackBank = std::move(bank);
gCallbackIban = std::move(ownIban);
// Deliberately does NOT log the path or the account: either would land in
// the journal, and from there in any log shipping or analytics that reads
// it. The bank's name is configuration and no secret.
std::println(std::cerr,
"bank callback shadow: on, Nostro's reader runs beside ours and "
"decides nothing (own account {})",
gShadowIban.empty() ? "not named" : "named");
"bank callback: enabled on a secret path ({} chars), reading {}'s "
"callbacks for the shop's own account",
gWebhookPath.size(), gCallbackBank);
}
bool CryptoPaymentAvailable() { return gRails.crypto != nullptr; }
@ -1411,7 +1385,7 @@ int Serve(std::uint16_t port) {
};
auto fallback = [](const HTTPRequest& req) -> HTTPResponse {
// The bunq callback, before anything else looks at the path. It is
// The bank's callback, before anything else looks at the path. It is
// matched here rather than added to the shared route table on purpose:
// ParseRoute is shared with the wasm frontend, and a secret URL has no
// business being compiled into a bundle served to browsers.
@ -1425,7 +1399,7 @@ int Serve(std::uint16_t port) {
// be an oracle: a GET returning 405 where every other unknown URL
// returns 404 confirms a guessed path is the right one, which is
// exactly the signal a secret-in-the-URL scheme cannot afford to give.
// bunq only ever POSTs, so nothing legitimate is lost.
// The bank only ever POSTs, so nothing legitimate is lost.
if (!gWebhookPath.empty() && req.method == "POST") {
const std::string_view path = PathWithoutQueryHTTP(req.path);
if (path.size() == gWebhookPath.size()) {
@ -1433,14 +1407,7 @@ int Serve(std::uint16_t port) {
for (std::size_t i = 0; i < path.size(); ++i) {
diff |= static_cast<unsigned char>(path[i] ^ gWebhookPath[i]);
}
if (diff == 0) {
// Ours decides, and has finished deciding, before the
// shadow looks at the same body. The answer is already
// made and is returned as it is.
HTTPResponse answer = HandleBunqCallback(req);
ShadowBunqCallback(req);
return answer;
}
if (diff == 0) return HandleBankCallback(req);
}
}
// A POST to a product page is a checkout submission.

View file

@ -6,8 +6,7 @@ The source code of this website is made available for viewing purposes only.
No permission is granted to copy, modify, distribute, or create derivative works.
*/
// The payment-rail roster, the fake rail the suites run on, and the one money
// parser both real rails share.
// The payment-rail roster and the fake rail the suites run on.
//
// Every rail this shop has is SELF-HOSTED: a bank transfer to its own account,
// or EURC to an address it generated itself. There is no hosted provider in the
@ -36,38 +35,6 @@ import Catcrafts.Shared;
namespace Catcrafts::Server {
std::optional<std::int64_t> ParseAmountToMinor(std::string_view s) {
// Exactly: 1*DIGIT ["." 1*2DIGIT]. Anything else — signs, exponents,
// spaces, thousands separators — is rejected. Money parsing has no
// "probably fine" mode.
//
// Shared because every amount that arrives from outside comes as a decimal
// string: the bank quotes "57.38", and the crypto rail's own decoding
// reduces to the same question. The sign is deliberately NOT accepted here
// (see ParseSignedAmountToMinor, which peels it off first) so that a stray
// minus can never quietly halve a total.
if (s.empty() || s.size() > 15) return std::nullopt;
std::int64_t units = 0;
std::size_t i = 0;
if (s[i] < '0' || s[i] > '9') return std::nullopt;
for (; i < s.size() && s[i] >= '0' && s[i] <= '9'; ++i) {
units = units * 10 + (s[i] - '0');
}
std::int64_t cents = 0;
if (i < s.size()) {
if (s[i] != '.') return std::nullopt;
++i;
const std::size_t fracStart = i;
for (; i < s.size() && s[i] >= '0' && s[i] <= '9'; ++i) {
cents = cents * 10 + (s[i] - '0');
}
const std::size_t digits = i - fracStart;
if (i != s.size() || digits == 0 || digits > 2) return std::nullopt;
if (digits == 1) cents *= 10;
}
return units * 100 + cents;
}
namespace {
// ── the fake rail ─────────────────────────────────────────────────────
@ -175,39 +142,13 @@ std::unique_ptr<PaymentRail> MakeRail(const RailConfig& config) {
// that will not load — and both return nullptr there, which main reports
// as a rail that could not load rather than as an unknown one.
if (config.mode == "transfer") {
// Which credit source depends on where the operator chose to keep the
// bank key. With BUNQ_API_KEY set here, this process reads the account
// itself — simpler, and strictly worse, because that key can move
// money and this process is reachable from the internet. Without it,
// the rail reads the credits file that `--pull-credits` fills from a
// trusted machine, and this host holds nothing that can spend.
std::unique_ptr<CreditSource> credits;
if (const char* key = std::getenv("BUNQ_API_KEY"); key && *key) {
std::println(std::cerr,
"transfer: WARNING — reading the bank directly with "
"BUNQ_API_KEY present in this process. A bunq key can "
"initiate payments and bunq has no read-only scope, so this "
"host now holds a credential that can spend the account. The "
"intended shape is `--pull-credits` on a trusted machine "
"writing the credits file this rail reads.");
BunqConfig bunq;
bunq.apiKey = key;
bunq.iban = config.transferIban;
if (const char* v = std::getenv("BUNQ_PERMITTED_IPS"); v) {
bunq.permittedIps = v;
}
if (const char* v = std::getenv("BUNQ_STATE"); v && *v) {
bunq.statePath = v;
} else {
bunq.statePath = config.transferCreditsPath;
bunq.statePath += ".bunq-context.json";
}
credits = MakeBunqCreditSource(bunq);
if (!credits) return nullptr;
} else {
credits = MakeFileCreditSource(config.transferCreditsPath);
}
return MakeTransferRail(config, std::move(credits));
// The rail reads the credits file, and nothing else. This process
// holds no bank credential: the file is filled by the bank's callback
// (HandleBankCallback) and by tools/pull-and-ship-credits.sh, which
// asks the bank from a trusted machine and ships the result here. A
// key that can read a bank account can as a rule also pay from it, so
// none belongs on a host that is reachable from the internet.
return MakeTransferRail(config, MakeFileCreditSource(config.transferCreditsPath));
}
if (config.mode == "eurc") return MakeEurcRail(config);
return nullptr; // "off"

View file

@ -25,13 +25,16 @@ No permission is granted to copy, modify, distribute, or create derivative works
// load-bearing rather than decorative (see PayInstructions).
//
// Trust direction is the same rule as every other rail: an order becomes paid
// only when the rail's own authenticated read of the account says a covering
// credit arrived. Nothing the buyer tells us is evidence, including "I paid".
// only on what the bank said about the account. Nothing the buyer tells us is
// evidence, including "I paid". What the bank said reaches this rail as the
// credits file. The bank's callback adds to it within seconds, and the
// periodic pull, which reads the account on a trusted machine with the bank's
// own authentication, replaces it with what is really there.
//
// The bank is behind a CreditSource so it is swappable. That is a deliberate
// hedge and not speculative generality: the account being reconciled is also
// the shop's own bank account, so the day that relationship ends, the rail
// must survive with one new adapter rather than a rewrite.
// The rail knows nothing of any bank: it reads credits through a CreditSource.
// That is a deliberate hedge and not speculative generality: the account being
// reconciled is also the shop's own bank account, so the day that relationship
// ends, what fills the file changes and the rail does not.
module;
module Catcrafts.Server;
@ -169,8 +172,17 @@ public:
BankCredit c;
c.id = std::string(doc->Str("id"));
c.reference = std::string(doc->Str("reference"));
// How it arrived: said outright in the ledger's words, or as
// the bank's own classification with the bank it is of, which is
// then put into those words here. A line with neither is a plain
// transfer. See MakeFileCreditSource in the interface.
c.method = std::string(doc->Str("method"));
if (c.method.empty()) c.method = "sepa";
if (c.method.empty()) {
const std::string_view kind = doc->Str("kind");
const std::string_view bank = doc->Str("bank");
c.method = (!kind.empty() && !bank.empty()) ? CreditMethodFor(bank, kind)
: std::string("sepa");
}
c.amountMinor = doc->Int("amount_minor");
out.push_back(std::move(c));
}
@ -372,11 +384,12 @@ std::unique_ptr<CreditSource> MakeFileCreditSource(std::filesystem::path path) {
bool AppendCreditTo(const std::filesystem::path& creditsPath,
const BankCredit& credit) {
if (credit.id.empty()) return false;
// Deduplicate on the bank's own payment id. bunq retries a callback about
// six times, and a periodic --pull-credits reads an overlapping window, so
// the SAME payment arrives more than once by design. Appending it twice
// would double the money against one reference — enough, on a part-paid
// order, to settle it without the balance ever arriving.
// Deduplicate on the bank's own payment id. A bank retries a callback it
// got no answer to, and the periodic pull ships a file that holds the same
// payment again, so the SAME payment arrives more than once by design.
// Appending it twice would double the money against one reference —
// enough, on a part-paid order, to settle it without the balance ever
// arriving.
{
std::ifstream in(creditsPath, std::ios::binary);
std::string line;
@ -400,59 +413,6 @@ bool AppendCreditTo(const std::filesystem::path& creditsPath,
return static_cast<bool>(out);
}
std::optional<int> PullCreditsInto(CreditSource& source,
const std::filesystem::path& creditsPath) {
const std::optional<std::vector<BankCredit>> fresh = source.Recent();
if (!fresh) return std::nullopt;
// Which ids the file already holds. Append-only and deduplicated by the
// bank's own payment id, so running this twice — or on an overlapping
// window, which every run does — adds nothing the second time. That
// matters more than it sounds: the file is evidence for settling money,
// and a duplicated credit would double a payment and settle an order
// nobody paid twice for.
std::set<std::string> known;
{
std::ifstream in(creditsPath, std::ios::binary);
std::string line;
while (std::getline(in, line)) {
if (line.empty()) continue;
const auto doc = Json::Parse(line);
if (!doc || !doc->IsObject()) continue;
if (const std::string_view id = doc->Str("id"); !id.empty()) {
known.emplace(id);
}
}
}
std::string add;
int appended = 0;
for (const BankCredit& c : *fresh) {
if (c.id.empty() || known.contains(c.id)) continue;
add += std::format(
R"({{"id":"{}","reference":"{}","amount_minor":{},"method":"{}"}})"
"\n",
EscT(c.id), EscT(c.reference), c.amountMinor, EscT(c.method));
++appended;
}
if (appended == 0) return 0;
// Append rather than rewrite: the file may also hold lines an operator
// added by hand to settle something, and a rewrite would lose them.
std::ofstream out(creditsPath, std::ios::app | std::ios::binary);
if (!out) {
std::println(std::cerr, "transfer: cannot append to {}", creditsPath.string());
return std::nullopt;
}
out << add;
out.flush();
if (!out) {
std::println(std::cerr, "transfer: write to {} failed", creditsPath.string());
return std::nullopt;
}
return appended;
}
std::unique_ptr<PaymentRail> MakeTransferRail(const RailConfig& config,
std::unique_ptr<CreditSource> credits) {
if (!credits) return nullptr;

View file

@ -408,18 +408,16 @@ int main(int argc, char** argv) {
// enable successful without the rail's own load line.
// Name the right files. This message used to describe EURC's
// chains file and address pool whichever rail had failed,
// which is actively misleading for the transfer rail: the
// likeliest way IT fails is a bad BUNQ_API_KEY, and being
// told to look at a chains file sends the reader away from
// the actual cause.
// which is actively misleading for the transfer rail: what IT
// needs is the account and the name on it, and being told to
// look at a chains file sends the reader away from the cause.
if (mode == "transfer") {
std::println(std::cerr,
"catcrafts-server: WARNING: the 'transfer' rail could "
"not load — see above. Usual causes: TRANSFER_IBAN or "
"TRANSFER_BENEFICIARY unset, or a BUNQ_API_KEY that "
"bunq refused. CONTINUING WITHOUT IT: bank transfer is "
"off, so checkout offers only the other rail, and the "
"rest of the site is unaffected.");
"not load — see above. The usual cause: TRANSFER_IBAN "
"or TRANSFER_BENEFICIARY unset. CONTINUING WITHOUT IT: "
"bank transfer is off, so checkout offers only the "
"other rail, and the rest of the site is unaffected.");
} else {
std::println(std::cerr,
"catcrafts-server: WARNING: the '{}' rail could not load "
@ -441,18 +439,17 @@ int main(int argc, char** argv) {
if (!build(cryptoMode, rails.crypto)) return 2;
Server::ConfigurePayments(std::move(rails), redirectBase);
// The bunq callback, which exists because the API key's IP allowlist
// forbids this host from asking bunq anything. Off unless a secret path
// is configured.
if (const char* v = std::getenv("BUNQ_WEBHOOK_PATH"); v && *v) {
Server::ConfigureBunqCallback(transferCreditsPath, v);
// The shadow run of Nostro's callback reader beside ours
// (temporary, see ShadowCallbackVerdict). It needs no setting of
// its own, so the test starts with the deploy that carries it, and
// it decides nothing. TRANSFER_IBAN is the account it reports a
// payment as being on or not on.
// The bank's callback, which is how a transfer settles within seconds:
// this host holds no bank credential and cannot ask the bank anything.
// Off unless a secret path is configured. BANK_CALLBACK_BANK says
// whose callbacks arrive there, as a Nostro connector names the bank
// ("bunq"): which bank it is is configuration, and no code here knows.
// TRANSFER_IBAN is the account a payment has to be on to count.
if (const char* v = std::getenv("BANK_CALLBACK_PATH"); v && *v) {
const char* bank = std::getenv("BANK_CALLBACK_BANK");
const char* iban = std::getenv("TRANSFER_IBAN");
Server::ConfigureCallbackShadow(iban ? iban : "");
Server::ConfigureBankCallback(transferCreditsPath, v, bank ? bank : "",
iban ? iban : "");
}
// Invoice signing: the GPG key uid/fingerprint; GNUPGHOME decides the
@ -488,85 +485,6 @@ int main(int argc, char** argv) {
return Server::Serve(port);
}
// --pull-credits: read the bank account once and append anything new to the
// credits file the transfer rail settles from. Prints how many arrived.
//
// A SEPARATE ENTRY POINT ON PURPOSE, and the reason is the whole point of
// the design. A bunq API key can initiate payments — bunq has no read-only
// scope — so the project's rule is that it never lives on the public host.
// Run this on a trusted machine on a timer, ship the credits file over, and
// the server settles orders while holding no credential that can move a
// cent. Configuring BUNQ_API_KEY on the server works too and is simpler,
// but it is strictly worse and this program will say so when it starts.
//
// catcrafts-server --pull-credits [--orders FILE] [--credits FILE]
if (!args.empty() && args[0] == "--pull-credits") {
std::filesystem::path ordersPath = "orders.jsonl";
std::filesystem::path creditsPath;
std::filesystem::path statePath;
for (std::size_t i = 1; i < args.size(); ++i) {
const std::string_view a = args[i];
auto next = [&]() -> std::string {
return (i + 1 < args.size()) ? std::string(args[++i]) : std::string{};
};
if (a == "--orders") ordersPath = next();
else if (a == "--credits") creditsPath = next();
else if (a == "--state") statePath = next();
}
if (creditsPath.empty()) {
if (const char* v = std::getenv("TRANSFER_CREDITS"); v && *v) {
creditsPath = v;
} else {
creditsPath = ordersPath;
creditsPath += ".transfer-credits.jsonl";
}
}
if (statePath.empty()) {
if (const char* v = std::getenv("BUNQ_STATE"); v && *v) {
statePath = v;
} else {
// Hung off the CREDITS file, not the orders file, because that
// is what MakeRail does — and the two MUST agree. They did not
// at first, and the cost is not cosmetic: a machine that ran
// both this command and the server would onboard twice against
// bunq, and bunq allows as few as TEN setup calls per DAY. Two
// conventions for one file is a way to spend that budget on
// nothing.
statePath = creditsPath;
statePath += ".bunq-context.json";
}
}
Server::BunqConfig bunq;
if (const char* v = std::getenv("BUNQ_API_KEY"); v) bunq.apiKey = v;
if (const char* v = std::getenv("TRANSFER_IBAN"); v) bunq.iban = v;
if (const char* v = std::getenv("BUNQ_PERMITTED_IPS"); v) bunq.permittedIps = v;
if (bunq.apiKey.empty()) {
std::println(std::cerr,
"catcrafts-server: BUNQ_API_KEY is not set — nothing to pull "
"with. This command reads the bank account; it never pays "
"anyone.");
return 2;
}
bunq.statePath = statePath;
std::unique_ptr<Server::CreditSource> source = Server::MakeBunqCreditSource(bunq);
if (!source) return 2;
const std::optional<int> added =
Server::PullCreditsInto(*source, creditsPath);
if (!added) {
// Distinct from "nothing new": a timer that cannot tell these
// apart will report success while the shop silently stops
// noticing payments.
std::println(std::cerr,
"catcrafts-server: could not read the account — nothing was "
"written; the credits file still holds what it did");
return 1;
}
std::println("pulled {} new credit(s) into {}", *added, creditsPath.string());
return 0;
}
// --orders [FILE]: the ledger, human-shaped. And the manual transitions —
// the escape hatch for a payment confirmed out-of-band (or a refund):
// --orders FILE --mark-paid TOKEN | --mark-shipped TOKEN | --cancel TOKEN
@ -647,7 +565,6 @@ int main(int argc, char** argv) {
" [--crypto-rail=off|fake-crypto|eurc]\n"
" [--rail-state=FILE] [--redirect-base=URL]\n"
" --orders [FILE] [--mark-paid TOKEN | --mark-shipped TOKEN | --cancel TOKEN]\n"
" --pull-credits [--orders FILE] [--credits FILE] [--state FILE]\n"
"\n"
"environment: TRANSFER_IBAN selects the bank-transfer rail (no key: that is\n"
" the point), with TRANSFER_BENEFICIARY the account-holder name\n"
@ -657,10 +574,11 @@ int main(int argc, char** argv) {
" EURC_CHAINS=FILE selects the self-hosted crypto rail (also no\n"
" key); EURC_POOL=FILE of receiving addresses, default\n"
" <orders>.eurc-addresses, EURC_WINDOW_HOURS (24).\n"
" BUNQ_API_KEY + BUNQ_PERMITTED_IPS, BUNQ_STATE are for\n"
" --pull-credits. That key CAN MOVE MONEY (bunq has no read-only\n"
" scope), so run --pull-credits on a trusted machine and ship the\n"
" credits file here, rather than setting it on this host.\n"
" BANK_CALLBACK_PATH=/secret/path turns on the endpoint the bank\n"
" posts payments to, with BANK_CALLBACK_BANK the bank whose\n"
" callbacks arrive there (as Nostro names it, e.g. bunq). This\n"
" server holds no bank credential: the credits file is filled by\n"
" that endpoint and by tools/pull-and-ship-credits.sh elsewhere.\n"
" ORDER_REDIRECT_BASE, SENDCLOUD_PUBLIC_KEY/SECRET_KEY/METHOD,\n"
" INVOICE_GPG_KEY, MAIL_COMMAND (e.g. 'msmtp -t'), MAIL_FROM");
return 0;

View file

@ -142,8 +142,8 @@ export namespace Catcrafts::Server {
//
// Bank-side donations and expenses come from an aggregates file written
// by the owner's own tooling, off this box — no bank credential and no
// bank callback exists here (the bunq mutation callback was retired
// 2026-08-17; its code is in git history). Aggregates by construction:
// bank callback feeds it (the callback that once kept these numbers live
// was retired 2026-08-17; its code is in git history). Aggregates by construction:
// category totals and an as-of date are all the file can carry, which is
// the page's privacy design.
@ -425,15 +425,6 @@ export namespace Catcrafts::Server {
}
};
// Exact decimal-string-to-minor-units parser for amounts that arrive as
// strings ("614.00" -> 61400), which is how every external source quotes
// them. Rejects anything that is not a plain non-negative decimal with at
// most two fraction digits — no floats touch money on the way in, and a
// sign is refused here so it cannot quietly halve a total (see
// ParseSignedAmountToMinor, which handles the one case where the sign is
// meaningful). Exported for the self-test.
std::optional<std::int64_t> ParseAmountToMinor(std::string_view s);
// One chain the EURC rail watches. Every field is configuration because
// every field is a fact about the world rather than about this shop:
// Circle deploys to a new chain, an RPC endpoint moves, a token is
@ -534,166 +525,115 @@ export namespace Catcrafts::Server {
TransferMatch MatchCredits(std::span<const BankCredit> credits,
std::string_view reference);
// Where a transfer rail gets its incoming credits. One implementation talks
// to the bank; the suites use a file-backed one so the whole rail — payment
// instructions, matching, settlement, the window — runs with no network.
// Where a transfer rail gets its incoming credits. The one implementation
// reads a file (MakeFileCreditSource) that is filled from outside the rail:
// by the bank's callback, by the periodic pull, and in the suites by the
// suite itself, so the whole rail — payment instructions, matching,
// settlement, the window — runs with no network and no credential.
class CreditSource {
public:
virtual ~CreditSource() = default;
// nullopt = the bank could not be reached. NEVER an empty vector for
// that case: "no credits yet" and "cannot ask" must not look alike, or
// an outage would read as a shop full of unpaid orders.
// nullopt = the credits could not be read. NEVER an empty vector for
// that case: "no credits yet" and "cannot tell" must not look alike,
// or a failure would read as a shop full of unpaid orders.
virtual std::optional<std::vector<BankCredit>> Recent() = 0;
virtual std::string_view Name() const = 0;
};
// The rail itself. Takes its credit source so the bank is swappable — a
// deliberate hedge, since the account that reconciles the shop is also the
// shop's bank account, and replacing one adapter must not mean rewriting
// the rail.
// The rail itself. Takes its credit source, so that where the credits
// come from can change without the rail being rewritten: it knows nothing
// of any bank.
std::unique_ptr<PaymentRail> MakeTransferRail(const RailConfig& config,
std::unique_ptr<CreditSource> credits);
// A CreditSource reading newline-delimited JSON from a file, one credit per
// line: {"id":…,"reference":…,"amount_minor":…,"method":…}. This is how the
// suites drive real settlement, and how an operator can settle a transfer
// by hand without touching the ledger. A missing file is an EMPTY list, not
// a failure: no transfers yet is a normal state.
// line. Two shapes are read:
//
// {"id":…,"reference":…,"amount_minor":…,"method":"sepa"}
// {"id":…,"reference":…,"amount_minor":…,"bank":"bunq","kind":"EBA_SCT/SCT"}
//
// The first names how the money arrived in the ledger's own words: what
// the callback endpoint writes, what a suite writes, and what an operator
// writes to settle a transfer by hand without touching the ledger. The
// second carries the bank's own classification as the bank wrote it, with
// the bank it came from, and the method is worked out here
// (CreditMethodFor): that is what the hourly pull ships, so the script
// that makes it needs no table of any bank's words. A line with neither is
// taken for a plain transfer. A missing file is an EMPTY list, not a
// failure: no transfers yet is a normal state.
std::unique_ptr<CreditSource> MakeFileCreditSource(std::filesystem::path path);
// ── the bunq credit source ────────────────────────────────────────
struct BunqConfig {
std::string apiKey; // BUNQ_API_KEY; can MOVE MONEY, see below
std::filesystem::path statePath; // keypair + tokens, 0600
// Which account, when the key can see more than one. Compared to the
// account's IBAN ignoring spacing and case; without it a key that sees
// several active accounts is a refusal rather than a guess, because
// guessing means reconciling the shop against its savings.
std::string iban;
// Registered with bunq ONCE, at device-server time. bunq has no
// read-only key scope, so this is the only thing standing between a
// leaked key and someone spending the balance. "*" works and is
// announced loudly; an explicit egress address is what should be used.
std::string permittedIps;
int count = 50; // payments per read
};
// nullptr when no key is configured. NOTE the deployment rule that goes
// with this: a bunq key can initiate payments and bunq offers no read-only
// scope, so the project's standing policy is that it does NOT live on the
// internet-facing host. Run `--pull-credits` on a trusted machine and ship
// the credits file to the server, which then holds no credential at all.
std::unique_ptr<CreditSource> MakeBunqCreditSource(const BunqConfig& config);
// bunq's payment list -> credits. Exported for the self-test: the money
// decisions downstream are only as good as this decoding, and the HTTP
// around it is thin. Same reasoning as ParseEthCallUint.
std::vector<BankCredit> ParseBunqPayments(std::string_view json);
// Amount strings as bunq quotes them, INCLUDING the leading minus an
// outgoing payment carries. Exported because the sign is the difference
// between income and a refund, and getting it wrong would let a refund pay
// for the order it reversed.
std::optional<std::int64_t> ParseSignedAmountToMinor(std::string_view s);
// bunq's Payment.type -> the ledger's `via` vocabulary. Exported so the
// suite can pin the mapping that decides whether an order is safe to ship:
// "sepa" is final, "card" can be reversed for months.
std::string_view BunqMethodFor(std::string_view paymentType);
// ── the bunq callback (webhook) ───────────────────────────────────
// ── the bank's callback (webhook) ─────────────────────────────────
//
// bunq pushes a notification when the account changes, which is the only
// way this shop learns about money when the API key's IP allowlist forbids
// the web host from asking. Shape:
//
// {"NotificationUrl":{"category":"MUTATION",
// "object":{"Payment":{…the same Payment object…}}}}
// The bank posts a notification to an address of ours when the account
// changes, which is how a transfer settles within seconds: this host
// holds no bank credential and cannot ask. Nothing in this server knows
// how any bank writes one. The body is read by Nostro's ReadCallback (the
// module Nostro.Money of https://forgejo.catcrafts.net/Catcrafts/Nostro),
// told which bank by configuration, and comes back in no bank's terms.
//
// SECURITY, stated plainly because the design depends on understanding it:
// **bunq does not sign these.** Verified against doc.bunq.com — no HMAC, no
// server signature; certificate pinning authenticates US to bunq, not bunq
// to us. So the body is an unauthenticated claim that money arrived, and
// the only things standing between it and the ledger are transport-level:
// a source-IP allowlist for bunq's published range (185.40.108.0/22, which
// bunq warns may change), a secret path segment, and the fact that nothing
// ships without a human. Treat a callback as evidence exactly as strong as
// those controls, and keep a periodic --pull-credits as the backstop:
// bunq retries roughly six times and then drops the notification forever,
// so a backend that was down during a deploy loses that payment silently.
std::optional<BankCredit> ParseBunqCallback(std::string_view json);
// a bank need not sign a callback, and bunq does not. The body is then an
// unauthenticated claim that money arrived, and what stands between it and
// the ledger is: a source-IP allowlist in the web server for the range the
// bank publishes, a secret path segment, the check that the payment is on
// the shop's OWN account, and the fact that nothing ships without a human.
// The account check is not a formality: a bank posts to whatever address
// any of its customers registered, so someone with an account there could
// register ours for an account of their own and pay themselves. Treat a
// callback as evidence exactly as strong as those controls, and keep the
// periodic pull (tools/pull-and-ship-credits.sh) as the backstop: a bank
// retries a failed callback a few times and then drops it for good, so a
// backend that was down during a deploy loses that callback silently.
// What one callback came to.
struct BankCallbackResult {
// The credit to record: set only for money coming IN, on the shop's
// own account, with the bank's id for it.
std::optional<BankCredit> credit;
// Without a credit: why there is none. In this server's words or the
// reader's own, with nothing of the body in them, so it can be logged:
// a body holds the payer's name and IBAN, and may repeat the address
// it was posted to, which is the endpoint's secret.
std::string note;
};
// Reads what the bank a Nostro connector calls `bank` ("bunq") posted.
// `ownIban` is the account the shop is paid into, compared ignoring
// spacing and case; with none, nothing is credited. Exported for the
// suite, for the reason ParseEthCallUint is: this is where a stranger's
// bytes become a claim on an order. Does not throw.
BankCallbackResult ReadBankCallback(std::string_view bank, std::string_view body,
std::string_view ownIban);
// How a payment arrived, in the ledger's `via` words, from the bank's own
// classification of it (`kind`, as the bank wrote it: bunq's
// "EBA_SCT/SCT"). The words are "sepa" (a credit transfer), "directdebit",
// "card", "ideal", "swift", and "internal" for a payment between two
// accounts at the bank itself. They are what tells an operator whether an
// order is safe to ship: a credit transfer is final, a card payment can be
// reversed for months. A kind the bank's table has no word for is NOT
// guessed at: it comes back as the bank's own word for it where that is a
// plain word, and as "bank" otherwise. The table is Nostro's
// (PaymentMethodOf), so a payment gets one word whether the callback
// delivered it or the pull did. Does not throw.
std::string CreditMethodFor(std::string_view bank, std::string_view kind);
// Append one credit to the file the transfer rail reads, unless an entry
// with the same id is already there. Returns false on a write failure or a
// duplicate — the caller answers the webhook 200 either way, because a
// duplicate is a SUCCESS from bunq's point of view and retrying it would
// achieve nothing.
// duplicate — the caller answers the callback 200 either way, because a
// duplicate is a SUCCESS from the bank's point of view and retrying it
// would achieve nothing.
bool AppendCreditTo(const std::filesystem::path& creditsPath,
const BankCredit& credit);
// Enable the bunq callback endpoint. Both arguments are required and the
// secret must be at least 24 characters, or the endpoint stays off — see
// ParseBunqCallback for why the path IS the authentication here, and why
// that is only acceptable alongside Caddy's source-IP allowlist.
void ConfigureBunqCallback(std::filesystem::path creditsPath,
std::string secretPath);
// ── the callback shadow (temporary, since 2026-11-25) ─────────────
//
// A second reading of every bank callback, by Nostro's ReadCallback (the
// module Nostro.Money of https://forgejo.catcrafts.net/Catcrafts/Nostro,
// at its 1.1.0 release), set beside what ParseBunqCallback made of the
// same body. It decides NOTHING: the handler has answered and written its
// credit before this runs, and all that comes out is one log line.
//
// Why it exists: ParseBunqCallback is to be replaced by that reader, so
// that this repo stops carrying bunq's wire format. The reader is
// stricter. It wants a time, a counterparty and the account's own IBAN
// where ours reads four members, and when this was written nobody had run
// it on a callback bunq really sent: its shape came from a sample in
// bunq's SDK dated 2017. Ours has settled real payments since 2026-08. So
// the two run side by side until the log shows the reader agreeing on
// real payments. Then it takes over, and this goes together with
// ParseBunqCallback.
//
// The line carries no payment data, on purpose: no id, no amount, no name
// and no reference, only whether the two readings match and a few fixed
// words. A callback's body holds the payer's name and IBAN, which the
// privacy notice says this shop does not copy out of the bank, and it may
// repeat the address it was sent to, which is a secret.
//
// AGREE in method=sepa account=ours event=transactions
// AGREE out method ours=MASTERCARD nostro=card account=other event=transactions
// DIFFER nostro refused what ours reads as a payment: <nostro's sentence>
// DIFFER id=same amount=DIFFERENT reference=same in method=sepa …
//
// AGREE means the id, the amount and the reference are the same, which is
// everything settlement rests on. The method is reported beside it and is
// allowed to differ: Nostro calls bunq's MASTERCARD a card payment, where
// ours passes a type it does not know through as bunq wrote it. `account`
// says whether the payment is on `ownIban`, which ours never looked at.
//
// `ours` is what ParseBunqCallback made of the same body, `bank` what a
// Nostro connector to the bank is called ("bunq"), and `ownIban` the
// account the shop is paid into; empty reports the account as unknown.
// Whatever the reading or the comparison throws is caught and becomes the
// verdict, in words that are not the body's.
std::string ShadowCallbackVerdict(std::string_view bank, std::string_view body,
const std::optional<BankCredit>& ours,
std::string_view ownIban);
// Turn the shadow on for the callback endpoint, naming the shop's own
// account. Without this call the endpoint behaves exactly as it did.
void ConfigureCallbackShadow(std::string ownIban);
// One pull: read the account and append every credit not already in the
// file to it, newest last. Returns the number appended, or nullopt if the
// bank could not be reached. This is what `--pull-credits` runs, and it is
// deliberately a separate entry point from the rail so the machine holding
// the key need not be the machine serving the shop.
std::optional<int> PullCreditsInto(CreditSource& source,
const std::filesystem::path& creditsPath);
// Enable the callback endpoint. All four are required and the secret must
// be at least 24 characters, or the endpoint stays off: the path IS the
// authentication (see above), which is only acceptable alongside the web
// server's source-IP allowlist; without the bank's name nothing can be
// read, and without the account nothing can be credited.
void ConfigureBankCallback(std::filesystem::path creditsPath, std::string secretPath,
std::string bank, std::string ownIban);
// ── shipping rates ────────────────────────────────────────────────
//