catcrafts.net/tools/pull-and-ship-credits.sh

205 lines
9.3 KiB
Shell
Raw Normal View History

2026-08-20 23:33:50 +02:00
#!/bin/sh
# Ask nostrod what arrived on the shop's bank account, and hand the incoming
# credits to the server, which cannot read the bank itself.
2026-08-20 23:33:50 +02:00
#
# WHY THIS EXISTS, so nobody "simplifies" it back:
#
# 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.
2026-08-20 23:33:50 +02:00
#
# 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.
2026-08-20 23:33:50 +02:00
#
# 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.
2026-08-20 23:33:50 +02:00
#
# 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:
2026-08-20 23:33:50 +02:00
# CREDITS_HOST ssh destination (default: hetzner)
# CREDITS_REMOTE the file the rail reads (default: the production path)
# CREDITS_DAYS how far back to ask (default: 90)
#
# 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.)
2026-08-20 23:33:50 +02:00
#
# 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.
2026-08-20 23:33:50 +02:00
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
2026-08-20 23:33:50 +02:00
HOST="${CREDITS_HOST:-hetzner}"
REMOTE="${CREDITS_REMOTE:-/var/lib/catcrafts/orders.jsonl.transfer-credits.jsonl}"
DAYS="${CREDITS_DAYS:-90}"
for tool in busctl python3; do
command -v "$tool" >/dev/null 2>&1 || { echo "$0: $tool is not installed" >&2; exit 1; }
done
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
2026-08-20 23:33:50 +02:00
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",
2026-08-20 23:33:50 +02:00
}
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 "<type>/<sub_type>", e.g. "EBA_SCT/SCT".
payment_type = kind.split("/", 1)[0]
method = METHODS.get(payment_type, payment_type) or "bank"
# Same keys, same order and same escaping as the server's own writer
# (AppendCreditTo): text as UTF-8, control characters escaped.
print(json.dumps({"id": bank_id, "reference": description,
"amount_minor": amount, "method": method},
ensure_ascii=False, separators=(",", ":")))
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)
2026-08-20 23:33:50 +02:00
PY
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
2026-08-20 23:33:50 +02:00
ssh "$HOST" "cat > $REMOTE && chown catcrafts:catcrafts $REMOTE && chmod 600 $REMOTE" < "$TMP"
echo "$0: shipped $COUNT incoming credit(s) to $HOST:$REMOTE"