- TypeScript 99.3%
- JavaScript 0.4%
- Dockerfile 0.3%
| Filnamn | Senaste incheckningsmeddelande | Senaste incheckningsdatum |
|---|---|---|
|
|
||
| .forgejo/workflows | ||
| contract | ||
| drizzle | ||
| src | ||
| .env.example | ||
| .gitignore | ||
| .markdownlint-cli2.jsonc | ||
| .prettierignore | ||
| .prettierrc.json | ||
| Containerfile | ||
| drizzle.config.ts | ||
| eslint.config.mjs | ||
| lefthook.json | ||
| LICENSE | ||
| package.json | ||
| pnpm-lock.yaml | ||
| pnpm-workspace.yaml | ||
| README.md | ||
| renovate.json | ||
| tsconfig.build.json | ||
| tsconfig.json | ||
| vitest.config.ts | ||
bitborg-payment
The billing service for bitborg — subscriptions, VAT/pricing, and entitlements (roadmap #5).
What it does
bitborg-payment owns:
- a vendor-agnostic
PaymentProviderinterface, with a single Mollie adapter behind it — application code never talks to the Mollie SDK directly, so swapping or adding a provider later doesn't touch pricing/entitlement logic; - pure VAT / pricing / entitlement logic (SE/NO/EU VAT rules, seats, trial → paid transitions);
- a Drizzle schema + initial migration for its own Postgres database (
bitborg_billingin production); - the publishable
@bitborg/payment-contractpackage (zod schemas + router types) other services consume.
What runs
pnpm start serves, on PORT:
GET /healthz: 200 when Postgres answers.POST /webhooks/mollie: Mollie posts only a payment id. The service re-fetches the payment, records each event once inprovider_eventand applies it once, so a replayed webhook changes nothing./trpc/*: the@bitborg/payment-contractrouter (startCheckout,subscriptionStatus,cancel,withdraw,updateBillingEmail,replaceCard,erase) behind a bearer token.
Present:
-
Mollie hosted checkout for the personal plan, in two ways at the same price, chosen by
renewal:auto(default): annual (default) or monthly. It offers only cards, Apple Pay and Google Pay, the methods that leave a card mandate for renewals.none: a one-time annual payment. Mollie's checkout offers cards, Apple Pay and Swish, and the customer picks there. No Mollie customer, mandate or subscription, whichever method pays. Monthly is refused (one_time_needs_annual). The subscription is created withcancelAtPeriodEnd, so the sweep ends it at the period end with no grace. Paying again while the period runs extends it from its end, and the invoice covers the new period from that date. One such payment can be in progress at a time (payment_pending).- Both accept an optional
locale(sv_SEoren_GB; omitted lets Mollie choose) and an optionalcancelUrl(https, same origin asreturnUrl; omitted returns a cancelling customer toreturnUrl).
-
One Mollie customer per customer: the first renewing checkout creates it and stores its id in
customer.provider_customer_ref. Later checkouts reuse it and send the current name and email, as does a billing email change. Migration 0012 fills the column from the newest stored payment method's Mollie customer. Each Mollie subscription description ends in a short subscription id, so a customer's subscriptions differ. -
Countries:
BILLING_SELL_COUNTRIESis the allowlist of countries billing sells to (ISO alpha-2, comma-separated). Unset means Sweden only.startCheckouttakes an optionalcountry, else the customer's stored country, else Sweden while Sweden is the only country listed. It refuses an unlisted country (country_not_sold) and a missing country when more than Sweden is listed (country_required). A non-Swedish checkout, one-time or not, offers cards only (no Apple Pay, no Swish) and asks Mollie to accept cards issued in the declared country. If the first payment still arrives with another or an unknown card country, it is refunded and not activated (card country mismatch). A Swedish checkout accepts any card. VAT is the destination country's standard rate (src/vat.ts, all EU-27, plus Norway, provisional), and the price stays the same gross. The service refuses to start when a listed country has no VAT rate. -
subscriptionStatus.latestChargereports the newest payment attempt aspending,paid,failed,canceledorexpired, so the portal can show the outcome after the return. A subscription whose first payment has not completed reports statusincomplete.A checkout while an auto-renew subscription is live is refused (
already_subscribed). An auto-renew checkout while a one-time period runs switches to automatic renewal: its first payment sets up the mandate and pays the period that starts at the one-time period end, and the Mollie subscription starts one interval later. The one-time subscription is closed, so a one-time extension paid after the switch is refunded. Withdrawal applies to the switch as to a rebuy not started yet: it is refunded in full and access runs to the one-time period end. The switch opens once the one-time purchase's 14-day withdrawal period has passed and no paid one-time year is waiting to start. Until then it is refused (one_time_in_withdrawal_period), so the one-time purchase stays withdrawable.A past due subscription the provider has cancelled or suspended does not count: a checkout is accepted, and its payment closes the old subscription and starts the new period at the old period end. The consumer's request to start during the withdrawal period is required and stored. The billing name and email come from the caller (the portal's signed-in session); the service reads no person data from Keycloak.
subscriptionStatusreportsrenewalandpaidUntil, andnextCharge(day, amount, card or Apple Pay, last four digits) while an auto-renew subscription is active and not cancelled. The portal sends the renewal reminders from it.card(brand, last four digits) is the live subscription's payment method, past due included, and null for a one-time payment. -
On payment: the renewal is scheduled as a Mollie subscription starting the day after the paid period (Amsterdam time, Mollie's calendar: an assumption, Mollie's docs only say a missing day of month falls back to the last day),
tier_prois granted in Keycloak (ADR 0017), and the invoice is issued with a gapless number as the last step of the transaction. A second paid checkout for a customer who is already subscribed is refunded, never activated. So is a paid auto-renew checkout that left no mandate to renew from. A one-time payment needs no mandate. -
Renewals extend the period and are invoiced. A renewal arriving after cancellation is refunded. A renewal paid for another amount than the subscription's last charge is not applied. It is recorded in
reconcile_orphanand handled as an orphan below. Resolve it by hand in the Mollie dashboard: extend the period locally or refund the payment, then close the orphan row as described below. A renewed period ends the day before Mollie's next charge day, read from the Mollie subscription after each renewal. After a successful retry Mollie counts the next charge from that payment. When the read fails, the period runs one interval from this renewal's charge day (the last day of a shorter month), which is Mollie's schedule while no retry moves it. -
Replace the card:
replaceCardreturns a hosted page for a small first payment (1 SEK) on the customer's existing Mollie customer. It works while the subscription isactiveorpast_due, renews automatically and the provider still has the subscription (elsenot_renewing,no_live_subscription,subscription_ended). One check may be open per subscription (payment_pending); one never completed is dropped after an hour. The check is acard_replacementrow, not a charge: no invoice, period or VAT. When it is paid with a usable mandate, the Mollie subscription is moved to the new mandate,payment_methodgets a new row, the old mandate is revoked and the check is refunded through the usualrefundrow. The subscription's status is left alone: apast_dueone becomesactivewhen Mollie's next attempt on the new mandate is paid. A check that cannot be applied (payment failed, invalid mandate, card country mismatch, the subscription ended meanwhile, the provider refused the move, or the start had expired) is refunded, its new mandate is revoked and the subscription is unchanged. It is logged as[card] card replacement <id> on <payment id> not applied: <why>. A check whose provider ref write was lost is matched by thecardReplacementIdthe payment carries. Only a failure that is not a refusal (a timeout, a 5xx) is retried: the webhook fails and Mollie or the reconcile pass sends it again. -
Mandate check: when a first payment is paid, the adapter reads its mandate. The card expiry goes to
payment_method.exp(YYYY-MM-DD) and the mandate's status topayment_method.status. Onlyvalid(cards) andpendingcount as usable. A paid auto-renew checkout whose mandate isinvalidis refunded and not activated, as one with no mandate is, and logged aspaid but its mandate is not usable. A mandate that cannot be read is taken asvalid, with no expiry stored. -
Mandates: when a chargeback, a withdrawal or a full dashboard refund ends a subscription, its card mandate is revoked at Mollie, so nothing stays chargeable. So is the mandate of a paid checkout that is refunded without activating (duplicate, after a withdrawal, card country mismatch).
payment_method.statusgoesvalid,revoking,invalid. A revoke that fails is logged as[mandate] <id> not revokedand retried by the sweep. A cancellation at period end leaves the mandate alone. -
Cancellation stops renewal at once; access runs to the end of the paid period. A sweep every 10 minutes ends subscriptions whose period is over (at once when cancelled, after an 8-day grace when no renewal came), retries refunds not yet issued and settles pending ones.
-
Every way access ends (sweep, withdrawal, chargeback) removes
tier_proand puts the user back intier_participant, unless a live paid subscription or complimentary grant still gives pro. A failedtier_participantwrite is logged as[revoke] could not add tier_participantand does not undo the revoke: the reconciler treats a user with no tier as a participant. -
Dunning: a failed renewal marks the subscription
past_due. Mollie retries it daily, up to 5 times, and cancels its subscription when the retries run out. Some failure reasons cancel it after 3 attempts or at once. The last attempt is assumed to land within 7 days of the period end (Mollie's docs say only up to 5 daily retries, varying by method and reason), so the grace is 8 days. It counts Amsterdam calendar days and ends at the end of the eighth day after the period end. Access continues through the grace;subscriptionStatusreportsgraceEndsAtso the portal can warn the customer. A failure reported 3 or more days before the period end is a stale delivery and is ignored. A later successful payment makes itactiveagain. At the end of the grace the sweep revokestier_proand cancels the Mollie subscription. A renewal paid after that is refunded, and the customer can check out again. -
Mollie sends no webhook when it cancels or suspends a subscription, e.g. after the mandate is revoked. Once an hour the sweep reads the Mollie subscription of each active auto-renew subscription from the portal's first reminder (30 days before an annual period end, 7 before a monthly one) until the grace ends. A cancelled or suspended one is marked
past_dueand follows the dunning path above, sonextChargeis null. -
Reconciliation after each sweep: every Mollie payment from the last 14 days that is paid but has no settled local charge is replayed through the webhook path. That repairs a first payment whose
tier_progrant kept failing past Mollie's webhook retries, and a checkout whose local charge write was lost after Mollie accepted the payment (matched by the subscription id in the payment's metadata and the recorded amount). A replayed checkout for a customer who has a live subscription, or any subscription started after it, is refunded and its Mollie subscription cancelled, as a second paid checkout always is. -
A payment that is still unmatched, or that was refunded or charged back before it was applied, is logged once, when first recorded in
reconcile_orphan, as[reconcile] <payment id> is paid at the provider with no settled local chargeand left alone: no refund, cancellation or grant is automatic. The row survives restarts and stays listed after the 14-day window, but is no longer replayed there. Every pass also logs[reconcile] <n> unresolved orphan(s), oldest <payment id> since <time>; needs manual reviewwhile any is open. Review the payment in the Mollie dashboard. Either refund it there and cancel the customer's Mollie subscription that carries the samesubscriptionIdmetadata, or fix the local rows and let the next pass replay it. A row resolves itself once the payment has a settled local charge. After the review, close one by hand:UPDATE reconcile_orphan SET resolved_at = now() WHERE payment_ref = '<payment id>'; -
Withdrawal within 14 days of the first purchase (Swedish calendar, moved past weekends and public holidays): revokes, stops renewal and refunds the unused share of the first period. A one-time period paid early that has not started yet is refunded in full. A one-time payment that lands after a withdrawal is refunded.
-
Chargeback on a payment that paid for a period:
tier_prois revoked, the Mollie subscription is cancelled and the subscription ends at once. Each chargeback is recorded once inchargeback, by its Mollie id. The invoice stays. A withdrawal of a charged-back purchase is refused (charged_back), and a refund claimed but not yet sent is cancelled. Once every chargeback on the subscription is reversed while the paid period runs, access is restored to the end of that period, and a cancelled refund is sent again. The renewal stays cancelled. A first payment with an open chargeback is never applied. Reconciliation also replays each chargeback from the last 14 days not yet recorded locally, and re-fetches the payment of each open chargeback from the last 180 days (up to 100) to see a reversal whose webhook was lost. Mollie sends no payment webhook when a chargeback is reversed, so a chargeback still open after 180 days is flagged once for review (open past the reversal window), which reopens a review closed earlier. Check the dispute in the Mollie dashboard. -
A refund the provider moves to
failed(for example the customer closed the bank account) cannot be issued again: its idempotency key finds the failed one. It is logged once, on the move, as[reconcile] refund <id> failed at the provider; customer still owed; needs manual review. Act on it promptly. Check the payment's refunds in the Mollie dashboard first. If a new dashboard refund is not possible or fails, ask the customer for new account details and pay by bank transfer. Note the manual payment on the Mollie payment so nobody pays twice. Leave the failed row as it is, apart from the review mark. A refund that fails while a chargeback is open is not logged: the bank already returned the money. Until a failed refund is reviewed, every reconcile pass also logs[reconcile] <n> failed refund(s) unreviewed, oldest <id> since <time>; needs manual review(one under an open chargeback is left out). After the customer has been paid:UPDATE refund SET reviewed_at = now() WHERE id = '<refund id>'; -
refund.provider_statuskeeps Mollie's own refund state (queued,processing,canceled, ...) beside the three-statestatus. A refund the dashboard cancelled is logged ascanceled at the provider; customer still owedinstead offailed, and is reviewed the same way. A refund webhook settles the row with the same update the sweep uses. A refund still pending 24 hours after it was claimed, for example queued for lack of balance, makes every reconcile pass log[reconcile] <n> refund(s) pending over 24 h, oldest <id> since <time>, provider status <state>; needs manual review. Top up the Mollie balance or look at the refund in the dashboard. -
Never refund a settled charge in the Mollie dashboard. Use the withdrawal flow, which revokes, stops renewal and records the refund. A refund seen at the provider that matches no local refund is logged once per refund as
[reconcile] refund <id> on <payment id> has no local record; needs manual review. If the payment is refunded in full and we issued no refund of our own on it (apart from failed ones), access ends and the renewal stops, but only when that charge pays the current period. A full refund of an older period is logged and changes nothing else. A partial refund changes nothing. A dashboard refund that is still pending already ends access, even if it later fails. Reconciliation re-reads refunded payments created in the last 14 days, so a lost webhook is caught. -
A withdrawal refund the provider refuses, for example because the payment is already refunded, is marked failed and not retried. Only the provider's "already refunded" and "above the refundable amount" answers count as refused; any other error is retried. It is logged once as
[reconcile] refund <id> refused by the provider: <why>; needs manual review, unless a chargeback is open. Settle it by hand. -
A chargeback on refunded money or on a subscription already ended, one with an amount not in SEK, a reversal that cannot restore access or that lands on a payment never applied, or a re-owed refund the provider fails, is logged as
[reconcile] chargeback <id> on <payment id>: <why>; needs manual review. While any is open, every reconcile pass also logs[reconcile] <n> unreviewed chargeback(s), oldest <id> since <time>; needs manual review. After the review in the Mollie dashboard:UPDATE chargeback SET reviewed_at = now() WHERE provider_ref = '<chargeback id>'; -
Chargeback evidence, kept per payment so a dispute is answered from stored data alone (
chargebackEvidenceinsrc/evidence.ts, keyed by the Mollie payment id):charge: the consent shown at checkout (consent_text_hash,consent_shown_at,consent_language, from the optionalconsentinput ofstartCheckout), and once paidpaid_at,mandate_ref,card_security(3dsecureas Mollie reports it, card payments only) andcard_country(the card issuer's country, card payments only).billing_countryis the country declared at checkout, copied to renewals from the customer.consent_textholds each distinct sentence once, keyed by its sha256 (hex). Renewals carry no consent of their own: the first checkout charge holds it.subscription: the renewal choice and the interval.cancellation: each cancel or withdrawal, with when it was requested and when it takes effect.chargerows are the renewal history: date, amount and mandate of each.chargeback.evidence:chargebackEvidencefor the payment, stored when the chargeback is first recorded and never overwritten. Read it withSELECT evidence FROM chargeback WHERE provider_ref = '<chargeback id>';. It is null, with anevidence not storedreview, if building it failed. Theneeds manual reviewline says when the evidence is on the row.- All of this evidence (consent texts, charge fields, cancellation rows and chargeback snapshots) is kept with the invoice records (see Data).
chargebackEvidenceis a library function; the operator reads the snapshot on the chargeback row. Charges paid before migration 0009 have nopaid_at,mandate_reforcard_security, and charges before migration 0011 have nobilling_countryorcard_country. None are backfilled.
-
Renewals are merchant-initiated and run without 3-D Secure, so they carry no liability shift. Only the first payment is authenticated. This is an accepted risk.
-
Every API error carries
data.reason(seeErrorReasonSchemain the contract).
Absent:
- Business status, VAT number and VIES in the contract. Checkout is for consumers only, so no address is collected (simplified invoice). A business pays destination VAT.
- VAT rules for the UK, Switzerland and Iceland. Only Sweden, Norway and the EU-27 are priceable.
- The org-seat plan and add-ons.
- Invoice PDFs (#161) and credit notes (#63). Both are issued by hand at launch. The gapless number on the invoice row is an internal sales reference, not a customer invoice number.
- Reminder emails for a failed renewal. The portal owns mail and reads
graceEndsAt. - Mail for a price change notice.
cli.js price noticeprints the recipients; the operator sends the mail and marks it withcli.js price sent. - The pro-rata refund on termination after a price change notice.
- A new card for a subscription the provider has already cancelled (
subscription_ended). Such a customer checks out again after the grace. - Row-Level Security (a restricted application role plus a
BYPASSRLSsystem role) and a deploy role. Designed, not built. - An immutable audit log of charge, refund and entitlement changes. Designed, not built.
provider_eventkeeps the raw webhook payloads, which is not the same thing.
Org billing is decided: a flat org add-on, with members holding their own accounts. It is not sold
at launch (#15). The code still carries
a per-seat org_seat plan with a seat_assignment table (src/pricing.ts, src/db/schema.ts,
the contract's PlanSchema). Nothing is built for either. Remove or keep them when org billing
is built.
Complimentary subscriptions
An operator can give a user pro access for free, for a friend or a tester, and withdraw it later.
A grant is a row in complimentary: the user, a reason, who granted it, when, and an optional
end date. No end date means it runs until withdrawn. It has no customer, charge, invoice, VAT or
provider object, and it is kept apart from subscription, which describes paid periods.
- Grant: adds
tier_proand removestier_participant, the same grant a paid activation makes, which kicks a reconcile. A second grant for the same user returns the live one unchanged and repeats the Keycloak write. A user with a live paid subscription is refused. - Withdraw now, or at the end date by the sweep (every 10 minutes, with payments disabled too):
revokes as an ended paid subscription does.
tier_prois removed unless a live paid subscription still gives it, and the user goes back totier_participant. No refund, invoice or credit note. A Keycloak failure rolls the change back. A withdrawal can be retried, and the sweep retries on its next pass. - A complimentary user can check out as normal. The grant stays live next to the paid
subscription, so a later cancellation, withdrawal or chargeback of the payment leaves the user
on pro. Only a withdrawal of the grant or its end date ends it (
end_reasoniswithdrawnorexpired).subscriptionStatusreports paid subscriptions only. - Grants and revokes for one user take a transaction-scoped advisory lock on the username, so a revoke never misses a payment or grant that commits at the same time.
There is no HTTP endpoint for this. Run the CLI inside the container, which holds the database and Keycloak credentials:
podman exec bitborg-billing node dist/src/cli.js comp grant <username> --reason "tester" --by <operator> [--until YYYY-MM-DD]
podman exec bitborg-billing node dist/src/cli.js comp list [--all]
podman exec bitborg-billing node dist/src/cli.js comp withdraw <username>
--until is the last day of access, Stockholm time. list prints one tab-separated line per
grant: username, granted at, end, state, granted by, reason. --all includes ended grants.
Usernames are matched as Keycloak stores them, in lower case, and the user must exist in
Keycloak.
The Keycloak write happens before the database commit. If a grant fails after printing a
Keycloak error, run comp list and run the grant again. If the user is in tier_pro with no
live grant, remove them from tier_pro by hand.
Backfill for users given tier_pro by hand before this existed: list the members of the
tier_pro group in the Keycloak admin console, leave out paying users (the grant refuses them),
and run for each of the rest:
podman exec bitborg-billing node dist/src/cli.js comp grant <username> --reason "given by hand before complimentary records" --by <operator>
Price change
The Terms promise renewing subscribers 30 days' email notice before a price change, and a
pro-rata refund if they terminate because of it. Prices live in src/pricing.ts.
-
Release the new price in
PLANS. New checkouts pay it from then on. -
List the notices for every renewing personal subscriber on that interval who pays another amount. The amount must equal the
PLANSprice for the interval, or the command refuses:podman exec bitborg-billing node dist/src/cli.js price notice <annual | monthly> <amount in öre> <YYYY-MM-DD>The date is the first day at the new price, in Amsterdam time (Mollie's calendar). It must be at least 30 days ahead. One line per notice is printed: notice id (
dry-rununtil recorded), subscription id, billing email, old amount, new amount, effective time. Nothing is written. -
Run it again with
--applyto record the notices, all in one transaction. A later run skips subscribers who already have an open notice, so run it again after a checkout that was in flight during step 1. -
Send the notice mail to each printed address, with the new price and the date. Then mark it sent, for one notice or every unsent one:
podman exec bitborg-billing node dist/src/cli.js price sent <notice id | all>A notice can only be marked sent 30 days or more before its change; a later one is printed as
late, will not apply. Theprice_noticetable enforces both 30-day minimums. -
From the effective time the sweep sets the new amount on each Mollie subscription (
PATCH /subscriptions/{id}) and closes the notice asapplied. A notice whose subscriber cancelled, withdrew or was stopped by Mollie meanwhile closes asendedwith no update. A notice never marked sent closes asunsentwith no update, logged as[price] notice <id> on subscription <id> not applied: ...; needs manual review. Record a new notice with a later date for it. A failed update is logged as[price] notice <id>: <why>and retried on the next sweep.
price cancel <notice id> closes an open notice as canceled without applying it.
A renewal at the new amount is accepted once the notice is applied, with the VAT split of the
new amount at the purchase's rate. One at the old amount stays accepted, for a payment Mollie
made before the update: a charge Mollie creates on the effective day before the sweep has run is
at the old price, in the customer's favour. Any other amount is parked as an orphan.
nextCharge reports the new amount for a charge on or after the effective date once the notice
is marked sent.
Provider choice
Mollie is a Dutch company and runs on Google Cloud, so it sits outside guiding principle 1 (hosted in
Sweden, no US-owned infrastructure). It receives payment metadata only: no card data (see below).
It was accepted because no EU-hosted provider met the need. The vendor-neutral PaymentProvider
interface (src/provider/types.ts) is the exit: a second adapter replaces Mollie without touching
pricing or entitlement logic.
Recurring billing uses Mollie managed subscriptions. The service has no scheduler of its own for renewals: Mollie charges, the webhook records it. The only timer is the sweep that ends expired subscriptions and settles refunds. Retries of a failed renewal are Mollie's too.
Sales report
cli.js sales <YYYY-Qn | YYYY> [--eur-rate <SEK per EUR>] prints tab-separated lines from the
invoices issued in the period, on Stockholm calendar days:
podman exec bitborg-billing node dist/src/cli.js sales 2026-Q4 --eur-rate 11.2345
Rows are grouped by country, basis, rate and currency, in sections: oss (consumer sales to
other EU countries), oss-total (one line per currency: the EU-wide threshold check, so use the
YYYY form for the annual figure), reverse-charge (one row per buyer VAT number), domestic,
other. Amounts are minor units. refunds lists succeeded refunds settled in the period, with
the VAT part following the invoice they reduce. --eur-rate is the ECB rate the operator looks
up. It adds EUR cents for SEK rows, half up per group. No network call is made. Rows in another
currency stay unconverted.
Data
Invoices and payment records are kept until the end of the seventh year after the calendar year in
which the financial year ended (bokföringslagen (1999:1078), 7 kap. 2 §), also after account
deletion. Records that support an OSS return (charge, invoice, customer.country) are kept
for ten years from the end of the year of the sale. Foreign keys do not cascade, so deleting a customer fails while charges or invoices
reference it.
On account deletion the portal calls erase with the username, before the identity is deleted.
It:
- sets
kanidm_reftoerased:<customer id>, so a username registered again later gets a new customer; - sets
billing_nameandbilling_emailtoerasedand clearsvat_numberand the address fields; - empties
payment_method.provider_dataand clearsbrand,last4andexp; - deletes the user's
complimentaryrows (no money, so nothing to keep), revoking a live grant; - sets
customer.erased_at, then deletes the provider's customer record and setsprovider_erased_at.
The customer id, country, provider_customer_ref, charges, invoices (with their customer
snapshot) and provider_event are kept. If the provider deletion fails, the local erase stays and
an [erase] customer <id> line is logged. Erase the same customer id again to retry it; nothing
else changes on a repeat. By username, a repeat finds no customer and returns null. It is refused
with live_subscription while a subscription is active or past due, and with payment_pending
while a payment, card replacement, refund or mandate revocation is still settling. Those settle by
themselves, so retry later. It works with payments disabled. An operator runs the same step with:
podman exec bitborg-billing node dist/src/cli.js customer erase <customer id | username>
Before live keys
The service accepts a live_ Mollie key. Set one in production only after all of these are done:
- The Swedish VAT rule is confirmed. The EU and Norway rules stay provisional (see
src/vat.ts). - The business is registered for VAT in Sweden. Launch sells to Sweden only.
- The Mollie account review (KYC) is complete.
- The SAQ A self-assessment is completed and filed. Mollie cannot confirm SAQ A for a merchant.
Test mode
- Mollie cancels a test subscription by itself after 10 payments.
- SEK test payments work. Mollie's note that test mode is EUR-only covers the magic failure amounts only (probed 2026-10-05).
- A one-time payment opens Mollie's test checkout, where the tester picks the outcome (paid, failed, canceled, expired) for any method. Only recurring payments skip it. A processed test card payment reports Mastercard whichever test card number is entered.
Migrations
The image ships drizzle/ and runs them with the drizzle-orm migrator (no drizzle-kit at
runtime):
podman run --rm -e DATABASE_URL=... <image> node dist/src/migrate.js
Run it before starting a new image. Locally: pnpm build && pnpm migrate.
Card-data boundary (SAQ-A)
This service never stores or transmits card data. Checkout happens on Mollie's hosted payment page; bitborg-payment only ever sees Mollie's tokenised references (payment/subscription IDs, status webhooks) via its Mollie adapter — keeping the PCI-DSS scope at the lightest self-assessment tier, SAQ-A.
Configuration
See .env.example: MOLLIE_API_KEY, PAYMENTS_ENABLED (defaults off; the
kill switch for every money-moving path), BILLING_SELL_COUNTRIES (optional; countries sold
to, default SE), DATABASE_URL, KEYCLOAK_URL /
KEYCLOAK_REALM / KEYCLOAK_CLIENT_ID / KEYCLOAK_CLIENT_SECRET, PUBLIC_URL (webhook base), PAYMENT_API_TOKEN, PORT, and the optional
RECONCILE_TRIGGER_URL / RECONCILE_TRIGGER_TOKEN. Never commit a real value. Secrets come from the environment (Ansible Vault in production) only.
With payments enabled, the service checks at start that the key works and that creditcard,
applepay and swish are enabled on the profile, and exits if not.
MOLLIE_API_KEY is optional while payments are disabled. Without it the service and the CLI start
with no payment provider: every provider call fails, and only complimentary grants and
subscriptionStatus work. PUBLIC_URL is then not read either. A set key must start with test_ or live_,
whether payments are enabled or not.
KEYCLOAK_CLIENT_* are the bitborg-billing client credentials. That client may manage
tier_pro and tier_participant membership and map the paid entitlement roles,
nothing else. Users are found by exact
username and the call fails if there is not exactly one match.
When both RECONCILE_TRIGGER_* variables are set, every successful tier_pro write (grant, revoke,
withdrawal, sweep) is followed by a fire-and-forget POST to the reconcile auth shim (ADR 0037),
bearer token only, 3 s timeout, and logs [reconcile-trigger] kick reason=payment. A failure is logged without the token and never affects the money
path. When unset, the reconcile timer applies the change.
Development
pnpm install
pnpm test # vitest; set TEST_DATABASE_URL to also run the Postgres tests
pnpm lint # eslint + prettier
pnpm typecheck
pnpm build # → dist/
pnpm dev # run from source
Deployed as a pinned container image (built + pushed by Forgejo Actions on a v* tag); consumed by
bitborg-infra, with Renovate opening the bump PR — the same mechanics as the other bitborg
services (ADR 0033). No :latest. Release order: merge the version bump, verify main and package.json, then tag. A tag pushed before the bump merges builds the wrong commit.