/* catcrafts.net Copyright (C) 2026 Catcrafts The source code of this website is made available for viewing purposes only. No permission is granted to copy, modify, distribute, or create derivative works. */ // The bank-transfer rail: the buyer sends a plain SEPA transfer to our own // IBAN quoting the order's creditor reference, and the order settles when a // credit carrying that reference shows up on the account. // // Why this rail exists at all: after the bank payment provider closed the // shop's account on 2026-08-20 with no appeal, the lesson taken was not "find // a better provider" but "stop putting a party with unilateral offboarding // power in the payment path". A transfer to our own account has no such party. // The bank can still close the account — that is unavoidable, every euro has // to land somewhere — but it cannot decline a payment method while leaving the // business running, which is what actually happened. // // Shape: self-hosted, like the EURC rail and unlike the hosted ones. There is // no checkout to redirect to, so CreateLink makes no network call at all and // Instructions() is what the buyer actually acts on. Three facts go on the // order page — IBAN, amount, reference — and the beneficiary name, which is // load-bearing rather than decorative (see PayInstructions). // // Trust direction is the same rule as every other rail: an order becomes paid // only on what the bank said about the account. Nothing the buyer tells us is // evidence, including "I paid". What the bank said reaches this rail as the // credits file. The bank's callback adds to it within seconds, and the // periodic pull, which reads the account on a trusted machine with the bank's // own authentication, replaces it with what is really there. // // The rail knows nothing of any bank: it reads credits through a CreditSource. // That is a deliberate hedge and not speculative generality: the account being // reconciled is also the shop's own bank account, so the day that relationship // ends, what fills the file changes and the rail does not. module; module Catcrafts.Server; import std; import Catcrafts.Shared; namespace Catcrafts::Server { namespace { // Reduce remittance text to the alphabet a reference lives in: upper-case // letters and digits, everything else dropped. Banks are free to reformat the // field — spacing, punctuation, case — and a payer types it by hand, so // comparing raw strings would fail on cosmetics. Dropping separators is also // what makes one needle match every form the payer might have used. std::string Fold(std::string_view s) { std::string out; out.reserve(s.size()); for (const char c : s) { if (c >= '0' && c <= '9') out += c; else if (c >= 'A' && c <= 'Z') out += c; else if (c >= 'a' && c <= 'z') out += static_cast(c - 'a' + 'A'); } return out; } // Minimal JSON string escaping for the credits file. The reference field is // text a stranger typed into their banking app, so a raw quote or newline in // it would corrupt the line-per-record format and silently truncate the // evidence a settlement decision reads. std::string EscT(std::string_view s) { std::string out; out.reserve(s.size() + 8); for (const char c : s) { switch (c) { case '"': out += "\\\""; break; case '\\': out += "\\\\"; break; case '\n': out += "\\n"; break; case '\r': out += "\\r"; break; case '\t': out += "\\t"; break; default: if (static_cast(c) < 0x20) { out += std::format("\\u{:04x}", static_cast(c)); } else { out += c; } } } return out; } // Does the folded remittance text carry a SECOND thing shaped like one of our // references, beyond the one at `foundAt`? "CC" followed by six characters of // the token alphabet is the shape. Used only to raise the advisory ambiguous // flag: one transfer quoting two orders cannot be attributed per-order, and a // human should look rather than two orders settling on the same money. bool HasOtherReferenceShape(std::string_view folded, std::size_t foundAt, std::size_t needleLen) { for (std::size_t i = 0; i + 8 <= folded.size(); ++i) { if (i >= foundAt && i < foundAt + needleLen) continue; // the known one if (folded[i] != 'C' || folded[i + 1] != 'C') continue; bool hex = true; for (std::size_t j = i + 2; j < i + 8; ++j) { const char c = folded[j]; const bool isHex = (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'); if (!isHex) { hex = false; break; } } if (hex) return true; } 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 TransferMatch MatchCredits(std::span credits, std::string_view reference, std::span claims) { TransferMatch out; const std::string needle = Fold(reference); // An empty needle would match every credit on the account. Refuse rather // than settle the whole ledger from one payment. if (needle.size() < 4) return out; // The bank's ids of the payments seen so far in this pass. std::set seen; for (const BankCredit& c : credits) { // Only money coming IN can pay for something. A negative amount is an // outgoing payment that happens to quote the reference — a refund we // sent, most likely — and counting it would be a refund paying for // the order it refunded. if (c.amountMinor <= 0) continue; const std::string folded = Fold(c.reference); const std::size_t at = folded.find(needle); 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.count; 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; } return out; } namespace { class FileCreditSource final : public CreditSource { public: explicit FileCreditSource(std::filesystem::path path) : path_(std::move(path)) {} std::optional> Recent() override { std::error_code ec; if (!std::filesystem::exists(path_, ec)) { // Not an error: a shop that has taken no transfers yet has no // file. Distinct from a read failure below, which IS unknown. return std::vector{}; } std::ifstream in(path_, std::ios::binary); if (!in) { std::println(std::cerr, "transfer: cannot read credits file {}", path_.string()); return std::nullopt; } std::vector out; std::string line; int lineNo = 0; while (std::getline(in, line)) { ++lineNo; if (line.empty()) continue; const auto doc = Json::Parse(line); if (!doc || !doc->IsObject()) { // One malformed line must not silently shrink the evidence a // settlement decision rests on, so say so and keep the rest: // dropping the whole file would strand every paid order. std::println(std::cerr, "transfer: {}:{} is not a JSON object, skipped", path_.string(), lineNo); continue; } BankCredit c; c.id = std::string(doc->Str("id")); c.reference = std::string(doc->Str("reference")); // How it arrived: said outright in the ledger's words, or as // the bank's own classification with the bank it is of, which is // then put into those words here. A line with neither is a plain // transfer. See MakeFileCreditSource in the interface. c.method = std::string(doc->Str("method")); if (c.method.empty()) { const std::string_view kind = doc->Str("kind"); const std::string_view bank = doc->Str("bank"); c.method = (!kind.empty() && !bank.empty()) ? CreditMethodFor(bank, kind) : std::string("sepa"); } c.amountMinor = doc->Int("amount_minor"); out.push_back(std::move(c)); } return out; } std::string_view Name() const override { return "file"; } private: std::filesystem::path path_; }; class TransferRail final : public PaymentRail { public: TransferRail(RailConfig cfg, std::unique_ptr 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 // burns a receiving address per order, a transfer reuses one IBAN forever // and the reference is what separates orders. So this cannot fail, which // is worth noticing — checkout can never lose a sale to a provider being // down, because there is no provider. std::optional CreateLink(std::int64_t, const std::string& description, const std::string& redirectUrl) override { PaymentLink link; // payId carries the reference AND the deadline, the same trick the // EURC rail uses: CheckPaid is given only the id and the amount, and // this rail has to know its own window. Both halves are wanted in the // ledger anyway. const std::int64_t deadline = NowUnix() + WindowSeconds(); link.payId = std::format("{}@{}", ReferenceOf(description), deadline); // Self-hosted: there is nowhere to send the buyer but the order page, // which is where Instructions() renders. link.payUrl = redirectUrl; return link; } std::optional CheckPaid(const std::string& payId, std::int64_t expectedMinor) override { const auto [reference, deadline] = SplitPayId(payId); if (reference.empty()) { // Not one of ours. This is the shape a ledger line from the OLD // hosted provider has, and this rail genuinely cannot decide it: // Pending lets the reconciler age it out instead of pretending to // know it is dead. return PaidStatus{ PayState::Pending, {} }; } const std::optional> all = Fetch(); if (!all) return std::nullopt; // unknown, retry — never "unpaid" // ONE order is judged at a time from here to the claim below. The // 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, "transfer: {} is quoted by a payment the credits file " "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; out.method = m.method.empty() ? std::string("sepa") : m.method; 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; return out; } // Money arrived but does not cover the order. The buyer is told to // send the difference to the same IBAN with the same reference, which // is why partials stay Pending and keep accumulating rather than // failing: the next credit adds to this sum. out.seen = m.paidMinor > 0; if (deadline > 0 && NowUnix() > deadline) { // The window closed. NOT bounced money: the IBAN is ours and a // late transfer still lands there — say so in the log, because the // operator settling it by hand is the one who needs to know. std::println(std::cerr, "transfer: {} lapsed with {} of {} received; the IBAN " "remains ours, a late payment still arrives and is " "settled with --mark-paid", reference, Money::FormatMinor(m.paidMinor), Money::FormatMinor(expectedMinor)); out.state = PayState::Dead; return out; } out.state = PayState::Pending; return out; } std::optional Instructions(const std::string& payId, std::int64_t totalMinor) const override { const auto [reference, deadline] = SplitPayId(payId); if (reference.empty() || totalMinor <= 0) return std::nullopt; PayInstructions out; out.address = cfg_.transferIban; out.beneficiary = cfg_.transferBeneficiary; out.bic = cfg_.transferBic; out.reference = reference; out.amount = Money::FormatMinor(totalMinor); out.deadlineUnix = deadline; return out; } std::string_view Name() const override { return "transfer"; } // A transfer does not arrive in seconds even under instant payments, and // the bank's API is rate limited per method — the shared cache below is // what keeps a sweep of many orders down to one request, but a slow // cadence is the other half of being a good citizen there. Configurable so // a suite reading a local file can run at a speed a test can wait for. std::chrono::seconds PollInterval() const override { return std::chrono::seconds(cfg_.transferPollSeconds > 0 ? cfg_.transferPollSeconds : 60); } private: static std::int64_t NowUnix() { return std::chrono::duration_cast( std::chrono::system_clock::now().time_since_epoch()).count(); } std::int64_t WindowSeconds() const { const int hours = cfg_.transferWindowHours > 0 ? cfg_.transferWindowHours : 14 * 24; return static_cast(hours) * 3600; } // "CC-2B6457 catcrafts.net" -> "CC-2B6457". The description checkout // builds starts with the reference; take the first token so the payId // stays short and the '@' split below cannot be confused by a space. static std::string ReferenceOf(std::string_view description) { const std::size_t sp = description.find(' '); return std::string(sp == std::string_view::npos ? description : description.substr(0, sp)); } static std::pair SplitPayId(std::string_view payId) { const std::size_t at = payId.rfind('@'); if (at == std::string_view::npos) return { {}, 0 }; const std::string_view ref = payId.substr(0, at); // The reference must look like ours before this rail claims the order. if (ref.size() < 4 || !ref.starts_with("CC")) return { {}, 0 }; std::int64_t deadline = 0; const std::string_view tail = payId.substr(at + 1); const auto [ptr, ec] = std::from_chars(tail.data(), tail.data() + tail.size(), deadline); if (ec != std::errc{} || ptr != tail.data() + tail.size()) return { {}, 0 }; return { std::string(ref), deadline }; } // ONE bank read per sweep, shared by every order in it. Not an // optimisation: the bank rate-limits reads to a few per second, and the // reconciler asks per order, so without this a shop with a dozen open // orders would throttle itself and the answers would start coming back as // "unknown" — which is indistinguishable, from the outside, from a shop // whose payments have stopped working. // // The window only has to span ONE sweep, not one poll interval. Setting it // to PollInterval() is the tempting mistake and it doubles the worst-case // wait: a sweep that lands just after a fetch would answer every order // from data already a minute old, so money could sit visible at the bank // for two minutes before any order noticed. A few seconds is enough to // collapse a sweep into a single request, and at one request per window // the rate limit is nowhere in sight. // Never longer than the poll interval itself: at the default 60 s cadence // five seconds comfortably spans one sweep, but a rail polling every // second would otherwise answer from data older than its own interval. std::chrono::seconds CacheWindow() const { return std::min(std::chrono::seconds(5), PollInterval()); } std::optional> Fetch() { std::lock_guard lock(mutex_); const auto now = std::chrono::steady_clock::now(); if (cached_ && now - fetchedAt_ < CacheWindow()) return cached_; std::optional> fresh = credits_->Recent(); if (!fresh) { // Keep serving the last good answer rather than turning a blip // into "unknown" for every order at once. Only when there has // never been one does the caller get nullopt. return cached_ ? cached_ : std::nullopt; } cached_ = std::move(fresh); fetchedAt_ = now; 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(in)), std::istreambuf_iterator()); 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::system_clock::now())); std::string lines; std::vector 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_; std::unique_ptr credits_; std::mutex mutex_; std::optional> cached_; 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 claims_; std::set told_; }; } // namespace std::unique_ptr MakeFileCreditSource(std::filesystem::path path) { return std::make_unique(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, const BankCredit& credit) { 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 // got no answer to, and the periodic pull ships a file that holds the same // payment again, so the SAME payment arrives more than once by design. // Appending it twice would double the money against one reference — // enough, on a part-paid order, to settle it without the balance ever // arriving. (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); const std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); 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; const auto doc = Json::Parse(line); if (!doc || !doc->IsObject()) continue; 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); if (!out) { std::println(std::cerr, "transfer: cannot append to {}", creditsPath.string()); return false; } if (torn) out << '\n'; out << std::format( R"({{"id":"{}","reference":"{}","amount_minor":{},"method":"{}"}})" "\n", EscT(credit.id), EscT(credit.reference), credit.amountMinor, EscT(credit.method)); out.flush(); return static_cast(out); } std::unique_ptr MakeTransferRail(const RailConfig& config, std::unique_ptr credits) { if (!credits) return nullptr; // The two facts the buyer is told. Without them the order page would // render an incomplete instruction, which loses the money rather than the // sale — refuse to start instead, the same way the EURC rail refuses // without its chains file. if (config.transferIban.empty()) { std::println(std::cerr, "transfer: TRANSFER_IBAN is not set — the order page would " "have no account to name"); return nullptr; } if (config.transferBeneficiary.empty()) { std::println(std::cerr, "transfer: TRANSFER_BENEFICIARY is not set — Verification of " "Payee shows the payer a mismatch warning without the exact " "account-holder name"); return nullptr; } auto rail = std::make_unique(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