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

@ -379,84 +379,146 @@ matching credit appears on the account. The order page is the payment page.
with `--mark-paid`. The server logs exactly this when it lapses one.
- `TRANSFER_CREDITS` (default `<orders>.transfer-credits.jsonl`) — where the
rail reads incoming credits from. One JSON object per line:
`{"id":"…","reference":"…","amount_minor":2500,"method":"sepa"}`. A missing
file is an empty list, not an error, since a shop that has taken no
transfers yet has no file.
`{"id":"…","reference":"…","amount_minor":2500,"method":"sepa"}`. In place of
`method` a line may carry the bank's own word for the payment and the bank
it is of (`"bank":"bunq","kind":"EBA_SCT/SCT"`), which the server puts into
the `via` words itself: that is what the hourly pull ships. A missing file
is an empty list, not an error, since a shop that has taken no transfers yet
has no file.
#### Filling the credits file
Two things write it, and neither puts a bank key on the web host: the bunq
webhook, which the server receives itself, and an hourly pull on a trusted
Two things write it, and neither puts a bank key on the web host: the bank's
callback, which the server receives itself, and an hourly pull on a trusted
machine, which asks nostrod and ships the result. The next section has both.
Every line carries bunq's own payment id. The webhook skips an id the file
already holds, and the pull replaces the file with one line per payment, so a
payment that both deliver is counted once and cannot settle an order nobody
paid twice for.
Every line carries the bank's own id for the payment. The callback skips an id
the file already holds, and the pull replaces the file with one line per
payment, so a payment that both deliver is counted once and cannot settle an
order nobody paid twice for.
The server knows no bank. What a bank posts is read by `ReadCallback`, and how
a payment arrived is said by `PaymentMethodOf`, both of the module
`Nostro.Money` of [Nostro](https://forgejo.catcrafts.net/Catcrafts/Nostro),
which `project.cpp` builds in at the commit of a Nostro release. That module
holds no credential. Which bank it is is configuration, in two places:
`--banks=` in `project.cpp`, for what the build can read, and
`BANK_CALLBACK_BANK` on the server, for what arrives.
#### How settlement actually reaches the shop
Two paths, and the split is deliberate.
**Primary: the bunq webhook.** bunq pushes a `MUTATION` notification when money
lands; the backend decodes the payment and appends it to the credits file, and
the reconciler settles from there. Normally seconds end to end. Registered with
`tools/register-bunq-webhook.sh` from a machine bunq's key permits (`--show`
lists what is registered, with the secret redacted). **That call REPLACES the
whole filter set**, so look before overwriting. The script needs an
authenticated bunq session for it, and takes that from this repo's own bunq
client: see "The old reader" below. Since its 1.1.0 Nostro lists and changes
callbacks itself (`nostro callbacks`, through nostrod), which is what replaces
this script.
**Primary: the bank's callback.** The bank posts a notification when money
lands; the backend has the payment read, appends it to the credits file, and
the reconciler settles from there. Normally seconds end to end. In
`payments.env`:
**bunq does not sign these notifications** — verified against doc.bunq.com: no
HMAC, no server signature, and certificate pinning authenticates us to bunq
rather than bunq to us. So the endpoint's authentication is three transport-level
controls, all of which have to stay in place:
- `BANK_CALLBACK_PATH=/hooks/bunq/<long random>`: the secret address the bank
posts to. Unset means the endpoint does not exist.
- `BANK_CALLBACK_BANK=bunq`: whose callbacks arrive there, as a Nostro
connector names the bank. Without it the endpoint stays off, and the startup
log says so: an endpoint that answered the bank and credited nothing would
look like working.
- `TRANSFER_IBAN`, above, is also the account a payment has to be on.
The startup log confirms it with `bank callback: enabled on a secret path`.
Where the bank posts is registered at the bank, with Nostro (1.1.0 or later),
on the machine where nostrod holds the connection:
```sh
nostro callbacks --connector NAME # what is registered, each address whole
nostro callbacks add --connector NAME # asks for the https address at a prompt
nostro callbacks remove --connector NAME # asks for the address, as listed
```
Each asks for your password, the listing too: the address is a secret. The
listing shows what is registered whoever set it. The registration in place on
2026-11-25 was made with a script this repo carried until then, and
`nostro callbacks` had not been run against it yet.
**A callback is not signed.** bunq's are not: verified against doc.bunq.com,
there is no HMAC and no server signature, and certificate pinning
authenticates us to bunq rather than bunq to us. So the endpoint's
authentication is the controls around it, all of which have to stay in place:
1. **Source-IP allowlist** for `185.40.108.0/22` in the Caddyfile. This is the
strong one: forging requires completing a TLS handshake from inside that
range. bunq warns the range may change; if it does, callbacks 403 and
settlement stops — it fails closed.
2. **A secret path.** Caddy matches only the non-secret prefix `/hooks/bunq/*`,
so the secret lives solely in `BUNQ_WEBHOOK_PATH` in `payments.env` and not
so the secret lives solely in `BANK_CALLBACK_PATH` in `payments.env` and not
in the web server config. The backend compares it in constant time, and a
non-POST to it falls through to an ordinary 404 rather than a distinctive
405 — a different answer there would confirm a guessed path.
3. **`log_skip` on that prefix.** Without it the secret would be written to the
access log and then ingested into the GoAccess database and shown in its
top-URLs panel, i.e. leaked to anyone who opens `/analytics/`.
4. **The account.** A bank posts to whatever address any of its customers
registered. Someone with an account at bunq could register this address for
an account of their own and pay themselves, and the callback that follows
would be bunq's own, from bunq's range. So only a payment on
`TRANSFER_IBAN` is credited.
The handler deliberately does the least it can: decode one payment, append it,
answer 200. It makes no settlement decision, so a forged callback can at worst
manufacture a credit line — it cannot bypass the reference match or the
covering-amount rule, and nothing ships without a human either way.
The handler deliberately does the least it can: have one payment read, append
it, answer 200. It makes no settlement decision, so a forged callback can at
worst manufacture a credit line — it cannot bypass the reference match or the
covering-amount rule, and nothing ships without a human either way. And a
credit line that never was a payment is gone at the next pull, which replaces
the file with what the bank says is on the account.
**Backstop: the hourly pull.** Not optional. bunq retries a callback about six
times and then drops it permanently, so a payment arriving while the backend
restarts — every deploy is a restart — is lost to the webhook with no error
anywhere. `deploy/catcrafts-credits.timer` runs `pull-and-ship-credits.sh`
hourly to turn that from a missing donation into an hour of delay.
Every callback leaves one line in the journal, with nothing of the payer in it:
**The pull holds no key.** A bunq API key can **initiate payments**, and bunq
offers no read-only scope, so there is no such thing as a key that can only
read. Since 2026-11-21 the pull therefore holds none. The bank connection lives
in [nostrod](https://forgejo.catcrafts.net/Catcrafts/Nostro) on a trusted
machine, under a system user of its own, and
**`tools/pull-and-ship-credits.sh`** asks it over the system bus for the
account's recent transactions (`Transactions` on `net.catcrafts.Nostro1`, the
interface Nostro publishes for other programs). nostrod lets a program look
without a password and lets nothing pay or change anything without one, which
is the read-only scope bunq lacks. A systemd USER timer runs the script
(`deploy/catcrafts-credits.{service,timer}`, install instructions in the
service file).
```
bank callback: credited 25.00 via sepa (id …)
bank callback: nothing credited: the payment was credited before, or …
bank callback: nothing credited: the payment is not money coming in
bank callback: nothing credited: the payment is on another account than the shop's
bank callback: nothing credited: the body was refused: <the reader's sentence>
```
`the body was refused` where a payment was expected is the line to act on: the
bank sent a shape Nostro's reader does not take. The pull still settles that
payment, the sentence names the check that failed, and the fix is Nostro's.
**How a payment arrived** is the ledger's `via`: `sepa` (a credit transfer),
`ideal`, `card`, `directdebit`, `swift`, and `internal` for a payment from
another account at the bank itself. A kind the table has no word for is not
guessed at and shows as the bank's own word: `ADYEN` is a bunq.me payment link,
which either a card or iDEAL may have paid. That column is what tells you
whether an order is safe to ship: a credit transfer is final, a card payment
can be reversed for months. Orders settled before 2026-11-25 say `bunq` where
newer ones say `internal`, and would have said `MASTERCARD` for `card`.
**Backstop: the hourly pull.** Not optional. A bank retries a callback a few
times (bunq: five, a minute apart) and then drops it permanently, so a payment
arriving while the backend restarts — every deploy is a restart — is lost to
the callback with no error anywhere. `deploy/catcrafts-credits.timer` runs
`pull-and-ship-credits.sh` hourly to turn that from a missing donation into an
hour of delay. It is also the one path that asks the bank with the bank's own
authentication.
**The pull holds no key.** A key that can read a bank account can as a rule
also pay from it (a bunq API key can, and bunq offers no read-only scope), so
the pull holds none. The bank connection lives in
[nostrod](https://forgejo.catcrafts.net/Catcrafts/Nostro) on a trusted machine,
under a system user of its own, and **`tools/pull-and-ship-credits.sh`** asks it
over the system bus for the account's recent transactions (`Transactions` on
`net.catcrafts.Nostro1`, the interface Nostro publishes for other programs).
nostrod lets a program look without a password and lets nothing pay or change
anything without one, which is the read-only scope the bank lacks. A systemd
USER timer runs the script (`deploy/catcrafts-credits.{service,timer}`, install
instructions in the service file).
The script turns nostrod's answer into credit lines and ships **incoming
credits only** to the file the rail reads. Outgoing lines are supplier payments
and card spending: the matcher ignores negative amounts, so shipping them would
put the business's outgoing payment history on a public-facing host for no
settlement benefit. It ships nothing when the read failed, and it never
overwrites the remote with an empty file, so a failure leaves the server
settling from the last good copy rather than from nothing.
settlement benefit. A line carries the payment's kind as the bank wrote it and
the bank's name as nostrod has it, and the server puts that into the `via`
words above, so the script knows no bank either. It ships nothing when the read
failed, and it never overwrites the remote with an empty file, so a failure
leaves the server settling from the last good copy rather than from nothing.
Each run ships the last 90 days (`CREDITS_DAYS`). That is the longest
`TRANSFER_WINDOW_HOURS` the server accepts, so no order can still be waiting
@ -492,13 +554,13 @@ them pay: paying and changing stay behind the password. With the rule in place,
**Why the server does not read the bank itself.** Besides the key policy above,
a standard bunq API key works only from the address it was registered at, and
**bunq enforces that on every request, not only at device registration**.
Verified the hard way on 2026-08-20, with this repo's own reader: registering
the server's address in the device's `permitted_ips` did not help (the device
registered fine from home with both addresses listed), and every read from the
server still came back `"Incorrect API key or IP address"`.
Verified the hard way on 2026-08-20, with the reader this repo had then:
registering the server's address in the device's `permitted_ips` did not help
(the device registered fine from home with both addresses listed), and every
read from the server still came back `"Incorrect API key or IP address"`.
Latency, so nobody wonders: through the webhook a fresh order confirms within
the reconciler's own 60 s cadence of the money landing. A payment the webhook
Latency, so nobody wonders: through the callback a fresh order confirms within
the reconciler's own 60 s cadence of the money landing. A payment the callback
lost waits for the next hourly pull on top of that. Orders more than two hours
old back off to a ten-minute poll, so an older one can take that long.
@ -507,110 +569,9 @@ Two operational notes. The timer only runs while that machine is awake, so
every window it missed. And when the connection in nostrod stops working
(`nostro connectors` says whether it does: a revoked key, or an IP-restricted
key after the home address changed), the pull fails and its unit says so, but
nothing tells the shop. Settlement then rests on the webhook alone, so a
nothing tells the shop. Settlement then rests on the callback alone, so a
failing `catcrafts-credits` unit is worth noticing.
#### The callback shadow (temporary, since 2026-11-25)
The webhook's parser (`ParseBunqCallback`) is to be replaced by Nostro's
`ReadCallback`, so that this repo stops carrying bunq's wire format. That
reader is stricter than ours and had never been run on a callback bunq really
sent, while ours has settled real payments since 2026-08. So for now both run:
ours decides exactly as before, and Nostro's reads the same body afterwards and
logs what it made of it. It cannot change the answer or the credit, and it
turns on by itself wherever `BUNQ_WEBHOOK_PATH` is set.
Read the result on the server, after any payment in or out of the account:
```sh
journalctl -u catcrafts-server | grep 'bank callback shadow'
```
- `AGREE in method=sepa account=ours event=transactions`: both readers read
the same id, amount and reference. This line on a real incoming transfer is
what the test is for.
- `AGREE … method ours=MASTERCARD nostro=card …`: still agreement. Only the
name for how the money arrived differs, which is expected for card payments.
- `account=other`: the payment is on another account than `TRANSFER_IBAN`. Our
parser never looked at that, and the replacement must.
- `DIFFER nostro refused what ours reads as a payment: <sentence>`: Nostro's
reader would have dropped a payment ours credited. The sentence names the
check that failed, and that is a fix for Nostro, not for this repo.
- `DIFFER id=… amount=… reference=…`: both read a payment and not the same one.
The line carries no payment data: no id, no amount, no name and no reference.
`ShouldCompareCallbackReaders` pins the verdicts and
`ShouldReceiveBankCallbacks` the endpoint, including that a payment Nostro's
reader refuses is credited all the same.
When real payments read `AGREE`, the reader takes over, and the shadow goes
together with `ParseBunqCallback`
(`server/implementations/Catcrafts.Server-CallbackShadow.cpp` and its call in
`Catcrafts.Server-Http.cpp`). Nostro's module is built in through
`project.cpp`, named at the commit of its 1.1.0 release.
#### The old reader: `--pull-credits`
`catcrafts-server --pull-credits` is this repo's own bunq client. It onboards
with the API key, keeps its context in a file, reads the account's newest
payments and appends them to a credits file, deduplicated by bunq's payment id.
It was the pull until 2026-11-21. Nothing runs it on a schedule any more, and
it is still here for one job: `tools/register-bunq-webhook.sh` needs a bunq
session to list or replace the notification filter, and takes it from this
reader's context file. Nostro does the same with no key in this checkout since
its 1.1.0 (`nostro callbacks`). Once that command has been seen to list the
shop's webhook, the reader, its key in `.env` and that script can all go.
The session in the context file expires, so refresh it right before using the
script, on a machine the key permits:
```sh
BUNQ_API_KEY=… TRANSFER_IBAN=NL.. \
bin/Catcrafts.Server-*/catcrafts-server --pull-credits \
--orders ~/.cache/catcrafts/orders.jsonl
# -> pulled 2 new credit(s) into ~/.cache/catcrafts/orders.jsonl.transfer-credits.jsonl
```
**The webhook was registered with this reader's key.** bunq's documentation
does not say whether a registration outlives the key that made it, so do not
revoke that key before `nostro callbacks` lists the webhook through the
connection nostrod holds, and look again after revoking it: if it is gone,
`nostro callbacks add` sets it again. Otherwise settlement may quietly fall
back to the hourly pull alone.
What the reader costs is the reason it is no longer the pull. Its key
(`BUNQ_KEY` in the repo-root `.env`) can **initiate payments**, and every
program run in that checkout can read it. Two things follow for as long as it
exists:
1. **Never put it on the server.** Setting `BUNQ_API_KEY` in `payments.env`
makes the rail run this same reader in-process instead of reading the
credits file. That puts a credential that can spend the account on a public
host, the startup log prints a warning saying exactly that, and with an
IP-restricted key it does not even work (see above). The server settles
orders while holding **no credential that can move a cent**, the same rule
the EURC rail follows by never holding a wallet key.
2. **Pin it.** `BUNQ_PERMITTED_IPS` is the egress address of the machine that
holds the key. bunq registers it once, at device-server time, and it is the
only thing standing between a leaked key and someone spending the balance.
The default is `*`, which works and is announced loudly. Changing it later
means deleting the context file and re-onboarding.
Its other settings: `BUNQ_STATE` (default `<credits>.bunq-context.json`) holds
the generated RSA keypair and the session tokens at 0600. **Deleting it forces
a re-onboard**, and bunq allows as few as ten setup calls PER DAY, so do not
delete it casually. If the key can see more than one active account,
`TRANSFER_IBAN` picks which; without it, a key seeing several accounts is a
refusal rather than a guess, because guessing means reconciling the shop
against its savings.
Rate limits worth respecting, whoever reads: bunq caps reads at roughly **3 GET
per 3 seconds** per method. One pull is a handful of requests (nostrod waits a
429 out by itself), and the rail shares a single read of the credits file
across all orders in a sweep, so neither path is anywhere near the cap. What
WOULD hit it is retrying the old reader's onboarding calls in a loop; its
context file is what prevents that.
The file source stays regardless — it is how the suites drive real settlement
with no network, and it is the manual escape hatch for settling a transfer by
hand. `--mark-paid` remains the other one.
@ -758,10 +719,18 @@ a fact about the rails rather than a difference in standard.
rail has no provider to authenticate to, so there is nothing to call and no
secret to hold. The suite drives the REAL transfer rail — not a stand-in — and
plays the part of the bank by writing a credits line, the same file the
webhook and the hourly pull fill in production. It covers the whole lifecycle: the order
page's account details, the reference in all the mangled forms a payer might
type, partial payments accumulating, an outgoing amount being ignored, and the
reconciler flipping the order to paid with the right `via`.
bank's callback and the hourly pull fill in production. It covers the whole
lifecycle: the order page's account details, the reference in all the mangled
forms a payer might type, partial payments accumulating, an outgoing amount
being ignored, and the reconciler flipping the order to paid with the right
`via`.
**`ShouldReceiveBankCallbacks` is its counterpart for the callback endpoint**,
and needs nothing either: it plays the bank by posting to the endpoint. An
order settles from a callback, a payment on another account or one the reader
refuses credits nothing, and the server's log repeats nothing a callback
carried. What the reader makes of each shape is pinned in
`ShouldReadBankCallbacks`.
**`ShouldSettleEurcOnTestnet` is the one live-counterparty suite**: a €1
donation paid with 1 real testnet EURC on Ethereum Sepolia, settled by the same

View file

@ -1,10 +1,9 @@
# Read the bank and hand the incoming credits to the server.
#
# A USER unit, on the machine where nostrod holds the bunq connection, NOT on
# the web host. The web host cannot call bunq at all (the key is IP-restricted
# at the key level and bunq enforces it on every request), and it should not be
# able to: a bunq key can initiate payments, because bunq offers no read-only
# scope. So the server only ever reads a file.
# A USER unit, on the machine where nostrod holds the bank connection, NOT on
# the web host. The web host holds no key to the bank, and should not: a key
# that can read the account can as a rule also pay from it. So the server only
# ever reads a file.
#
# This unit holds no key either. tools/pull-and-ship-credits.sh asks nostrod
# (https://forgejo.catcrafts.net/Catcrafts/Nostro) over the system bus, and

View file

@ -1,12 +1,12 @@
# Hourly, because this is now the BACKSTOP rather than the primary path.
#
# Since the bunq webhook landed, a payment normally settles within seconds: bunq
# pushes it, the handler writes the credit, the reconciler picks it up. This
# timer exists for the case the webhook cannot cover — bunq retries a callback
# roughly six times over a few minutes and then DROPS IT FOREVER, so a payment
# that arrives while the backend is restarting (every deploy is a restart) is
# lost to the webhook with no error anywhere. An hourly pull turns that from a
# silently missing donation into an hour of delay.
# A payment normally settles within seconds: the bank posts a callback, the
# handler writes the credit, the reconciler picks it up. This timer exists for
# the case the callback cannot cover — a bank retries a callback a few times
# over a few minutes and then DROPS IT FOREVER, so a payment that arrives while
# the backend is restarting (every deploy is a restart) is lost to the callback
# with no error anywhere. An hourly pull turns that from a silently missing
# donation into an hour of delay.
#
# It was five minutes while the pull WAS the settlement path. Hourly is the
# right cadence for a safety net, and it keeps the noise down.
@ -14,7 +14,7 @@
# Persistent=true so a laptop that was asleep pulls once on waking instead of
# silently skipping every window it missed.
[Unit]
Description=Backstop pull of bunq credits for catcrafts.net (hourly)
Description=Backstop pull of bank credits for catcrafts.net (hourly)
[Timer]
OnBootSec=2min

View file

@ -87,8 +87,8 @@ static Configuration* SharedLibrary(std::span<const std::string_view> args) {
// Catcrafts.ServerCore — every implementation unit of the server except
// main.cpp, as a static library. The split exists for the tests: a test can
// only LINK a library-type dependency (crafter-build exports -L/-l for
// libraries alone), and the bunq/EURC/Sendcloud parsers and the invoice
// builder all live here. The exe is main.cpp plus this library, so the
// libraries alone), and the bank-callback/EURC/Sendcloud readers and the
// invoice builder all live here. The exe is main.cpp plus this library, so the
// split costs nothing at deploy time.
//
// Same `static unique_ptr` convention as SharedLibrary, and the same warning:
@ -108,15 +108,14 @@ static Configuration* ServerCore(std::span<const std::string_view> args, Configu
std::array<fs::path, 1> ifaces = {
"server/interfaces/Catcrafts.Server",
};
std::array<fs::path, 11> impls = {
std::array<fs::path, 10> impls = {
"server/implementations/Catcrafts.Server-Http",
"server/implementations/Catcrafts.Server-Orders",
"server/implementations/Catcrafts.Server-Rails",
"server/implementations/Catcrafts.Server-Invoice",
"server/implementations/Catcrafts.Server-Eurc",
"server/implementations/Catcrafts.Server-Transfer",
"server/implementations/Catcrafts.Server-Bunq",
"server/implementations/Catcrafts.Server-CallbackShadow",
"server/implementations/Catcrafts.Server-BankCallback",
"server/implementations/Catcrafts.Server-Shipping",
"server/implementations/Catcrafts.Server-Mail",
"server/implementations/Catcrafts.Server-Financials",
@ -124,14 +123,12 @@ static Configuration* ServerCore(std::span<const std::string_view> args, Configu
core->GetInterfacesAndImplementations(ifaces, impls);
// The rails reach the outside world over TLS, which is what libssl is for.
// libcrypto is named EXPLICITLY again because the bunq credit source signs
// every request body with RSA-SHA256 through EVP: relying on it arriving as
// libssl's transitive dependency worked while nothing called EVP directly,
// and would break confusingly the moment a linker ordered them otherwise.
// On the lib rather than the exe because link flags propagate to consumers
// — the exe and every test get them from here.
// Nothing in this library calls libcrypto itself any more (the bank client
// that signed its requests through EVP is gone), so it is no longer named
// here: what Crafter.Network needs of it, Crafter.Network names. On the lib
// rather than the exe because link flags propagate to consumers — the exe
// and every test get them from here.
core->linkFlags.push_back("-lssl");
core->linkFlags.push_back("-lcrypto");
return core.get();
}
@ -180,13 +177,14 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
.args = netArgs,
});
// Nostro.Money: the part of Nostro (the bank library this shop's own
// bunq code is being replaced by) that reads what a bank posts to a
// callback's address. `--product=money` is that module alone: it holds
// no credential and brings no Crafter.Network, Crafter.DB or OpenSSL
// of its own, which is why it can sit in this server at all. Nostro's
// full library pins Crafter.Network at a commit and without QUIC, and
// loading it here would stop the build on two builds of one module.
// Nostro.Money: the part of Nostro (a bank library) that reads what a
// bank posts to a callback's address and says how a payment arrived.
// `--product=money` is that module alone: it holds no credential and
// brings no Crafter.Network, Crafter.DB or OpenSSL of its own, which
// is why it can sit in this server at all. Nostro's full library pins
// Crafter.Network at a commit and without QUIC, and loading it here
// would stop the build on two builds of one module. `--banks=` is the
// one place this build says which bank's formats it wants read.
//
// Named at the commit of the 1.1.0 release, not at a branch. This is
// code that reads claims about money, so what is built is what was
@ -262,8 +260,7 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.AddTest("ShouldFoldTheOrderLedger").Dependencies({ core, shared });
cfg.AddTest("ShouldIssueEurcAddresses").Dependencies({ core, shared });
cfg.AddTest("ShouldMatchBankTransfers").Dependencies({ core, shared });
cfg.AddTest("ShouldParseBunqPayments").Dependencies({ core, shared });
cfg.AddTest("ShouldCompareCallbackReaders").Dependencies({ core, shared });
cfg.AddTest("ShouldReadBankCallbacks").Dependencies({ core, shared });
// ── black-box suites (the tools/e2e.sh port) ──────────────────
// Each spawns the REAL binary — depending on &cfg is what builds it
@ -313,11 +310,9 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
.Timeout(std::chrono::seconds(180));
// The callback endpoint itself, over real HTTP: what the bank posts is
// credited by our own parser exactly as before, an order settles from
// it, and the shadow run of Nostro's reader beside it says what it
// made of the same body without being able to change any of that.
// No secret and no network, like the suite above. It waits out the
// reconciler once.
// read and credited, an order settles from it, and what is not a
// payment to the shop's own account credits nothing. No secret and no
// network, like the suite above. It waits out the reconciler once.
cfg.AddTest("ShouldReceiveBankCallbacks", harness)
.Dependencies({ &cfg, shared, network }).Args({ serverBin })
.Timeout(std::chrono::seconds(180));

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,67 +675,34 @@ 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());
// 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";
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;
}
// 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";
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;
}
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.
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 (...) {
}
}
}
HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) {
HTTPResponse res;
@ -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 ────────────────────────────────────────────────
//

View file

@ -1,269 +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's verdict: what Nostro's reader makes of a bank callback
// beside what our own parser made of it (ShadowCallbackVerdict). Temporary,
// like the shadow itself.
//
// Three things are held here, and the third is the one that must not regress:
//
// * AGREE is said when, and only when, the id, the amount and the reference
// are the same in both readings. Those are what settlement rests on.
// * Each way the two can part is said in words that tell them apart: Nostro
// refusing a body ours reads, reading none where ours does, reading one
// where ours does not, and reading another value.
// * NOTHING OF THE BODY COMES OUT. The verdict goes to the server's log, and
// a callback holds the payer's name and IBAN and may repeat the secret
// address it was posted to. Every verdict this suite produces is searched
// for the values its bodies carry.
//
// The bodies are made up. Their shape is bunq's own sample of a MUTATION
// callback (bunq/sdk_python, tests/assets/NotificationUrlJsons/Mutation.json),
// which is also what Nostro's reader was written against. Whether bunq still
// writes one like it is exactly what the shadow is in production to find out,
// and no suite can.
import std;
import Catcrafts.Shared;
import Catcrafts.Server;
using namespace Catcrafts;
namespace {
int failures = 0;
void Check(bool ok, std::string_view what, std::string_view got = {}) {
if (ok) return;
++failures;
std::println(std::cerr, "FAIL: {}{}{}", what,
got.empty() ? "" : " got: ", got);
}
// Not real accounts, and not the shop's: see ShouldSettleBankTransfers.
constexpr std::string_view kOwnIban = "NL00TEST0123456789";
constexpr std::string_view kOtherIban = "NL00OTHR0000000002";
// Every value below that a verdict must never repeat.
constexpr std::string_view kSecrets[] = {
"SECRETMARK", "CC-2B6457", "4155999", "570", "24.95", "NL00", "Payer",
"shop.invalid", "bad type",
};
struct Sent {
std::string_view id = "4155999";
std::string_view type = "EBA_SCT";
std::string_view description = "CC-2B6457";
std::string_view value = "570.43";
std::string_view account = kOwnIban; // the payment's own side
};
// A callback as bunq's sample has one: the envelope with the address it was
// sent to, and a Payment with both sides on it.
std::string Callback(const Sent& s) {
return std::format(R"({{
"NotificationUrl": {{
"target_url": "https://shop.invalid/hooks/SECRETMARK",
"category": "MUTATION",
"event_type": "MUTATION_CREATED",
"object": {{"Payment": {{
"id": {},
"created": "2026-11-25 10:15:30.498520",
"updated": "2026-11-25 10:15:30.498520",
"monetary_account_id": 42,
"amount": {{"currency": "EUR", "value": "{}"}},
"description": "{}",
"type": "{}",
"alias": {{"iban": "{}", "display_name": "SECRETMARK Shop", "country": "NL"}},
"counterparty_alias": {{"iban": "NL00PAYR0000000001",
"display_name": "SECRETMARK Payer", "country": "NL"}}
}}}}
}}
}})", s.id, s.value, s.description, s.type, s.account);
}
// The four members our own parser reads, and nothing else: the shape this
// repo's suites have always used for a callback, which Nostro's reader
// refuses for what it lacks.
constexpr std::string_view kReduced = R"({
"NotificationUrl": {
"category": "MUTATION",
"object": {"Payment": {
"id": 4155999,
"type": "EBA_SCT",
"description": "CC-2B6457",
"amount": {"currency": "EUR", "value": "570.43"}
}}
}
})";
std::vector<std::string> verdicts;
// The verdict on `body`, with our own parser's reading of the same body, as
// the server calls it.
std::string Verdict(std::string_view body, std::string_view ownIban = kOwnIban,
std::string_view bank = "bunq") {
const std::optional<Server::BankCredit> ours = Server::ParseBunqCallback(body);
verdicts.push_back(Server::ShadowCallbackVerdict(bank, body, ours, ownIban));
return verdicts.back();
}
void Equal(const std::string& got, std::string_view want, std::string_view what) {
Check(got == want, what, got);
}
void Has(const std::string& got, std::string_view part, std::string_view what) {
Check(got.find(part) != std::string::npos, what, got);
}
} // namespace
int main() {
// ── the two readings agree ────────────────────────────────────────
Equal(Verdict(Callback({})),
"AGREE in method=sepa account=ours event=transactions",
"an incoming transfer on the shop's account reads the same both ways");
Equal(Verdict(Callback({}), "nl00 test 0123 4567 89"),
"AGREE in method=sepa account=ours event=transactions",
"the shop's IBAN is compared as a person wrote it down");
Equal(Verdict(Callback({ .account = kOtherIban })),
"AGREE in method=sepa account=other event=transactions",
"a payment on another account is said to be on another account");
Equal(Verdict(Callback({}), ""),
"AGREE in method=sepa account=unknown event=transactions",
"with no account named, whose it is on is not guessed");
Equal(Verdict(Callback({ .value = "-24.95" })),
"AGREE out method=sepa account=ours event=transactions",
"money going out keeps its sign in both readings");
// ── the method, which may differ without the readings differing ───
Equal(Verdict(Callback({ .type = "IDEAL" })),
"AGREE in method=ideal account=ours event=transactions", "iDEAL");
Equal(Verdict(Callback({ .type = "BUNQ" })),
"AGREE in method=bunq account=ours event=transactions",
"between two bunq accounts");
Equal(Verdict(Callback({ .type = "MASTERCARD", .value = "-24.95" })),
"AGREE out method ours=MASTERCARD nostro=card account=ours event=transactions",
"a card payment, which ours passes through and Nostro names, is still AGREE");
Equal(Verdict(Callback({ .type = "ADYEN" })),
"AGREE in method=ADYEN account=ours event=transactions",
"a type neither table has is the bank's own word in both");
Equal(Verdict(Callback({ .type = "" })),
"AGREE in method=bank account=ours event=transactions",
"no type at all is 'bank' in both");
{
const std::string v = Verdict(Callback({ .type = "bad type!" }));
Has(v, "method=?", "a type that is no bank's word is not printed");
Has(v, "AGREE in ", "and the readings still agree");
}
// ── Nostro refuses what ours reads ────────────────────────────────
//
// The outcome the shadow is in production to rule out, or to find.
{
const std::string v = Verdict(kReduced);
Has(v, "DIFFER nostro refused what ours reads as a payment: ",
"the four members ours reads are not enough for Nostro's reader");
}
{
const std::string v = Verdict(Callback({ .account = "" }));
Has(v, "DIFFER nostro refused what ours reads as a payment: ",
"a payment that does not say which account it is on is refused");
Has(v, "which account", "and the refusal says that is why");
}
{
// Past what Nostro reads at all, with a payment ours still decodes.
std::string big = Callback({});
const std::size_t at = big.find("\"category\"");
big.insert(at, std::format("\"padding\": \"{}\", ", std::string(70000, 'x')));
const std::string v = Verdict(big);
Has(v, "DIFFER nostro refused what ours reads as a payment: ",
"a body past Nostro's limit is refused");
Check(v.size() < 400, "and the verdict stays one line's worth", v);
}
Has(Verdict(Callback({}), kOwnIban, "nobank"),
"DIFFER nostro refused what ours reads as a payment: ",
"a bank Nostro was not built with reads nothing");
// ── one reads a payment where the other reads none ────────────────
{
// Two things under `object`: ours looks for the Payment among them,
// Nostro takes a callback to be about one thing.
std::string two(kReduced);
const std::size_t at = two.rfind("}}");
two.insert(at + 1, R"(, "Other": {})");
Equal(Verdict(two),
"DIFFER nostro reads no payment in it (event=transactions), ours does",
"a second object beside the payment");
}
{
verdicts.push_back(Server::ShadowCallbackVerdict("bunq", Callback({}),
std::nullopt, kOwnIban));
Equal(verdicts.back(),
"DIFFER nostro reads a payment, ours does not (in account=ours event=transactions)",
"a payment only Nostro reads");
}
// ── both read a payment, and not the same one ─────────────────────
{
const std::string body = Callback({});
const std::optional<Server::BankCredit> ours = Server::ParseBunqCallback(body);
Check(ours.has_value(), "our parser reads the sample's shape");
if (ours) {
Server::BankCredit other = *ours;
other.amountMinor += 1;
verdicts.push_back(Server::ShadowCallbackVerdict("bunq", body, other, kOwnIban));
Equal(verdicts.back(),
"DIFFER id=same amount=DIFFERENT reference=same in method=sepa "
"account=ours event=transactions",
"another amount");
other = *ours;
other.id = "1";
verdicts.push_back(Server::ShadowCallbackVerdict("bunq", body, other, kOwnIban));
Has(verdicts.back(), "DIFFER id=DIFFERENT amount=same reference=same ",
"another id");
other = *ours;
other.reference = "something else";
verdicts.push_back(Server::ShadowCallbackVerdict("bunq", body, other, kOwnIban));
Has(verdicts.back(), "DIFFER id=same amount=same reference=DIFFERENT ",
"another reference");
}
}
// ── neither reads a payment ───────────────────────────────────────
for (const std::string_view none : { std::string_view(""), std::string_view("not json"),
std::string_view("SECRETMARK"),
std::string_view(R"({"SECRETMARK": 1})"),
std::string_view(R"({"NotificationUrl": {}})") }) {
Has(Verdict(none), "AGREE neither reads a payment (nostro: ",
std::format("a body that is no callback: '{}'", none.substr(0, 16)));
}
Equal(Verdict(R"({"NotificationUrl": {"category": "REQUEST",
"event_type": "REQUEST_INQUIRY_CREATED",
"object": {"RequestInquiry": {"id": 7}}}})"),
"AGREE no payment in it (event=bunq:REQUEST)",
"a callback about something that is no payment");
// ── and none of it says anything a body carried ───────────────────
Check(verdicts.size() >= 25, "the verdicts above were all collected",
std::format("{}", verdicts.size()));
for (const std::string& v : verdicts) {
for (const std::string_view secret : kSecrets) {
Check(v.find(secret) == std::string::npos,
std::format("a verdict repeats '{}' from a body", secret), v);
}
Check(v.find('\n') == std::string::npos, "a verdict is one line", v);
}
if (failures != 0) {
std::println(std::cerr, "{} check(s) failed", failures);
return 1;
}
std::println("ShouldCompareCallbackReaders: all checks passed");
return 0;
}

View file

@ -149,68 +149,6 @@ int main() {
// simply the state of every order between checkout and payment.
Check(PaidFor({}, ref) == 0, "no credits at all is zero, not an error");
// ── pulling credits into the file the rail reads ──────────────────
//
// Every pull re-reads an overlapping window of the account, so the SAME
// credit arrives on every run. Appending it twice would double a payment
// and settle an order nobody paid twice for, which makes deduplication by
// the bank's own payment id the load-bearing property here. A file source
// stands in for the bank so this needs no network.
{
const std::filesystem::path dir =
std::filesystem::temp_directory_path() / "cc-transfer-pull-test";
std::error_code ec;
std::filesystem::remove_all(dir, ec);
std::filesystem::create_directories(dir, ec);
const std::filesystem::path bank = dir / "bank.jsonl";
const std::filesystem::path target = dir / "credits.jsonl";
{
std::ofstream out(bank);
out << R"({"id":"p1","reference":"CC-2B6457","amount_minor":2500,)"
R"("method":"sepa"})" << "\n";
out << R"({"id":"p2","reference":"CC-AAAAAA","amount_minor":900,)"
R"("method":"ideal"})" << "\n";
}
auto pull = [&] {
auto src = Server::MakeFileCreditSource(bank);
return Server::PullCreditsInto(*src, target);
};
const std::optional<int> first = pull();
Check(first.has_value() && *first == 2, "the first pull appends both credits",
first ? std::format("{}", *first) : "nullopt");
const std::optional<int> second = pull();
Check(second.has_value() && *second == 0,
"pulling the same window again appends nothing",
second ? std::format("{}", *second) : "nullopt");
// A new payment arrives at the bank; only it should be appended.
{
std::ofstream out(bank, std::ios::app);
out << R"({"id":"p3","reference":"CC-2B6457","amount_minor":100,)"
R"("method":"sepa"})" << "\n";
}
const std::optional<int> third = pull();
Check(third.has_value() && *third == 1, "only the new credit is appended",
third ? std::format("{}", *third) : "nullopt");
// And what the rail now reads settles correctly: 25.00 + 1.00.
{
auto reader = Server::MakeFileCreditSource(target);
const auto all = reader->Recent();
Check(all.has_value() && all->size() == 3,
"the credits file holds exactly the three distinct credits",
all ? std::format("{}", all->size()) : "nullopt");
if (all) {
Check(Server::MatchCredits(*all, ref).paidMinor == 2600,
"the deduplicated file sums to the real total");
}
}
std::filesystem::remove_all(dir, ec);
}
if (failures != 0) {
std::println(std::cerr, "{} check(s) failed", failures);
return 1;

View file

@ -1,260 +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.
*/
// Decoding bunq's payment list into credits. The HTTP around this is thin; the
// decoding is where a mistake costs money and says nothing, which is the same
// reason ParseEthCallUint and ParseEurcChains are pinned here rather than
// trusted to integration.
//
// Two properties carry real weight:
//
// * The SIGN. bunq quotes an outgoing payment as a negative value, and the
// shop sends refunds quoting the very reference of the order they refund.
// Lose the minus and a refund pays for the order it reversed.
// * The METHOD. `Payment.type` decides whether an order is safe to post: a
// SEPA credit transfer is final, a card payment can be reversed for
// months. Collapsing them to "paid" is how a chargeback becomes a
// shipped parcel.
import std;
import Catcrafts.Shared;
import Catcrafts.Server;
using namespace Catcrafts;
namespace {
int failures = 0;
void Check(bool ok, std::string_view what, std::string_view got = {}) {
if (ok) return;
++failures;
std::println(std::cerr, "FAIL: {}{}{}", what,
got.empty() ? "" : " got: ", got);
}
// The shape bunq actually answers with: everything wrapped in Response, one
// object per entry keyed by type.
constexpr std::string_view kList = R"({
"Response": [
{"Payment": {
"id": 4155551,
"type": "EBA_SCT",
"description": "CC-2B6457 catcrafts.net",
"amount": {"currency": "EUR", "value": "57.38"}
}},
{"Payment": {
"id": 4155552,
"type": "IDEAL",
"description": "donation cc2b6457",
"amount": {"currency": "EUR", "value": "5.00"}
}},
{"Payment": {
"id": 4155553,
"type": "EBA_SCT",
"description": "supplier invoice",
"amount": {"currency": "EUR", "value": "-513.00"}
}},
{"Payment": {
"id": 4155554,
"type": "FIS",
"description": "card payment",
"amount": {"currency": "USD", "value": "20.00"}
}}
]
})";
} // namespace
int main() {
const std::vector<Server::BankCredit> credits = Server::ParseBunqPayments(kList);
// The USD entry is dropped: counting 20 of something else as 20 euro is
// the kind of bug that only shows up as a shortfall nobody can explain.
Check(credits.size() == 3, "only the euro payments are decoded",
std::format("{}", credits.size()));
if (credits.size() == 3) {
Check(credits[0].id == "4155551", "the bank's own id is kept, for dedupe",
credits[0].id);
Check(credits[0].reference == "CC-2B6457 catcrafts.net",
"the description is the remittance text, verbatim", credits[0].reference);
Check(credits[0].amountMinor == 5738, "57.38 decodes to 5738 minor units",
std::format("{}", credits[0].amountMinor));
Check(credits[0].method == "sepa", "EBA_SCT is a plain SEPA transfer",
credits[0].method);
Check(credits[1].method == "ideal", "IDEAL is carried as its own method",
credits[1].method);
// The load-bearing one.
Check(credits[2].amountMinor == -51300,
"an outgoing payment keeps its minus sign",
std::format("{}", credits[2].amountMinor));
}
// End to end through the matcher: the outgoing line must not pay for
// anything, and the two incoming ones must sum.
{
const Server::TransferMatch m = Server::MatchCredits(credits, "CC-2B6457");
Check(m.paidMinor == 6238,
"the two incoming credits sum and the outgoing one is ignored",
std::format("{}", m.paidMinor));
Check(m.count == 2, "two credits matched", std::format("{}", m.count));
}
// ── the method mapping, pinned individually ───────────────────────
Check(Server::BunqMethodFor("EBA_SCT") == "sepa", "EBA_SCT -> sepa");
Check(Server::BunqMethodFor("IDEAL") == "ideal", "IDEAL -> ideal");
Check(Server::BunqMethodFor("FIS") == "card", "FIS -> card (reversible!)");
Check(Server::BunqMethodFor("BUNQ") == "bunq", "BUNQ -> bunq");
Check(Server::BunqMethodFor("SWIFT") == "swift", "SWIFT -> swift");
Check(Server::BunqMethodFor("EBA_SDD") == "directdebit", "EBA_SDD -> directdebit");
// An unknown type reaches the ledger verbatim rather than as a comfortable
// guess: the `via` column should show what bunq said, so a new payment
// type is visible instead of silently filed as an ordinary transfer.
Check(Server::BunqMethodFor("SOMETHING_NEW") == "SOMETHING_NEW",
"an unknown type is passed through, not guessed at");
Check(Server::BunqMethodFor("") == "bank", "an absent type falls back to 'bank'");
// ── signed amount parsing ─────────────────────────────────────────
Check(Server::ParseSignedAmountToMinor("0.01") == 1, "one cent");
Check(Server::ParseSignedAmountToMinor("-0.01") == -1, "minus one cent");
Check(Server::ParseSignedAmountToMinor("57.4") == 5740, "one decimal is tenths");
Check(Server::ParseSignedAmountToMinor("665") == 66500, "no decimal point");
Check(!Server::ParseSignedAmountToMinor("1.234").has_value(),
"three decimals is not money");
Check(!Server::ParseSignedAmountToMinor("1,00").has_value(),
"a comma decimal is refused rather than guessed");
Check(!Server::ParseSignedAmountToMinor("1e2").has_value(), "no exponents");
Check(!Server::ParseSignedAmountToMinor("").has_value(), "empty is not zero");
Check(!Server::ParseSignedAmountToMinor("-").has_value(), "a bare sign is not zero");
Check(!Server::ParseSignedAmountToMinor(" 1.00").has_value(), "no leading space");
// ── malformed input yields nothing, never a wrong number ──────────
Check(Server::ParseBunqPayments("").empty(), "empty input decodes to nothing");
Check(Server::ParseBunqPayments("not json").empty(), "garbage decodes to nothing");
Check(Server::ParseBunqPayments(R"({"Response":[]})").empty(),
"an empty account decodes to nothing");
Check(Server::ParseBunqPayments(R"({"Response":"nope"})").empty(),
"a Response that is not an array decodes to nothing");
// A payment whose amount will not parse is SKIPPED, not counted as zero:
// an unparseable amount means we do not know what arrived.
Check(Server::ParseBunqPayments(
R"({"Response":[{"Payment":{"id":1,"type":"EBA_SCT","description":"x",)"
R"("amount":{"currency":"EUR","value":"1.234"}}}]})").empty(),
"an unparseable amount is skipped rather than read as zero");
// ── the callback shape ────────────────────────────────────────────
//
// bunq does not sign these, so the parser is the only thing between an
// arbitrary POST body and a line in the credits file. It must therefore be
// strict about what it accepts and must never invent a field.
{
constexpr std::string_view kHook = R"({
"NotificationUrl": {
"category": "MUTATION",
"object": {"Payment": {
"id": 4155999,
"type": "EBA_SCT",
"description": "CC-2B6457",
"amount": {"currency": "EUR", "value": "570.43"}
}}
}
})";
const auto c = Server::ParseBunqCallback(kHook);
Check(c.has_value(), "a MUTATION callback decodes to a credit");
if (c) {
Check(c->id == "4155999", "the payment id is kept", c->id);
Check(c->amountMinor == 57043, "the amount decodes",
std::format("{}", c->amountMinor));
Check(c->reference == "CC-2B6457", "the description is the reference",
c->reference);
Check(c->method == "sepa", "the type maps to a via", c->method);
}
// An id is what deduplication rests on, and bunq RETRIES callbacks. A
// credit with no id could therefore be applied twice, so it must be
// refused outright rather than stored with a blank.
Check(!Server::ParseBunqCallback(R"({"NotificationUrl":{"object":{"Payment":{)"
R"("type":"EBA_SCT","description":"x",)"
R"("amount":{"currency":"EUR","value":"1.00"}}}}})").has_value(),
"a payment with no id is refused, because retries need one");
// Everything that is not a payment notification: bunq sends several
// categories, and none of the others may produce a credit.
for (const std::string_view junk : {
std::string_view(""),
std::string_view("not json"),
std::string_view(R"({})"),
std::string_view(R"({"NotificationUrl":{}})"),
std::string_view(R"({"NotificationUrl":{"object":{}}})"),
std::string_view(R"({"NotificationUrl":{"object":{"Payment":{}}}})"),
// A Payment whose amount is another currency, or unparseable.
std::string_view(R"({"NotificationUrl":{"object":{"Payment":{"id":1,)"
R"("amount":{"currency":"USD","value":"1.00"}}}}})"),
std::string_view(R"({"NotificationUrl":{"object":{"Payment":{"id":1,)"
R"("amount":{"currency":"EUR","value":"1.234"}}}}})"),
}) {
Check(!Server::ParseBunqCallback(junk).has_value(),
"a body with no usable euro payment yields nothing", junk);
}
// The sign survives here too: an outgoing payment must not be able to
// arrive through the webhook as income.
const auto out = Server::ParseBunqCallback(
R"({"NotificationUrl":{"object":{"Payment":{"id":7,"type":"EBA_SCT",)"
R"("description":"supplier","amount":{"currency":"EUR","value":"-99.00"}}}}})");
Check(out.has_value() && out->amountMinor == -9900,
"an outgoing callback keeps its sign for the caller to reject",
out ? std::format("{}", out->amountMinor) : "nullopt");
}
// ── appending, and refusing to append twice ───────────────────────
//
// bunq retries a callback about six times, and a periodic pull re-reads an
// overlapping window, so the same payment WILL arrive more than once. If a
// second copy landed in the file it would double the money against one
// reference — enough to settle a part-paid order whose balance never came.
{
const std::filesystem::path dir =
std::filesystem::temp_directory_path() / "cc-bunq-append-test";
std::error_code ec;
std::filesystem::remove_all(dir, ec);
std::filesystem::create_directories(dir, ec);
const std::filesystem::path credits = dir / "credits.jsonl";
Server::BankCredit c;
c.id = "999";
c.reference = "CC-2B6457";
c.amountMinor = 2500;
c.method = "sepa";
Check(Server::AppendCreditTo(credits, c), "the first append succeeds");
Check(!Server::AppendCreditTo(credits, c),
"the same payment id is refused the second time");
auto src = Server::MakeFileCreditSource(credits);
const auto all = src->Recent();
Check(all && all->size() == 1, "the file holds exactly one copy",
all ? std::format("{}", all->size()) : "nullopt");
if (all) {
Check(Server::MatchCredits(*all, "CC-2B6457").paidMinor == 2500,
"so the order sees 25.00 once, not twice");
}
// A credit with no id cannot be deduplicated and must be refused.
Server::BankCredit noId = c;
noId.id.clear();
Check(!Server::AppendCreditTo(credits, noId), "a credit with no id is refused");
std::filesystem::remove_all(dir, ec);
}
if (failures != 0) {
std::println(std::cerr, "{} check(s) failed", failures);
return 1;
}
std::println("ShouldParseBunqPayments: all checks passed");
return 0;
}

View file

@ -0,0 +1,367 @@
/*
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.
*/
// What the bank's callback comes to (ReadBankCallback), how a payment is said
// to have arrived (CreditMethodFor), and the credits file both end up in. The
// HTTP around these is thin; this is where a stranger's bytes become a claim
// on an order, which is the same reason ParseEthCallUint and ParseEurcChains
// are pinned here rather than trusted to integration.
//
// The properties that carry real weight:
//
// * THE ACCOUNT. A bank posts to whatever address any of its customers
// registered, so a callback about a payment on SOMEONE ELSE's account can
// be the bank's own, from the bank's own addresses. Only a payment on the
// shop's account may become a credit.
// * THE SIGN. An outgoing payment is a negative amount, and the shop sends
// refunds quoting the very reference of the order they refund. Lose the
// minus and a refund pays for the order it reversed.
// * THE METHOD. How the money arrived decides whether an order is safe to
// post: a credit transfer is final, a card payment can be reversed for
// months. A kind nobody has a word for must stay recognisably unknown.
// * NOTHING OF THE BODY IS SAID BACK in a note, which goes to the log. A
// body holds the payer's name and IBAN, and may repeat the secret address.
// * THE ID. A callback is retried and the pull delivers the same payment
// again, so a credit is recorded once per id of the bank's.
//
// The reading itself is Nostro's (the module Nostro.Money), which has suites
// of its own for what it refuses. What is held here is what THIS shop makes of
// what it reads. The bodies are made up, in the shape of bunq's own sample of
// a callback; a real one was read the same way in production on 2026-11-25,
// by the reader this replaced and by this one side by side.
import std;
import Catcrafts.Shared;
import Catcrafts.Server;
using namespace Catcrafts;
namespace {
int failures = 0;
void Check(bool ok, std::string_view what, std::string_view got = {}) {
if (ok) return;
++failures;
std::println(std::cerr, "FAIL: {}{}{}", what,
got.empty() ? "" : " got: ", got);
}
// Not real accounts, and not the shop's: see ShouldSettleBankTransfers.
constexpr std::string_view kOwnIban = "NL00TEST0123456789";
constexpr std::string_view kOtherIban = "NL00OTHR0000000002";
constexpr std::string_view kBank = "bunq";
// Every value below that a note must never repeat.
constexpr std::string_view kSecrets[] = {
"SECRETMARK", "CC-2B6457", "4155999", "570", "24.95", "NL00", "Payer",
"shop.invalid", "bad type",
};
struct Sent {
std::string_view id = "4155999";
std::string_view type = "EBA_SCT";
std::string_view description = "CC-2B6457";
std::string_view value = "570.43";
std::string_view currency = "EUR";
std::string_view account = kOwnIban; // the payment's own side
std::string_view category = "MUTATION";
};
// A callback as the bank's sample has one: the envelope with the address it
// was sent to, and a Payment with both sides on it.
std::string Callback(const Sent& s) {
return std::format(R"({{
"NotificationUrl": {{
"target_url": "https://shop.invalid/hooks/SECRETMARK",
"category": "{}",
"event_type": "MUTATION_CREATED",
"object": {{"Payment": {{
"id": {},
"created": "2026-11-25 10:15:30.498520",
"updated": "2026-11-25 10:15:30.498520",
"monetary_account_id": 42,
"amount": {{"currency": "{}", "value": "{}"}},
"description": "{}",
"type": "{}",
"alias": {{"iban": "{}", "display_name": "SECRETMARK Shop", "country": "NL"}},
"counterparty_alias": {{"iban": "NL00PAYR0000000001",
"display_name": "SECRETMARK Payer", "country": "NL"}}
}}}}
}}
}})", s.category, s.id, s.currency, s.value, s.description, s.type, s.account);
}
// The few members a reader could get by on, and no more: no time, no
// counterparty, and not the account the payment is on. Refused whole.
constexpr std::string_view kReduced = R"({
"NotificationUrl": {
"category": "MUTATION",
"object": {"Payment": {
"id": 4155999,
"type": "EBA_SCT",
"description": "CC-2B6457",
"amount": {"currency": "EUR", "value": "570.43"}
}}
}
})";
std::vector<std::string> notes;
Server::BankCallbackResult Read(std::string_view body, std::string_view ownIban = kOwnIban,
std::string_view bank = kBank) {
Server::BankCallbackResult r = Server::ReadBankCallback(bank, body, ownIban);
notes.push_back(r.note);
return r;
}
// No credit, and a note that starts as said.
void Nothing(std::string_view body, std::string_view noteStart, std::string_view what,
std::string_view ownIban = kOwnIban, std::string_view bank = kBank) {
const Server::BankCallbackResult r = Read(body, ownIban, bank);
Check(!r.credit.has_value(), std::format("{}: nothing is credited", what));
Check(r.note.starts_with(noteStart), std::format("{}: the note says why", what), r.note);
}
std::string MethodOf(std::string_view type) {
const Server::BankCallbackResult r = Read(Callback({ .type = type }));
return r.credit ? r.credit->method : std::format("<no credit: {}>", r.note);
}
} // namespace
int main() {
// ── money coming in, on the shop's own account ────────────────────
{
const Server::BankCallbackResult r = Read(Callback({}));
Check(r.credit.has_value(), "an incoming transfer on the shop's account is a credit",
r.note);
if (r.credit) {
Check(r.credit->id == "4155999", "the bank's own id is kept, for dedupe",
r.credit->id);
Check(r.credit->reference == "CC-2B6457", "the description is the reference",
r.credit->reference);
Check(r.credit->amountMinor == 57043, "570.43 is 57043 minor units",
std::format("{}", r.credit->amountMinor));
Check(r.credit->method == "sepa", "a credit transfer is 'sepa'",
r.credit->method);
}
Check(r.note.empty(), "and there is nothing to explain", r.note);
}
Check(Read(Callback({}), "nl00 test 0123 4567 89").credit.has_value(),
"the shop's IBAN is compared as a person wrote it down");
{
const Server::BankCallbackResult r = Read(Callback({ .value = "0.01" }));
Check(r.credit && r.credit->amountMinor == 1, "one cent is one cent");
}
// ── the account ───────────────────────────────────────────────────
Nothing(Callback({ .account = kOtherIban }),
"the payment is on another account than the shop's",
"a payment on someone else's account");
Nothing(Callback({}), "the payment is on another account than the shop's",
"with no account of the shop's named", "");
Nothing(Callback({ .account = "" }), "the body was refused: ",
"a payment that does not say which account it is on");
// ── the sign ──────────────────────────────────────────────────────
Nothing(Callback({ .value = "-24.95" }), "the payment is not money coming in",
"money going out");
Nothing(Callback({ .value = "0.00" }), "the payment is not money coming in",
"a payment of nothing");
// ── what is not euro, or not an amount ────────────────────────────
Nothing(Callback({ .currency = "USD" }), "the body was refused: ", "dollars");
Nothing(Callback({ .value = "570,43" }), "the body was refused: ",
"an amount with a comma");
Nothing(Callback({ .value = "1e2" }), "the body was refused: ", "an exponent");
Nothing(Callback({ .value = "184467440737095516.17" }), "the body was refused: ",
"an amount that does not fit");
// ── the id ────────────────────────────────────────────────────────
Nothing(Callback({ .id = "\"4155999\"" }), "the body was refused: ", "an id in a string");
Nothing(Callback({ .id = "-1" }), "the body was refused: ", "a negative id");
Nothing(Callback({ .id = "1.5" }), "the body was refused: ", "half an id");
// ── how it arrived ────────────────────────────────────────────────
Check(MethodOf("EBA_SCT") == "sepa", "a credit transfer", MethodOf("EBA_SCT"));
Check(MethodOf("IDEAL") == "ideal", "iDEAL", MethodOf("IDEAL"));
Check(MethodOf("EBA_SDD") == "directdebit", "a direct debit", MethodOf("EBA_SDD"));
Check(MethodOf("SWIFT") == "swift", "SWIFT", MethodOf("SWIFT"));
Check(MethodOf("BUNQ") == "internal", "between two accounts at the bank itself",
MethodOf("BUNQ"));
Check(MethodOf("MASTERCARD") == "card", "a card payment (reversible!)",
MethodOf("MASTERCARD"));
Check(MethodOf("FIS") == "card", "a card payment, by its other name", MethodOf("FIS"));
// Not guessed: a type the table has no word for stays the bank's own word,
// so the `via` column shows what the bank said, and a link that either a
// card or iDEAL may have paid is not taken for final money.
Check(MethodOf("ADYEN") == "ADYEN", "a type without a word is passed on as it is",
MethodOf("ADYEN"));
Check(MethodOf("SOMETHING_NEW") == "SOMETHING_NEW", "and so is a new one",
MethodOf("SOMETHING_NEW"));
Check(MethodOf("eba_sct") == "eba_sct", "another spelling is not the word it resembles",
MethodOf("eba_sct"));
Check(MethodOf("") == "bank", "no type at all is 'bank'", MethodOf(""));
Check(MethodOf("bad type!") == "bank", "what is no bank's word is not passed on",
MethodOf("bad type!"));
// The same table, asked directly: it is also what puts a pulled credit's
// kind into words, so the two ways a payment arrives give it one word.
Check(Server::CreditMethodFor(kBank, "EBA_SCT/SCT") == "sepa", "EBA_SCT/SCT");
Check(Server::CreditMethodFor(kBank, "IDEAL/REQUEST") == "ideal", "IDEAL/REQUEST");
Check(Server::CreditMethodFor(kBank, "MASTERCARD/PAYMENT") == "card", "MASTERCARD/PAYMENT");
Check(Server::CreditMethodFor(kBank, "BUNQ/PAYMENT") == "internal", "BUNQ/PAYMENT");
Check(Server::CreditMethodFor(kBank, "ADYEN/PAYMENT") == "ADYEN", "ADYEN/PAYMENT");
Check(Server::CreditMethodFor(kBank, "") == "bank", "no kind");
Check(Server::CreditMethodFor(kBank, "/SCT") == "bank", "a kind without a type");
Check(Server::CreditMethodFor(kBank, "<script>/x") == "bank", "a kind that is no word");
Check(Server::CreditMethodFor(kBank, std::string(60, 'A')) == "bank", "a word too long");
// A bank this build was not made with has no table: its kinds are unknown.
Check(Server::CreditMethodFor("nobank", "EBA_SCT/SCT") == "EBA_SCT",
"another bank's kind is not read by this bank's table",
Server::CreditMethodFor("nobank", "EBA_SCT/SCT"));
Check(Server::CreditMethodFor("", "EBA_SCT/SCT") == "EBA_SCT", "nor is no bank's");
// ── what is no callback about a payment ───────────────────────────
Nothing(kReduced, "the body was refused: ", "a payment with only a few of its members");
for (const std::string_view none : { std::string_view(""), std::string_view("not json"),
std::string_view("SECRETMARK"),
std::string_view("[1,2]"),
std::string_view(R"({"SECRETMARK": 1})"),
std::string_view(R"({"NotificationUrl": {}})") }) {
Nothing(none, "the body was refused: ",
std::format("a body that begins '{}'", none.substr(0, 12)));
}
Nothing(R"({"NotificationUrl": {"category": "REQUEST",
"event_type": "REQUEST_INQUIRY_CREATED",
"object": {"RequestInquiry": {"id": 7}}}})",
"no payment in it (event=bunq:REQUEST)", "an event about something else");
Nothing(R"({"NotificationUrl": {"category": "MUTATION"}})",
"no payment in it (event=transactions)", "an event with nothing in it");
// A payment under another event than the one payments are counted from.
// The same payment also arrives under that one, where it is counted.
Nothing(Callback({ .category = "PAYMENT" }),
"not the event payments are counted from (event=bunq:PAYMENT)",
"a payment under another event");
{
// Two things where a callback is about one.
std::string two(kReduced);
const std::size_t at = two.rfind("}}");
two.insert(at + 1, R"(, "Other": {})");
Nothing(two, "no payment in it (event=transactions)",
"a second object beside the payment");
}
{
// Past what the reader takes at all.
std::string big = Callback({});
big.insert(big.find("\"category\""),
std::format("\"padding\": \"{}\", ", std::string(70000, 'x')));
const Server::BankCallbackResult r = Read(big);
Check(!r.credit.has_value(), "a body of 70 kB credits nothing");
Check(r.note.starts_with("the body was refused: ") && r.note.size() < 300,
"and its note stays a line's worth", r.note);
}
Nothing(Callback({}), "the body was refused: ",
"a bank this build was not made with", kOwnIban, "nobank");
Nothing(Callback({}), "the body was refused: ", "no bank named", kOwnIban, "");
// ── and no note says anything a body carried ──────────────────────
Check(notes.size() >= 40, "the notes above were all collected",
std::format("{}", notes.size()));
for (const std::string& note : notes) {
for (const std::string_view secret : kSecrets) {
Check(note.find(secret) == std::string::npos,
std::format("a note repeats '{}' from a body", secret), note);
}
Check(note.find('\n') == std::string::npos, "a note is one line", note);
}
// ── the credits file ──────────────────────────────────────────────
{
const std::filesystem::path dir =
std::filesystem::temp_directory_path() / "cc-bank-callback-test";
std::error_code ec;
std::filesystem::remove_all(dir, ec);
std::filesystem::create_directories(dir, ec);
const std::filesystem::path credits = dir / "credits.jsonl";
// One credit per id of the bank's: a retried callback, or the pull
// delivering the same payment, must not count the money twice.
const Server::BankCallbackResult read = Read(Callback({ .id = "999",
.value = "25.00" }));
Check(read.credit.has_value(), "the callback to record reads as a credit");
if (read.credit) {
Check(Server::AppendCreditTo(credits, *read.credit), "the first append succeeds");
Check(!Server::AppendCreditTo(credits, *read.credit),
"the same payment id is refused the second time");
Server::BankCredit noId = *read.credit;
noId.id.clear();
Check(!Server::AppendCreditTo(credits, noId), "a credit with no id is refused");
}
{
auto src = Server::MakeFileCreditSource(credits);
const auto all = src->Recent();
Check(all && all->size() == 1, "the file holds exactly one copy",
all ? std::format("{}", all->size()) : "nullopt");
if (all && all->size() == 1) {
Check(Server::MatchCredits(*all, "CC-2B6457").paidMinor == 2500,
"so the order sees 25.00 once, not twice");
Check((*all)[0].method == "sepa", "with how it arrived", (*all)[0].method);
}
}
// What the pull ships: the bank's own kind with the bank it is of,
// put into the ledger's words when the file is read. A line that names
// the method outright keeps it, and one with neither is a transfer.
{
std::ofstream out(credits, std::ios::app | std::ios::binary);
out << R"({"id":"p1","reference":"a","amount_minor":100,"bank":"bunq","kind":"EBA_SCT/SCT"})" "\n"
<< R"({"id":"p2","reference":"b","amount_minor":100,"bank":"bunq","kind":"IDEAL/REQUEST"})" "\n"
<< R"({"id":"p3","reference":"c","amount_minor":100,"bank":"bunq","kind":"MASTERCARD/PAYMENT"})" "\n"
<< R"({"id":"p4","reference":"d","amount_minor":100,"bank":"bunq","kind":"ADYEN/PAYMENT"})" "\n"
<< R"({"id":"p5","reference":"e","amount_minor":100,"bank":"bunq","kind":"BUNQ/PAYMENT"})" "\n"
<< R"({"id":"p6","reference":"f","amount_minor":100,"method":"ideal","bank":"bunq","kind":"EBA_SCT/SCT"})" "\n"
<< R"({"id":"p7","reference":"g","amount_minor":100})" "\n"
<< R"({"id":"p8","reference":"h","amount_minor":100,"kind":"EBA_SCT/SCT"})" "\n";
}
{
auto src = Server::MakeFileCreditSource(credits);
const auto all = src->Recent();
Check(all && all->size() == 9, "every line is read",
all ? std::format("{}", all->size()) : "nullopt");
if (all && all->size() == 9) {
const auto method = [&](std::string_view id) {
for (const Server::BankCredit& c : *all) {
if (c.id == id) return c.method;
}
return std::string("<missing>");
};
Check(method("p1") == "sepa", "a pulled transfer", method("p1"));
Check(method("p2") == "ideal", "a pulled iDEAL payment", method("p2"));
Check(method("p3") == "card", "a pulled card payment", method("p3"));
Check(method("p4") == "ADYEN", "a pulled kind without a word", method("p4"));
Check(method("p5") == "internal", "a pulled payment from inside the bank",
method("p5"));
Check(method("p6") == "ideal", "a method said outright wins", method("p6"));
Check(method("p7") == "sepa", "a line that says neither is a transfer",
method("p7"));
Check(method("p8") == "sepa", "and so is a kind without its bank",
method("p8"));
}
}
std::filesystem::remove_all(dir, ec);
}
if (failures != 0) {
std::println(std::cerr, "{} check(s) failed", failures);
return 1;
}
std::println("ShouldReadBankCallbacks: all checks passed");
return 0;
}

View file

@ -6,27 +6,30 @@ 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 bank's callback endpoint, over real HTTP, with the shadow run of
// Nostro's reader attached to it (see ShadowCallbackVerdict in the server's
// interface). The endpoint is how a transfer settles within seconds in
// production, and until this suite it was only ever exercised there.
// The bank's callback endpoint, over real HTTP. It is how a transfer settles
// within seconds in production, and the one place where bytes a stranger can
// send become a line in the file orders are settled from.
//
// What it holds, in the order that matters:
//
// * OUR PARSER STILL DECIDES, ALONE. A payment it reads is credited whatever
// Nostro's reader makes of the same body, including when that reader
// refuses it. The shadow is in production to find out whether it would
// refuse real callbacks, so the one thing it must not be able to do is
// turn a refusal into a missed payment.
// * An order settles from a callback, end to end: the body the bank posts,
// the credit, the reconciler, the paid page.
// * The shadow says what it found, once per callback, in the server's log.
// * That log says nothing a callback carried: not the payer, not the
// reference, and not the address, which is the endpoint's only secret.
// * ONLY a payment to the shop's own account credits anything. A payment on
// another account, money going out, and a body the reader refuses each get
// the bank its 200 and credit nothing.
// * A payment is credited once, however often the bank sends it.
// * Every callback leaves one line in the server's log, and the log says
// nothing a callback carried beyond the credit itself: not the payer, not
// the reference, and not the address, which is the endpoint's only secret.
// * Without the bank's name the endpoint does not exist at all, and says so
// at startup: an endpoint that answered 200 and credited nothing would
// look like working.
//
// No secret and no network: the suite plays the bank by posting to the
// endpoint, as ShouldSettleBankTransfers plays it by writing the credits file.
// The bodies are made up, in the shape of bunq's own sample of a callback.
// What the reader makes of each shape is pinned in ShouldReadBankCallbacks;
// what only this suite can show is that the endpoint is wired to it.
import std;
import Crafter.Network;
@ -49,7 +52,7 @@ constexpr std::string_view kHook = "/hooks/bank/e2e-HOOKSECRET-0123456789abcdef"
// copy, and not a badge, is the signal.
constexpr std::string_view kPaidCopy = "Your donation funds";
constexpr std::string_view kShadow = "bank callback shadow: ";
constexpr std::string_view kLine = "bank callback: ";
struct Sent {
std::string_view id;
@ -59,8 +62,8 @@ struct Sent {
std::string_view account = kIban; // the payment's own side
};
// A callback as bunq's sample has one: the envelope with the address it was
// sent to, and a Payment with both sides on it.
// A callback as the bank's sample has one: the envelope with the address it
// was sent to, and a Payment with both sides on it.
std::string Callback(const Sent& s) {
return std::format(R"({{
"NotificationUrl": {{
@ -83,8 +86,8 @@ std::string Callback(const Sent& s) {
}})", kHook, s.id, s.value, s.description, s.type, s.account);
}
// The four members our own parser reads and nothing else, which Nostro's
// reader refuses for what it lacks.
// A payment with only a few of its members: no time, no counterparty, and not
// the account it is on. The reader refuses it whole.
std::string Reduced(std::string_view id, std::string_view value) {
return std::format(R"({{"NotificationUrl": {{"category": "MUTATION",
"object": {{"Payment": {{"id": {}, "type": "EBA_SCT",
@ -115,14 +118,7 @@ std::string NewestReference(const TestServer& srv) {
return found;
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
std::println(std::cerr, "usage: ShouldReceiveBankCallbacks <server-binary>");
return 2;
}
ServerOptions Options(std::string_view bank) {
ServerOptions options;
// The REAL transfer rail in the bank slot, settling from the credits file
// the callback endpoint writes. The crypto slot is off.
@ -131,12 +127,22 @@ int main(int argc, char** argv) {
{ "TRANSFER_IBAN", std::string(kIban) },
{ "TRANSFER_BENEFICIARY", std::string(kBeneficiary) },
{ "TRANSFER_POLL_SECONDS", "1" },
{ "BUNQ_WEBHOOK_PATH", std::string(kHook) },
// A developer's shell may carry the real key, and with one the rail
// would read the real bank instead of the credits file. Never here.
{ "BUNQ_API_KEY", "" },
{ "BANK_CALLBACK_PATH", std::string(kHook) },
{ "BANK_CALLBACK_BANK", std::string(bank) },
};
TestServer srv(argv[1], 8223, options);
return options;
}
} // namespace
int main(int argc, char** argv) {
if (argc < 2) {
std::println(std::cerr, "usage: ShouldReceiveBankCallbacks <server-binary>");
return 2;
}
{
TestServer srv(argv[1], 8223, Options("bunq"));
const fs::path credits(srv.Orders().string() + ".transfer-credits.jsonl");
const fs::path log = srv.Work() / "server.log";
@ -150,11 +156,10 @@ int main(int argc, char** argv) {
return srv.Post(std::string(kHook), std::move(body), "application/json").status;
};
Check(Logged("bank callback shadow: on") == 1 && Logged("own account named") == 1,
"the shadow says at startup that it is on, and that it knows the account",
ReadFile(log));
Check(Logged("bank callback: enabled on a secret path") == 1,
"the endpoint says at startup that it is on", ReadFile(log));
// ── the endpoint is the secret address, and only for a POST ───────
// ── the endpoint is the secret address, and only for a POST ───
srv.CheckStatus(std::string(kHook), "404");
{
std::string near(kHook);
@ -162,12 +167,13 @@ int main(int argc, char** argv) {
const std::string status =
srv.Post(near, Callback({ .id = "9000099", .value = "5.00" }),
"application/json").status;
Check(status != "200", "an address one character off is not the endpoint", status);
Check(status != "200", "an address one character off is not the endpoint",
status);
Check(Credited("9000099") == 0, "and what is posted there credits nothing");
Check(Logged(kShadow) == 1, "nor does the shadow look at it"); // the startup line
Check(Logged(kLine) == 1, "nor is it read at all"); // the startup line
}
// ── a payment both readers read ───────────────────────────────────
// ── a payment to the shop ─────────────────────────────────────
Check(Send(Callback({ .id = "9000001", .value = "5.00" })) == "200",
"a callback is answered 200");
Check(Credited("9000001") == 1, "and its payment is credited", ReadFile(credits));
@ -177,57 +183,49 @@ int main(int argc, char** argv) {
&& text.find("\"method\":\"sepa\"") != std::string::npos,
"with its amount and how it arrived", text);
}
Check(Logged("bank callback shadow: AGREE in method=sepa account=ours "
"event=transactions") == 1,
"the shadow says Nostro's reader read the same payment", ReadFile(log));
Check(Logged("bank callback: credited 5.00 via sepa (id 9000001)") == 1,
"the log says what was credited", ReadFile(log));
// The bank retries, and a retry must not count twice. The shadow looks at
// each one: it compares readings, it keeps no books.
// The bank retries, and a retry must not count twice.
Check(Send(Callback({ .id = "9000001", .value = "5.00" })) == "200",
"the same callback again is answered 200 as well");
Check(Credited("9000001") == 1, "and is credited once", ReadFile(credits));
Check(Logged("bank callback shadow: AGREE in method=sepa account=ours "
"event=transactions") == 2,
"the shadow compares the retry too", ReadFile(log));
Check(Logged("bank callback: nothing credited: the payment was credited before") == 1,
"the log says the retry added nothing", ReadFile(log));
// ── a payment Nostro's reader refuses: ours decides, alone ────────
Check(Send(Reduced("9000002", "3.00")) == "200",
"a callback Nostro's reader refuses is answered 200");
Check(Credited("9000002") == 1,
"and is CREDITED all the same: the shadow has no say", ReadFile(credits));
Check(Logged("bank callback shadow: DIFFER nostro refused what ours reads "
"as a payment: ") == 1,
"the shadow says that Nostro's reader would have refused it", ReadFile(log));
// ── a payment on another account ──────────────────────────────
//
// The bank's own callback, from the bank's own addresses, about an
// account that is not the shop's: what someone who registered this
// address for an account of their own, and paid themselves, would
// have the bank send.
Check(Send(Callback({ .id = "9000004", .value = "5.00", .account = kOtherIban }))
== "200",
"a callback about another account is answered 200");
Check(Credited("9000004") == 0, "and credits NOTHING", ReadFile(credits));
Check(Logged("bank callback: nothing credited: the payment is on another account "
"than the shop's") == 1,
"the log says why", ReadFile(log));
// ── money going out ───────────────────────────────────────────────
// ── money going out ───────────────────────────────────────────
Check(Send(Callback({ .id = "9000003", .value = "-24.95", .type = "MASTERCARD" }))
== "200",
"a callback about an outgoing card payment is answered 200");
Check(Credited("9000003") == 0, "and credits nothing", ReadFile(credits));
Check(Logged("bank callback shadow: AGREE out method ours=MASTERCARD nostro=card "
"account=ours event=transactions") == 1,
"the shadow reads it the same, and names the method each reader gives",
ReadFile(log));
Check(Logged("bank callback: nothing credited: the payment is not money coming in")
== 1,
"the log says why", ReadFile(log));
// ── a payment on another account ──────────────────────────────────
//
// Only the shadow's word is held here. Our parser never looked at which
// account a payment is on, and what the endpoint does with one on another
// account is for the change that replaces the parser to decide and pin.
Check(Send(Callback({ .id = "9000004", .value = "5.00", .account = kOtherIban }))
== "200",
"a callback about another account is answered 200");
Check(Logged("bank callback shadow: AGREE in method=sepa account=other "
"event=transactions") == 1,
"the shadow says the payment is not on the shop's account", ReadFile(log));
// ── what is no callback ───────────────────────────────────────────
// ── what the reader refuses ───────────────────────────────────
Check(Send(Reduced("9000002", "3.00")) == "200",
"a payment without most of its members is answered 200");
Check(Credited("9000002") == 0, "and credits nothing", ReadFile(credits));
Check(Send("not a callback PAYERNOTE") == "200",
"a body that is no callback is answered 200, so the bank stops retrying");
Check(Logged("bank callback shadow: AGREE neither reads a payment") == 1,
"and neither reader reads a payment in it", ReadFile(log));
Check(Logged("bank callback: nothing credited: the body was refused: ") == 2,
"the log says both were refused", ReadFile(log));
// ── an order settles from a callback, end to end ──────────────────
// ── an order settles from a callback, end to end ──────────────
{
const auto res = srv.Post("/shop/donation", "amount=7.00");
Check(res.status == "303", "a donation on the transfer rail is accepted",
@ -239,34 +237,62 @@ int main(int argc, char** argv) {
const std::string path = "/order/" + token;
srv.BodyHas(path, "awaiting payment", "the order starts out unpaid");
// The same payment on someone else's account must not pay for it.
const std::string note = std::format("betaling {} bedankt", reference);
Check(Send(Callback({ .id = "9000011", .value = "7.00", .description = note,
.account = kOtherIban })) == "200",
"a callback quoting the order from another account is answered 200");
std::this_thread::sleep_for(std::chrono::seconds(3));
srv.BodyHas(path, "awaiting payment",
"and the order is still unpaid after the reconciler has run");
Check(Send(Callback({ .id = "9000010", .value = "7.00", .description = note }))
== "200",
"the bank's callback for it is answered 200");
"the bank's callback for the payment to the shop is answered 200");
const std::string body = srv.WaitForBody(path, kPaidCopy, 120);
Check(body.find(kPaidCopy) != std::string::npos,
"and the order is paid, from the callback alone");
Check(Logged("bank callback shadow: AGREE in method=sepa account=ours "
"event=transactions") == 3,
"with the shadow agreeing on that payment too", ReadFile(log));
}
// ── one verdict a callback, and nothing a callback carried ────────
// ── one line a callback, and nothing a callback carried ───────
{
const std::string text = ReadFile(log);
// Seven callbacks reached the endpoint, and the startup line makes eight.
Check(CountOccurrences(text, kShadow) == 8,
"the shadow spoke once for each callback", text);
// Eight callbacks reached the endpoint, and the startup line makes nine.
Check(CountOccurrences(text, kLine) == 9,
"the log has one line for each callback", text);
for (const std::string_view secret :
{ kHook, std::string_view("HOOKSECRET"), std::string_view("PAYERNAME"),
std::string_view("PAYEENAME"), std::string_view("PAYERNOTE"),
std::string_view("NL00PAYR"), kIban, kOtherIban,
std::string_view("shop.invalid") }) {
std::string_view("betaling"), std::string_view("NL00PAYR"), kIban,
kOtherIban, std::string_view("shop.invalid") }) {
Check(text.find(secret) == std::string::npos,
std::format("the server's log repeats '{}' from a callback", secret),
text);
}
}
}
// ── without the bank's name there is no endpoint ──────────────────
//
// The state a server is in when its configuration names the address and
// not whose callbacks arrive there. It must not answer the bank 200 and
// drop the payment: the bank would take that for delivered, and nothing
// anywhere would say that no order can settle from a callback.
{
TestServer srv(argv[1], 8224, Options(""));
const fs::path credits(srv.Orders().string() + ".transfer-credits.jsonl");
const std::string logText = ReadFile(srv.Work() / "server.log");
Check(logText.find("BANK_CALLBACK_BANK") != std::string::npos
&& logText.find("the endpoint is NOT enabled") != std::string::npos,
"a server not told whose callbacks arrive says the endpoint is off",
logText);
const std::string status =
srv.Post(std::string(kHook), Callback({ .id = "9000020", .value = "5.00" }),
"application/json").status;
Check(status != "200", "and does not answer a callback as if it took it", status);
Check(ReadFile(credits).find("9000020") == std::string::npos,
"nor credit what it carried");
}
return Finish();
}

View file

@ -22,14 +22,14 @@ No permission is granted to copy, modify, distribute, or create derivative works
//
// So this needs no secret, never flakes on someone else's RPC, and runs on
// every deploy unconditionally. The bank stands in for itself only in the sense
// that the suite writes the credits file — the same file the bunq webhook and
// tools/pull-and-ship-credits.sh fill from the real account, read by the same
// parser, matched by the same matcher.
// that the suite writes the credits file — the same file the bank's callback
// and tools/pull-and-ship-credits.sh fill from the real account, read by the
// same parser, matched by the same matcher.
// Everything downstream of that line is production code.
//
// What the unit suites already cover, and this one deliberately does not
// re-prove: the matching table (ShouldMatchBankTransfers) and bunq's payload
// decoding (ShouldParseBunqPayments). What only this suite can show is that the
// re-prove: the matching table (ShouldMatchBankTransfers) and what the bank's
// callback comes to (ShouldReadBankCallbacks). What only this suite can show is that the
// pieces are wired to each other — that the reference the PAGE prints is the
// reference the MATCHER looks for, which is the seam where a rename or a
// refactor would quietly break settlement while every unit test still passed.
@ -182,9 +182,9 @@ int main(int argc, char** argv) {
// "ideal" rather than "sepa" on purpose, and it is not fiction even
// though checkout offers no iDEAL. `via` is not a method this shop
// OFFERS — it is what the bank reports about how the money reached the
// account, straight out of bunq's Payment.type. Money can arrive there
// iDEAL-funded without our checkout being involved: an old bunq.me
// link, or a bunq-to-bunq payment, both land in the same account, and
// account, from the bank's own classification of the payment. Money
// can arrive there iDEAL-funded without our checkout being involved: a
// payment link of the bank's, for one, lands in the same account, and
// the rail settles on the REFERENCE regardless of how the payer funded
// it. Using a non-default method here is what proves that passthrough
// works, which matters because the `via` column is what tells the

View file

@ -152,7 +152,8 @@ public:
// .env must not leak real provider keys into the test server — live
// Sendcloud rates would silently change the shipping totals the
// suites assert.
for (const char* v : { "TRANSFER_IBAN", "EURC_CHAINS", "EURC_POOL",
for (const char* v : { "TRANSFER_IBAN", "BANK_CALLBACK_PATH",
"BANK_CALLBACK_BANK", "EURC_CHAINS", "EURC_POOL",
"SENDCLOUD_PUBLIC_KEY", "SENDCLOUD_SECRET_KEY",
"SENDCLOUD_METHOD",
"INVOICE_GPG_KEY", "MAIL_COMMAND", "MAIL_FROM" }) {

View file

@ -4,7 +4,7 @@
#
# The transfer rail settles an order when a credit quoting its reference shows
# up in the credits file. In production that file is filled from the real
# account, by the bunq webhook and by tools/pull-and-ship-credits.sh; here it is
# account, by the bank's callback and by tools/pull-and-ship-credits.sh; here it is
# filled by hand. Same file, same format, same matching code — which is the point:
# this exercises the real settlement path rather than a test double.
#

View file

@ -4,22 +4,20 @@
#
# WHY THIS EXISTS, so nobody "simplifies" it back:
#
# A bunq API key can INITIATE PAYMENTS (bunq has no read-only scope), so the
# A key that can read a bank account can as a rule also pay from it, so the
# public web host must never hold one. It never does: the server only ever
# reads a file of incoming credits, and this script is what fills that file
# from a trusted machine.
# from a trusted machine. The bank's callback adds to the same file within
# seconds of a payment; this is the backstop for a callback that got lost, and
# the one path that asks the bank with the bank's own authentication.
#
# Since 2026-11-21 this script holds no key either. The bank connection lives
# in nostrod (https://forgejo.catcrafts.net/Catcrafts/Nostro), which keeps it
# under a system user of its own and answers over the system bus: a program
# may LOOK at the accounts without a password, and nothing pays or changes
# anything without one. That is the read-only scope bunq does not offer. This
# script only looks. Until then it ran this repo's own bunq client
# (`catcrafts-server --pull-credits`) with the key from .env.
#
# The bunq key is also IP-restricted at the KEY level, and bunq enforces that
# on every call, so the reading has to happen on a machine the key permits.
# That is now nostrod's concern: run this where nostrod has the connection.
# This script holds no key either. The bank connection lives in nostrod
# (https://forgejo.catcrafts.net/Catcrafts/Nostro), which keeps it under a
# system user of its own and answers over the system bus: a program may LOOK at
# the accounts without a password, and nothing pays or changes anything without
# one. This script only looks. It also names no bank and knows no bank's words:
# it ships each payment's kind as the bank wrote it, with the name nostrod has
# for the bank, and the server puts that into the ledger's words.
#
# tools/pull-and-ship-credits.sh pull and ship
# tools/pull-and-ship-credits.sh --dry-run pull, print the credit lines
@ -37,11 +35,14 @@
#
# WHY 90 DAYS: it is the longest TRANSFER_WINDOW_HOURS the server accepts, so no
# order can still be waiting for a credit older than that. Nothing accumulates
# here any more: nostrod keeps the account's whole history and answers for any
# window, so every run ships the complete window, and a machine that was off
# for a month leaves no hole. (The copy this script used to keep under
# ~/.cache/catcrafts did, because the old reader only ever saw the newest 50
# payments.)
# here: nostrod keeps the account's whole history and answers for any window,
# so every run ships the complete window, and a machine that was off for a
# month leaves no hole.
#
# THE REMOTE FILE IS REPLACED, not added to. What the bank says is on the
# account in that window becomes the whole file, so a line the callback wrote
# for a payment that is really there is kept (the same payment, by the bank's
# id), and a line that never was a payment is gone at the next run.
#
# WHEN IT IS REFUSED WITH "needs your password": nostrod lets a program look
# without one only while you are logged in at this machine, in an active local
@ -89,23 +90,17 @@ IBAN=$(printf '%s' "$IBAN" | tr -d ' \t' | tr '[:lower:]' '[:upper:]')
RAW=$(mktemp); ERR=$(mktemp); TMP=$(mktemp)
trap 'rm -f "$RAW" "$ERR" "$TMP"' EXIT
# Times on nostrod's interface are microseconds since 1970 UTC.
FROM_US=$(( ($(date +%s) - DAYS * 86400) * 1000000 ))
# Far above anything 90 days of this account holds. The window is what bounds
# the answer; an answer that fills the limit is treated as cut short below.
LIMIT=100000
# One call to nostrod's published interface (packaging/dbus/
# net.catcrafts.Nostro1.xml in Nostro). Interactive authorization is OFF on
# purpose: nobody is there to answer a password dialog from a timer, and a
# dialog popping up hourly would train its reader to type a password without
# looking.
ask() {
busctl --system --json=short --timeout=300 --allow-interactive-authorization=no \
call net.catcrafts.Nostro1 /net/catcrafts/Nostro1 net.catcrafts.Nostro1 "$@"
}
# Transactions asks the bank for what is new before it answers, so this is as
# fresh as a direct read. The interface is nostrod's published one
# (packaging/dbus/net.catcrafts.Nostro1.xml in Nostro):
# Transactions(account s, query a{sv}) -> (a(sssssxxss) transactions, as notes)
# Interactive authorization is OFF on purpose: nobody is there to answer a
# password dialog from a timer, and a dialog popping up hourly would train its
# reader to type a password without looking.
if ! busctl --system --json=short --timeout=300 --allow-interactive-authorization=no \
call net.catcrafts.Nostro1 /net/catcrafts/Nostro1 net.catcrafts.Nostro1 \
Transactions 'sa{sv}' "$IBAN" 2 from x "$FROM_US" limit t "$LIMIT" \
>"$RAW" 2>"$ERR"; then
refused() {
cat "$ERR" >&2
if grep -qi 'password' "$ERR"; then
echo "$0: nostrod only lets a program look without a password in your active" \
@ -115,8 +110,47 @@ if ! busctl --system --json=short --timeout=300 --allow-interactive-authorizatio
echo "$0: could not read the account through nostrod; nothing was shipped and the" \
"remote file still holds what it did" >&2
exit 1
}
# Which bank the account is at, as nostrod names it. Accounts answers
# a(ssa(ssssx)) connectors: name, bank, accounts: name, BIC, IBAN, currency, balance
# and all that is taken from it is the bank of the connector that has this
# IBAN. The answer goes through a pipe and is never written down: it carries
# every account's balance.
BANK=$( { ask Accounts 2>"$ERR" || true; } | python3 -I -c '
import json, sys
want = sys.argv[1]
try:
reply = json.load(sys.stdin)
except ValueError:
sys.exit(0) # nostrod refused: the caller reads why from its stderr
if reply.get("type") != "a(ssa(ssssx))as":
sys.exit("pull-and-ship-credits: nostrod answered Accounts with type %r, not the "
"a(ssa(ssssx))as this script reads; nothing was shipped" % reply.get("type"))
for name, bank, accounts in reply["data"][0]:
for account in accounts:
if account[2].replace(" ", "").upper() == want:
print(bank)
sys.exit(0)
' "$IBAN" ) || exit 1
if [ -z "$BANK" ]; then
[ -s "$ERR" ] && refused
echo "$0: no account with the IBAN in TRANSFER_IBAN is connected in nostrod" \
"(\`nostro accounts\` lists them); nothing was shipped" >&2
exit 1
fi
# Times on nostrod's interface are microseconds since 1970 UTC.
FROM_US=$(( ($(date +%s) - DAYS * 86400) * 1000000 ))
# Far above anything 90 days of this account holds. The window is what bounds
# the answer; an answer that fills the limit is treated as cut short below.
LIMIT=100000
# Transactions asks the bank for what is new before it answers, so this is as
# fresh as a direct read:
# Transactions(account s, query a{sv}) -> (a(sssssxxss) transactions, as notes)
ask Transactions 'sa{sv}' "$IBAN" 2 from x "$FROM_US" limit t "$LIMIT" >"$RAW" 2>"$ERR" || refused
# nostrod's answer -> the credit lines the rail reads. INCOMING ONLY: outgoing
# lines are supplier payments and card spending, the matcher ignores negative
# amounts anyway, and sending them would put the business's outgoing payment
@ -124,11 +158,11 @@ fi
#
# -I keeps python from importing anything out of this directory or the
# environment: this is the step that decides what counts as money received.
python3 -I - "$RAW" "$LIMIT" >"$TMP" <<'PY'
python3 -I - "$RAW" "$LIMIT" "$BANK" >"$TMP" <<'PY'
import json
import sys
raw_path, limit = sys.argv[1], int(sys.argv[2])
raw_path, limit, bank = sys.argv[1], int(sys.argv[2]), sys.argv[3]
with open(raw_path, encoding="utf-8") as f:
reply = json.load(f)
@ -146,38 +180,24 @@ if len(transactions) >= limit:
"limit asked for, so the answer may be cut short; nothing was shipped"
% len(transactions))
# bunq's Payment.type -> the ledger's `via` vocabulary. THE SAME TABLE AS
# BunqMethodFor in server/implementations/Catcrafts.Server-Bunq.cpp, which
# labels the credits the webhook writes. Keep the two in step: a payment must
# get one label whichever path delivers it first. An unknown type goes through
# verbatim, never guessed, because "sepa" is final and a card payment is not.
METHODS = {
"EBA_SCT": "sepa",
"IDEAL": "ideal",
"FIS": "card",
"BUNQ": "bunq",
"SWIFT": "swift",
"EBA_SDD": "directdebit",
}
without_id = 0
for name, bic, iban, description, currency, amount, time, bank_id, kind in transactions:
# Only euro can pay a euro order, and only money coming in pays anything.
if currency != "EUR" or amount <= 0:
continue
# The id is what the server deduplicates on when the webhook delivers the
# same payment. A line without one could be counted twice, so it is left out
# and said aloud instead.
# The id is what the server tells the same payment by when the callback
# delivered it too. A line without one could be counted twice, so it is
# left out and said aloud instead.
if not bank_id:
without_id += 1
continue
# nostrod's kind is "<type>/<sub_type>", e.g. "EBA_SCT/SCT".
payment_type = kind.split("/", 1)[0]
method = METHODS.get(payment_type, payment_type) or "bank"
# Same keys, same order and same escaping as the server's own writer
# (AppendCreditTo): text as UTF-8, control characters escaped.
# How it arrived is not decided here. The line carries the bank's own
# kind for the payment ("<type>/<sub type>") and the bank it is of, and the
# server puts that into the ledger's words with the same table it uses for
# a payment the callback delivered (CreditMethodFor). So this script needs
# no table of any bank's words, and a payment gets one word either way.
print(json.dumps({"id": bank_id, "reference": description,
"amount_minor": amount, "method": method},
"amount_minor": amount, "bank": bank, "kind": kind},
ensure_ascii=False, separators=(",", ":")))
if without_id:

View file

@ -1,78 +0,0 @@
#!/bin/sh
# Tell bunq where to push payment notifications.
#
# Run from a machine whose address the bunq API key permits — the web host is
# not one, which is the whole reason webhooks exist in this setup. The session
# it uses comes from the context file that tools/pull-and-ship-credits.sh
# created, so run that at least once first.
#
# tools/register-bunq-webhook.sh 'https://catcrafts.net/hooks/bunq/<secret>'
# tools/register-bunq-webhook.sh --show # list what is registered
#
# THIS REPLACES THE WHOLE FILTER SET. bunq treats the POST as "here is the
# complete list", so a call that omits an existing filter deletes it. Every
# filter wanted has to be in the one request, which is why --show exists: look
# before overwriting.
#
# The target URL is never echoed: it is a shared secret, and this script's
# output tends to end up pasted into issues and chat logs.
set -eu
cd "$(dirname "$0")/.."
CTX="${CREDITS_LOCAL:-$HOME/.cache/catcrafts}/orders.jsonl.transfer-credits.jsonl.bunq-context.json"
[ -f "$CTX" ] || { echo "$0: no bunq context at $CTX — run tools/pull-and-ship-credits.sh first" >&2; exit 1; }
SESSION=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["session_token"])' "$CTX")
USERID=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["user_id"])' "$CTX")
[ -n "$SESSION" ] && [ "$USERID" != "0" ] || { echo "$0: context has no session — run the pull once" >&2; exit 1; }
API="https://api.bunq.com/v1/user/$USERID/notification-filter-url"
HDRS="-H Content-Type:application/json -H X-Bunq-Client-Authentication:$SESSION -H User-Agent:catcrafts.net-register/1.0"
if [ "${1:-}" = "--show" ]; then
# Redact the secret out of the response before it reaches a terminal.
# shellcheck disable=SC2086
curl -s $HDRS "$API" | python3 -c '
import json,sys,re
try: d=json.load(sys.stdin)
except Exception: print("could not parse bunq response"); sys.exit(1)
for item in d.get("Response",[]):
f=item.get("NotificationFilterUrl") or {}
t=f.get("notification_target","")
print(" category=%-22s target=%s" % (f.get("category","?"), re.sub(r"(/hooks/bunq/).*", r"\1<redacted>", t)))
'
exit 0
fi
TARGET="${1:-}"
case "$TARGET" in
https://*) ;;
*) echo "$0: pass the full https:// callback URL (bunq refuses plain http)" >&2; exit 2 ;;
esac
# MUTATION alone: it fires on every balance change and carries the Payment
# object, which is exactly what the handler decodes. Adding PAYMENT as well
# would deliver most events twice, and while the handler deduplicates on the
# payment id, doubling the traffic to buy nothing is not a trade.
BODY=$(python3 -c '
import json,sys
# No notification_delivery_method: bunq rejects it as "Superfluous" on this
# endpoint, because /notification-filter-url already means URL delivery.
print(json.dumps({"notification_filters":[
{"notification_target":sys.argv[1],
"category":"MUTATION"}]}))
' "$TARGET")
# shellcheck disable=SC2086
OUT=$(printf '%s' "$BODY" | curl -s -w '\n%{http_code}' $HDRS -X POST --data-binary @- "$API")
CODE=$(printf '%s' "$OUT" | tail -1)
if [ "$CODE" = 200 ]; then
echo "$0: registered MUTATION callbacks (target not shown)"
echo "$0: verify with $0 --show"
else
# The body can echo the target back, so redact before printing an error.
printf '%s\n' "$OUT" | sed 's#\(/hooks/bunq/\)[^"]*#\1<redacted>#g' >&2
echo "$0: bunq refused the registration (HTTP $CODE)" >&2
exit 1
fi