security-review-fixes #1

Merged
jorijnvdgraaf merged 5 commits from security-review-fixes into master 2026-11-26 10:09:20 +00:00
16 changed files with 2315 additions and 170 deletions

View file

@ -169,6 +169,45 @@ catcrafts.net {
file_server file_server
} }
# ── the bank's callback ──────────────────────────────────────────────
#
# The bank posts here when money lands (deploy/README.md, "How settlement
# actually reaches the shop"). A callback is NOT signed, so what makes one
# believable is the controls around the endpoint, and three of the four
# are this block. None of it is optional once BANK_CALLBACK_PATH is set:
#
# remote_ip only the range the bank publishes for its callbacks reaches
# the backend. Anyone else is answered 403 here, whatever
# follows the prefix, so the answer says nothing about
# whether a guessed path was the right one. When the bank
# moves its range, callbacks 403 and settlement falls back to
# the hourly pull: it fails closed.
# the path only the NON-secret prefix is written here. The secret
# segment is BANK_CALLBACK_PATH in payments.env and nowhere
# else, which is what lets this file be public.
# log_skip the request line carries the secret, and the access log
# below feeds the PUBLIC analytics report. Without this line
# the path is published within the hour. (The analytics
# script drops /hooks lines from the public tier as well, so
# the report does not rest on this directive alone.)
#
# remote_ip is the address of the connection itself, which is the right
# thing to match while this Caddy faces the internet directly. Behind
# another proxy every connection is that proxy's: match client_ip there,
# with trusted_proxies set, or this allowlist admits everyone or no one.
#
# All of it assumes this block is the only way to the backend. See the
# note on port 8081 above the catch-all below.
log_skip /hooks/bunq/*
handle /hooks/bunq/* {
@not_the_bank not remote_ip 185.40.108.0/22
respond @not_the_bank 403
request_body {
max_size 64KiB
}
reverse_proxy 127.0.0.1:8081
}
# ── everything else: server-rendered ───────────────────────────────── # ── everything else: server-rendered ─────────────────────────────────
# #
# Pages, /feed.xml, /sitemap.xml and later /api/*. The backend sets its own # Pages, /feed.xml, /sitemap.xml and later /api/*. The backend sets its own
@ -178,15 +217,29 @@ catcrafts.net {
# possible: reverse_proxy APPENDS the real client address to # possible: reverse_proxy APPENDS the real client address to
# X-Forwarded-For, and the backend reads the rightmost entry (see # X-Forwarded-For, and the backend reads the rightmost entry (see
# ClientAddressFromForwarded — the leftmost is whatever the client claimed). # ClientAddressFromForwarded — the leftmost is whatever the client claimed).
# That is only sound while nothing but Caddy can reach 8081, which is why # That is only sound while nothing but Caddy can reach 8081, and the same
# the backend binds loopback and why the warning at the top of this file # goes for the bank callback's allowlist above. THE BACKEND DOES NOT
# says not to expose the port. # ENFORCE THAT ITSELF: Crafter.Network's ListenerHTTP1 takes a port and no
# address and binds every IPv4 interface, whatever the server's startup
# line says (Crafter.Network issue #11 asks for the address). Until it can
# be given 127.0.0.1 the host firewall is what keeps the port private, so
# check it: `ss -ltn 'sport = :8081'` on the box shows 0.0.0.0, and
# `curl -m 5 http://<this host>:8081/api/healthz` from anywhere else must
# time out.
#
# request_body is the same 64 KiB the backend sets on its own listener
# (kMaxRequestBodyBytes): nothing proxied here is larger than a checkout
# form or a bank's callback, and refusing more at the edge means an
# oversized upload never crosses to the backend at all.
# #
# Caddy's own rate_limit directive is a third-party module and is NOT in a # Caddy's own rate_limit directive is a third-party module and is NOT in a
# standard build — adding it here without rebuilding Caddy stops the server # standard build — adding it here without rebuilding Caddy stops the server
# from starting. If volume ever justifies limiting at the edge, build Caddy # from starting. If volume ever justifies limiting at the edge, build Caddy
# with github.com/mholt/caddy-ratelimit first. # with github.com/mholt/caddy-ratelimit first.
handle { handle {
request_body {
max_size 64KiB
}
reverse_proxy 127.0.0.1:8081 { reverse_proxy 127.0.0.1:8081 {
health_uri /api/healthz health_uri /api/healthz
} }

View file

@ -54,6 +54,32 @@ Crafter.Network's `ListenerHTTP1` rather than its HTTP/3 `ListenerHTTP` for one
concrete reason: **Caddy cannot `reverse_proxy` to an h3 upstream.** Port 8081 concrete reason: **Caddy cannot `reverse_proxy` to an h3 upstream.** Port 8081
must never be exposed directly. must never be exposed directly.
**The backend does not enforce that itself, and its startup line is wrong
about it.** `ListenerHTTP1` takes a port and no address, and binds every IPv4
interface (`0.0.0.0`), while the server logs `listening on 127.0.0.1`. Until
the listener can be given `127.0.0.1`
([Crafter.Network issue #11](https://forgejo.catcrafts.net/Catcrafts/Crafter.Network/issues/11)),
the host firewall is the only thing keeping the port private. Three things
rest on it:
- the per-peer checkout limit, which trusts the address Caddy puts in
`X-Forwarded-For`;
- the bank callback's source-IP allowlist, which lives in Caddy and is simply
skipped by anyone who can reach the backend directly;
- the bound on what one request can make the server hold. The backend's own
64 KiB limit is on the decoded body. A chunked request sent straight to the
port can pad its chunk framing and have one connection hold hundreds of
megabytes for 64 KiB of body (reproduced in review, 2026-11-26). Caddy's
`request_body` cap is what refuses an oversized request before it gets
there, and the parser itself is Crafter.Network's to fix.
So check it after any firewall change:
```sh
ss -ltn 'sport = :8081' # on the box: shows 0.0.0.0:8081
curl -m 5 http://<this host>:8081/api/healthz # from anywhere else: must time out
```
## One-time host setup ## One-time host setup
```sh ```sh
@ -393,8 +419,19 @@ 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. machine, which asks nostrod and ships the result. The next section has both.
Every line carries the bank's own id for the payment. The callback skips an id 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 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 payment, so a payment that both deliver is meant to be in the file once. The
order nobody paid twice for. rail does not depend on that: it counts an id once however many lines carry
it, because two lines can still happen (a callback landing while the pull is
replacing the file, an address registered twice at the bank), and summed they
would settle an order on half its price. When it sees a duplicate it says so
in the journal, once per order:
```
transfer: CC-… is quoted by a payment the credits file lists 1 time(s) too many. …
```
Seen regularly, that means the callback address is registered more than once:
`nostro callbacks --connector NAME` lists what is, and there should be one.
The server knows no bank. What a bank posts is read by `ReadCallback`, and how 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 a payment arrived is said by `PaymentMethodOf`, both of the module
@ -440,12 +477,19 @@ listing shows what is registered whoever set it. The registration in place on
**A callback is not signed.** bunq's are not: verified against doc.bunq.com, **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 there is no HMAC and no server signature, and certificate pinning
authenticates us to bunq rather than bunq to us. So the endpoint's 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: authentication is the controls around it, all of which have to stay in place.
The first three are one block of `deploy/Caddyfile.example`, "the bank's
callback": merge it with the rest of that file. A Caddyfile without it still
proxies the callback to the backend, from anyone, and logs the secret path.
1. **Source-IP allowlist** for `185.40.108.0/22` in the Caddyfile. This is the 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 strong one: forging requires completing a TLS handshake from inside that
range. bunq warns the range may change; if it does, callbacks 403 and range. bunq warns the range may change; if it does, callbacks 403 and
settlement stops — it fails closed. settlement stops — it fails closed. It is only as strong as Caddy being
the one way in: a request that reaches port 8081 directly never meets this
rule, and the backend's listener does not bind loopback on its own (see
"Why the backend speaks plaintext HTTP/1.1"), so the firewall on that port
is part of this control.
2. **A secret path.** Caddy matches only the non-secret prefix `/hooks/bunq/*`, 2. **A secret path.** Caddy matches only the non-secret prefix `/hooks/bunq/*`,
so the secret lives solely in `BANK_CALLBACK_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 in the web server config. The backend compares it in constant time, and a
@ -453,7 +497,13 @@ authentication is the controls around it, all of which have to stay in place:
405 — a different answer there would confirm a guessed path. 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 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 access log and then ingested into the GoAccess database and shown in its
top-URLs panel, i.e. leaked to anyone who opens `/analytics/`. top-URLs panel, i.e. leaked to anyone who opens `/analytics/`. The
analytics script drops `/hooks` lines from the public tier as well
(`CENSOR_RE`), so the public page does not rest on this one directive; the
raw log and the private tier do, which is why it stays. If it was ever
missing while callbacks arrived, the path is in the retained logs: set a
new `BANK_CALLBACK_PATH`, register it with `nostro callbacks`, and rebuild
the public analytics DB (the procedure is at the top of the script).
4. **The account.** A bank posts to whatever address any of its customers 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 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 an account of their own and pay themselves, and the callback that follows
@ -576,8 +626,9 @@ 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 with no network, and it is the manual escape hatch for settling a transfer by
hand. `--mark-paid` remains the other one. hand. `--mark-paid` remains the other one.
Two matching properties worth knowing, both pinned in Four matching properties worth knowing. The first three are pinned in
`ShouldMatchBankTransfers`: `ShouldMatchBankTransfers` (the third over HTTP as well, in
`ShouldSettleBankTransfers`), the fourth in `ShouldFoldTheOrderLedger`:
* **The reference matches in whatever form the payer typed it.** Both sides * **The reference matches in whatever form the payer typed it.** Both sides
are reduced to upper-case alphanumerics and the match is on the reference are reduced to upper-case alphanumerics and the match is on the reference
@ -591,11 +642,50 @@ Two matching properties worth knowing, both pinned in
Outgoing amounts are ignored, so a refund quoting the reference cannot pay Outgoing amounts are ignored, so a refund quoting the reference cannot pay
for the order it refunded. for the order it refunded.
One known limitation, logged rather than solved: a single transfer quoting * **A payment is spent once.** A transfer that settled one order pays for no
**two** order references cannot be attributed by a per-order matcher, and both other, however many references its description quotes. Before the rail
orders would settle on the same money. The rail detects the shape and logs reports an order paid it writes which payment settled it, by the bank's id,
"settle this one by hand"; at this volume that is proportionate, but do not to `<credits>.claims` (default
assume the matcher is total. `/var/lib/catcrafts/orders.jsonl.transfer-credits.jsonl.claims`), and every
later match leaves a claimed payment out. It cannot live in the credits
file, which the pull replaces every hour. This used to be a "known
limitation": the rail only logged a transfer that quoted two orders and
settled both. It was a way to pay once for several orders (place three,
send one transfer naming all three; found in review on 2026-11-26), and
what a description looks like is no defence, because the payer writes it.
* **A reference names one order.** The reference is 24 bits of the order
token, short on purpose because a person types it, and two orders sharing
one would both be paid by a transfer quoting it. Checkout therefore mints
its token against every reference the ledger has ever held, lapsed and
cancelled orders included: their payments are still in the bank's history.
What the first of those means in practice. A payer who really does send ONE
transfer for two orders gets the first of them settled; the other keeps
waiting, and the journal says so once per order and per run of the server:
```
transfer: CC-… is quoted by 1 payment(s) whose money already settled another order, …
```
Settle that one with `--mark-paid` after looking at the amount. The amount is
not split across orders automatically; at this volume a human finishing the
rare case is proportionate. A settlement on a payment that *looks* as if it
names a second order is logged too, as a pointer, and decides nothing: a name
followed by a date has the same shape as a reference.
The claims file is small and append-only, like the ledger. Keep it with the
ledger backup. Without it nothing is lost that the bank does not also have,
but a payment that named several orders could then settle a second one of
them. If it cannot be written (a full disk, wrong ownership after a restore)
the rail settles nothing and says why, rather than settle on money it cannot
mark as spent. If it is there and cannot be READ at startup, the bank rail
does not start at all, for the same reason: the journal names the file, and
checkout offers only the other rail until it is fixed and the server
restarted.
How far "written before the order is reported paid" goes: it holds across a
crash or a restart of the server at any moment. Neither this file nor the
ledger is fsynced, so a power cut can keep one line and lose the other.
### The EURC rail ### The EURC rail
@ -991,6 +1081,23 @@ Each appends a status event to the log — nothing is ever rewritten, so the
file remains its own audit trail. Deleting personal data on request is an edit file remains its own audit trail. Deleting personal data on request is an edit
of the fields the seven-year fiscal retention does not cover. of the fields the seven-year fiscal retention does not cover.
Neither needs a restart. The running server holds the ledger folded in memory
(an order page or `/financials` is a lookup, not a read of the whole history)
and folds the file again whenever its size or modification time has changed,
which a CLI transition and an edit in any editor both do. The first request
after one takes the length of a fold: between a third and two thirds of a
second for 40 000 orders, in two measurements. The file is the ledger and the
server's copy is a reading of it; memory for that copy is 3 to 4 KB an order.
Two changes it cannot see, both narrow. One leaves BOTH the size and the
modification time as they were: a same-length edit by a tool that then puts
the old time back (`touch -r`, a sync tool patching in place). The other is a
same-length edit that lands in the few microseconds in which the server is
itself appending a line, because the server takes the file's new time as its
own doing. A person with an editor will not hit that one; a script rewriting
fields in a loop could. Nothing here does either, and a restart reads the
file afresh.
## The open financials page ## The open financials page
`/financials` publishes running totals only: sales, donations, and expenses `/financials` publishes running totals only: sales, donations, and expenses
@ -1034,11 +1141,13 @@ reports, each with its own persistent DB and ingest ledger:
anonymized at ingest (last octet zeroed before anything reaches its DB), anonymized at ingest (last octet zeroed before anything reaches its DB),
no HOSTS or full-URL REFERRERS panels, and log lines matching `CENSOR_RE` no HOSTS or full-URL REFERRERS panels, and log lines matching `CENSOR_RE`
in the script never enter its DB at all — the public tier cannot leak in the script never enter its DB at all — the public tier cannot leak
what it never ingested. `CENSOR_RE` covers `/api` **and `/order`**: an what it never ingested. `CENSOR_RE` covers `/api`, **`/order`** and
order token is the entire capability to read that buyer's status page and `/hooks`: an order token is the entire capability to read that buyer's
their invoice (name, street, postal code, city), so publishing the path status page and their invoice (name, street, postal code, city), so
publishes the buyer. Keep secrets out of URL *paths* regardless — query publishing the path publishes the buyer, and `/hooks/bunq/<secret>` is the
strings are already stripped, paths are not. bank callback's shared secret (Caddy's `log_skip` already keeps it out of
the log; this is the second layer). Keep secrets out of URL *paths*
regardless — query strings are already stripped, paths are not.
- `https://catcrafts.net/analytics/private/` — **uncensored** (basic auth, - `https://catcrafts.net/analytics/private/` — **uncensored** (basic auth,
hash in the Caddyfile): full IPs, all panels. hash in the Caddyfile): full IPs, all panels.

View file

@ -37,11 +37,19 @@ OUT_PRIVATE=/var/www/analytics-private/index.html
# PATH), so an uncensored public tier would have published a harvestable index # PATH), so an uncensored public tier would have published a harvestable index
# of every buyer's address within an hour of the first sale. # of every buyer's address within an hour of the first sale.
# #
# /hooks is here as the second of two layers. /hooks/bunq/<secret> is where the
# bank posts its callbacks, and that path is the endpoint's shared secret. The
# Caddyfile keeps it out of the access log altogether (log_skip on the
# prefix), so normally there is no such line to drop. But that is one
# directive in a file that is merged by hand, and the cost of it going missing
# would be the secret on a public page: with this, the public tier does not
# depend on it. The raw log and the private tier still do, so log_skip stays.
#
# Filters apply at INGEST, so this must be correct BEFORE the shop opens. # Filters apply at INGEST, so this must be correct BEFORE the shop opens.
# Should an order URL ever reach the public DB, changing this line is not # Should an order URL ever reach the public DB, changing this line is not
# enough — follow the re-filter procedure at the top of this file to rebuild # enough — follow the re-filter procedure at the top of this file to rebuild
# from the retained raw logs. # from the retained raw logs.
CENSOR_RE='"uri":"/(api|order)' CENSOR_RE='"uri":"/(api|order|hooks)'
# Serialize runs: a manual run racing the hourly timer once ingested the same # Serialize runs: a manual run racing the hourly timer once ingested the same
# rotated log twice (both processes passed the ledger check before either # rotated log twice (both processes passed the ledger check before either

View file

@ -47,6 +47,127 @@ std::string_view ClientAddressFromForwarded(std::string_view forwarded) {
return Form::Trim(last); return Form::Trim(last);
} }
namespace {
// "203.0.113.7": four decimal octets and nothing else.
std::optional<std::array<std::uint8_t, 4>> ParseIPv4(std::string_view s) {
std::array<std::uint8_t, 4> out{};
for (std::size_t i = 0; i < 4; ++i) {
const std::size_t dot = s.find('.');
if ((dot == std::string_view::npos) != (i == 3)) return std::nullopt;
const std::string_view part = s.substr(0, dot);
if (part.empty() || part.size() > 3) return std::nullopt;
unsigned value = 0;
const auto [end, ec] =
std::from_chars(part.data(), part.data() + part.size(), value);
if (ec != std::errc{} || end != part.data() + part.size() || value > 255) {
return std::nullopt;
}
out[i] = static_cast<std::uint8_t>(value);
if (i < 3) s = s.substr(dot + 1);
}
return out;
}
// An IPv6 address as its eight 16-bit groups. Takes what a proxy writes: the
// "::" shorthand, any case, leading zeros or none, a dotted IPv4 tail, and a
// zone after '%' (dropped). Refuses anything else, so a string that is merely
// full of colons is not mistaken for an address.
std::optional<std::array<std::uint16_t, 8>> ParseIPv6(std::string_view s) {
if (const std::size_t zone = s.find('%'); zone != std::string_view::npos) {
s = s.substr(0, zone);
}
// A dotted tail stands for the last two groups.
std::optional<std::array<std::uint8_t, 4>> v4;
if (s.find('.') != std::string_view::npos) {
const std::size_t colon = s.rfind(':');
if (colon == std::string_view::npos) return std::nullopt;
v4 = ParseIPv4(s.substr(colon + 1));
if (!v4) return std::nullopt;
s = s.substr(0, colon + 1);
// What is left ends in the colon that led up to the tail. It goes,
// unless it is the second half of a "::", which is the shorthand.
if (!s.ends_with("::")) s.remove_suffix(1);
}
const std::size_t gap = s.find("::");
if (gap != std::string_view::npos
&& s.find("::", gap + 1) != std::string_view::npos) {
return std::nullopt; // one "::" at most, and never ":::"
}
auto groups = [](std::string_view part, std::vector<std::uint16_t>& into) {
if (part.empty()) return true;
while (true) {
const std::size_t colon = part.find(':');
const std::string_view group = part.substr(0, colon);
if (group.empty() || group.size() > 4) return false;
std::uint16_t value = 0;
const auto [end, ec] = std::from_chars(
group.data(), group.data() + group.size(), value, 16);
if (ec != std::errc{} || end != group.data() + group.size()) return false;
into.push_back(value);
if (colon == std::string_view::npos) return true;
part = part.substr(colon + 1);
}
};
std::vector<std::uint16_t> head, tail;
if (gap == std::string_view::npos) {
if (!groups(s, head)) return std::nullopt;
} else if (!groups(s.substr(0, gap), head) || !groups(s.substr(gap + 2), tail)) {
return std::nullopt;
}
const std::size_t dotted = v4 ? 2 : 0;
const std::size_t have = head.size() + tail.size() + dotted;
// Without the shorthand all eight are written out; with it, it stands
// for at least one.
if (gap == std::string_view::npos ? have != 8 : have > 7) return std::nullopt;
std::array<std::uint16_t, 8> out{};
std::ranges::copy(head, out.begin());
std::ranges::copy(tail, out.end() - static_cast<std::ptrdiff_t>(dotted + tail.size()));
if (v4) {
out[6] = static_cast<std::uint16_t>(((*v4)[0] << 8) | (*v4)[1]);
out[7] = static_cast<std::uint16_t>(((*v4)[2] << 8) | (*v4)[3]);
}
return out;
}
} // namespace
std::string RateLimitKeyFor(std::string_view address) {
address = Form::Trim(address);
if (address.empty()) return {};
const std::string asWritten(address);
auto dotted = [](unsigned a, unsigned b, unsigned c, unsigned d) {
return std::format("{}.{}.{}.{}", a, b, c, d);
};
if (address.find(':') == std::string_view::npos) {
const auto v4 = ParseIPv4(address);
return v4 ? dotted((*v4)[0], (*v4)[1], (*v4)[2], (*v4)[3]) : asWritten;
}
if (address.size() > 2 && address.front() == '[' && address.back() == ']') {
address = address.substr(1, address.size() - 2);
}
const auto v6 = ParseIPv6(address);
if (!v6) return asWritten;
const std::array<std::uint16_t, 8>& g = *v6;
// ::ffff:a.b.c.d is an IPv4 client seen through an IPv6 socket. Keyed as
// the IPv4 address it is, so one client is not two peers depending on
// which way it was reported.
if (g[0] == 0 && g[1] == 0 && g[2] == 0 && g[3] == 0 && g[4] == 0 && g[5] == 0xffff) {
return dotted(g[6] >> 8, g[6] & 0xff, g[7] >> 8, g[7] & 0xff);
}
return std::format("{:x}:{:x}:{:x}::/48", g[0], g[1], g[2]);
}
bool OriginAllowed(std::string_view origin, std::string_view redirectBase) { bool OriginAllowed(std::string_view origin, std::string_view redirectBase) {
if (origin.empty()) return true; // not a browser form post; see the header if (origin.empty()) return true; // not a browser form post; see the header
// A trailing slash is legal in a configured base and never present in an // A trailing slash is legal in a configured base and never present in an
@ -85,6 +206,11 @@ std::string gWebhookPath;
std::string gCallbackBank; std::string gCallbackBank;
std::string gCallbackIban; std::string gCallbackIban;
// The ceiling on one request's body, handed to the listener in Serve(), where
// the reasoning is. 64 KiB: four times the largest form checkout accepts, and
// well above what a bank posts.
constexpr std::uint64_t kMaxRequestBodyBytes = 64 * 1024;
// The bank-derived aggregates for /financials live in Catcrafts.Server- // The bank-derived aggregates for /financials live in Catcrafts.Server-
// Financials.cpp, which owns their file. They are read through // Financials.cpp, which owns their file. They are read through
// CurrentFinancials() per request rather than cached: unlike the content // CurrentFinancials() per request rather than cached: unlike the content
@ -370,12 +496,14 @@ HTTPResponse RenderPage(std::string_view target) {
// The financials page: lifetime sales folded live from the order ledger, // The financials page: lifetime sales folded live from the order ledger,
// donations and expenses from the bank-aggregates file. Server-rendered // donations and expenses from the bank-aggregates file. Server-rendered
// here because both inputs are runtime state; the shared dispatch's case // here because both inputs are runtime state; the shared dispatch's case
// is the backend-down fallback, like orders. Refolding the ledger per // is the backend-down fallback, like orders. The page's whole promise is
// request is what every order lookup already does, and the page's whole // that a refresh shows the current totals, so the response is not cached:
// promise is that a refresh shows the current totals — so no caching. // the totals are summed on every request, from the fold of the ledger the
// order store holds, which follows the file (LedgerSales). That is a pass
// over orders already in memory, not a read of the ledger from disk,
// which is what this page cost each visitor before 2026-11-26.
if (route.kind == RouteKind::Financials) { if (route.kind == RouteKind::Financials) {
const std::vector<OrderRecord> orders = ListOrders(); const SalesSummary sales = LedgerSales();
const SalesSummary sales = SummarizeSales(orders);
const Financials fin = CurrentFinancials(); const Financials fin = CurrentFinancials();
// Shop donations ride along from the same fold: they are live like // Shop donations ride along from the same fold: they are live like
// sales, and the renderer joins them with the bank-side donations. // sales, and the renderer joins them with the bank-side donations.
@ -485,6 +613,12 @@ HTTPResponse ServeFeed() {
// pull, since tripping it still denies everyone. A flood broad enough to reach // pull, since tripping it still denies everyone. A flood broad enough to reach
// it is an infrastructure problem, and belongs to Caddy and the host. // it is an infrastructure problem, and belongs to Caddy and the host.
// //
// A "peer" is an IPv4 address or an IPv6 /48, never a single IPv6 address
// (RateLimitKeyFor). One subscriber holds a whole IPv6 prefix, so a budget per
// address was six submissions per ten minutes for each of an unlimited number
// of addresses: the per-peer cap did nothing over IPv6, and the global cap
// was the only limit an IPv6 client ever met.
//
// Unproxied requests (dev, e2e, a direct curl at the loopback port) carry no // Unproxied requests (dev, e2e, a direct curl at the loopback port) carry no
// X-Forwarded-For. They are charged to the global budget only — there is no // X-Forwarded-For. They are charged to the global budget only — there is no
// peer to key on, and inventing one would be a lie. // peer to key on, and inventing one would be a lie.
@ -795,10 +929,13 @@ HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) {
} }
// Charged to this peer's own budget, so a flood costs the flooder their // Charged to this peer's own budget, so a flood costs the flooder their
// checkout and nobody else theirs. // checkout and nobody else theirs. The budget is kept per IPv4 address
std::string_view peer; // and per IPv6 /48, not per IPv6 address: one subscriber holds a whole
// prefix and could otherwise submit from a fresh address every time
// (RateLimitKeyFor has the reasoning).
std::string peer;
if (const auto fwd = req.headers.find("x-forwarded-for"); fwd != req.headers.end()) { if (const auto fwd = req.headers.find("x-forwarded-for"); fwd != req.headers.end()) {
peer = ClientAddressFromForwarded(fwd->second); peer = RateLimitKeyFor(ClientAddressFromForwarded(fwd->second));
} }
if (!RateLimitAllows(peer)) { if (!RateLimitAllows(peer)) {
return reject({{ "", "Too many submissions just now — please try again shortly." }}, return reject({{ "", "Too many submissions just now — please try again shortly." }},
@ -845,6 +982,12 @@ HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) {
parsed.value, "422"); parsed.value, "422");
} }
parsed.value.color = variant->slug; parsed.value.color = variant->slug;
} else {
// A product without variants has no colour. Whatever was posted
// in the field is dropped here, not stored: validation only
// bounds its length, and the stored colour is printed on the
// order page and into the invoice's amounts table.
parsed.value.color.clear();
} }
unitMinor = variant ? variant->priceInclMinor : product->priceInclMinor; unitMinor = variant ? variant->priceInclMinor : product->priceInclMinor;
@ -886,8 +1029,25 @@ HTTPResponse HandleCheckout(const HTTPRequest& req, const Route& route) {
unitMinor, parsed.value.quantity, *shippingMinor, parsed.value.country); unitMinor, parsed.value.quantity, *shippingMinor, parsed.value.country);
} }
// A token whose reference no other order has. The reference is what a
// payer quotes and a transfer is matched on, and it is only 24 bits of
// the token, so it is checked against the whole ledger rather than left
// to chance (NewUniqueOrderToken has the reasoning). Minted here, after
// validation and both rate limits, so a flood of refused submissions
// never reads the ledger at all.
const std::optional<std::string> token = NewUniqueOrderToken();
if (!token) {
std::println(std::cerr,
"checkout: no order reference could be minted that no other "
"order has. The ledger holds too many orders for a six-digit "
"reference; it needs lengthening before checkout can resume");
return reject({{ "", "Couldn't create the order — something is wrong on this "
"end. Nothing was charged. Please try again later." }},
parsed.value, "500");
}
OrderRecord order; OrderRecord order;
order.token = NewOrderToken(); order.token = *token;
order.reference = ReferenceFromToken(order.token); order.reference = ReferenceFromToken(order.token);
order.product = product->slug; order.product = product->slug;
order.color = parsed.value.color; order.color = parsed.value.color;
@ -1459,6 +1619,29 @@ int Serve(std::uint16_t port) {
}); });
ListenerHTTP1 listener(port, std::move(routes), std::move(fallback)); ListenerHTTP1 listener(port, std::move(routes), std::move(fallback));
// The largest body this server accepts for one request. The listener's
// own default is 512 MiB, which suits a library that also takes uploads,
// and nothing here takes one: a checkout form is refused above 16 KiB
// (Form::kMaxBodyBytes) and a bank's callback is a few kilobytes of JSON.
// A request that announces more than this in Content-Length is answered
// 400 from its headers, with none of its body read. Set before Listen(),
// which is when the limit starts being used.
//
// What it does NOT bound is everything a connection can make this
// process hold. The limit is on the DECODED body. A chunked request
// spends bytes on framing too, each chunk-size line may run to 8 KiB
// with its extension, and the parser only releases what it has consumed
// once nothing is left unread. A client talking to this port directly
// can therefore send a one-byte chunk behind every 8 KiB of framing and
// have the connection hold hundreds of megabytes for 64 KiB of body
// (reproduced in review, 2026-11-26: 476 MiB on the wire). Through Caddy
// an oversized body is refused by its own request_body cap, which was
// tested; and Caddy decodes a chunked body and frames it again itself,
// so a client's padded chunk lines should end there, which is from
// reading and was not measured. Either way the bound that matters is one
// more thing that rests on port 8081 being private, until the parser
// counts raw bytes (Crafter.Network) and the listener binds loopback.
listener.limits.maxBody = kMaxRequestBodyBytes;
// std::cerr like every other diagnostic, and not for consistency alone: // std::cerr like every other diagnostic, and not for consistency alone:
// under journald stdout is a pipe, so it is FULLY buffered — this line // under journald stdout is a pipe, so it is FULLY buffered — this line
// once sat invisible for hours (or died unflushed with the process) while // once sat invisible for hours (or died unflushed with the process) while

View file

@ -48,9 +48,15 @@ std::string BuildInvoiceMarkdown(const OrderRecord& o,
std::string md; std::string md;
md.reserve(2048); md.reserve(2048);
const std::string item = colorLabel.empty() // The item goes into a cell of the amounts table. Its two halves come from
? std::string(productName) // the catalogue, except that a colour the catalogue no longer lists is
: std::format("{} — {}", productName, colorLabel); // passed through as the ledger has it, and that was once whatever was
// posted. So it is kept to one line and cannot close its cell: a '|' here
// would otherwise add columns to a row of a signed document.
std::string item = Form::SingleLine(
colorLabel.empty() ? std::string(productName)
: std::format("{} — {}", productName, colorLabel));
std::ranges::replace(item, '|', '/');
// The number scheme continues the pre-shop administration: the customer // The number scheme continues the pre-shop administration: the customer
// number is a UUID series, the invoice number counts within it. // number is a UUID series, the invoice number counts within it.
@ -75,9 +81,29 @@ std::string BuildInvoiceMarkdown(const OrderRecord& o,
md += std::format("* Paid via: {}\n", o.paidVia); md += std::format("* Paid via: {}\n", o.paidVia);
} }
md += "\n## Billed and shipped to\n\n"; md += "\n## Billed and shipped to\n\n";
md += std::format("{} \n{} \n{} {} \n{}\n\n", // The one block of this document the buyer wrote, and it is about to be
o.buyer.name, o.buyer.street, o.buyer.postal, // signed, so it is printed as what it is: text, not markup. Two things
o.buyer.city, o.buyer.country); // make that so, and each needs the other.
//
// Every field is held to ONE LINE (Form::SingleLine). Checkout refuses a
// field that is not, but what is signed is decided here, by what is in
// the record, and a record can be older than that check or written by
// hand.
//
// And every line is indented four spaces, which is Markdown's literal
// block: nothing in it is read as a heading, a table, a link or HTML.
// One line alone was not enough. These fields sit at the start of
// consecutive lines, so a name of "# CREDIT NOTE" was a heading, and a
// name, a street and a city of "| a | b |", "|---|---|" and "| c | d |"
// were a table, with not a line break among them (found in review,
// 2026-11-26). Indented, they are the characters the buyer typed. It
// also reads right as plain text, which is how this file is mostly read,
// and a line that starts with spaces is never dash-escaped by the
// clearsigning.
md += std::format(" {}\n {}\n {} {}\n {}\n\n",
Form::SingleLine(o.buyer.name), Form::SingleLine(o.buyer.street),
Form::SingleLine(o.buyer.postal), Form::SingleLine(o.buyer.city),
Form::SingleLine(o.buyer.country));
md += "## Amounts\n\n"; md += "## Amounts\n\n";
md += "| Description | Qty | Amount |\n|---|---|---|\n"; md += "| Description | Qty | Amount |\n|---|---|---|\n";

View file

@ -22,7 +22,13 @@ No permission is granted to copy, modify, distribute, or create derivative works
// Current state is a left fold over the file; later events win. Nothing is // Current state is a left fold over the file; later events win. Nothing is
// ever rewritten, so the log doubles as the audit trail the tax records need, // ever rewritten, so the log doubles as the audit trail the tax records need,
// and a crash mid-write costs at most its own line (a truncated last line is // and a crash mid-write costs at most its own line (a truncated last line is
// skipped by the reader, not fatal). // skipped by the reader, not fatal, and the next event starts a line of its
// own rather than being written onto the end of the broken one).
//
// The fold is held in memory and redone only when the file changes, so a
// request costs a stat and a lookup, not a parse of the whole history. The
// file stays the one source of truth: an append from the CLI or an edit by
// hand is noticed on the next call (see Ledger, below).
// //
// Why not SQLite yet: single-digit orders per week, one writer, no relations. // Why not SQLite yet: single-digit orders per week, one writer, no relations.
// The day volume proves that wrong, this imports into a database in one // The day volume proves that wrong, this imports into a database in one
@ -67,113 +73,274 @@ std::string JsonEscape(std::string_view s) {
return out; return out;
} }
// A reference as a transfer is matched: upper-case letters and digits, nothing
// else. Two references that reduce to the same thing are one reference to the
// bank-transfer rail, so that is the form uniqueness is decided in.
std::string ReferenceKey(std::string_view reference) {
std::string out;
out.reserve(reference.size());
for (const char c : reference) {
if (c >= '0' && c <= '9') out += c;
else if (c >= 'A' && c <= 'Z') out += c;
else if (c >= 'a' && c <= 'z') out += static_cast<char>(c - 'a' + 'A');
}
return out;
}
// ── the fold, kept ────────────────────────────────────────────────────
//
// The ledger folded into its current state, held in memory between calls and
// folded again only when the FILE changes underneath it.
//
// It used to be folded from disk on every call: every order page, every
// /financials request, every reconciler sweep, and every two seconds for the
// mailer. And each event found its order by walking the orders so far, so the
// fold was quadratic. Neither mattered at a dozen orders. But anyone can add
// orders, and a ledger of 40 000 took twelve seconds to fold (measured
// 2026-11-26), on a path a visitor can hit as often as they like while the
// ledger lock is held. So: orders are found through an index, which makes a
// fold one pass, and the result is kept.
//
// Kept, and still never trusted over the file. The file is the ledger; this
// is a reading of it. Two things other than this process change the file, and
// both have to show up without a restart: `--orders --mark-paid` and its
// siblings append from a second process, and an operator edits fields by hand
// (the erasure request). So every call asks the file what it looks like now,
// one stat, and a different size or modification time means fold it all
// again. What this process appends itself is applied to the held fold by the
// same code that folds a line from disk, so the two cannot come to mean
// different things.
struct Ledger {
std::vector<OrderRecord> orders; // in the order placed
std::unordered_map<std::string, std::size_t> byToken; // token -> index in orders
std::set<std::string> references; // ReferenceKey of every order
// The file does not end in a line break: its last line was cut short by a
// crash mid-write, or it was edited by hand without one. Remembered
// because the next append has to start a line of its own (see AppendLine).
bool tornTail = false;
};
// What the file looked like when it was folded. Size catches every append and
// nearly every edit; the modification time catches the edit that keeps the
// size, which is what blanking a name in place is.
struct FileStamp {
bool exists = false;
std::uintmax_t size = 0;
std::filesystem::file_time_type modified{};
bool operator==(const FileStamp&) const = default;
};
Ledger gLedger;
FileStamp gLedgerStamp;
// gLedger is the fold of the file as gLedgerStamp describes it. False until
// the first fold, after SetOrdersPath, and whenever something happened that
// leaves that in doubt; the next reader then folds from disk.
bool gLedgerCurrent = false;
FileStamp StampOf(const std::filesystem::path& path) {
FileStamp stamp;
if (path.empty()) return stamp;
std::error_code ec;
// One stat: a directory_entry reads size and time together.
const std::filesystem::directory_entry entry(path, ec);
if (ec || !entry.is_regular_file(ec) || ec) return stamp;
stamp.size = entry.file_size(ec);
if (ec) return stamp;
stamp.modified = entry.last_write_time(ec);
if (ec) return stamp;
stamp.exists = true;
return stamp;
}
// Fold ONE line into the ledger. The whole meaning of the file is here, and
// it is the only place it is: a fold from disk calls this for every line, and
// an append calls it for the line it has just written. A line that is not an
// event (corrupt, cut short, blank) changes nothing — one bad line must not
// take the rest of the ledger with it.
void Apply(Ledger& ledger, std::string_view line) {
const auto doc = Json::Parse(line);
if (!doc || !doc->IsObject()) return;
auto find = [&](std::string_view token) -> OrderRecord* {
const auto at = ledger.byToken.find(std::string(token));
return at == ledger.byToken.end() ? nullptr : &ledger.orders[at->second];
};
const std::string_view type = doc->Str("type");
if (type == "order") {
OrderRecord r;
r.token = std::string(doc->Str("id"));
r.reference = std::string(doc->Str("ref"));
r.product = std::string(doc->Str("product"));
r.color = std::string(doc->Str("color"));
r.quantity = doc->Int("quantity", 1);
r.unitMinor = doc->Int("unit_minor");
r.createdAt = std::string(doc->Str("at"));
r.updatedAt = r.createdAt;
r.buyer.email = std::string(doc->Str("email"));
r.buyer.name = std::string(doc->Str("name"));
r.buyer.street = std::string(doc->Str("street"));
r.buyer.postal = std::string(doc->Str("postal"));
r.buyer.city = std::string(doc->Str("city"));
r.buyer.country = std::string(doc->Str("country"));
r.goodsMinor = doc->Int("goods_minor");
r.shippingMinor = doc->Int("shipping_minor");
r.totalMinor = doc->Int("total_minor");
r.vatIncluded = doc->Bool("vat_included");
// Additive key: absent (every pre-donations line) reads false,
// so an old ledger's orders all stay sales.
r.donation = doc->Bool("donation");
r.status = std::string(doc->Str("status", "awaiting_payment"));
// Read as written, with no default applied here: the ledger
// should keep saying exactly what it recorded, and resolving an
// unexpected value to a rail is PaymentRails::For's single job.
r.payChoice = std::string(doc->Str("pay_choice"));
r.payUrl = std::string(doc->Str("pay_url"));
r.payId = std::string(doc->Str("pay_id"));
if (r.token.empty()) return;
// A duplicate "order" event for an id would be a writer bug; first
// one wins so a replayed line cannot rewrite history.
if (find(r.token)) return;
ledger.byToken.emplace(r.token, ledger.orders.size());
if (std::string key = ReferenceKey(r.reference); !key.empty()) {
ledger.references.insert(std::move(key));
}
ledger.orders.push_back(std::move(r));
} else if (type == "invoice") {
OrderRecord* r = find(doc->Str("id"));
if (!r) return;
r->invoiceNumber = std::string(doc->Str("number"));
r->invoicedAt = std::string(doc->Str("at"));
} else if (type == "notified") {
OrderRecord* r = find(doc->Str("id"));
if (!r) return;
// "what" names the message so a future shipped-notice can share
// the event type without re-marking the confirmation as sent.
if (doc->Str("what") == "confirmation") {
r->confirmationSentAt = std::string(doc->Str("at"));
}
} else if (type == "status") {
OrderRecord* r = find(doc->Str("id"));
if (!r) return; // status for an unknown order: nothing to change
const std::string_view status = doc->Str("status");
if (status.empty()) return;
r->status = std::string(status);
r->updatedAt = std::string(doc->Str("at"));
if (const std::string_view via = doc->Str("via"); !via.empty()) {
r->paidVia = std::string(via);
}
// The FIRST paid event is the sale, whatever happens later — a
// refund folds the status onward but never unhappens the payment
// (see SummarizeSales). First, not last, so a replayed line
// cannot move the recorded moment.
if (status == "paid" && r->paidAt.empty()) {
r->paidAt = std::string(doc->Str("at"));
}
}
}
// The ledger as the file has it now: the held fold when the file is as it was
// folded, a fresh fold from disk otherwise. Called with gOrdersMutex held,
// and the reference it returns is good only until the next call that may fold
// or append (AppendLine does both), so nothing keeps it across one.
const Ledger& CurrentLocked() {
const FileStamp before = StampOf(gOrdersPath);
if (gLedgerCurrent && before == gLedgerStamp) return gLedger;
std::string text;
bool read = true;
if (before.exists) {
std::ifstream in(gOrdersPath, std::ios::binary);
if (in) {
text.assign(std::istreambuf_iterator<char>(in),
std::istreambuf_iterator<char>());
} else {
read = false; // there and unreadable: an empty fold, and not kept
}
}
Ledger fresh;
for (std::size_t start = 0; start < text.size();) {
const std::size_t nl = text.find('\n', start);
const std::size_t end = nl == std::string::npos ? text.size() : nl;
Apply(fresh, std::string_view(text).substr(start, end - start));
if (nl == std::string::npos) break;
start = nl + 1;
}
fresh.tornTail = !text.empty() && text.back() != '\n';
gLedger = std::move(fresh);
// Kept only when the file held still while it was read: the same before
// and after, and exactly as many bytes as were folded. A file that
// another process was writing at that moment gives this caller what was
// read, and the next caller a fresh fold.
const FileStamp after = StampOf(gOrdersPath);
gLedgerStamp = after;
gLedgerCurrent = read && after == before
&& (after.exists ? after.size == text.size() : text.empty());
return gLedger;
}
bool AppendLine(const std::string& line) { bool AppendLine(const std::string& line) {
if (gOrdersPath.empty()) return false; if (gOrdersPath.empty()) return false;
// Fold first if the file moved, so that what is written below can be
// applied on top of a fold that matches the file it is appended to.
const bool torn = CurrentLocked().tornTail;
const bool current = gLedgerCurrent;
const std::uintmax_t sizeBefore = gLedgerStamp.exists ? gLedgerStamp.size : 0;
// Open per append: orders arrive rarely, and a file reopened each time can // Open per append: orders arrive rarely, and a file reopened each time can
// be rotated or edited underneath the running process without a restart. // be rotated or edited underneath the running process without a restart.
std::ofstream out(gOrdersPath, std::ios::app | std::ios::binary); std::ofstream out(gOrdersPath, std::ios::app | std::ios::binary);
if (!out) return false; if (!out) return false;
// A file that ends mid-line gets its line break first. Without it this
// event would be written onto the end of the broken line and be read as
// part of it: a crash that cut one line short would cost the NEXT event
// too, and that event is as likely as not somebody's "paid".
if (torn) out << '\n';
out << line << '\n'; out << line << '\n';
out.flush(); out.flush();
// Report the stream state: a full disk must surface as a visible error, // Report the stream state: a full disk must surface as a visible error,
// not a payment link over an order that was never recorded. // not a payment link over an order that was never recorded.
return static_cast<bool>(out); if (!out) {
} gLedgerCurrent = false; // part of the line may be on disk: fold again
return false;
// Fold the whole log into id -> record. Corrupt lines are skipped — one bad
// line must not take the rest of the ledger with it.
std::vector<OrderRecord> FoldLocked() {
std::vector<OrderRecord> out;
if (gOrdersPath.empty()) return out;
std::ifstream in(gOrdersPath, std::ios::binary);
if (!in) return out;
auto find = [&](std::string_view token) -> OrderRecord* {
for (OrderRecord& r : out) {
if (r.token == token) return &r;
}
return nullptr;
};
std::string line;
while (std::getline(in, line)) {
auto doc = Json::Parse(line);
if (!doc || !doc->IsObject()) continue;
const std::string_view type = doc->Str("type");
if (type == "order") {
OrderRecord r;
r.token = std::string(doc->Str("id"));
r.reference = std::string(doc->Str("ref"));
r.product = std::string(doc->Str("product"));
r.color = std::string(doc->Str("color"));
r.quantity = doc->Int("quantity", 1);
r.unitMinor = doc->Int("unit_minor");
r.createdAt = std::string(doc->Str("at"));
r.updatedAt = r.createdAt;
r.buyer.email = std::string(doc->Str("email"));
r.buyer.name = std::string(doc->Str("name"));
r.buyer.street = std::string(doc->Str("street"));
r.buyer.postal = std::string(doc->Str("postal"));
r.buyer.city = std::string(doc->Str("city"));
r.buyer.country = std::string(doc->Str("country"));
r.goodsMinor = doc->Int("goods_minor");
r.shippingMinor = doc->Int("shipping_minor");
r.totalMinor = doc->Int("total_minor");
r.vatIncluded = doc->Bool("vat_included");
// Additive key: absent (every pre-donations line) reads false,
// so an old ledger's orders all stay sales.
r.donation = doc->Bool("donation");
r.status = std::string(doc->Str("status", "awaiting_payment"));
// Read as written, with no default applied here: the ledger
// should keep saying exactly what it recorded, and resolving an
// unexpected value to a rail is PaymentRails::For's single job.
r.payChoice = std::string(doc->Str("pay_choice"));
r.payUrl = std::string(doc->Str("pay_url"));
r.payId = std::string(doc->Str("pay_id"));
if (r.token.empty()) continue;
// A duplicate "order" event for an id would be a writer bug; first
// one wins so a replayed line cannot rewrite history.
if (!find(r.token)) out.push_back(std::move(r));
} else if (type == "invoice") {
OrderRecord* r = find(doc->Str("id"));
if (!r) continue;
r->invoiceNumber = std::string(doc->Str("number"));
r->invoicedAt = std::string(doc->Str("at"));
} else if (type == "notified") {
OrderRecord* r = find(doc->Str("id"));
if (!r) continue;
// "what" names the message so a future shipped-notice can share
// the event type without re-marking the confirmation as sent.
if (doc->Str("what") == "confirmation") {
r->confirmationSentAt = std::string(doc->Str("at"));
}
} else if (type == "status") {
OrderRecord* r = find(doc->Str("id"));
if (!r) continue; // status for an unknown order: skip, keep folding
const std::string_view status = doc->Str("status");
if (status.empty()) continue;
r->status = std::string(status);
r->updatedAt = std::string(doc->Str("at"));
if (const std::string_view via = doc->Str("via"); !via.empty()) {
r->paidVia = std::string(via);
}
// The FIRST paid event is the sale, whatever happens later — a
// refund folds the status onward but never unhappens the payment
// (see SummarizeSales). First, not last, so a replayed line
// cannot move the recorded moment.
if (status == "paid" && r->paidAt.empty()) {
r->paidAt = std::string(doc->Str("at"));
}
}
} }
return out; out.close();
// Apply the line to the held fold, provided the file grew by exactly what
// was written. If it grew by more, another process appended in the same
// moment and its line is in there unread: fold from disk next time.
const FileStamp after = StampOf(gOrdersPath);
const std::uintmax_t wrote = line.size() + 1 + (torn ? 1 : 0);
if (current && after.exists && after.size == sizeBefore + wrote) {
Apply(gLedger, line);
gLedger.tornTail = false;
gLedgerStamp = after;
} else {
gLedgerCurrent = false;
}
return true;
} }
// References handed out by NewUniqueOrderToken whose order is not in the
// ledger yet: the gap between minting a token and CreateOrder writing it,
// which is where the payment rail is asked for its link. Guarded by
// gOrdersMutex. A checkout that fails in that gap leaves its entry behind
// until the process restarts, which costs one reference out of sixteen
// million and is not worth a second code path to hand back.
std::set<std::string> gHeldReferences;
} // namespace } // namespace
void SetOrdersPath(const std::filesystem::path& p) { void SetOrdersPath(const std::filesystem::path& p) {
std::lock_guard lock(gOrdersMutex); std::lock_guard lock(gOrdersMutex);
gOrdersPath = p; gOrdersPath = p;
// Another file, or the same name for a file that has just been replaced:
// either way what is held is not a fold of it.
gLedger = Ledger{};
gLedgerStamp = FileStamp{};
gLedgerCurrent = false;
} }
bool CreateOrder(const OrderRecord& o) { bool CreateOrder(const OrderRecord& o) {
@ -181,7 +348,7 @@ bool CreateOrder(const OrderRecord& o) {
// "donation" is written only when true, matching the status writer's // "donation" is written only when true, matching the status writer's
// omit-rather-than-empty rule: absent-means-false is what lets a ledger // omit-rather-than-empty rule: absent-means-false is what lets a ledger
// from before donations existed keep reading correctly. // from before donations existed keep reading correctly.
return AppendLine(std::format( const bool written = AppendLine(std::format(
R"({{"type":"order","at":"{}","id":"{}","ref":"{}","product":"{}",)" R"({{"type":"order","at":"{}","id":"{}","ref":"{}","product":"{}",)"
R"("color":"{}","quantity":{},"unit_minor":{},)" R"("color":"{}","quantity":{},"unit_minor":{},)"
R"("email":"{}","name":"{}","street":"{}","postal":"{}","city":"{}","country":"{}",)" R"("email":"{}","name":"{}","street":"{}","postal":"{}","city":"{}","country":"{}",)"
@ -196,6 +363,13 @@ bool CreateOrder(const OrderRecord& o) {
o.donation ? R"("donation":true,)" : "", o.donation ? R"("donation":true,)" : "",
JsonEscape(o.status), JsonEscape(o.payChoice), JsonEscape(o.status), JsonEscape(o.payChoice),
JsonEscape(o.payUrl), JsonEscape(o.payId))); JsonEscape(o.payUrl), JsonEscape(o.payId)));
// The order is in the ledger now, which is where the next mint looks for
// its reference, so the hold NewUniqueOrderToken placed has done its job.
// Kept when the write failed: nothing was stored, and handing the same
// reference straight to the next checkout would only be confusing in the
// log of what went wrong.
if (written) gHeldReferences.erase(ReferenceKey(o.reference));
return written;
} }
bool AppendOrderStatus(std::string_view token, std::string_view status, bool AppendOrderStatus(std::string_view token, std::string_view status,
@ -255,12 +429,12 @@ std::optional<std::string> AssignInvoiceNumber(std::string_view token,
// append-only ledger plus the payment provider's records carry the // append-only ledger plus the payment provider's records carry the
// completeness proof an auditor actually wants. // completeness proof an auditor actually wants.
std::lock_guard lock(gOrdersMutex); std::lock_guard lock(gOrdersMutex);
const OrderRecord* target = nullptr; // `ledger` and `target` are read up to the append at the end and not
std::vector<OrderRecord> all = FoldLocked(); // after it: the append updates the held fold and may replace it.
for (const OrderRecord& r : all) { const Ledger& ledger = CurrentLocked();
if (r.token == token) { target = &r; break; } const auto at = ledger.byToken.find(std::string(token));
} if (at == ledger.byToken.end()) return std::nullopt;
if (!target) return std::nullopt; const OrderRecord* target = &ledger.orders[at->second];
// Idempotent: a paid order re-processed (manual CLI after the reconciler, // Idempotent: a paid order re-processed (manual CLI after the reconciler,
// say) keeps its number — a sequence never burns a member on a retry. // say) keeps its number — a sequence never burns a member on a retry.
if (!target->invoiceNumber.empty()) return target->invoiceNumber; if (!target->invoiceNumber.empty()) return target->invoiceNumber;
@ -270,7 +444,7 @@ std::optional<std::string> AssignInvoiceNumber(std::string_view token,
const std::string key = CustomerKey(target->buyer.email); const std::string key = CustomerKey(target->buyer.email);
std::string customer; std::string customer;
std::int64_t maxSeq = 0; std::int64_t maxSeq = 0;
for (const OrderRecord& r : all) { for (const OrderRecord& r : ledger.orders) {
if (r.invoiceNumber.size() < 38 || CustomerKey(r.buyer.email) != key) continue; if (r.invoiceNumber.size() < 38 || CustomerKey(r.buyer.email) != key) continue;
customer = r.invoiceNumber.substr(0, 36); customer = r.invoiceNumber.substr(0, 36);
std::int64_t seq = 0; std::int64_t seq = 0;
@ -299,15 +473,20 @@ bool AppendOrderNotified(std::string_view token, std::string_view isoTimestamp)
std::optional<OrderRecord> FindOrder(std::string_view token) { std::optional<OrderRecord> FindOrder(std::string_view token) {
std::lock_guard lock(gOrdersMutex); std::lock_guard lock(gOrdersMutex);
for (OrderRecord& r : FoldLocked()) { const Ledger& ledger = CurrentLocked();
if (r.token == token) return std::move(r); const auto at = ledger.byToken.find(std::string(token));
} if (at == ledger.byToken.end()) return std::nullopt;
return std::nullopt; return ledger.orders[at->second];
} }
std::vector<OrderRecord> ListOrders() { std::vector<OrderRecord> ListOrders() {
std::lock_guard lock(gOrdersMutex); std::lock_guard lock(gOrdersMutex);
return FoldLocked(); return CurrentLocked().orders;
}
SalesSummary LedgerSales() {
std::lock_guard lock(gOrdersMutex);
return SummarizeSales(CurrentLocked().orders);
} }
SalesSummary SummarizeSales(std::span<const OrderRecord> orders) { SalesSummary SummarizeSales(std::span<const OrderRecord> orders) {
@ -345,6 +524,37 @@ std::string NewOrderToken() {
return out; return out;
} }
std::optional<std::string> NewUniqueOrderToken() {
return NewUniqueOrderToken([] { return NewOrderToken(); });
}
std::optional<std::string> NewUniqueOrderToken(const std::function<std::string()>& draw) {
std::lock_guard lock(gOrdersMutex);
// Every reference the ledger holds, from the held fold: no pass over the
// file for a checkout. Nothing below folds or appends, so the reference
// stays good for the loop.
const std::set<std::string>& taken = CurrentLocked().references;
// A draw collides with probability (orders ever placed) / 2^24, so even a
// ledger of a million orders gets through in a couple of draws. The bound
// is there so that a ledger too full to mint for ends in an honest
// refusal at checkout instead of a loop.
for (int i = 0; i < kUniqueTokenDraws; ++i) {
std::string token = draw();
std::string key = ReferenceKey(ReferenceFromToken(token));
if (taken.contains(key) || gHeldReferences.contains(key)) continue;
gHeldReferences.insert(std::move(key));
return token;
}
return std::nullopt;
}
bool ReferenceInUse(std::string_view reference) {
std::lock_guard lock(gOrdersMutex);
const std::string key = ReferenceKey(reference);
if (key.empty()) return false;
return gHeldReferences.contains(key) || CurrentLocked().references.contains(key);
}
std::string ReferenceFromToken(std::string_view token) { std::string ReferenceFromToken(std::string_view token) {
// Derived, not random: an order can never carry a mismatched pair. Six hex // Derived, not random: an order can never carry a mismatched pair. Six hex
// chars is what a human will actually type into a transfer description; at // chars is what a human will actually type into a transfer description; at

View file

@ -108,16 +108,31 @@ bool HasOtherReferenceShape(std::string_view folded, std::size_t foundAt,
return false; return false;
} }
// What a credit is claimed under. The bank's own id for the payment is the
// key wherever there is one, and the callback and the pull both always carry
// it. A line an operator wrote by hand may not, and is then known by what it
// says: its reduced text and its amount. Two hand-written lines saying the
// same thing share a key, which errs the safe way — spent for one order, both
// are spent for every other.
std::string ClaimKey(const BankCredit& credit, std::string_view folded) {
if (!credit.id.empty()) return credit.id;
return std::format("text:{}:{}", folded, credit.amountMinor);
}
} // namespace } // namespace
TransferMatch MatchCredits(std::span<const BankCredit> credits, TransferMatch MatchCredits(std::span<const BankCredit> credits,
std::string_view reference) { std::string_view reference,
std::span<const CreditClaim> claims) {
TransferMatch out; TransferMatch out;
const std::string needle = Fold(reference); const std::string needle = Fold(reference);
// An empty needle would match every credit on the account. Refuse rather // An empty needle would match every credit on the account. Refuse rather
// than settle the whole ledger from one payment. // than settle the whole ledger from one payment.
if (needle.size() < 4) return out; if (needle.size() < 4) return out;
// The bank's ids of the payments seen so far in this pass.
std::set<std::string_view> seen;
for (const BankCredit& c : credits) { for (const BankCredit& c : credits) {
// Only money coming IN can pay for something. A negative amount is an // Only money coming IN can pay for something. A negative amount is an
// outgoing payment that happens to quote the reference — a refund we // outgoing payment that happens to quote the reference — a refund we
@ -127,9 +142,37 @@ TransferMatch MatchCredits(std::span<const BankCredit> credits,
const std::string folded = Fold(c.reference); const std::string folded = Fold(c.reference);
const std::size_t at = folded.find(needle); const std::size_t at = folded.find(needle);
if (at == std::string::npos) continue; if (at == std::string::npos) continue;
// One payment is counted once, however many lines of the file carry
// it. The callback handler skips an id the file already holds and
// the pull writes each payment once, so a second line is not meant
// to happen. It still can: the same callback delivered on two
// connections at once, a callback landing while the pull is
// replacing the file, an address registered twice at the bank. Left
// to be summed, a second line doubles the money, and a payer who
// sent half the price finds the order settled. A line with no id
// cannot be told from another payment that says the same, so those
// are each counted.
if (!c.id.empty() && !seen.insert(c.id).second) {
++out.duplicates;
continue;
}
// Spent once. This credit quotes the reference, but if it already
// settled a DIFFERENT order its money is gone, whatever its text
// says. A claim by this same reference is the order's own and counts.
const std::string key = ClaimKey(c, folded);
const bool spent = std::ranges::any_of(claims, [&](const CreditClaim& claim) {
return claim.credit == key && Fold(claim.reference) != needle;
});
if (spent) {
++out.spentElsewhere;
continue;
}
out.paidMinor += c.amountMinor; out.paidMinor += c.amountMinor;
++out.count; ++out.count;
out.method = c.method; out.method = c.method;
if (std::ranges::find(out.credits, key) == out.credits.end()) {
out.credits.push_back(key);
}
if (HasOtherReferenceShape(folded, at, needle.size())) out.ambiguous = true; if (HasOtherReferenceShape(folded, at, needle.size())) out.ambiguous = true;
} }
return out; return out;
@ -198,7 +241,22 @@ private:
class TransferRail final : public PaymentRail { class TransferRail final : public PaymentRail {
public: public:
TransferRail(RailConfig cfg, std::unique_ptr<CreditSource> credits) TransferRail(RailConfig cfg, std::unique_ptr<CreditSource> credits)
: cfg_(std::move(cfg)), credits_(std::move(credits)) {} : cfg_(std::move(cfg)), credits_(std::move(credits)) {
// The record of which credit paid for which order hangs off the
// credits path, the way the EURC rail's cursor hangs off its pool.
// It cannot be IN the credits file: the pull replaces that every hour.
if (!cfg_.transferCreditsPath.empty()) {
claimsPath_ = cfg_.transferCreditsPath;
claimsPath_ += ".claims";
}
claimsLoaded_ = LoadClaims();
}
// False when there is a claims file and it could not be read. The rail
// must not run like that: with the claims unknown, every payment looks
// unspent, and one that named several orders would settle another of
// them. MakeTransferRail refuses to hand out a rail in that state.
bool ClaimsLoaded() const { return claimsLoaded_; }
// No network call, and nothing to reserve: unlike the EURC rail, which // No network call, and nothing to reserve: unlike the EURC rail, which
// burns a receiving address per order, a transfer reuses one IBAN forever // burns a receiving address per order, a transfer reuses one IBAN forever
@ -235,16 +293,60 @@ public:
const std::optional<std::vector<BankCredit>> all = Fetch(); const std::optional<std::vector<BankCredit>> all = Fetch();
if (!all) return std::nullopt; // unknown, retry — never "unpaid" if (!all) return std::nullopt; // unknown, retry — never "unpaid"
const TransferMatch m = MatchCredits(*all, reference); // ONE order is judged at a time from here to the claim below. The
if (m.ambiguous) { // reconciler and every buyer's arrival poll call this from their own
// threads, and two orders quoted by the same credit must not both
// look, both find it unspent, and both settle: the second has to see
// the first one's claim. Nothing under this lock touches the network
// (the credits were read above, under their own lock), so it is held
// for a comparison and at most one short file append.
std::lock_guard lock(claimsMutex_);
const TransferMatch m = MatchCredits(*all, reference, claims_);
if (m.duplicates > 0 && Once("duplicate", reference)) {
std::println(std::cerr, std::println(std::cerr,
"transfer: {} matched a credit that also quotes another " "transfer: {} is quoted by a payment the credits file "
"order reference — settle this one by hand", reference); "lists {} time(s) too many. It is counted once. If this "
"keeps happening, check that the callback address is "
"registered at the bank only once (`nostro callbacks`)",
reference, m.duplicates);
}
if (m.spentElsewhere > 0 && Once("spent", reference)) {
std::println(std::cerr,
"transfer: {} is quoted by {} payment(s) whose money "
"already settled another order, so none of it is counted "
"here: one payment pays for one order. If the payer meant "
"a single transfer for several orders, settle this one "
"with --mark-paid", reference, m.spentElsewhere);
} }
PaidStatus out; PaidStatus out;
out.method = m.method.empty() ? std::string("sepa") : m.method; out.method = m.method.empty() ? std::string("sepa") : m.method;
if (m.paidMinor >= expectedMinor) { if (m.paidMinor >= expectedMinor) {
// Claim first, report second. Done the other way round, a crash
// between the two leaves an order reported paid whose money
// nothing marks as spent, free to settle whatever else its text
// names. This way round it leaves a claim whose order is still
// awaiting, and the next poll settles that order from its own
// claim.
if (!Claim(m, reference)) {
if (Once("unrecorded", reference)) {
std::println(std::cerr,
"transfer: {} is covered, but {} cannot be "
"written, so its payment cannot be recorded as "
"spent. NOT settling it until it can: the same "
"money could otherwise settle a second order",
reference, claimsPath_.string());
}
return std::nullopt; // unknown, retry
}
if (m.ambiguous) {
std::println(std::cerr,
"transfer: {} settled on a payment that also quotes "
"what looks like another order reference. That "
"payment is spent on this order now and will not "
"count toward another; if the payer meant it for "
"both, the other one is settled by hand", reference);
}
out.state = PayState::Paid; out.state = PayState::Paid;
return out; return out;
} }
@ -368,11 +470,130 @@ private:
return cached_; return cached_;
} }
// ── claims: which credit paid for which order ─────────────────────
//
// One JSON object per line, {"credit":…,"reference":…,"at":…}, appended
// and never rewritten, like the ledger. Read once at start and kept in
// memory from then on: this process is the only thing that settles
// orders from credits, so the file is never ahead of what is held here.
// False only when there IS a claims file and it cannot be read; see
// ClaimsLoaded. No file at all is the ordinary state of a rail no order
// has settled on yet.
bool LoadClaims() {
if (claimsPath_.empty()) return true;
std::error_code ec;
const std::filesystem::file_status status =
std::filesystem::status(claimsPath_, ec);
if (!std::filesystem::exists(status)) return true;
if (!std::filesystem::is_regular_file(status)) return false;
std::ifstream in(claimsPath_, std::ios::binary);
if (!in) return false;
const std::string text((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
if (in.bad()) return false;
// A file that stops mid-line: a write cut short by a full disk or a
// crash. The next claim has to start a line of its own (see Claim).
claimsTorn_ = !text.empty() && text.back() != '\n';
int lineNo = 0;
for (std::size_t start = 0; start < text.size();) {
const std::size_t nl = text.find('\n', start);
const std::size_t end = nl == std::string::npos ? text.size() : nl;
const std::string_view line = std::string_view(text).substr(start, end - start);
start = nl == std::string::npos ? text.size() : nl + 1;
++lineNo;
if (line.empty()) continue;
const auto doc = Json::Parse(line);
CreditClaim claim;
if (doc && doc->IsObject()) {
claim.credit = std::string(doc->Str("credit"));
claim.reference = std::string(doc->Str("reference"));
}
if (claim.credit.empty() || claim.reference.empty()) {
// Said aloud and skipped, as the credits file does it: a
// line lost here is one payment that could be counted again
// for another order its text names, which is worth knowing
// about and not worth refusing every settlement over.
std::println(std::cerr, "transfer: {}:{} is not a claim, skipped",
claimsPath_.string(), lineNo);
continue;
}
claims_.push_back(std::move(claim));
}
return true;
}
// Record that the credits `m` counted are spent on `reference`. Called
// with claimsMutex_ held. False when the record could not be written, and
// then nothing is held in memory either: the caller does not settle.
//
// What "before the order is reported paid" is worth: the claim is in the
// file before this returns, so a crash of the PROCESS between the claim
// and the ledger's paid line leaves the claim. It is not fsynced, and
// neither is the ledger, so a power cut can still keep one line and lose
// the other.
bool Claim(const TransferMatch& m, const std::string& reference) {
const std::string now = std::format(
"{:%FT%TZ}", std::chrono::floor<std::chrono::seconds>(
std::chrono::system_clock::now()));
std::string lines;
std::vector<CreditClaim> fresh;
for (const std::string& key : m.credits) {
// A counted credit that already has a claim has THIS order's: one
// held by any other order was not counted. It is here again
// because the settlement it was written for never reached the
// ledger, and it needs no second line.
const bool held = std::ranges::any_of(claims_, [&](const CreditClaim& c) {
return c.credit == key;
});
if (held) continue;
lines += std::format(R"({{"credit":"{}","reference":"{}","at":"{}"}})" "\n",
EscT(key), EscT(reference), now);
fresh.push_back({ key, reference });
}
if (fresh.empty()) return true;
if (!claimsPath_.empty()) {
std::ofstream out(claimsPath_, std::ios::app | std::ios::binary);
if (!out) return false;
// A file that ends mid-line gets its line break first, for the
// reason the ledger does: written onto the end of a broken line,
// this claim would be read as part of it and skipped at the next
// start, and the payment would be free to settle a second order.
if (claimsTorn_) out << '\n';
out << lines;
out.flush();
if (!out) {
// Some of it may be on disk. Whatever is, the next write
// starts on a new line; a blank one is skipped on load.
claimsTorn_ = true;
return false;
}
claimsTorn_ = false;
}
for (CreditClaim& c : fresh) claims_.push_back(std::move(c));
return true;
}
// True the first time `what` is asked about `reference`, so a line that
// would otherwise repeat on every poll of an order nobody has settled yet
// is said once per run of the server. Called with claimsMutex_ held.
bool Once(std::string_view what, std::string_view reference) {
return told_.insert(std::format("{}/{}", what, reference)).second;
}
RailConfig cfg_; RailConfig cfg_;
std::unique_ptr<CreditSource> credits_; std::unique_ptr<CreditSource> credits_;
std::mutex mutex_; std::mutex mutex_;
std::optional<std::vector<BankCredit>> cached_; std::optional<std::vector<BankCredit>> cached_;
std::chrono::steady_clock::time_point fetchedAt_{}; std::chrono::steady_clock::time_point fetchedAt_{};
bool claimsLoaded_ = true;
bool claimsTorn_ = false; // the claims file does not end in a line break
std::filesystem::path claimsPath_;
std::mutex claimsMutex_;
std::vector<CreditClaim> claims_;
std::set<std::string> told_;
}; };
} // namespace } // namespace
@ -381,30 +602,53 @@ std::unique_ptr<CreditSource> MakeFileCreditSource(std::filesystem::path path) {
return std::make_unique<FileCreditSource>(std::move(path)); return std::make_unique<FileCreditSource>(std::move(path));
} }
namespace {
// Held from the look for the id to the append. The listener serves each
// connection on its own thread, and a bank that delivers one callback on two
// connections at once would otherwise have both look, both find the id
// absent, and both append it.
std::mutex gCreditAppendMutex;
} // namespace
bool AppendCreditTo(const std::filesystem::path& creditsPath, bool AppendCreditTo(const std::filesystem::path& creditsPath,
const BankCredit& credit) { const BankCredit& credit) {
if (credit.id.empty()) return false; if (credit.id.empty()) return false;
std::lock_guard lock(gCreditAppendMutex);
// Deduplicate on the bank's own payment id. A bank retries a callback it // 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 // 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. // payment again, so the SAME payment arrives more than once by design.
// Appending it twice would double the money against one reference — // Appending it twice would double the money against one reference —
// enough, on a part-paid order, to settle it without the balance ever // enough, on a part-paid order, to settle it without the balance ever
// arriving. // arriving. (MatchCredits counts an id once regardless; this keeps the
// file itself to one line a payment where it can.)
bool torn = false;
{ {
std::ifstream in(creditsPath, std::ios::binary); std::ifstream in(creditsPath, std::ios::binary);
std::string line; const std::string text((std::istreambuf_iterator<char>(in)),
while (std::getline(in, line)) { std::istreambuf_iterator<char>());
for (std::size_t start = 0; start < text.size();) {
const std::size_t nl = text.find('\n', start);
const std::size_t end = nl == std::string::npos ? text.size() : nl;
const std::string_view line = std::string_view(text).substr(start, end - start);
start = nl == std::string::npos ? text.size() : nl + 1;
if (line.empty()) continue; if (line.empty()) continue;
const auto doc = Json::Parse(line); const auto doc = Json::Parse(line);
if (!doc || !doc->IsObject()) continue; if (!doc || !doc->IsObject()) continue;
if (doc->Str("id") == credit.id) return false; if (doc->Str("id") == credit.id) return false;
} }
// The pull writes this file over ssh, and an upload cut short leaves
// it ending mid-line. Start a new line then, so this credit is not
// read as the tail of the broken one.
torn = !text.empty() && text.back() != '\n';
} }
std::ofstream out(creditsPath, std::ios::app | std::ios::binary); std::ofstream out(creditsPath, std::ios::app | std::ios::binary);
if (!out) { if (!out) {
std::println(std::cerr, "transfer: cannot append to {}", creditsPath.string()); std::println(std::cerr, "transfer: cannot append to {}", creditsPath.string());
return false; return false;
} }
if (torn) out << '\n';
out << std::format( out << std::format(
R"({{"id":"{}","reference":"{}","amount_minor":{},"method":"{}"}})" "\n", R"({{"id":"{}","reference":"{}","amount_minor":{},"method":"{}"}})" "\n",
EscT(credit.id), EscT(credit.reference), credit.amountMinor, EscT(credit.id), EscT(credit.reference), credit.amountMinor,
@ -433,7 +677,19 @@ std::unique_ptr<PaymentRail> MakeTransferRail(const RailConfig& config,
"account-holder name"); "account-holder name");
return nullptr; return nullptr;
} }
return std::make_unique<TransferRail>(config, std::move(credits)); auto rail = std::make_unique<TransferRail>(config, std::move(credits));
if (!rail->ClaimsLoaded()) {
std::filesystem::path claims = config.transferCreditsPath;
claims += ".claims";
std::println(std::cerr,
"transfer: {} is there and cannot be read. It records which "
"payments have already settled an order; without it a payment "
"that named several orders could settle another of them. Fix "
"its ownership or permissions (it belongs to the user the "
"server runs as) and restart", claims.string());
return nullptr;
}
return rail;
} }
} // namespace Catcrafts::Server } // namespace Catcrafts::Server

View file

@ -45,6 +45,11 @@ export namespace Catcrafts::Server {
// Nothing is ever rewritten in place, so the file is also the audit // Nothing is ever rewritten in place, so the file is also the audit
// trail, and a crash mid-append costs at most the line being written. // trail, and a crash mid-append costs at most the line being written.
// //
// The fold is held in memory and redone when the file's size or
// modification time changes, so the calls below cost a stat and a lookup
// and still see what the CLI appended or an operator edited a moment ago.
// The file is the ledger; nothing here is trusted over it.
//
// The volume argument: this sells single-digit units per week. When that // The volume argument: this sells single-digit units per week. When that
// is wrong by two orders of magnitude, the log imports into SQLite in one // is wrong by two orders of magnitude, the log imports into SQLite in one
// sitting — the reverse migration would not be so kind. // sitting — the reverse migration would not be so kind.
@ -138,6 +143,12 @@ export namespace Catcrafts::Server {
}; };
SalesSummary SummarizeSales(std::span<const OrderRecord> orders); SalesSummary SummarizeSales(std::span<const OrderRecord> orders);
// The same summary over the ledger as it stands, without handing out a
// copy of every order to get it. /financials is public and uncached and
// asks on every request; ListOrders() would copy the whole ledger each
// time for four integers.
SalesSummary LedgerSales();
// ── the bank side of /financials ────────────────────────────────── // ── the bank side of /financials ──────────────────────────────────
// //
// Bank-side donations and expenses come from an aggregates file written // Bank-side donations and expenses come from an aggregates file written
@ -199,6 +210,39 @@ export namespace Catcrafts::Server {
std::string NewOrderToken(); std::string NewOrderToken();
std::string ReferenceFromToken(std::string_view token); std::string ReferenceFromToken(std::string_view token);
// A token for a new order whose REFERENCE no other order has, or nullopt
// when none could be found in a bounded number of draws.
//
// The token is 128 bits and never repeats. The reference is its first six
// hex digits, 24 bits, because a person types it into a transfer: two
// orders in a ledger of a few thousand share one often enough to plan
// for, and a transfer quoting it would then be a payment for both. So the
// reference is checked against every order the ledger has ever held,
// paid, lapsed or cancelled alike (an old order's payment is still in the
// bank's history, quoting it), and a colliding token is thrown away for a
// fresh draw. The reference is HELD from this call on, so two checkouts
// minting at the same moment cannot both be handed it; CreateOrder
// releases the hold once the order is in the ledger, where the next call
// finds it.
//
// Checkout mints through this. NewOrderToken stays for what needs only
// the token's shape.
std::optional<std::string> NewUniqueOrderToken();
// The same, drawing candidate tokens from `draw` instead of the CSPRNG,
// and giving up after kUniqueTokenDraws of them. It exists for the
// self-test: a collision is one draw in sixteen million from the real
// generator, so the only way to see a colliding draw thrown away, or a
// run of them end in a refusal, is to hand the draws in.
inline constexpr int kUniqueTokenDraws = 32;
std::optional<std::string> NewUniqueOrderToken(const std::function<std::string()>& draw);
// Whether an order with this reference exists, or one is being created.
// Compared the way a transfer is matched, on upper-case alphanumerics, so
// "CC-2B6457" and "cc 2b6457" are one reference. Exported for the
// self-test.
bool ReferenceInUse(std::string_view reference);
// The same reference again, as an ISO 11649 structured creditor reference: // The same reference again, as an ISO 11649 structured creditor reference:
// "RF" + two ISO 7064 mod-97-10 check digits + the CC-style body. Derived // "RF" + two ISO 7064 mod-97-10 check digits + the CC-style body. Derived
// from the same token for the same reason, so the two can never disagree. // from the same token for the same reason, so the two can never disagree.
@ -498,22 +542,56 @@ export namespace Catcrafts::Server {
std::string method; // ledger `via`: "sepa", "ideal", … std::string method; // ledger `via`: "sepa", "ideal", …
}; };
// A credit that has paid for an order.
//
// MONEY IS SPENT ONCE. A payment that settled one order pays for no other,
// however many references its remittance text quotes. Without that rule a
// payer could place several orders, send ONE transfer naming all of them,
// and watch each order find the full amount against its own reference:
// every order settled, one of them paid for. (Found in review on
// 2026-11-26; three €5 orders settled on a single €5 credit.) The text is
// a stranger's to write, so the rule cannot rest on what the text looks
// like. It rests on this record instead: which credit, which order.
struct CreditClaim {
// The credit, by its key: the bank's own id for the payment, or, for
// a line written by hand without one, a key made of its text and
// amount (see MatchCredits).
std::string credit;
std::string reference; // the order it settled, "CC-2B6457"
};
// What the credits say about one order. // What the credits say about one order.
struct TransferMatch { struct TransferMatch {
std::int64_t paidMinor = 0; // summed over every credit carrying the reference std::int64_t paidMinor = 0; // summed over every credit counted
int count = 0; // how many credits carried it int count = 0; // how many credits were counted
std::string method; // the method of the last matching credit std::string method; // the method of the last one counted
// Set when a matching credit's remittance text ALSO carries something // The credits that were counted, by key, each once. What the rail
// shaped like a second order reference. One transfer quoting two // claims for the order at the moment it settles.
// references cannot be attributed by a per-order matcher, and at that std::vector<std::string> credits;
// point a human should look rather than two orders both settling on the // Credits that quote the reference and were NOT counted, because
// same money. Advisory: the caller logs it, it does not block. // their money already settled another order. Not an error, and worth
// saying aloud: it is either the trick described at CreditClaim or a
// payer who meant one transfer for several orders, and in both cases
// the order in hand is one a human settles.
int spentElsewhere = 0;
// Lines left out because an earlier line carried the same bank id:
// one payment listed more than once. Counted once, and reported so
// the log can say the file is carrying duplicates.
int duplicates = 0;
// Set when a counted credit's remittance text ALSO carries something
// shaped like a second order reference. Advisory, as it always was:
// the shape test cannot tell a second reference from a name followed
// by a date, so it decides nothing. What stops two orders settling on
// the same money is the claim, not this flag; the flag is so the log
// can say which settlement to look at.
bool ambiguous = false; bool ambiguous = false;
}; };
// Sum the credits that quote `reference`, in whatever form the payer typed // Sum the credits that quote `reference`, in whatever form the payer typed
// it. Pure, and exported for the self-test, because this is the decision // it, leaving out any that `claims` says already paid for a DIFFERENT
// that releases goods — the same reason ParseEthCallUint is exported. // order. Pure, and exported for the self-test, because this is the
// decision that releases goods — the same reason ParseEthCallUint is
// exported.
// //
// Matching is on the reference BODY ("CC2B6457") after reducing both sides // Matching is on the reference BODY ("CC2B6457") after reducing both sides
// to upper-case alphanumerics. That one choice covers every form a payer // to upper-case alphanumerics. That one choice covers every form a payer
@ -522,8 +600,20 @@ export namespace Catcrafts::Server {
// survives whatever spacing a bank puts in the field. The RF check digits // survives whatever spacing a bank puts in the field. The RF check digits
// deliberately do NO work here: their job was done at the payer's own bank, // deliberately do NO work here: their job was done at the payer's own bank,
// which refuses a mistyped reference before the transfer ever leaves. // which refuses a mistyped reference before the transfer ever leaves.
//
// A claim by the SAME reference does not exclude a credit: an order whose
// settlement was claimed but never reached the ledger (a crash between
// the two) must find its own money still there. Claims are compared on
// the reduced form too, so how a claim spells its reference is not part
// of it.
//
// A payment is also counted ONCE within a pass: credits that share a
// bank id are one payment, and only the first is summed. Two lines for
// one payment are not supposed to reach the file, but summing them would
// settle a half-paid order, so the sum does not depend on it.
TransferMatch MatchCredits(std::span<const BankCredit> credits, TransferMatch MatchCredits(std::span<const BankCredit> credits,
std::string_view reference); std::string_view reference,
std::span<const CreditClaim> claims = {});
// Where a transfer rail gets its incoming credits. The one implementation // Where a transfer rail gets its incoming credits. The one implementation
// reads a file (MakeFileCreditSource) that is filled from outside the rail: // reads a file (MakeFileCreditSource) that is filled from outside the rail:
@ -543,6 +633,17 @@ export namespace Catcrafts::Server {
// The rail itself. Takes its credit source, so that where the credits // The rail itself. Takes its credit source, so that where the credits
// come from can change without the rail being rewritten: it knows nothing // come from can change without the rail being rewritten: it knows nothing
// of any bank. // of any bank.
//
// It keeps one file of its own, "<transferCreditsPath>.claims": a line
// for each credit that settled an order, written BEFORE the order is
// reported paid and read back at start (CreditClaim has the reason). The
// credits file is replaced wholesale by the pull every hour, so the
// record of what was spent cannot live in it. A settlement whose claim
// cannot be written is not made: the answer is "unknown, retry", and the
// log says why. A claims file that is there and cannot be READ is a rail
// that cannot know what was spent, so this returns nullptr for it, with
// the reason logged. With no credits path there is nowhere to keep the
// file, and the claims then last as long as the process.
std::unique_ptr<PaymentRail> MakeTransferRail(const RailConfig& config, std::unique_ptr<PaymentRail> MakeTransferRail(const RailConfig& config,
std::unique_ptr<CreditSource> credits); std::unique_ptr<CreditSource> credits);
@ -738,6 +839,32 @@ export namespace Catcrafts::Server {
// limit rather than invent a peer. // limit rather than invent a peer.
std::string_view ClientAddressFromForwarded(std::string_view forwarded); std::string_view ClientAddressFromForwarded(std::string_view forwarded);
// What a rate limit is kept under for the client at `address`: the
// identity whose budget a submission is charged to.
//
// An IPv4 address is its own key. An IPv6 address is keyed by its /48,
// written "2001:db8:1234::/48", because one IPv6 address is not one
// client. A home line is handed a whole prefix (a /56 from most ISPs, a
// /48 from some, RIPE's guidance being one or the other) and every
// device on it picks addresses freely inside, so a limit kept per
// address is no limit: a /56 is 2^72 of them. A /64 is not the boundary
// either, a /56 holds 256. The /48 is the largest block a single
// subscriber is normally given, so it is the smallest key that no one
// subscriber can step out of.
//
// The price is that on a /56 ISP 256 neighbouring households share one
// budget. For that to cost a real buyer anything, one of 255 neighbours
// has to be flooding checkout in the same ten minutes, and what it costs
// them then is "try again shortly". Weighed on 2026-11-26 and taken.
// Phones and VPN exits share a /48 more widely, and already share one
// IPv4 address, so nothing changes for them.
//
// An IPv4-mapped address (::ffff:203.0.113.7) is keyed as the IPv4
// client it is. Anything that does not read as an address is keyed as
// written, so a peer is never dropped to "no peer" by its spelling.
// Empty in, empty out. Pure, and exported for the self-test.
std::string RateLimitKeyFor(std::string_view address);
// Whether a state-changing POST may proceed, given its Origin header. // Whether a state-changing POST may proceed, given its Origin header.
// //
// A MISSING Origin is allowed: browsers have sent it on form POSTs for // A MISSING Origin is allowed: browsers have sent it on form POSTs for

View file

@ -135,6 +135,55 @@ export std::string_view Trim(std::string_view s) {
return s; return s;
} }
// `s` as one line of text, read in the order it is written: every character
// that starts a new line, is not text at all, or changes the direction text
// is drawn in, becomes a space. That is
//
// * the C0 controls and DEL;
// * the C1 controls, U+0080 to U+009F, which include NEL (a line break)
// and CSI (the start of a terminal escape sequence);
// * LS U+2028 and PS U+2029, line breaks to an editor that are not control
// characters to anything that only looks at bytes below 0x20;
// * the bidirectional embedding, override and isolate controls, U+202A to
// U+202E and U+2066 to U+2069, which make a line DISPLAY in another
// order than it is stored. An address in Arabic or Hebrew needs none of
// them; a line that reads one thing and holds another does.
//
// It exists for the address fields. They are free text and stay free text,
// but they are printed into an invoice the shop then SIGNS, one field to a
// line, and a name carrying a line break would write lines of its own into
// that document under the shop's signature. So one definition is shared:
// validation refuses a field this function would change (a tab aside, which
// it makes the same space), and the invoice builder applies it to whatever a
// ledger already holds.
//
// This is about LINES, not about Markdown. A field that stays on its line can
// still begin with '#' or '|', which is why the invoice prints the address as
// a literal block instead of trusting this to keep it inert.
export std::string SingleLine(std::string_view s) {
auto at = [&](std::size_t i) { return static_cast<unsigned char>(s[i]); };
std::string out;
out.reserve(s.size());
for (std::size_t i = 0; i < s.size(); ++i) {
const unsigned char c = at(i);
if (c < 0x20 || c == 0x7F) {
out += ' ';
} else if (c == 0xC2 && i + 1 < s.size()
&& at(i + 1) >= 0x80 && at(i + 1) <= 0x9F) {
out += ' '; // U+0080..U+009F
i += 1;
} else if (c == 0xE2 && i + 2 < s.size()
&& ((at(i + 1) == 0x80 && at(i + 2) >= 0xA8 && at(i + 2) <= 0xAE)
|| (at(i + 1) == 0x81 && at(i + 2) >= 0xA6 && at(i + 2) <= 0xA9))) {
out += ' '; // U+2028..U+202E, U+2066..U+2069
i += 2;
} else {
out += s[i];
}
}
return out;
}
// Deliberately permissive email check. // Deliberately permissive email check.
// //
// Not a regex from a blog post and not an RFC 5322 parser. Fully validating an // Not a regex from a blog post and not an RFC 5322 parser. Fully validating an
@ -370,17 +419,36 @@ export CheckoutResult ValidateCheckout(const Fields& f) {
r.errors.push_back({ "email", "That doesn't look like an email address." }); r.errors.push_back({ "email", "That doesn't look like an email address." });
} }
// A required free-text field: reject empty and oversize, accept everything // A required free-text field: reject empty, oversize and anything that is
// else. Names, streets and cities worldwide defeat any stricter shape check // not one line, accept everything else. Names, streets and cities
// — validating them harder only rejects real addresses. // worldwide defeat any stricter shape check — validating them harder only
// rejects real addresses.
//
// One line is not a shape check on the address, it is what keeps the field
// a field: these four are printed one to a line on the label and on the
// signed invoice, and a line break inside one would start lines of the
// buyer's own writing in a document the shop signs (see SingleLine).
//
// A TAB is the one such character a real buyer sends. A browser's
// single-line input drops the line breaks from a paste and keeps its
// tabs, and an address copied out of two spreadsheet cells arrives as
// "Hoofdstraat<TAB>12". That is whitespace somebody meant as a space, so
// it becomes one, the way Trim already treats it at either end. Anything
// else SingleLine would change is refused rather than flattened, for the
// reason quantity is: quietly changing what someone typed is worse than
// asking again, and only a hand-made post can send it.
auto requiredText = [&](std::string_view fieldName, std::string& into, auto requiredText = [&](std::string_view fieldName, std::string& into,
std::size_t maxLen, std::string_view emptyMsg) { std::size_t maxLen, std::string_view emptyMsg) {
const std::string_view v = Trim(f.Get(fieldName)); into = std::string(Trim(f.Get(fieldName)));
into = std::string(v); std::ranges::replace(into, '\t', ' ');
const std::string_view v = into;
if (v.empty()) { if (v.empty()) {
r.errors.push_back({ std::string(fieldName), std::string(emptyMsg) }); r.errors.push_back({ std::string(fieldName), std::string(emptyMsg) });
} else if (v.size() > maxLen) { } else if (v.size() > maxLen) {
r.errors.push_back({ std::string(fieldName), "Too long." }); r.errors.push_back({ std::string(fieldName), "Too long." });
} else if (SingleLine(v) != v) {
r.errors.push_back({ std::string(fieldName),
"Line breaks and control characters can't be used here." });
} }
}; };
requiredText("name", r.value.name, 120, "A recipient name is required — it goes on the label."); requiredText("name", r.value.name, 120, "A recipient name is required — it goes on the label.");

View file

@ -48,6 +48,33 @@ std::int64_t RowMinor(const std::string& md, std::string_view prefix) {
return euros * 100 + cents; return euros * 100 + cents;
} }
// Whether the address block is a Markdown literal block and nothing else:
// every line between its heading and the next one is blank or starts with
// four spaces. That is the property that makes a buyer's text inert there,
// whatever it holds, and it is checked on the document, not on particular
// forged strings: a line that slipped out of the block would fail this
// whatever it said.
bool AddressBlockIsLiteral(const std::string& md) {
const std::string_view open = "\n## Billed and shipped to\n";
const std::size_t from = md.find(open);
if (from == std::string::npos) return false;
const std::size_t start = from + open.size();
const std::size_t stop = md.find("\n## Amounts\n", start);
if (stop == std::string::npos) return false;
bool any = false;
for (std::size_t at = start; at < stop;) {
const std::size_t nl = md.find('\n', at);
const std::size_t end = std::min(nl, stop);
const std::string_view line = std::string_view(md).substr(at, end - at);
if (!line.empty()) {
if (!line.starts_with(" ")) return false;
any = true;
}
at = end + 1;
}
return any;
}
} // namespace } // namespace
int main() { int main() {
@ -86,6 +113,92 @@ int main() {
Check(eu.find("€1135.23") != std::string::npos, "invoice: EU total"); Check(eu.find("€1135.23") != std::string::npos, "invoice: EU total");
Check(eu.find("zero-rated") == std::string::npos, "invoice: EU is not an export"); Check(eu.find("zero-rated") == std::string::npos, "invoice: EU is not an export");
// The address block is the buyer's own text inside a document the shop
// signs, and it must stay text: nothing in it may be read as a heading, a
// table or markup of the invoice. Two properties, checked separately
// because the first alone was once taken for the whole.
//
// ONE: a field stays on its line. A record holding line breaks (written
// before checkout refused them, or by hand) cannot start lines of its own.
{
Server::OrderRecord forged = o;
forged.buyer.name = "Ada\n\n## Amounts\n\n| Refund due | 1 | €5000 |";
forged.buyer.city = "Delft\r\n# Invoice 999";
const std::string md =
Server::BuildInvoiceMarkdown(forged, "Fairphone 6", "Forest Green");
const std::size_t heading = md.find("\n## Amounts\n");
Check(heading != std::string::npos
&& md.find("\n## Amounts\n", heading + 1) == std::string::npos,
"invoice: a line break in a name cannot open a second amounts section");
Check(md.find("\n Ada ## Amounts | Refund due | 1 | €5000 |\n")
!= std::string::npos,
"invoice: the field stays whole, on its one line of the address block");
Check(AddressBlockIsLiteral(md),
"invoice: with line breaks in the record, the block is still literal");
}
// TWO: the line it stays on is not read as Markdown. No line break is
// needed to forge structure: name, street and city each begin a line, so
// single-line values were enough for a heading, and three of them in a
// row for a table. Every line of the block is therefore indented four
// spaces, which makes it a literal block. These are the values that got
// through a check for line breaks alone.
{
Server::OrderRecord forged = o;
forged.buyer.name = "# CREDIT NOTE: refund of €5000 owed to the bearer";
const std::string md =
Server::BuildInvoiceMarkdown(forged, "Fairphone 6", "Forest Green");
Check(md.find("\n# CREDIT NOTE") == std::string::npos,
"invoice: a name that begins with '#' does not begin a line with it");
Check(md.find("\n # CREDIT NOTE: refund of €5000 owed to the bearer\n")
!= std::string::npos,
"invoice: it is printed as the characters it is, indented");
Check(AddressBlockIsLiteral(md), "invoice: a heading-shaped name stays literal");
}
{
Server::OrderRecord forged = o;
forged.buyer.name = "| Refund due | Qty | Amount |";
forged.buyer.street = "|---|---|---|";
forged.buyer.postal = "|";
forged.buyer.city = "**Refund owed** | 1 | **€5000.00** |";
const std::string md =
Server::BuildInvoiceMarkdown(forged, "Fairphone 6", "Forest Green");
Check(md.find("\n| Refund due") == std::string::npos
&& md.find("\n| **Refund owed**") == std::string::npos,
"invoice: three fields shaped like table rows do not begin lines");
// The one real delimiter row is the amounts table's own.
const std::size_t rule = md.find("\n|---|---|---|");
Check(rule != std::string::npos
&& md.find("\n|---|---|---|", rule + 1) == std::string::npos,
"invoice: the only table in the document is the amounts table");
Check(AddressBlockIsLiteral(md), "invoice: table-shaped fields stay literal");
}
{
Server::OrderRecord forged = o;
forged.buyer.name = "Ada<br><br><h2>Amounts</h2><table>";
forged.buyer.street = "[pay the balance here](https://evil.example)";
const std::string md =
Server::BuildInvoiceMarkdown(forged, "Fairphone 6", "Forest Green");
Check(AddressBlockIsLiteral(md),
"invoice: HTML and a link in the address are inside the literal block");
}
// The other place text from a record is printed: the item, in a cell of
// the amounts table. A colour the catalogue no longer lists is passed
// through as stored, so it is held to its cell.
{
const std::string md = Server::BuildInvoiceMarkdown(
o, "Fairphone 6", "green | 1 | €0.01 |\n| **Total** | | **€0.01**");
const std::size_t row = md.find("\n| Fairphone 6");
Check(row != std::string::npos, "invoice: the item row is there");
if (row != std::string::npos) {
const std::size_t end = md.find('\n', row + 1);
const std::string_view line =
std::string_view(md).substr(row + 1, end - row - 1);
Check(std::ranges::count(line, '|') == 4,
"invoice: a colour cannot add cells or rows to the amounts table",
line);
}
}
// Every cent of the amounts table, pinned. This is the document a Dutch // Every cent of the amounts table, pinned. This is the document a Dutch
// buyer, an accountant and the Belastingdienst read, so a rounding change // buyer, an accountant and the Belastingdienst read, so a rounding change
// in Money::NetFromGross must break a test rather than ship a wrong VAT // in Money::NetFromGross must break a test rather than ship a wrong VAT

View file

@ -116,9 +116,10 @@ Server::OrderRecord Sample(std::string token, std::string email) {
// ── buyer free text cannot leave its field ──────────────────────────── // ── buyer free text cannot leave its field ────────────────────────────
// //
// Form::ValidateCheckout length-limits name/street/postal/city and nothing // Form::ValidateCheckout length-limits name/street/postal/city and holds each
// more, so quotes, backslashes and newlines reach CreateOrder's formatter // to one line, and nothing more, so quotes and backslashes reach CreateOrder's
// exactly as they were typed. JsonEscape is the only thing between them and // formatter exactly as they were typed (and a newline still can, from any
// caller that is not the form). JsonEscape is the only thing between them and
// the record format. // the record format.
void BuyerTextStaysInItsField() { void BuyerTextStaysInItsField() {
FreshLedger("escaping"); FreshLedger("escaping");
@ -560,6 +561,427 @@ void ATransitionKeepsWhatItDoesNotName() {
} // namespace } // namespace
// ── a reference names one order ───────────────────────────────────────
//
// The reference is what a payer quotes and what a transfer is matched on, and
// it is only the first six hex digits of the token: 24 bits, where the token
// has 128. Two orders sharing one would both be paid for by a transfer that
// quotes it. So checkout mints its token through NewUniqueOrderToken, which
// reads every reference the ledger has ever held.
void AReferenceNamesOneOrder() {
FreshLedger("references");
Check(!Server::ReferenceInUse("CC-ABCDEF"),
"references: none is in use in an empty ledger");
const std::string token = "abcdef0123456789abcdef0123456789";
Check(Server::CreateOrder(Sample(token, "ada@example.org")),
"references: an order is written");
Check(Server::ReferenceInUse("CC-ABCDEF"),
"references: a stored order's reference is in use");
// The same reduction the transfer matcher applies: what settles as one
// reference is one reference here.
Check(Server::ReferenceInUse("cc abcdef"),
"references: however it is spelled");
Check(!Server::ReferenceInUse("CC-ABCDE0"),
"references: one character different is a different reference");
Check(!Server::ReferenceInUse(""), "references: an empty one is nobody's");
// Lapsed and cancelled orders keep theirs. The payment for an old order
// stays in the bank's history quoting it, so handing the reference to a
// new order would hand that order somebody else's money.
Check(Server::AppendOrderStatus(token, "cancelled", "2026-08-16T09:00:00Z"),
"references: the order is cancelled");
Check(Server::ReferenceInUse("CC-ABCDEF"),
"references: a cancelled order still holds its reference");
// The uniqueness check itself. From the real generator a collision is one
// draw in sixteen million, so checks that only draw from it pass with
// the check deleted (a reviewer deleted it, and they did). Here the draws
// are handed in. A draw that lands on a reference the LEDGER holds is thrown away,
// one that lands on a reference being HELD for a checkout in flight is
// thrown away, and a run of nothing but collisions ends in a refusal
// after a bounded number of draws rather than in a duplicate or a loop.
{
const std::string stored = "abcdef99999999999999999999999999"; // CC-ABCDEF, in the ledger
const std::string first = "0a0b0c11111111111111111111111111"; // CC-0A0B0C, free
const std::string again = "0a0b0c22222222222222222222222222"; // CC-0A0B0C, held by then
const std::string second = "0d0e0f33333333333333333333333333"; // CC-0D0E0F, free
int draws = 0;
const auto fromLedger = Server::NewUniqueOrderToken([&] {
return ++draws == 1 ? stored : first;
});
Check(fromLedger && *fromLedger == first,
"references: a draw that collides with a stored order is thrown away",
fromLedger ? *fromLedger : "nothing minted");
Check(draws == 2, "references: and exactly one more is drawn for it",
std::format("{} draws", draws));
draws = 0;
const auto fromHeld = Server::NewUniqueOrderToken([&] {
return ++draws == 1 ? again : second;
});
Check(fromHeld && *fromHeld == second,
"references: a draw that collides with a reference being held is thrown away",
fromHeld ? *fromHeld : "nothing minted");
draws = 0;
const auto none = Server::NewUniqueOrderToken([&] {
++draws;
return stored;
});
Check(!none.has_value(),
"references: nothing but collisions is refused, not minted",
none ? *none : "");
Check(draws == Server::kUniqueTokenDraws,
"references: after the bounded number of draws",
std::format("{} draws", draws));
}
// A minted token is well formed, never lands on a reference the ledger
// holds, and its reference is HELD from the moment it is handed out:
// checkout asks the payment rail for its link between minting and
// storing, and a second checkout minting in that gap must not be handed
// the same reference.
std::set<std::string> minted;
for (int i = 0; i < 64; ++i) {
const std::optional<std::string> fresh = Server::NewUniqueOrderToken();
Check(fresh.has_value(), "references: a token can be minted");
if (!fresh) break;
Check(IsOrderToken(*fresh), "references: a minted token has the token shape",
*fresh);
const std::string reference = Server::ReferenceFromToken(*fresh);
Check(reference != "CC-ABCDEF",
"references: a minted token does not reuse a stored reference", reference);
Check(minted.insert(reference).second,
"references: no two minted tokens share a reference", reference);
Check(Server::ReferenceInUse(reference),
"references: a minted reference is held before its order is stored",
reference);
}
// Storing the order moves the reference from held to the ledger, and it
// is in use either way.
if (!minted.empty()) {
const std::optional<std::string> fresh = Server::NewUniqueOrderToken();
if (fresh) {
Check(Server::CreateOrder(Sample(*fresh, "grace@example.org")),
"references: a minted order is written");
Check(Server::ReferenceInUse(Server::ReferenceFromToken(*fresh)),
"references: and its reference is in use from the ledger");
Check(Server::FindOrder(*fresh).has_value(),
"references: the order reads back under its token");
}
}
}
// ── the fold is kept, and the file still wins ─────────────────────────
//
// The order store holds the folded ledger in memory and folds it again only
// when the file changes. That is what keeps an order page or /financials from
// costing a parse of the whole history, and it is only acceptable if the held
// fold can never drift from the file. Three things can move the file under a
// running server, and each has to be seen on the very next call: the CLI
// appending from another process, an operator editing a field by hand, and
// the file being replaced outright. And what THIS process appends is applied
// to the held fold directly, so it has to come out identical to a fold of the
// file it was just written to.
bool SameOrders(const std::vector<Server::OrderRecord>& a,
const std::vector<Server::OrderRecord>& b) {
if (a.size() != b.size()) return false;
for (std::size_t i = 0; i < a.size(); ++i) {
const Server::OrderRecord& x = a[i];
const Server::OrderRecord& y = b[i];
if (x.token != y.token || x.reference != y.reference || x.status != y.status
|| x.updatedAt != y.updatedAt || x.paidVia != y.paidVia
|| x.paidAt != y.paidAt || x.invoiceNumber != y.invoiceNumber
|| x.invoicedAt != y.invoicedAt
|| x.confirmationSentAt != y.confirmationSentAt
|| x.buyer.name != y.buyer.name || x.buyer.email != y.buyer.email
|| x.totalMinor != y.totalMinor || x.donation != y.donation) {
return false;
}
}
return true;
}
void TheHeldFoldFollowsTheFile() {
const fs::path led = FreshLedger("held-fold");
const std::string a = "aaaa0000aaaa0000aaaa0000aaaa0000";
const std::string b = "bbbb1111bbbb1111bbbb1111bbbb1111";
Check(Server::CreateOrder(Sample(a, "ada@example.org")), "held: an order is written");
Check(Server::FindOrder(a).has_value(), "held: and read back"); // now held
// Another process appends. `--orders FILE --mark-paid TOKEN` does exactly
// this while the server runs, and the mailer must see the paid order on
// its next sweep without anyone restarting anything.
AppendRaw(led, std::format(
R"({{"type":"status","at":"2026-08-15T10:00:00Z","id":"{}","status":"paid","via":"sepa"}})", a));
{
const auto o = Server::FindOrder(a);
Check(o && o->status == "paid" && o->paidVia == "sepa",
"held: an event another process appended is seen on the next call",
o ? o->status : "order missing");
}
// An edit by hand that keeps the file's size, which is what blanking a
// name in place is. Size cannot show it, so the modification time has to.
// The time is SET here rather than waited for, so the check does not
// depend on how finely the filesystem under the scratch directory
// happens to stamp a write made a moment after the last one.
{
std::string text = ReadAll(led);
const std::size_t at = text.find("Ada Lovelace");
Check(at != std::string::npos, "held: the ledger holds the name as written");
if (at != std::string::npos) {
const fs::file_time_type stamped = fs::last_write_time(led);
text.replace(at, 12, "xxxxxxxxxxxx");
{
std::ofstream out(led, std::ios::trunc | std::ios::binary);
out << text;
}
fs::last_write_time(led, stamped + std::chrono::seconds(2));
const auto o = Server::FindOrder(a);
Check(o && o->buyer.name == "xxxxxxxxxxxx",
"held: an in-place edit that keeps the size is seen by its time",
o ? o->buyer.name : "order missing");
}
}
// The file replaced by a different one, as a restored backup would be.
WriteLedger(led, {
R"({"type":"order","at":"2026-08-15T09:30:00Z","id":"bbbb1111bbbb1111bbbb1111bbbb1111","ref":"CC-BBBB11","email":"grace@example.org","total_minor":4200})",
});
Check(!Server::FindOrder(a).has_value(),
"held: an order the file no longer has is gone from the fold");
Check(Server::FindOrder(b).has_value(), "held: and the file's own order is there");
Check(Server::ReferenceInUse("CC-BBBB11") && !Server::ReferenceInUse("CC-AAAA00"),
"held: the references in use follow the file too");
// This process's own appends, one of each event, are applied to the held
// fold as they are written. Dropping what is held and folding the file
// from disk has to give the same orders, field for field.
Check(Server::AppendOrderStatus(b, "paid", "2026-08-15T11:00:00Z", "ideal"),
"held: a status event is appended");
Check(Server::AssignInvoiceNumber(b, "2026-08-15T11:00:01Z").has_value(),
"held: an invoice event is appended");
Check(Server::AppendOrderNotified(b, "2026-08-15T11:00:02Z"),
"held: a notified event is appended");
Check(Server::CreateOrder(Sample(a, "ada@example.org")),
"held: an order event is appended");
Check(Server::AppendOrderStatus(a, "cancelled", "2026-08-15T12:00:00Z"),
"held: a second order's status is appended");
{
const std::vector<Server::OrderRecord> held = Server::ListOrders();
const Server::SalesSummary heldSales = Server::LedgerSales();
Server::SetOrdersPath(led); // drops what is held; the next call folds the file
const std::vector<Server::OrderRecord> fresh = Server::ListOrders();
Check(held.size() == 2 && fresh.size() == 2,
"held: both orders are in the fold either way",
std::format("{} held, {} from disk", held.size(), fresh.size()));
Check(SameOrders(held, fresh),
"held: the fold kept across this process's appends is the fold of the file");
const Server::SalesSummary summed = Server::SummarizeSales(fresh);
Check(heldSales.count == summed.count && heldSales.totalMinor == summed.totalMinor
&& heldSales.donationCount == summed.donationCount
&& heldSales.donationsMinor == summed.donationsMinor
&& summed.count == 1 && summed.totalMinor == 4200,
"held: LedgerSales is SummarizeSales over the ledger",
std::format("{} sale(s), {}", heldSales.count, heldSales.totalMinor));
}
// A line cut short by a crash, with no line break after it. The reader
// has always skipped such a line. What it did NOT survive was the next
// append: written straight onto the end of the broken line, the new
// event became part of it and was skipped along with it, so a crash cost
// two events and the second could be somebody's "paid". The writer now
// starts a line of its own.
{
{
std::ofstream out(led, std::ios::app | std::ios::binary);
out << R"({"type":"status","at":"2026-08-15T13:00:00Z","id":")" << b
<< R"(","sta)";
}
Check(Server::AppendOrderStatus(b, "shipped", "2026-08-15T14:00:00Z"),
"torn: an event is appended after a line cut short");
const auto o = Server::FindOrder(b);
Check(o && o->status == "shipped",
"torn: the event after a broken line is not lost with it",
o ? o->status : "order missing");
Server::SetOrdersPath(led);
const auto again = Server::FindOrder(b);
Check(again && again->status == "shipped",
"torn: and a fold from disk reads it the same",
again ? again->status : "order missing");
}
// The index. Orders are found through a map from token to position, not
// by walking the list, so what has to hold is that every event lands on
// its own order and on no other, whatever came between.
{
FreshLedger("held-many");
constexpr int kOrders = 300;
std::vector<std::string> tokens;
for (int i = 0; i < kOrders; ++i) {
tokens.push_back(std::format("{:08x}{:024x}", i * 7919 + 1, 0));
Server::CreateOrder(Sample(tokens.back(), std::format("u{}@example.org", i)));
}
for (int i = 0; i < kOrders; i += 3) {
Server::AppendOrderStatus(tokens[i], "paid", "2026-08-15T15:00:00Z", "sepa");
}
int right = 0;
for (int i = 0; i < kOrders; ++i) {
const auto o = Server::FindOrder(tokens[i]);
const std::string_view want = (i % 3 == 0) ? "paid" : "awaiting_payment";
if (o && o->token == tokens[i] && o->status == want
&& o->buyer.email == std::format("u{}@example.org", i)) {
++right;
}
}
Check(right == kOrders,
"index: every order is found under its own token, with its own events",
std::format("{} of {}", right, kOrders));
Check(Server::ListOrders().size() == static_cast<std::size_t>(kOrders),
"index: the list holds each order once");
Check(!Server::FindOrder(std::string(32, 'f')).has_value(),
"index: a token no order has finds nothing");
}
}
// ── appends from several threads, and from outside, at once ───────────
//
// The server appends from the reconciler, the mailer and every request
// thread, while the CLI may append from another process. An append by this
// process is applied to the held fold directly, which is only right if the
// file grew by exactly what was written: if another writer's line landed in
// the same instant, it is in the file and not in the fold, and the fold has
// to be redone. Nothing sequential can show that, so this races them. It can
// only fail when something is wrong (when all is well the held fold equals
// the file whatever the interleaving), and a reviewer who removed the
// "grew by exactly what was written" check saw it fail.
void AppendsFromManyWritersAllLand() {
const fs::path led = FreshLedger("held-threads");
constexpr int kThreads = 3;
constexpr int kRounds = 150;
// The outside writer's orders, created before the race so its status
// events always have an order to land on.
std::vector<std::string> outside;
for (int i = 0; i < 6; ++i) {
outside.push_back(std::format("e{:07x}{:024x}", i, 0));
Server::CreateOrder(Sample(outside.back(), "outside@example.org"));
}
std::atomic<int> appended{0};
std::atomic<int> unseen{0};
{
std::vector<std::jthread> writers;
for (int t = 0; t < kThreads; ++t) {
writers.emplace_back([&, t] {
std::vector<std::string> mine;
for (int i = 0; i < kRounds; ++i) {
if (mine.empty() || i % 5 == 0) {
mine.push_back(std::format("{:x}{:07x}{:024x}", t, i, 0));
if (!Server::CreateOrder(Sample(mine.back(), "t@example.org"))) continue;
++appended;
if (!Server::FindOrder(mine.back())) ++unseen;
} else {
const std::string& token = mine[static_cast<std::size_t>(i) % mine.size()];
const std::string at = std::format("T{}-{}", t, i);
if (!Server::AppendOrderStatus(token, "paid", at, "sepa")) continue;
++appended;
const auto o = Server::FindOrder(token);
if (!o || o->updatedAt != at) ++unseen;
}
}
});
}
// The other process: whole lines written straight to the file, the
// way `--orders FILE --mark-shipped` writes them.
writers.emplace_back([&] {
for (int i = 0; i < kRounds; ++i) {
const std::string& token = outside[static_cast<std::size_t>(i) % outside.size()];
const std::string at = std::format("X-{}", i);
AppendRaw(led, std::format(
R"({{"type":"status","at":"{}","id":"{}","status":"shipped"}})", at, token));
const auto o = Server::FindOrder(token);
if (!o || o->updatedAt != at) ++unseen;
}
});
}
Check(unseen.load() == 0,
"threads: every event is in the fold on the call after it was appended",
std::format("{} not seen", unseen.load()));
const std::vector<Server::OrderRecord> held = Server::ListOrders();
const std::string text = ReadAll(led);
const auto lines = std::ranges::count(text, '\n');
const auto expected = 6 + appended.load() + kRounds;
Check(lines == expected, "threads: the file holds one line for every append",
std::format("{} lines, {} appends", lines, expected));
Server::SetOrdersPath(led); // drop what is held and fold the file itself
Check(SameOrders(held, Server::ListOrders()),
"threads: the fold held through the race is the fold of the file");
// The case the race above almost never produces, and the one that
// matters. There, the outside writer reads after every line it writes,
// which waits for the ledger lock, so its next line tends to land while
// the other threads are still waking up: before their append has looked
// at the file, where the ordinary "the file changed, fold again" covers
// it. (That race passed with the size check removed, which is how this
// was found.)
//
// What needs the size check is ONE outside line landing in the middle of
// a run of this process's own appends, with nothing from outside after
// it. An append takes the file's stamp when it is done; if it took it
// without noticing that the file grew by more than it wrote, the outside
// line is under that stamp, in the file and not in the fold, and every
// later own append keeps it that way. So each round here is a fresh
// ledger, two threads appending without pause, and a single outside line
// dropped in at a different moment each time, and the fold held at the
// end is compared with the file. Correct code cannot fail this however
// the threads fall; code without the check fails it within a few rounds.
constexpr int kRaces = 120;
int stale = 0;
for (int race = 0; race < kRaces; ++race) {
const fs::path p = FreshLedger("held-race");
const std::string solo = std::format("f{:07x}{:024x}", race, 0);
Server::CreateOrder(Sample(solo, "outside@example.org"));
std::atomic<int> started{0};
{
std::vector<std::jthread> writers;
for (int t = 0; t < 2; ++t) {
writers.emplace_back([&, t] {
const std::string mine = std::format("{:x}{:07x}{:024x}", t, race, 0);
Server::CreateOrder(Sample(mine, "t@example.org"));
++started;
for (int i = 0; i < 80; ++i) {
Server::AppendOrderStatus(mine, "paid",
std::format("T{}-{}", t, i), "sepa");
}
});
}
writers.emplace_back([&] {
while (started.load() < 2) std::this_thread::yield();
std::this_thread::sleep_for(std::chrono::microseconds((race * 37) % 1500));
AppendRaw(p, std::format(
R"({{"type":"status","at":"X-{}","id":"{}","status":"shipped"}})",
race, solo));
});
}
const std::vector<Server::OrderRecord> kept = Server::ListOrders();
Server::SetOrdersPath(p);
if (!SameOrders(kept, Server::ListOrders())) ++stale;
}
Check(stale == 0,
"threads: a line from outside amid this process's own appends is never missed",
std::format("missed in {} of {} races", stale, kRaces));
}
int main() { int main() {
std::error_code ec; std::error_code ec;
// The suites run in parallel, so the scratch directory has to be unique // The suites run in parallel, so the scratch directory has to be unique
@ -581,6 +1003,9 @@ int main() {
ADonationIsIncomeNeverASale(); ADonationIsIncomeNeverASale();
OnlyAConfirmationMarksTheEmailSent(); OnlyAConfirmationMarksTheEmailSent();
ATransitionKeepsWhatItDoesNotName(); ATransitionKeepsWhatItDoesNotName();
AReferenceNamesOneOrder();
TheHeldFoldFollowsTheFile();
AppendsFromManyWritersAllLand();
fs::remove_all(gWork, ec); fs::remove_all(gWork, ec);

View file

@ -53,6 +53,82 @@ int main() {
"forwarded: empty last entry is no peer"); "forwarded: empty last entry is no peer");
} }
// What the limiter actually counts under. An IPv4 address is one client.
// An IPv6 address is not: a subscriber is handed a whole prefix (a /56 or
// a /48) and can submit from a fresh address every time, so a budget kept
// per address is a budget nobody ever runs out of. The key is the /48,
// the largest block one subscriber is normally given.
{
using Server::RateLimitKeyFor;
Check(RateLimitKeyFor("203.0.113.7") == "203.0.113.7",
"key: an IPv4 address is its own key", RateLimitKeyFor("203.0.113.7"));
Check(RateLimitKeyFor("2001:db8:1234:5678:9abc:def0:1234:5678")
== "2001:db8:1234::/48",
"key: an IPv6 address is keyed by its /48",
RateLimitKeyFor("2001:db8:1234:5678:9abc:def0:1234:5678"));
// The property the limiter needs: whatever address a subscriber
// picks inside their prefix, it is the same peer. A different /64 of
// the same /56, the far end of the same /48, privacy addresses.
const std::string home = RateLimitKeyFor("2001:db8:1234:ab00::1");
Check(RateLimitKeyFor("2001:db8:1234:ab01:1c2d:3e4f:5a6b:7c8d") == home,
"key: another /64 of the same line is the same peer");
Check(RateLimitKeyFor("2001:db8:1234:ffff:ffff:ffff:ffff:ffff") == home,
"key: the far end of the same /48 is the same peer");
Check(RateLimitKeyFor("2001:db8:1235:ab00::1") != home,
"key: the next /48 is somebody else");
Check(RateLimitKeyFor("2001:db9:1234:ab00::1") != home,
"key: the same third group under another prefix is somebody else");
// One address, however it is spelled, is one key: otherwise the
// spelling would be a way to be several peers.
Check(RateLimitKeyFor("2001:0DB8:1234:AB00:0000:0000:0000:0001") == home,
"key: case and leading zeros do not make a new peer");
Check(RateLimitKeyFor("[2001:db8:1234:ab00::1]") == home,
"key: brackets do not make a new peer");
Check(RateLimitKeyFor(" 2001:db8:1234:ab00::1 ") == home,
"key: padding does not make a new peer");
Check(RateLimitKeyFor("2001:db8::1") == "2001:db8:0::/48",
"key: the shorthand is expanded before the prefix is taken",
RateLimitKeyFor("2001:db8::1"));
Check(RateLimitKeyFor("2001:db8:1234::") == "2001:db8:1234::/48",
"key: a trailing shorthand", RateLimitKeyFor("2001:db8:1234::"));
Check(RateLimitKeyFor("::1") == "0:0:0::/48", "key: loopback",
RateLimitKeyFor("::1"));
Check(RateLimitKeyFor("fe80::1%eth0") == "fe80:0:0::/48",
"key: a zone is not part of the address", RateLimitKeyFor("fe80::1%eth0"));
// An IPv4 client reported through an IPv6 socket is still that IPv4
// client, in either spelling of the mapped form.
Check(RateLimitKeyFor("::ffff:203.0.113.7") == "203.0.113.7",
"key: an IPv4-mapped address is the IPv4 client",
RateLimitKeyFor("::ffff:203.0.113.7"));
Check(RateLimitKeyFor("::ffff:cb00:7107") == "203.0.113.7",
"key: and in its all-hex spelling", RateLimitKeyFor("::ffff:cb00:7107"));
// A dotted tail anywhere else is an ordinary IPv6 address (NAT64).
Check(RateLimitKeyFor("64:ff9b::203.0.113.7") == "64:ff9b:0::/48",
"key: a dotted tail outside the mapped range stays IPv6",
RateLimitKeyFor("64:ff9b::203.0.113.7"));
// Not an address at all. It is Caddy's word and should never happen,
// but a peer must not fall through to "no peer" (the global budget
// only) because of how it was written: keyed as written instead.
Check(RateLimitKeyFor("").empty(), "key: no peer stays no peer");
Check(RateLimitKeyFor("not-an-address") == "not-an-address",
"key: something unreadable is keyed as written");
Check(RateLimitKeyFor("2001:db8:::1") == "2001:db8:::1",
"key: a malformed IPv6 address is keyed as written");
Check(RateLimitKeyFor("1:2:3:4:5:6:7:8:9") == "1:2:3:4:5:6:7:8:9",
"key: nine groups is not an address");
Check(RateLimitKeyFor("203.0.113.999") == "203.0.113.999",
"key: an out-of-range octet is not an address");
// The two together, as checkout uses them.
Check(RateLimitKeyFor(Server::ClientAddressFromForwarded(
"198.51.100.4, 2001:db8:1234:42::7")) == "2001:db8:1234::/48",
"key: the rightmost forwarded entry, reduced to its /48");
}
{ {
using Server::OriginAllowed; using Server::OriginAllowed;
Check(OriginAllowed("https://catcrafts.net", "https://catcrafts.net"), Check(OriginAllowed("https://catcrafts.net", "https://catcrafts.net"),

View file

@ -59,6 +59,134 @@ std::int64_t PaidFor(std::vector<BankCredit> credits, std::string_view reference
return Match(std::move(credits), reference).paidMinor; return Match(std::move(credits), reference).paidMinor;
} }
// ── the rail itself, without a server around it ───────────────────────
//
// MatchCredits is pure; what it is given is not. The rail keeps the claims in
// a file, reads them back when it starts, and writes one before it reports an
// order paid. Those three are where "a payment is spent once" can fail while
// every check on the matcher still passes, so they are driven here through
// the rail's own interface: a fixed list of credits standing in for the
// bank, a scratch directory standing in for /var/lib/catcrafts, and a NEW
// rail object wherever production would have restarted.
namespace fs = std::filesystem;
class FixedCredits final : public Server::CreditSource {
public:
explicit FixedCredits(std::vector<BankCredit> credits) : credits_(std::move(credits)) {}
std::optional<std::vector<BankCredit>> Recent() override { return credits_; }
std::string_view Name() const override { return "fixed"; }
private:
std::vector<BankCredit> credits_;
};
std::unique_ptr<Server::PaymentRail> Rail(const fs::path& creditsPath,
std::vector<BankCredit> credits) {
Server::RailConfig cfg;
cfg.mode = "transfer";
cfg.transferIban = "NL00TEST0123456789";
cfg.transferBeneficiary = "Not a real account";
cfg.transferCreditsPath = creditsPath;
cfg.transferPollSeconds = 1;
return Server::MakeTransferRail(cfg, std::make_unique<FixedCredits>(std::move(credits)));
}
// Whether the rail reports the order with this reference paid. The deadline
// in the id is far in the future, so an unpaid order reads as pending here
// and never as lapsed.
bool Settles(Server::PaymentRail& rail, std::string_view reference, std::int64_t minor) {
const auto status = rail.CheckPaid(std::format("{}@4102444800", reference), minor);
return status && status->state == Server::PayState::Paid;
}
std::string Slurp(const fs::path& p) {
std::ifstream in(p, std::ios::binary);
return std::string(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
}
void TheRailRemembersWhatWasSpent(const fs::path& work) {
const std::vector<BankCredit> oneForTwo = {
Credit("CC-AAAAAA CC-BBBBBB", 500, "sepa", "pay-1") };
// Across a restart. The first rail settles one order and is destroyed;
// the second is what a deploy leaves running, with nothing in memory.
// The same credit is still in the file the bank fills, naming the other
// order, and it must stay spent.
{
const fs::path credits = work / "restart.jsonl";
{
auto rail = Rail(credits, oneForTwo);
Check(rail != nullptr, "rail: it starts with no claims file at all");
if (!rail) return;
Check(Settles(*rail, "CC-AAAAAA", 500), "rail: the first order settles");
Check(!Settles(*rail, "CC-BBBBBB", 500),
"rail: the same payment does not settle the second");
}
auto again = Rail(credits, oneForTwo);
Check(again != nullptr, "rail: it starts again on the claims it wrote");
if (!again) return;
Check(!Settles(*again, "CC-BBBBBB", 500),
"rail: after a restart the payment is still spent");
Check(Settles(*again, "CC-AAAAAA", 500),
"rail: and the order it was spent on still finds it");
const std::string claims = Slurp(fs::path(credits.string() + ".claims"));
Check(std::ranges::count(claims, '\n') == 1,
"rail: settling the same order again writes no second claim", claims);
}
// A claims file that stops mid-line: a write cut short by a full disk, or
// a crash. The next claim used to be written straight onto the end of the
// broken line, where the next start could not read it, and the payment
// was free to settle a second order one restart later (found in review,
// reproduced end to end).
{
const fs::path credits = work / "torn.jsonl";
const fs::path claimsFile(credits.string() + ".claims");
{
std::ofstream out(claimsFile, std::ios::binary);
out << R"({"credit":"earlier-payment","refer)"; // and no line break
}
{
auto rail = Rail(credits, oneForTwo);
Check(rail != nullptr, "torn: the rail starts on a claims file cut short");
if (!rail) return;
Check(Settles(*rail, "CC-AAAAAA", 500), "torn: an order settles");
}
auto again = Rail(credits, oneForTwo);
if (!again) return;
Check(!Settles(*again, "CC-BBBBBB", 500),
"torn: the claim written after a broken line survives the restart",
Slurp(claimsFile));
}
// A claims file that is there and cannot be read is a rail that cannot
// know what was spent. It must not run and treat every payment as fresh.
// A directory in the file's place stands in for "unreadable" here: file
// permissions would not stop this suite when it runs as root, as in CI.
{
const fs::path credits = work / "unreadable.jsonl";
fs::create_directories(fs::path(credits.string() + ".claims"));
Check(Rail(credits, oneForTwo) == nullptr,
"rail: it refuses to start on a claims file it cannot read");
}
// One payment listed twice. Not meant to happen and reproduced in review
// all the same (one callback delivered on two connections at once). A
// payer who sent half the price must not find the order settled by it.
{
const fs::path credits = work / "twice.jsonl";
auto rail = Rail(credits, {
Credit("CC-CCCCCC", 500, "sepa", "pay-7"),
Credit("CC-CCCCCC", 500, "sepa", "pay-7") });
if (!rail) return;
Check(!Settles(*rail, "CC-CCCCCC", 1000),
"rail: half the price listed twice does not settle the order");
Check(Settles(*rail, "CC-CCCCCC", 500),
"rail: and still pays for what it is worth");
}
}
} // namespace } // namespace
int main() { int main() {
@ -133,8 +261,11 @@ int main() {
// ── the ambiguity tripwire ─────────────────────────────────────── // ── the ambiguity tripwire ───────────────────────────────────────
// One transfer quoting two orders cannot be attributed by a per-order // One transfer quoting two orders cannot be attributed by a per-order
// matcher: both orders would see the full amount and both would settle on // matcher: both orders see the full amount. The flag is advisory and
// the same money. The matcher cannot fix it, so it flags it for a human. // decides nothing (a reference shape is also what a name followed by a
// date looks like); it is there so the log can point at the settlement.
// What keeps both orders from settling on the same money is the next
// section.
{ {
const Server::TransferMatch m = const Server::TransferMatch m =
Match({ Credit("CC-2B6457 and CC-AAAAAA", 10000) }, ref); Match({ Credit("CC-2B6457 and CC-AAAAAA", 10000) }, ref);
@ -145,6 +276,138 @@ int main() {
Check(!clean.ambiguous, "an ordinary credit is not flagged"); Check(!clean.ambiguous, "an ordinary credit is not flagged");
} }
// ── money is spent once ──────────────────────────────────────────
//
// The trick this closes: place three orders, then send ONE transfer whose
// text names all three. Each order looks for its own reference, finds it,
// and sees the full amount, so with nothing recording that the money was
// used, all three settle on a single payment. The flag above cannot stop
// that (it is a guess about text a stranger wrote). The claim does: a
// payment that settled one order pays for no other.
{
const std::vector<BankCredit> credits = {
Credit("CC-2B6457 CC-AAAAAA CC-BBBBBB", 5000, "sepa", "pay-1") };
// Unspent, every order it names sees the money. That much is right:
// which of them it pays for is decided by which settles first.
const Server::TransferMatch first = Server::MatchCredits(credits, ref);
Check(first.paidMinor == 5000, "an unspent payment counts for an order it names");
Check(Server::MatchCredits(credits, "CC-AAAAAA").paidMinor == 5000,
"and, until one of them settles, for the others it names too");
Check(first.credits == std::vector<std::string>{ "pay-1" },
"the match names the payment to claim, by the bank's id");
Check(first.spentElsewhere == 0, "nothing is reported spent before a claim");
const std::vector<Server::CreditClaim> claims = { { "pay-1", "CC-2B6457" } };
const Server::TransferMatch other =
Server::MatchCredits(credits, "CC-AAAAAA", claims);
Check(other.paidMinor == 0 && other.count == 0,
"a payment that settled one order pays for no other",
std::format("{}", other.paidMinor));
Check(other.spentElsewhere == 1,
"and the match says the money was there and is spent");
Check(other.credits.empty(), "a spent payment is not offered for a second claim");
Check(Server::MatchCredits(credits, "CC-BBBBBB", claims).paidMinor == 0,
"nor for a third order");
// The order that holds the claim must still find its own money: a
// settlement that was claimed and then never reached the ledger is
// completed from exactly this.
const Server::TransferMatch own = Server::MatchCredits(credits, ref, claims);
Check(own.paidMinor == 5000 && own.spentElsewhere == 0,
"the order that claimed a payment still counts it");
const std::vector<Server::CreditClaim> spelled = { { "pay-1", "cc 2b6457" } };
Check(Server::MatchCredits(credits, ref, spelled).paidMinor == 5000,
"however the claim spells that order's reference");
Check(Server::MatchCredits(credits, "CC-AAAAAA", spelled).paidMinor == 0,
"and it still shuts the other orders out");
}
// A claim is on ONE PAYMENT, not on a reference. Another payment for the
// same order is untouched by it, which is what keeps "send the rest the
// same way" true for an order that shared its first transfer.
{
const std::vector<BankCredit> credits = {
Credit("CC-AAAAAA and CC-2B6457", 3000, "sepa", "pay-1"),
Credit("CC-AAAAAA", 2000, "ideal", "pay-2") };
const std::vector<Server::CreditClaim> claims = { { "pay-1", "CC-2B6457" } };
const Server::TransferMatch m =
Server::MatchCredits(credits, "CC-AAAAAA", claims);
Check(m.paidMinor == 2000 && m.count == 1,
"only the spent payment is left out of the sum",
std::format("{} in {}", m.paidMinor, m.count));
Check(m.spentElsewhere == 1, "the spent one is counted as spent");
Check(m.credits == std::vector<std::string>{ "pay-2" },
"only the payment still unspent is offered for a claim");
Check(m.method == "ideal", "the method is that of a payment that counted", m.method);
}
// A claim for a payment the account no longer shows changes nothing: the
// pull replaces the credits file every hour and old payments leave it.
{
const std::vector<BankCredit> credits = {
Credit("CC-2B6457", 5000, "sepa", "pay-9") };
const std::vector<Server::CreditClaim> claims = { { "long-gone", "CC-ZZZZZZ" } };
Check(Server::MatchCredits(credits, ref, claims).paidMinor == 5000,
"a claim on some other payment does not touch this one");
}
// A line written by hand may carry no id. It is still one payment, and
// has to be claimable like one, or the hand-written escape hatch would be
// the one place the old trick still worked.
{
const std::vector<BankCredit> credits = {
Credit("CC-2B6457 CC-AAAAAA", 5000, "sepa", "") };
const Server::TransferMatch first = Server::MatchCredits(credits, ref);
Check(first.credits.size() == 1 && !first.credits[0].empty(),
"a credit with no id still has a key to be claimed under");
if (first.credits.size() == 1) {
const std::vector<Server::CreditClaim> claims = {
{ first.credits[0], "CC-2B6457" } };
Check(Server::MatchCredits(credits, "CC-AAAAAA", claims).paidMinor == 0,
"and is spent once like any other");
Check(Server::MatchCredits(credits, ref, claims).paidMinor == 5000,
"while its own order still counts it");
}
}
// ── one payment is counted once ──────────────────────────────────
//
// Two lines with the same bank id are one payment. Summed, they double
// the money against the reference, which settles a half-paid order.
{
const Server::TransferMatch twice = Match(
{ Credit("CC-2B6457", 2500, "sepa", "pay-1"),
Credit("CC-2B6457", 2500, "sepa", "pay-1") }, ref);
Check(twice.paidMinor == 2500 && twice.count == 1,
"a payment listed twice is counted once",
std::format("{} in {}", twice.paidMinor, twice.count));
Check(twice.duplicates == 1, "and the second line is reported as a duplicate");
Check(twice.credits == std::vector<std::string>{ "pay-1" },
"it is still one payment to claim");
// Different ids are different payments, however alike they look:
// this is the top-up the order page asks for.
Check(PaidFor({ Credit("CC-2B6457", 2500, "sepa", "pay-1"),
Credit("CC-2B6457", 2500, "sepa", "pay-2") }, ref) == 5000,
"two payments of the same amount are both counted");
// And with no id there is nothing to tell two lines apart by, so a
// hand-written pair is taken as two payments, as it always was.
Check(PaidFor({ Credit("CC-2B6457", 2500, "sepa", ""),
Credit("CC-2B6457", 2500, "sepa", "") }, ref) == 5000,
"two lines without an id are each counted");
}
// ── the rail: claims on disk, across restarts ────────────────────
{
std::error_code ec;
const fs::path work = fs::temp_directory_path(ec)
/ std::format("catcrafts-transfer-{}", Server::NewOrderToken());
fs::create_directories(work, ec);
if (ec) {
std::println(std::cerr, "could not create {}: {}", work.string(), ec.message());
return 1;
}
TheRailRemembersWhatWasSpent(work);
fs::remove_all(work, ec);
}
// An empty account is a clean zero rather than anything alarming: it is // An empty account is a clean zero rather than anything alarming: it is
// simply the state of every order between checkout and payment. // simply the state of every order between checkout and payment.
Check(PaidFor({}, ref) == 0, "no credits at all is zero, not an error"); Check(PaidFor({}, ref) == 0, "no credits at all is zero, not an error");

View file

@ -11,6 +11,7 @@ No permission is granted to copy, modify, distribute, or create derivative works
// backend exists: a client-side router cannot produce one. // backend exists: a client-side router cannot produce one.
import std; import std;
import Crafter.Network;
import Catcrafts.Shared; import Catcrafts.Shared;
import Catcrafts.E2eHarness; import Catcrafts.E2eHarness;
@ -98,6 +99,54 @@ int main(int argc, char** argv) {
srv.CheckStatus("/shop/donation", "413", "POST", srv.CheckStatus("/shop/donation", "413", "POST",
"email=a%40b.example&name=" + std::string(20000, 'x') "email=a%40b.example&name=" + std::string(20000, 'x')
+ "&street=x&postal=1&city=y&country=NL"); + "&street=x&postal=1&city=y&country=NL");
// Past 64 KiB the listener refuses the request from its headers, so the
// body is never buffered and no handler runs. The answer is a 400 and a
// closed connection; a client still writing its body when the connection
// closes sees the close instead, and either is the refusal. What must not
// come back is the handler's own 413 above, which would mean the whole
// body was read into memory first.
{
std::string status = "connection closed";
try {
status = srv.Post("/shop/donation", std::string(70000, 'x')).status;
} catch (...) {
// Closed mid-write: refused before the body was taken.
}
Check(status == "400" || status == "connection closed",
"a body past 64 KiB is refused before it is read", status);
// A closed connection is only a refusal if the server is still
// there: one that had died would close every connection too.
srv.CheckStatus("/api/healthz", "200");
}
// The per-peer checkout budget, over IPv6. A subscriber holds a whole
// prefix and can submit from a different address every time, so the
// budget is kept per /48 (Server::RateLimitKeyFor, pinned in
// ShouldGuardRequestProvenance). What only a request can show is that
// checkout really counts under that key: six submissions from six
// addresses of one /48 use the budget up, a seventh address in it is
// refused, and the next /48 over is not.
{
auto submit = [&](std::string from) {
return srv.Request(Crafter::CreateRequestHTTP(
"POST", "/shop/donation", "127.0.0.1",
{{ "content-type", "application/x-www-form-urlencoded" },
{ "x-forwarded-for", std::move(from) }},
"amount=5")).status;
};
int accepted = 0;
for (int i = 0; i < 6; ++i) {
if (submit(std::format("2001:db8:1234:{:x}::{:x}", i, i + 1)) == "303") {
++accepted;
}
}
Check(accepted == 6, "six submissions from one /48 are within its budget",
std::format("{} of 6 accepted", accepted));
const std::string seventh = submit("2001:db8:1234:ffff:1c2d:3e4f:5a6b:7c8d");
Check(seventh == "429",
"a seventh from a fresh address in the same /48 is refused", seventh);
const std::string neighbour = submit("2001:db8:1235::1");
Check(neighbour == "303", "the next /48 has a budget of its own", neighbour);
}
{ {
const auto json = srv.Post("/shop/donation", "{}", "application/json"); const auto json = srv.Post("/shop/donation", "{}", "application/json");
Check(json.status == "415", "POST with a JSON content-type -> 415", json.status); Check(json.status == "415", "POST with a JSON content-type -> 415", json.status);

View file

@ -275,5 +275,89 @@ int main(int argc, char** argv) {
"the order's own credit still settles it afterwards"); "the order's own credit still settles it afterwards");
} }
// ── one payment pays for one order ────────────────────────────────
//
// Three orders, then ONE transfer for the price of one whose text names
// all three. Each order looks for its own reference and finds the full
// amount against it, so before the rail recorded what a payment had been
// spent on, all three settled: three thank-you pages, three entries in
// the public donations total, one payment. Found in review on 2026-11-26.
//
// Over HTTP and not only in ShouldMatchBankTransfers, because the rule is
// not in the matcher alone: it needs the rail to write the claim when it
// settles and to judge the next order against it, across separate polls
// on separate threads. That wiring is what this proves.
{
const std::array<Order, 3> orders = {
PlaceDonation(srv, "5.00"), PlaceDonation(srv, "5.00"),
PlaceDonation(srv, "5.00") };
for (const Order& o : orders) {
if (o.token.empty()) return Finish();
}
Credit(credits, "e2e-4",
std::format("{} {} {}", orders[0].reference, orders[1].reference,
orders[2].reference),
500);
auto settled = [&](const Order& o) {
return srv.Body("/order/" + o.token).find(kPaidCopy) != std::string::npos;
};
auto settledCount = [&] {
int n = 0;
for (const Order& o : orders) n += settled(o) ? 1 : 0;
return n;
};
int paid = 0;
for (int i = 0; i < 120 && paid == 0; ++i) {
paid = settledCount();
if (paid == 0) std::this_thread::sleep_for(std::chrono::milliseconds(250));
}
Check(paid >= 1, "a payment naming three orders settles one of them");
// Long enough for several sweeps to have judged the other two against
// the same credit, which is still sitting in the file naming them.
std::this_thread::sleep_for(std::chrono::seconds(4));
paid = settledCount();
Check(paid == 1, "and only one: the same money does not settle the others",
std::format("{} of 3 settled", paid));
// The two it did not pay for read as plainly unpaid. Not "part
// payment received": that would be counting the spent money toward
// them after all, only short of the total.
const Order* passedOver = nullptr;
for (const Order& o : orders) {
if (settled(o)) continue;
if (!passedOver) passedOver = &o;
srv.BodyHas("/order/" + o.token, "awaiting payment",
"an order the payment did not settle still reads as unpaid");
srv.BodyLacks("/order/" + o.token, "part payment received",
"and is not shown the spent money as a part payment");
}
// What was spent is on disk, next to the credits, so a restart does
// not forget it, and the log says why two orders are still waiting.
const std::string claims = ReadFile(fs::path(credits.string() + ".claims"));
Check(CountOccurrences(claims, "\"credit\":\"e2e-4\"") == 1,
"the settlement recorded one claim for that payment",
std::format("{} claim line(s) for it",
CountOccurrences(claims, "\"credit\":\"e2e-4\"")));
Check(ReadFile(srv.Work() / "server.log").find("one payment pays for one order")
!= std::string::npos,
"the log says why the other orders are not settled");
// An order that was passed over is not stuck: a payment of its own
// settles it, and the third still waits.
if (passedOver) {
Credit(credits, "e2e-4b", passedOver->reference, 500);
const std::string body =
srv.WaitForBody("/order/" + passedOver->token, kPaidCopy, 120);
Check(body.find(kPaidCopy) != std::string::npos,
"an order passed over settles on a payment of its own");
Check(settledCount() == 2, "and the third order is still unpaid",
std::format("{} of 3 settled", settledCount()));
}
}
return Finish(); return Finish();
} }

View file

@ -169,6 +169,101 @@ int main() {
+ "&street=x&postal=1&city=y&country=NL").Ok(), + "&street=x&postal=1&city=y&country=NL").Ok(),
"checkout: overlong name rejected"); "checkout: overlong name rejected");
// One line each. The address fields are printed one to a line on the
// invoice the shop signs, so a line break inside one is a way to write
// lines of one's own into that document: a heading, a row of the amounts
// table, a sentence about a refund. A browser's single-line input cannot
// send one; %0A in a hand-made post can.
{
auto broken = validate("email=a%40b.example"
"&name=Ada%0A%0A%23%23%20Amounts%0A%0ARefund%20due"
"&street=x&postal=1&city=y&country=NL");
Check(!broken.Ok(), "checkout: a line break inside the name is rejected");
Check(broken.errors.size() == 1 && broken.errors[0].field == "name",
"checkout: and the refusal hangs off the name field");
}
Check(!validate("email=a%40b.example&name=Ada&street=Main%20St%201%0D%0AMore"
"&postal=1&city=y&country=NL").Ok(),
"checkout: CRLF inside the street is rejected");
// A tab is the one of these a real buyer sends: a single-line input drops
// the line breaks from a paste and keeps the tabs, and an address copied
// out of two spreadsheet cells arrives with one in the middle. It is
// whitespace someone meant as a space, so it is stored as one. Refusing
// it told a buyer who pasted their own address that it "must be a single
// line", which it was.
{
auto pasted = validate("email=a%40b.example&name=Ada&street=Hoofdstraat%0912"
"&postal=1234%09AB&city=y&country=NL");
Check(pasted.Ok(), "checkout: a pasted tab does not refuse the address");
Check(pasted.value.street == "Hoofdstraat 12",
"checkout: a tab inside a field is stored as the space it stood for",
pasted.value.street);
Check(pasted.value.postal == "1234 AB",
"checkout: in every address field", pasted.value.postal);
}
// What a refusal says. It names the cause, because the buyer who meets it
// pasted something they cannot see.
{
auto broken = validate("email=a%40b.example&name=Ada%0AMore&street=x&postal=1"
"&city=y&country=NL");
Check(broken.errors.size() == 1
&& broken.errors[0].message.find("Line breaks") != std::string::npos,
"checkout: the refusal says line breaks are the problem",
broken.errors.empty() ? "no error" : broken.errors[0].message);
}
// Two more kinds of character that are not text on a line. U+009B is CSI,
// which starts an escape sequence in a terminal showing the ledger or the
// invoice. U+202E turns the rest of the line around on screen, so that a
// line reads one thing and holds another.
Check(!validate("email=a%40b.example&name=Ada%C2%9B31mRed&street=x&postal=1"
"&city=y&country=NL").Ok(),
"checkout: a C1 control character inside the name is rejected");
Check(!validate("email=a%40b.example&name=Ada&street=x&postal=1"
"&city=y%E2%80%AEdiap&country=NL").Ok(),
"checkout: a direction override inside the city is rejected");
// U+2028 and U+0085: line breaks to an editor, and not control characters
// to a check that only looks below 0x20.
Check(!validate("email=a%40b.example&name=Ada&street=x&postal=1"
"&city=Delft%E2%80%A8More&country=NL").Ok(),
"checkout: a Unicode line separator inside the city is rejected");
Check(!validate("email=a%40b.example&name=Ada%C2%85More&street=x&postal=1"
"&city=y&country=NL").Ok(),
"checkout: a Unicode next-line inside the name is rejected");
// What must NOT be caught: a line break at the very end is trimmed like
// any other stray whitespace, and a name outside ASCII is a name. Zoë and
// Łukasz are here for their bytes — C3 AB and C5 81 sit right next to the
// C2 85 the rule looks for.
Check(validate("email=a%40b.example&name=Ada%0D%0A&street=x&postal=1"
"&city=y&country=NL").Ok(),
"checkout: a trailing line break is trimmed, not refused");
Check(validate("email=a%40b.example&name=Zo%C3%AB%20%C5%81ukasz&street=x"
"&postal=1&city=%C2%A3%E2%80%99s-Hertogenbosch&country=NL").Ok(),
"checkout: names and cities outside ASCII are still accepted");
Check(SingleLine("a\nb\r\nc\td") == "a b c d",
"single line: each control character becomes one space");
Check(SingleLine("x\xC2\x85y\xE2\x80\xA8z\xE2\x80\xA9!") == "x y z !",
"single line: NEL, LS and PS each become one space");
Check(SingleLine("Zo\xC3\xAB \xC2\xA3 \xE2\x80\x99s") == "Zo\xC3\xAB \xC2\xA3 \xE2\x80\x99s",
"single line: other multi-byte characters pass through untouched");
// The edges of each range, so a neighbour is not swept up with it:
// U+007F..U+00A0 around the C1 block, U+2027..U+202F around the line
// breaks and overrides, U+2065..U+206A around the isolates.
Check(SingleLine("a\xC2\x80" "b\xC2\x9F" "c") == "a b c",
"single line: the first and last C1 controls become spaces");
Check(SingleLine("a\xC2\xA0" "b") == "a\xC2\xA0" "b",
"single line: a no-break space, one past the C1 block, is text");
Check(SingleLine("a\xE2\x80\xAA" "b\xE2\x80\xAE" "c\xE2\x81\xA6" "d\xE2\x81\xA9" "e")
== "a b c d e",
"single line: the direction controls become spaces");
Check(SingleLine("a\xE2\x80\xA7" "b\xE2\x80\xAF" "c\xE2\x81\xA5" "d\xE2\x81\xAA" "e")
== "a\xE2\x80\xA7" "b\xE2\x80\xAF" "c\xE2\x81\xA5" "d\xE2\x81\xAA" "e",
"single line: their neighbours on either side are left alone");
// Arabic and Hebrew text needs none of the explicit controls: its
// direction comes from the letters. A name in either must pass whole.
Check(SingleLine("\xD7\xA9\xD7\x9C\xD7\x95\xD7\x9D \xD9\x85\xD8\xB1\xD8\xAD\xD8\xA8\xD8\xA7")
== "\xD7\xA9\xD7\x9C\xD7\x95\xD7\x9D \xD9\x85\xD8\xB1\xD8\xAD\xD8\xA8\xD8\xA7",
"single line: right-to-left text itself is untouched");
// Colour and quantity: shape checks here, catalogue checks in the handler. // Colour and quantity: shape checks here, catalogue checks in the handler.
Check(validate(std::string(kGoodOrder) + "&color=green&quantity=2").Ok(), Check(validate(std::string(kGoodOrder) + "&color=green&quantity=2").Ok(),
"checkout: colour and quantity accepted"); "checkout: colour and quantity accepted");