diff --git a/deploy/README.md b/deploy/README.md index 3c87362..c39072a 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -383,19 +383,15 @@ matching credit appears on the account. The order page is the payment page. file is an empty list, not an error, since a shop that has taken no transfers yet has no file. -#### Filling the credits file: the bunq reader +#### Filling the credits file -`--pull-credits` reads the bunq account once and appends anything new to the -credits file, deduplicated by bunq's own payment id, then prints how many -arrived. Every pull re-reads an overlapping window, so that dedupe is what -stops a credit being counted twice and settling an order nobody paid twice -for. It appends rather than rewrites, so lines added by hand survive. - -```sh -BUNQ_API_KEY=… TRANSFER_IBAN=NL.. \ - catcrafts-server --pull-credits --orders /var/lib/catcrafts/orders.jsonl -# -> pulled 2 new credit(s) into /var/lib/catcrafts/orders.jsonl.transfer-credits.jsonl -``` +Two things write it, and neither puts a bank key on the web host: the bunq +webhook, which the server receives itself, and an hourly pull on a trusted +machine, which asks nostrod and ships the result. The next section has both. +Every line carries bunq's own payment id. The webhook skips an id the file +already holds, and the pull replaces the file with one line per payment, so a +payment that both deliver is counted once and cannot settle an order nobody +paid twice for. #### How settlement actually reaches the shop @@ -406,7 +402,11 @@ lands; the backend decodes the payment and appends it to the credits file, and the reconciler settles from there. Normally seconds end to end. Registered with `tools/register-bunq-webhook.sh` from a machine bunq's key permits (`--show` lists what is registered, with the secret redacted). **That call REPLACES the -whole filter set**, so look before overwriting. +whole filter set**, so look before overwriting. The script needs an +authenticated bunq session for it, and takes that from this repo's own bunq +client: see "The old reader" below. Since its 1.1.0 Nostro lists and changes +callbacks itself (`nostro callbacks`, through nostrod), which is what replaces +this script. **bunq does not sign these notifications** — verified against doc.bunq.com: no HMAC, no server signature, and certificate pinning authenticates us to bunq @@ -437,71 +437,139 @@ restarts — every deploy is a restart — is lost to the webhook with no error anywhere. `deploy/catcrafts-credits.timer` runs `pull-and-ship-credits.sh` hourly to turn that from a missing donation into an hour of delay. -**The key is IP-restricted, and that decides the shape.** Verified the hard way -on 2026-08-20: the bunq API key permits one address (the owner's home -connection), and **bunq enforces that on every request, not only at device -registration**. Registering the server's address in the device's -`permitted_ips` does not help — the device registered fine from home with both -addresses listed, and every read from the server still came back -`"Incorrect API key or IP address"`. So `BUNQ_API_KEY` on the web host cannot -work unless the key's allowlist is widened in the bunq app. +**The pull holds no key.** A bunq API key can **initiate payments**, and bunq +offers no read-only scope, so there is no such thing as a key that can only +read. Since 2026-11-21 the pull therefore holds none. The bank connection lives +in [nostrod](https://forgejo.catcrafts.net/Catcrafts/Nostro) on a trusted +machine, under a system user of its own, and +**`tools/pull-and-ship-credits.sh`** asks it over the system bus for the +account's recent transactions (`Transactions` on `net.catcrafts.Nostro1`, the +interface Nostro publishes for other programs). nostrod lets a program look +without a password and lets nothing pay or change anything without one, which +is the read-only scope bunq lacks. A systemd USER timer runs the script +(`deploy/catcrafts-credits.{service,timer}`, install instructions in the +service file). -That constraint happens to enforce the right design, so it is now the supported -one: **`tools/pull-and-ship-credits.sh`**, run by a systemd USER timer on the -machine bunq permits (`deploy/catcrafts-credits.{service,timer}`, install -instructions in the service file). It pulls, keeps an accumulating local copy, -and ships **incoming credits only** to the file the rail reads. Outgoing lines -are supplier payments and card spending: the matcher ignores negative amounts, -so shipping them would put the business's outgoing payment history on a -public-facing host for no settlement benefit. The script refuses to overwrite -the remote with an empty file, so an upstream parse failure leaves the server +The script turns nostrod's answer into credit lines and ships **incoming +credits only** to the file the rail reads. Outgoing lines are supplier payments +and card spending: the matcher ignores negative amounts, so shipping them would +put the business's outgoing payment history on a public-facing host for no +settlement benefit. It ships nothing when the read failed, and it never +overwrites the remote with an empty file, so a failure leaves the server settling from the last good copy rather than from nothing. -Latency, so nobody wonders: five minutes for the timer plus the reconciler's own -60 s cadence, so a fresh order confirms within about six minutes of the money -landing. Orders more than two hours old back off to a ten-minute poll, so an -older one can take that long. +Each run ships the last 90 days (`CREDITS_DAYS`). That is the longest +`TRANSFER_WINDOW_HOURS` the server accepts, so no order can still be waiting +for an older credit. nostrod keeps the account's whole history and answers for +any window, so a machine that was off for weeks leaves no hole in what it +ships. + +Setting it up, once, on that machine: install Nostro (its README), connect the +account with `nostro connectors add bunq`, and check that `nostro accounts` +lists the IBAN in `TRANSFER_IBAN`. `tools/pull-and-ship-credits.sh --dry-run` +then prints the lines it would ship, and ships nothing. + +**Who may look.** As nostrod ships, a program may look without a password only +in an active local session: while you are logged in at that machine. A user +timer counts as part of that session, so the pull works while you are logged +in, and is refused with nobody logged in or over SSH (the script says so when +it happens). To let it run regardless, an administrator adds a polkit rule: + +```js +// /etc/polkit-1/rules.d/50-catcrafts-credits.rules +polkit.addRule(function(action, subject) { + if (action.id == "net.catcrafts.Nostro1.View" && subject.user == "YOUR_USER") { + return polkit.Result.YES; + } +}); +``` + +That lets every program running as that user look at the accounts, session or +not, and polkit cannot tell this script from any other of them. It lets none of +them pay: paying and changing stay behind the password. With the rule in place, +`loginctl enable-linger` makes the timer run with nobody logged in at all. + +**Why the server does not read the bank itself.** Besides the key policy above, +a standard bunq API key works only from the address it was registered at, and +**bunq enforces that on every request, not only at device registration**. +Verified the hard way on 2026-08-20, with this repo's own reader: registering +the server's address in the device's `permitted_ips` did not help (the device +registered fine from home with both addresses listed), and every read from the +server still came back `"Incorrect API key or IP address"`. + +Latency, so nobody wonders: through the webhook a fresh order confirms within +the reconciler's own 60 s cadence of the money landing. A payment the webhook +lost waits for the next hourly pull on top of that. Orders more than two hours +old back off to a ten-minute poll, so an older one can take that long. Two operational notes. The timer only runs while that machine is awake, so `Persistent=true` makes it pull once on waking rather than silently skipping -every window it missed. And if the home address changes, both the key's -allowlist (in the bunq app) and settlement stop working until it is updated — -the failure mode is silent from the shop's side, so the credits file's mtime is -worth glancing at. +every window it missed. And when the connection in nostrod stops working +(`nostro connectors` says whether it does: a revoked key, or an IP-restricted +key after the home address changed), the pull fails and its unit says so, but +nothing tells the shop. Settlement then rests on the webhook alone, so a +failing `catcrafts-credits` unit is worth noticing. -**Read this before deciding where to put the key.** A bunq API key can -**initiate payments**, and bunq offers no read-only scope, so there is no such -thing as a key that can only read. That gives two deployment shapes, and they -are not equivalent: +#### The old reader: `--pull-credits` -1. **Key off the public host (intended).** Run `--pull-credits` on a trusted - machine on a timer, and ship the credits file to the server (rsync, scp, - whatever). The server settles orders while holding **no credential that can - move a cent**, so even a full compromise of the web host cannot spend the - account. This is the same rule the EURC rail follows by never holding a - wallet key. -2. **Key on the server (simpler, strictly worse).** Set `BUNQ_API_KEY` in - `payments.env` and the rail reads the bank itself, no file shipping. The - startup log prints a warning saying exactly what has been traded away. +`catcrafts-server --pull-credits` is this repo's own bunq client. It onboards +with the API key, keeps its context in a file, reads the account's newest +payments and appends them to a credits file, deduplicated by bunq's payment id. +It was the pull until 2026-11-21. Nothing runs it on a schedule any more, and +it is still here for one job: `tools/register-bunq-webhook.sh` needs a bunq +session to list or replace the notification filter, and takes it from this +reader's context file. Nostro does the same with no key in this checkout since +its 1.1.0 (`nostro callbacks`). Once that command has been seen to list the +shop's webhook, the reader, its key in `.env` and that script can all go. -Either way, set **`BUNQ_PERMITTED_IPS`** to the egress address of whatever -machine holds the key. bunq registers it once, at device-server time, and it is -the only thing standing between a leaked key and someone spending the balance. -The default is `*`, which works and is announced loudly. Changing it later -means deleting the context file and re-onboarding. +The session in the context file expires, so refresh it right before using the +script, on a machine the key permits: -Other bunq settings: `BUNQ_STATE` (default `.bunq-context.json`) holds -the generated RSA keypair and the session tokens at 0600 — **back it up or at -least know that deleting it forces a re-onboard**, and bunq allows as few as -ten setup calls PER DAY, so do not delete it casually. If the key can see more -than one active account, `TRANSFER_IBAN` picks which; without it, a key seeing -several accounts is a refusal rather than a guess, because guessing means -reconciling the shop against its savings. +```sh +BUNQ_API_KEY=… TRANSFER_IBAN=NL.. \ + bin/Catcrafts.Server-*/catcrafts-server --pull-credits \ + --orders ~/.cache/catcrafts/orders.jsonl +# -> pulled 2 new credit(s) into ~/.cache/catcrafts/orders.jsonl.transfer-credits.jsonl +``` -Rate limits worth respecting: bunq caps reads at roughly **3 GET per 3 -seconds** per method. One pull is one request, and the rail additionally shares -a single read across all orders in a sweep, so neither path is anywhere near -the cap. What WOULD hit it is retrying the onboarding calls in a loop; the +**The webhook was registered with this reader's key.** bunq's documentation +does not say whether a registration outlives the key that made it, so do not +revoke that key before `nostro callbacks` lists the webhook through the +connection nostrod holds, and look again after revoking it: if it is gone, +`nostro callbacks add` sets it again. Otherwise settlement may quietly fall +back to the hourly pull alone. + +What the reader costs is the reason it is no longer the pull. Its key +(`BUNQ_KEY` in the repo-root `.env`) can **initiate payments**, and every +program run in that checkout can read it. Two things follow for as long as it +exists: + +1. **Never put it on the server.** Setting `BUNQ_API_KEY` in `payments.env` + makes the rail run this same reader in-process instead of reading the + credits file. That puts a credential that can spend the account on a public + host, the startup log prints a warning saying exactly that, and with an + IP-restricted key it does not even work (see above). The server settles + orders while holding **no credential that can move a cent**, the same rule + the EURC rail follows by never holding a wallet key. +2. **Pin it.** `BUNQ_PERMITTED_IPS` is the egress address of the machine that + holds the key. bunq registers it once, at device-server time, and it is the + only thing standing between a leaked key and someone spending the balance. + The default is `*`, which works and is announced loudly. Changing it later + means deleting the context file and re-onboarding. + +Its other settings: `BUNQ_STATE` (default `.bunq-context.json`) holds +the generated RSA keypair and the session tokens at 0600. **Deleting it forces +a re-onboard**, and bunq allows as few as ten setup calls PER DAY, so do not +delete it casually. If the key can see more than one active account, +`TRANSFER_IBAN` picks which; without it, a key seeing several accounts is a +refusal rather than a guess, because guessing means reconciling the shop +against its savings. + +Rate limits worth respecting, whoever reads: bunq caps reads at roughly **3 GET +per 3 seconds** per method. One pull is a handful of requests (nostrod waits a +429 out by itself), and the rail shares a single read of the credits file +across all orders in a sweep, so neither path is anywhere near the cap. What +WOULD hit it is retrying the old reader's onboarding calls in a loop; its context file is what prevents that. The file source stays regardless — it is how the suites drive real settlement @@ -650,8 +718,8 @@ a fact about the rails rather than a difference in standard. **`ShouldSettleBankTransfers` needs nothing and always runs.** A self-hosted rail has no provider to authenticate to, so there is nothing to call and no secret to hold. The suite drives the REAL transfer rail — not a stand-in — and -plays the part of the bank by writing a credits line, the same file -`--pull-credits` fills in production. It covers the whole lifecycle: the order +plays the part of the bank by writing a credits line, the same file the +webhook and the hourly pull fill in production. It covers the whole lifecycle: the order page's account details, the reference in all the mangled forms a payer might type, partial payments accumulating, an outgoing amount being ignored, and the reconciler flipping the order to paid with the right `via`. diff --git a/deploy/catcrafts-credits.service b/deploy/catcrafts-credits.service index e298ed1..0489ffb 100644 --- a/deploy/catcrafts-credits.service +++ b/deploy/catcrafts-credits.service @@ -1,21 +1,34 @@ # Read the bank and hand the incoming credits to the server. # -# A USER unit, on the machine whose IP the bunq API key permits — NOT on the -# web host. The web host cannot call bunq at all (the key is IP-restricted at -# the key level and bunq enforces it on every request), and it should not be +# A USER unit, on the machine where nostrod holds the bunq connection, NOT on +# the web host. The web host cannot call bunq at all (the key is IP-restricted +# at the key level and bunq enforces it on every request), and it should not be # able to: a bunq key can initiate payments, because bunq offers no read-only -# scope. So the key stays here and the server only ever reads a file. +# scope. So the server only ever reads a file. +# +# This unit holds no key either. tools/pull-and-ship-credits.sh asks nostrod +# (https://forgejo.catcrafts.net/Catcrafts/Nostro) over the system bus, and +# nostrod lets a program look at the accounts without ever handing it the key. # # Install: # mkdir -p ~/.config/systemd/user # cp deploy/catcrafts-credits.{service,timer} ~/.config/systemd/user/ # systemctl --user daemon-reload # systemctl --user enable --now catcrafts-credits.timer -# loginctl enable-linger "$USER" # so it runs when nobody is logged in +# +# WHO MAY LOOK. As nostrod ships, a program may look without a password only +# while you are logged in at this machine (an active local session, which a +# user unit counts as part of). So as installed above, this pulls while you are +# logged in and is refused otherwise: with nobody logged in, or on a machine +# you only reach over SSH. To have it run regardless, add the polkit rule in +# deploy/README.md ("Who may look"), and then, so the unit runs with nobody +# logged in at all: +# loginctl enable-linger "$USER" +# Lingering without the rule only produces a refused pull every hour. # # Watch: journalctl --user -u catcrafts-credits -f [Unit] -Description=Pull bunq credits and ship them to catcrafts.net +Description=Pull bank credits from nostrod and ship them to catcrafts.net Documentation=file:deploy/README.md # Pointless without a route to the bank or to the server. After=network-online.target @@ -24,7 +37,8 @@ After=network-online.target Type=oneshot WorkingDirectory=%h/repos/catcrafts.net ExecStart=%h/repos/catcrafts.net/tools/pull-and-ship-credits.sh -# A failed pull must not look like a successful one. The script already refuses -# to overwrite the remote with an empty file, so a failure here leaves the -# server settling from the last good copy rather than from nothing. +# A failed pull must not look like a successful one. The script ships nothing +# when it could not read the account, and never overwrites the remote with an +# empty file, so a failure here leaves the server settling from the last good +# copy rather than from nothing. SuccessExitStatus=0 diff --git a/tests/ShouldSettleBankTransfers/main.cpp b/tests/ShouldSettleBankTransfers/main.cpp index 3cf8225..b1546b8 100644 --- a/tests/ShouldSettleBankTransfers/main.cpp +++ b/tests/ShouldSettleBankTransfers/main.cpp @@ -22,8 +22,9 @@ No permission is granted to copy, modify, distribute, or create derivative works // // So this needs no secret, never flakes on someone else's RPC, and runs on // every deploy unconditionally. The bank stands in for itself only in the sense -// that the suite writes the credits file — the same file `--pull-credits` fills -// from the real account, read by the same parser, matched by the same matcher. +// that the suite writes the credits file — the same file the bunq webhook and +// tools/pull-and-ship-credits.sh fill from the real account, read by the same +// parser, matched by the same matcher. // Everything downstream of that line is production code. // // What the unit suites already cover, and this one deliberately does not diff --git a/tools/dev-credit.sh b/tools/dev-credit.sh index 8549499..93f057a 100755 --- a/tools/dev-credit.sh +++ b/tools/dev-credit.sh @@ -3,9 +3,9 @@ # without a bank. # # The transfer rail settles an order when a credit quoting its reference shows -# up in the credits file. In production that file is filled by -# `catcrafts-server --pull-credits` reading the real account; here it is filled -# by hand. Same file, same format, same matching code — which is the point: +# up in the credits file. In production that file is filled from the real +# account, by the bunq webhook and by tools/pull-and-ship-credits.sh; here it is +# filled by hand. Same file, same format, same matching code — which is the point: # this exercises the real settlement path rather than a test double. # # tools/dev-credit.sh [method] diff --git a/tools/pull-and-ship-credits.sh b/tools/pull-and-ship-credits.sh index e02df91..22f617f 100755 --- a/tools/pull-and-ship-credits.sh +++ b/tools/pull-and-ship-credits.sh @@ -1,94 +1,205 @@ #!/bin/sh -# Read the bank from a machine bunq's API key actually permits, and hand the -# result to the server that cannot read it itself. +# Ask nostrod what arrived on the shop's bank account, and hand the incoming +# credits to the server, which cannot read the bank itself. # # WHY THIS EXISTS, so nobody "simplifies" it back: # -# The bunq API key is IP-restricted at the KEY level, and bunq enforces that on -# EVERY call — not only at device registration. Registering the server's IP in -# the device's permitted_ips does NOT help; that was tried on 2026-08-20 and -# every read from the server still came back "Incorrect API key or IP address". -# So the only two options are to widen the key's allowlist in the bunq app, or -# to call from an address it already permits. This script is the second. +# A bunq API key can INITIATE PAYMENTS (bunq has no read-only scope), so the +# public web host must never hold one. It never does: the server only ever +# reads a file of incoming credits, and this script is what fills that file +# from a trusted machine. # -# It also happens to be the shape the project's key policy wants: a bunq key -# can INITIATE PAYMENTS (bunq has no read-only scope), so the public web host -# should never hold one. Here it never does — the server only ever reads a file -# of incoming credits. +# Since 2026-11-21 this script holds no key either. The bank connection lives +# in nostrod (https://forgejo.catcrafts.net/Catcrafts/Nostro), which keeps it +# under a system user of its own and answers over the system bus: a program +# may LOOK at the accounts without a password, and nothing pays or changes +# anything without one. That is the read-only scope bunq does not offer. This +# script only looks. Until then it ran this repo's own bunq client +# (`catcrafts-server --pull-credits`) with the key from .env. # -# tools/pull-and-ship-credits.sh +# The bunq key is also IP-restricted at the KEY level, and bunq enforces that +# on every call, so the reading has to happen on a machine the key permits. +# That is now nostrod's concern: run this where nostrod has the connection. # -# Environment (BUNQ_KEY is read from the repo-root .env, which is gitignored): +# tools/pull-and-ship-credits.sh pull and ship +# tools/pull-and-ship-credits.sh --dry-run pull, print the credit lines +# that would be shipped, ship nothing +# +# Needs: nostrod with a connection to the account (`nostro connectors`), +# busctl and python3. Only TRANSFER_IBAN is read from the repo-root .env (or +# from the environment), to say which account; nothing else in .env reaches +# this script or the programs it starts. +# +# Environment: # CREDITS_HOST ssh destination (default: hetzner) # CREDITS_REMOTE the file the rail reads (default: the production path) -# CREDITS_LOCAL local accumulating copy (default: ~/.cache/catcrafts) +# CREDITS_DAYS how far back to ask (default: 90) # -# BUNQ_PERMITTED_IPS is read from .env if set. Leaving it unset registers the -# device with "*", which sounds worse than it is HERE: bunq already enforces the -# key's own IP allowlist on every call, so "*" on the device is overridden by -# the stricter thing. Pinning it as well is defence in depth, at the price of -# breaking on a DHCP change — and a residential address does change. Note the -# registration happens ONCE, so switching later means deleting the context file -# and spending two more of the day's setup calls. +# WHY 90 DAYS: it is the longest TRANSFER_WINDOW_HOURS the server accepts, so no +# order can still be waiting for a credit older than that. Nothing accumulates +# here any more: nostrod keeps the account's whole history and answers for any +# window, so every run ships the complete window, and a machine that was off +# for a month leaves no hole. (The copy this script used to keep under +# ~/.cache/catcrafts did, because the old reader only ever saw the newest 50 +# payments.) +# +# WHEN IT IS REFUSED WITH "needs your password": nostrod lets a program look +# without one only while you are logged in at this machine, in an active local +# session. From a timer that runs with nobody logged in, or over SSH, it would +# have to ask, and here it is told not to. deploy/README.md has the polkit +# rule that lets this user look without a session. set -eu cd "$(dirname "$0")/.." +DRY_RUN=0 +case "${1:-}" in + --dry-run) DRY_RUN=1 ;; + "") ;; + *) echo "$0: unknown argument '$1' (the only one is --dry-run)" >&2; exit 2 ;; +esac + HOST="${CREDITS_HOST:-hetzner}" REMOTE="${CREDITS_REMOTE:-/var/lib/catcrafts/orders.jsonl.transfer-credits.jsonl}" -LOCAL_DIR="${CREDITS_LOCAL:-$HOME/.cache/catcrafts}" -LOCAL="$LOCAL_DIR/orders.jsonl" +DAYS="${CREDITS_DAYS:-90}" -[ -f .env ] || { echo "$0: no .env — the bunq key lives there" >&2; exit 1; } -# shellcheck disable=SC1091 -set -a; . ./.env; set +a +for tool in busctl python3; do + command -v "$tool" >/dev/null 2>&1 || { echo "$0: $tool is not installed" >&2; exit 1; } +done -# The .env still calls it BUNQ_KEY, from the previous integration. Accept both -# rather than making someone rename a working secret. -KEY="${BUNQ_API_KEY:-${BUNQ_KEY:-}}" -[ -n "$KEY" ] && [ -n "${TRANSFER_IBAN:-}" ] || { - echo "$0: need BUNQ_KEY (or BUNQ_API_KEY) and TRANSFER_IBAN in .env" >&2 +case "$DAYS" in + ''|*[!0-9]*) echo "$0: CREDITS_DAYS='$DAYS' is not a whole number of days" >&2; exit 2 ;; +esac +[ "$DAYS" -ge 1 ] || { echo "$0: CREDITS_DAYS must be at least 1" >&2; exit 2; } + +# Which account. Read in a subshell, without exporting: .env also holds the +# shipping, mail and hosting secrets, and none of them is this script's or its +# children's business. +IBAN="${TRANSFER_IBAN:-}" +if [ -z "$IBAN" ] && [ -f .env ]; then + # shellcheck disable=SC1091 + IBAN=$(set +eu; . ./.env >/dev/null 2>&1; printf '%s' "${TRANSFER_IBAN:-}") +fi +[ -n "$IBAN" ] || { echo "$0: need TRANSFER_IBAN, in the environment or in .env" >&2; exit 1; } +# nostrod compares an IBAN exactly as the bank writes it: no spaces, upper case. +IBAN=$(printf '%s' "$IBAN" | tr -d ' \t' | tr '[:lower:]' '[:upper:]') + +# mktemp makes these 0600. The raw answer is the account's transactions with +# names and IBANs in it, so it lives exactly as long as this run. +RAW=$(mktemp); ERR=$(mktemp); TMP=$(mktemp) +trap 'rm -f "$RAW" "$ERR" "$TMP"' EXIT + +# Times on nostrod's interface are microseconds since 1970 UTC. +FROM_US=$(( ($(date +%s) - DAYS * 86400) * 1000000 )) +# Far above anything 90 days of this account holds. The window is what bounds +# the answer; an answer that fills the limit is treated as cut short below. +LIMIT=100000 + +# Transactions asks the bank for what is new before it answers, so this is as +# fresh as a direct read. The interface is nostrod's published one +# (packaging/dbus/net.catcrafts.Nostro1.xml in Nostro): +# Transactions(account s, query a{sv}) -> (a(sssssxxss) transactions, as notes) +# Interactive authorization is OFF on purpose: nobody is there to answer a +# password dialog from a timer, and a dialog popping up hourly would train its +# reader to type a password without looking. +if ! busctl --system --json=short --timeout=300 --allow-interactive-authorization=no \ + call net.catcrafts.Nostro1 /net/catcrafts/Nostro1 net.catcrafts.Nostro1 \ + Transactions 'sa{sv}' "$IBAN" 2 from x "$FROM_US" limit t "$LIMIT" \ + >"$RAW" 2>"$ERR"; then + cat "$ERR" >&2 + if grep -qi 'password' "$ERR"; then + echo "$0: nostrod only lets a program look without a password in your active" \ + "local session. Run this while logged in at this machine, or see" \ + "deploy/README.md for the polkit rule that lets the timer look." >&2 + fi + echo "$0: could not read the account through nostrod; nothing was shipped and the" \ + "remote file still holds what it did" >&2 exit 1 +fi + +# nostrod's answer -> the credit lines the rail reads. INCOMING ONLY: outgoing +# lines are supplier payments and card spending, the matcher ignores negative +# amounts anyway, and sending them would put the business's outgoing payment +# history on a public-facing host for no settlement benefit at all. +# +# -I keeps python from importing anything out of this directory or the +# environment: this is the step that decides what counts as money received. +python3 -I - "$RAW" "$LIMIT" >"$TMP" <<'PY' +import json +import sys + +raw_path, limit = sys.argv[1], int(sys.argv[2]) +with open(raw_path, encoding="utf-8") as f: + reply = json.load(f) + +# The signature is checked rather than assumed: the fields below are read by +# position, so an interface that grew or reordered one must stop this script, +# not shift a description into an amount. +if reply.get("type") != "a(sssssxxss)as": + sys.exit("pull-and-ship-credits: nostrod answered with type %r, not the " + "a(sssssxxss)as this script reads; nothing was shipped" % reply.get("type")) +transactions, notes = reply["data"] +for note in notes: + print("nostrod: " + note, file=sys.stderr) +if len(transactions) >= limit: + sys.exit("pull-and-ship-credits: nostrod returned %d transactions, which is the " + "limit asked for, so the answer may be cut short; nothing was shipped" + % len(transactions)) + +# bunq's Payment.type -> the ledger's `via` vocabulary. THE SAME TABLE AS +# BunqMethodFor in server/implementations/Catcrafts.Server-Bunq.cpp, which +# labels the credits the webhook writes. Keep the two in step: a payment must +# get one label whichever path delivers it first. An unknown type goes through +# verbatim, never guessed, because "sepa" is final and a card payment is not. +METHODS = { + "EBA_SCT": "sepa", + "IDEAL": "ideal", + "FIS": "card", + "BUNQ": "bunq", + "SWIFT": "swift", + "EBA_SDD": "directdebit", } -# Exactly one server binary, or fail loudly: a variant directory embeds a -# config hash, so two matches means picking one would be a coin flip. -matches=$(find bin -maxdepth 1 -type d -name 'Catcrafts.Server-*' 2>/dev/null | sort) -count=$(printf '%s\n' "$matches" | grep -c . || true) -[ "$count" = 1 ] || { echo "$0: expected one Catcrafts.Server-* under bin/, found $count" >&2; exit 1; } -BIN="$matches/catcrafts-server" +without_id = 0 +for name, bic, iban, description, currency, amount, time, bank_id, kind in transactions: + # Only euro can pay a euro order, and only money coming in pays anything. + if currency != "EUR" or amount <= 0: + continue + # The id is what the server deduplicates on when the webhook delivers the + # same payment. A line without one could be counted twice, so it is left out + # and said aloud instead. + if not bank_id: + without_id += 1 + continue + # nostrod's kind is "/", e.g. "EBA_SCT/SCT". + payment_type = kind.split("/", 1)[0] + method = METHODS.get(payment_type, payment_type) or "bank" + # Same keys, same order and same escaping as the server's own writer + # (AppendCreditTo): text as UTF-8, control characters escaped. + print(json.dumps({"id": bank_id, "reference": description, + "amount_minor": amount, "method": method}, + ensure_ascii=False, separators=(",", ":"))) -mkdir -p "$LOCAL_DIR" -chmod 700 "$LOCAL_DIR" - -# Pull. Appends only what is new, deduplicated on bunq's own payment id, so -# running this every few minutes over an overlapping window cannot double-count -# a payment into settling an order twice. -BUNQ_API_KEY="$KEY" "$BIN" --pull-credits --orders "$LOCAL" >/dev/null - -CREDITS="$LOCAL.transfer-credits.jsonl" -[ -f "$CREDITS" ] || { echo "$0: nothing pulled, not shipping" >&2; exit 1; } -# This file is the business's bank statement in miniature, and the context file -# beside it holds a private key. The directory is 0700 already; narrow the files -# too rather than inheriting whatever umask happened to apply. -chmod 600 "$CREDITS" "$LOCAL.transfer-credits.jsonl.bunq-context.json" 2>/dev/null || true - -# Ship INCOMING credits only. Outgoing lines are supplier payments and card -# spending: the matcher ignores negative amounts anyway, so sending them would -# put the business's outgoing payment history on a public-facing host for no -# settlement benefit at all. -TMP=$(mktemp); trap 'rm -f "$TMP"' EXIT -python3 - "$CREDITS" >"$TMP" <<'PY' -import json, sys -for line in open(sys.argv[1]): - line = line.strip() - if line and json.loads(line)["amount_minor"] > 0: - print(line) +if without_id: + print("pull-and-ship-credits: left out %d incoming payment(s) nostrod stored " + "without the bank's id" % without_id, file=sys.stderr) PY -# Refuse to ship an empty file over a good one: a parse failure upstream must -# not blank the evidence the server settles from. -[ -s "$TMP" ] || { echo "$0: no incoming credits — refusing to overwrite the remote" >&2; exit 1; } +COUNT=$(wc -l < "$TMP" | tr -d ' ') + +# The read worked and nothing came in. That is a quiet quarter, not a failure, +# and there is nothing to add: leave the remote alone rather than blank the +# evidence the server settles from. +if [ "$COUNT" -eq 0 ]; then + echo "$0: no incoming credits in the last $DAYS days; the remote file is left as it is" >&2 + exit 0 +fi + +if [ "$DRY_RUN" -eq 1 ]; then + cat "$TMP" + echo "$0: dry run, would ship $COUNT incoming credit(s) to $HOST:$REMOTE" >&2 + exit 0 +fi ssh "$HOST" "cat > $REMOTE && chown catcrafts:catcrafts $REMOTE && chmod 600 $REMOTE" < "$TMP" -echo "$0: shipped $(wc -l < "$TMP") incoming credit(s) to $HOST:$REMOTE" +echo "$0: shipped $COUNT incoming credit(s) to $HOST:$REMOTE"