bank: run Nostro's callback reader beside ours, as a shadow
All checks were successful
Deploy / build-deploy (push) Successful in 7m33s

ParseBunqCallback is to be replaced by ReadCallback of Nostro.Money
(Nostro 1.1.0), so that this repo stops carrying bunq's wire format.
That reader is stricter than ours: it wants a time, a counterparty and
the account's own IBAN where ours reads four members, and nobody has
run it on a callback bunq really sent. Ours has settled real payments
since 2026-08. So before anything is swapped, both run.

- The handler is untouched and still decides alone. Once it has
  answered and written its credit, Nostro's reader reads the same body
  and one line goes to the log: `bank callback shadow: AGREE ...` when
  the id, the amount and the reference are the same in both readings,
  and `DIFFER ...` with what parted them otherwise.
- The line carries no payment data: no id, amount, name or reference,
  only whether values match and a few fixed words. A body holds the
  payer's name and IBAN, and may repeat the secret address.
- It is on wherever BUNQ_WEBHOOK_PATH is set, with no setting of its
  own.
- project.cpp takes Nostro with --product=money --banks=bunq, at the
  commit of its 1.1.0 release: the module alone, which brings no
  credential and no Crafter.Network, Crafter.DB or OpenSSL of its own.

ShouldCompareCallbackReaders pins every verdict, and that none repeats
anything a body carried. ShouldReceiveBankCallbacks posts callbacks to
the real endpoint: an order settles from one, a payment Nostro's reader
refuses is credited all the same, and the server's log holds nothing of
what was posted.

Built 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 the same way without this change
where the post media is not mirrored. The binary needs the same shared
libraries as before.

Temporary: once real payments read AGREE the reader takes over, and
this goes together with ParseBunqCallback. deploy/README.md says how to
read the result.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Jorijn van der Graaf 2026-11-25 14:21:55 +01:00
commit 36a635fd48
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
8 changed files with 906 additions and 5 deletions

View file

@ -0,0 +1,179 @@
/*
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

@ -82,6 +82,11 @@ std::string gRedirectBase = "https://catcrafts.net";
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;
// The bank-derived aggregates for /financials live in Catcrafts.Server-
// Financials.cpp, which owns their file. They are read through
// CurrentFinancials() per request rather than cached: unlike the content
@ -703,6 +708,32 @@ HTTPResponse HandleBunqCallback(const HTTPRequest& req) {
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 (...) {
}
}
}
HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) {
HTTPResponse res;
@ -1153,6 +1184,17 @@ void ConfigureBunqCallback(std::filesystem::path creditsPath, std::string secret
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.
std::println(std::cerr,
"bank callback shadow: on, Nostro's reader runs beside ours and "
"decides nothing (own account {})",
gShadowIban.empty() ? "not named" : "named");
}
bool CryptoPaymentAvailable() { return gRails.crypto != nullptr; }
bool BankPaymentAvailable() { return gRails.bank != nullptr; }
@ -1391,7 +1433,14 @@ 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) return HandleBunqCallback(req);
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;
}
}
}
// A POST to a product page is a checkout submission.

View file

@ -446,6 +446,13 @@ int main(int argc, char** argv) {
// 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.
const char* iban = std::getenv("TRANSFER_IBAN");
Server::ConfigureCallbackShadow(iban ? iban : "");
}
// Invoice signing: the GPG key uid/fingerprint; GNUPGHOME decides the

View file

@ -639,6 +639,54 @@ export namespace Catcrafts::Server {
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