feat: http runtime with mollie checkout, webhook, withdrawal and gapless invoices #59

Sammanfogat
supernaut sammanfogade 21 incheckningar från feat/runtime in i main 2026-09-30 21:08:47 +00:00
Ägare

What

The first runtime for the billing service, in test mode only.

  • HTTP server with /healthz and tRPC under /trpc (bearer PAYMENT_API_TOKEN, timing-safe compare).
  • Mollie hosted checkout for the personal plan, annual or monthly.
  • Mollie webhook: re-fetches the payment, dedupes on provider_event, applies each event once. Only paid grants.
  • tier_pro grant and revoke through the Kanidm group API (ADR 0017).
  • Cancel at period end, and a 10-minute sweep that ends due subscriptions and settles pending refunds.
  • Withdrawal (withdraw) with a proportional refund, measured against the first purchase. The deadline is 14 days, moved past Swedish weekends and public holidays (lag 1930:173).
  • Gapless invoice numbers from a counter row in the invoicing transaction (#52).
  • Contract 0.3.0: displayName and email on startCheckout, withdraw, cancel, interval, startImmediatelyRequestedAt, withdrawalDeadline, refundStatus, and error.data.reason on every error.
  • Migrations run from the image: node dist/src/migrate.js.

Refuses to start with a live_ Mollie key. PAYMENTS_ENABLED gates every money-moving path.

Review

An independent review found 16 issues, including a double charge from two paid checkouts, a renewal charged after cancel, a sweep revoking a just-renewed subscription, backdated withdrawals and missing public holidays. All are fixed with a test that fails without the fix, except credit notes for refunds, which wait on the accountant.

Verified

  • pnpm test with TEST_DATABASE_URL against a throwaway Postgres 17: 244 passed.
  • Without it: 216 passed, 28 skipped. CI has no Postgres, so the DB tests (webhook, withdrawal, sweep, allocator) do not run in CI. That is why billing.ts coverage reads about 10 % there.
  • Typecheck, lint, build, drizzle-kit check, audit, gitleaks: clean.
  • Smoke run of the built server: /healthz 200, unauthenticated tRPC 401, webhook 503 with payments disabled, live_ key refused.

Known gaps

  • If Kanidm stays down past Mollie's webhook retry schedule during a first payment, a Mollie subscription can exist with no local record. Needs a reconciliation job.
  • No credit notes, invoice PDFs, chargeback revocation or org seats yet. Listed in the README.
  • Migration 0003 adds NOT NULL columns without defaults. It fails loudly on a non-empty subscription table. No environment has run the service, so none should have rows. Confirm before the first deploy.

Before this is live

  • Kanidm service account bitborg-billing: member write on tier_pro only. No person reads: the portal passes display name and email in startCheckout.
  • bitborg-infra#496: PUBLIC_URL, PAYMENT_API_TOKEN, /trpc off the public edge, run the migrate entry before each new image.
  • Accountant: numbering scheme, no credit notes yet, holiday rule, the 7-day requestedAt bound.

Refs #51, #52. Neither closes on merge: #51 needs an end-to-end test-mode payment from the portal, #52 needs the accountant's sign-off.

## What The first runtime for the billing service, in test mode only. - HTTP server with `/healthz` and tRPC under `/trpc` (bearer `PAYMENT_API_TOKEN`, timing-safe compare). - Mollie hosted checkout for the personal plan, annual or monthly. - Mollie webhook: re-fetches the payment, dedupes on `provider_event`, applies each event once. Only `paid` grants. - `tier_pro` grant and revoke through the Kanidm group API (ADR 0017). - Cancel at period end, and a 10-minute sweep that ends due subscriptions and settles pending refunds. - Withdrawal (`withdraw`) with a proportional refund, measured against the first purchase. The deadline is 14 days, moved past Swedish weekends and public holidays (lag 1930:173). - Gapless invoice numbers from a counter row in the invoicing transaction (#52). - Contract 0.3.0: `displayName` and `email` on `startCheckout`, `withdraw`, `cancel`, `interval`, `startImmediatelyRequestedAt`, `withdrawalDeadline`, `refundStatus`, and `error.data.reason` on every error. - Migrations run from the image: `node dist/src/migrate.js`. Refuses to start with a `live_` Mollie key. `PAYMENTS_ENABLED` gates every money-moving path. ## Review An independent review found 16 issues, including a double charge from two paid checkouts, a renewal charged after cancel, a sweep revoking a just-renewed subscription, backdated withdrawals and missing public holidays. All are fixed with a test that fails without the fix, except credit notes for refunds, which wait on the accountant. ## Verified - `pnpm test` with `TEST_DATABASE_URL` against a throwaway Postgres 17: 244 passed. - Without it: 216 passed, 28 skipped. **CI has no Postgres, so the DB tests (webhook, withdrawal, sweep, allocator) do not run in CI.** That is why `billing.ts` coverage reads about 10 % there. - Typecheck, lint, build, `drizzle-kit check`, audit, gitleaks: clean. - Smoke run of the built server: `/healthz` 200, unauthenticated tRPC 401, webhook 503 with payments disabled, `live_` key refused. ## Known gaps - If Kanidm stays down past Mollie's webhook retry schedule during a first payment, a Mollie subscription can exist with no local record. Needs a reconciliation job. - No credit notes, invoice PDFs, chargeback revocation or org seats yet. Listed in the README. - Migration 0003 adds NOT NULL columns without defaults. It fails loudly on a non-empty `subscription` table. No environment has run the service, so none should have rows. Confirm before the first deploy. ## Before this is live - Kanidm service account `bitborg-billing`: member write on `tier_pro` only. No person reads: the portal passes display name and email in `startCheckout`. - bitborg-infra#496: `PUBLIC_URL`, `PAYMENT_API_TOKEN`, `/trpc` off the public edge, run the migrate entry before each new image. - Accountant: numbering scheme, no credit notes yet, holiday rule, the 7-day `requestedAt` bound. Refs #51, #52. Neither closes on merge: #51 needs an end-to-end test-mode payment from the portal, #52 needs the accountant's sign-off.
supernaut lade till 20 incheckningar 2026-09-30 18:21:39 +00:00
A counter row is incremented under its row lock in the transaction that
writes the invoice, so a rollback returns the number and concurrent
issuers queue. Database tests run when TEST_DATABASE_URL is set.

Refs #52
The checkout payment and the subscription carry the webhook url, the
subscription starts at the first renewal with an idempotency key, and a
payment event carries a provider-neutral detail so the core never reads
the Mollie payload.
StartCheckoutInput requires startImmediatelyRequestedAt and takes an
optional interval (annual when omitted). subscriptionStatus returns null
without a subscription and reports interval and cancelAtPeriodEnd.
- node:http server: /healthz, the Mollie webhook and the tRPC API behind
  a bearer token. PAYMENTS_ENABLED gates every money-moving path.
- Checkout for the personal plan, annual by default, storing the
  consumer's start-immediately request.
- The webhook re-fetches the payment, dedupes on provider_event and
  applies each event once: tier_pro is granted in Kanidm, the invoice is
  issued and the renewal is scheduled at the provider.
- Cancel stops renewal; a sweep revokes at period end.
- Withdrawal within 14 days refunds the unused share and revokes.

Refs #51
The deadline is Stockholm midnight after the last day, exclusive, and
follows the summer and winter time offset.
subscriptionStatus returns withdrawalDeadline, computed by the same
function withdraw enforces. The window is judged on requestedAt, clamped
to server time, so a retry that arrives after the deadline but was
declared before it succeeds. A replay returns the first result whatever
requestedAt it carries.

Refs #51
Customer and payment creation get distinct key suffixes. A subscription
or refund created before Mollie forgot its idempotency key is found by
metadata and reused. provider_event keeps only ids, status, amounts,
metadata and timestamps, never consumer or card holder data.
Per lag 1930:173 a deadline ending on a Saturday, Sunday, allmän
helgdag, midsommarafton, julafton or nyårsafton moves to the next
working day. Easter-derived days come from the Gregorian computus.
A partial unique index allows one active or past_due subscription per
customer. Charges record their paid period. The image ships drizzle/
and dist/src/migrate.js so migrations run with the drizzle-orm migrator
and no drizzle-kit at runtime.
- A second paid checkout for a live customer is refunded, not
  activated; the customer row is locked for the decision.
- Renewals start the day after the paid period in Amsterdam time. One
  arriving after cancellation is refunded instead of extending.
- The Mollie subscription is created before the Kanidm grant and reused
  by reference on retry; the invoice number is allocated last.
- The sweep re-checks each row under its lock, also ends active
  subscriptions past period end plus grace, isolates failing rows, and
  retries unissued refunds and settles pending ones.
- Revoke keeps tier_pro while another live subscription maps to the
  user.
- Withdrawal applies to the first paid charge and its period. A
  requestedAt before the purchase or more than 7 days old is refused.
  The result carries refundStatus, and a replay re-issues a refund that
  never reached the provider.
- Errors carry data.reason so callers do not match on message text.

Refs #51
tRPC onError logs the procedure, code and root cause. Kanidm errors name
the call instead of the path, which carries the username.
docs: running migrations from the image and the refund paths
Alla kontroller lyckades
ci / ci (pull_request) Successful in 48s
2a3f2791a9
supernaut lade till 1 incheckning 2026-09-30 19:21:46 +00:00
feat: take the billing name and email from the caller, not kanidm
Alla kontroller lyckades
ci / ci (pull_request) Successful in 56s
0293253f61
StartCheckoutInput requires displayName and email from the portal's
signed-in session. The Kanidm client now only adds and removes tier
group members, so the bitborg-billing service account needs member
write on tier_pro and no person reads. Contract bumped to 0.3.0.
supernaut sammanfogade incheckning f9b2e7ebf0 till main 2026-09-30 21:08:47 +00:00
supernaut tog bort grenen feat/runtime 2026-09-30 21:08:47 +00:00
Logga in för att delta i denna konversation.
Inga granskare
Ingen milstolpe
Inget projekt
Inga tilldelade
1 deltagare
Notiser
Förfallodatum
Förfallodatumet är ogiltigt eller utanför gränserna. Använd formatet "åååå-mm-dd".

Inget förfallodatum satt.

Beroenden

Inga beroenden satta

Referens
bitborg/bitborg-payment!59
Ingen beskrivning angiven.