catcrafts.net/server/implementations/Catcrafts.Server-BankCallback.cpp
Jorijn van der Graaf 33ce8f45d8
All checks were successful
Deploy / build-deploy (push) Successful in 7m20s
bank: Nostro reads the bank's callback, and the shop's bunq code is gone
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>
2026-11-25 15:08:42 +01:00

206 lines
8.5 KiB
C++

/*
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