fix(credits): stop minting a Checkout Session on every credit-gated 402
Implements the second defect in recoupable/chat#1960. Row 4 of that issue's PR matrix.
Stacked on api#835. Both PRs edit checkCreditsAvailable.ts and buildInsufficientCreditsResponse.ts (the charge and the session-minting lived in the same function), so this branch is based on that one. The issue's matrix originally called the two removals independent and mergeable in any order; that was wrong and is corrected there. Review the last commit only, or diff against chore/credits-remove-auto-recharge. Once #835 merges, this diff reduces to that commit.
The credit gate called createCreditsStripeSession on both exit paths (L57-62 for opted-out, L98-103 as the fallback) purely to populate checkoutUrl in the 402 body. So every credit-gated request that came up short minted a live Stripe Checkout Session, whether or not a human was there to see it.
Measured on prod for the 30 days to 2026-08-17: 2,779 sessions, 46 accounts, 0 with a customer_email, 0 paid. They cluster on cron minutes (244 at 06:01, 206 at 06:02, 117 at 09:03), which is scheduled-task traffic hitting the gate, not people. Removing the off-session charge in #835 does not fix this on its own.
What changes
checkCreditsAvailable loses the session minting, the Stripe customer resolution and the successUrl parameter. It reads remaining_credits and returns. It makes no Stripe calls on any path. 61 lines → 42.
buildInsufficientCreditsResponse returns a static billingUrl in place of checkoutUrl:
{
"error": "insufficient_credits",
"remaining_credits": 12,
"required_credits": 100,
"billingUrl": "https://chat.recoupable.dev"
}
CREDIT_BILLING_URL is CHAT_APP_URL. Deliberately the app root rather than a deep link, so the app can move where a card is saved without changing this contract.
successUrl is gone from ensureCreditsOrShortCircuit and all eight credit-gated call sites (lib/chat/validateChatRequest.ts, lib/socials/ensureSocialScrapeCredits.ts, and six under lib/research/). CREDIT_SHORTFALL_TOPUP_CREDITS and CREDIT_SHORTFALL_SUCCESS_URL are deleted. The latter pointed at sandbox.recoupable.com, which is not a host we serve, so a share of those 2,779 sessions would have returned users to the wrong place even if anyone had paid one.
POST /api/credits/sessions is untouched. That is where someone asked for a session, so that is where a session is still minted, and it keeps declineReason. open-agents' credits-topup dialog parses that { id, url, declineReason? } response, not the 402, so it keeps working. The buildInsufficientCreditsResponse docstring now says the two shapes are deliberately different; claiming they were the same is what conflated them.
Out of scope, but worth knowing
lib/research/measurement_jobs/ensureSongstatsPaymentMethod.ts still mints a createCardOnFileSession on every denied request. It is a payment-method gate, not a credit gate, so it is outside this issue, but it is the same shape of problem and now carries a comment saying so. Its successUrl is repointed at CREDIT_BILLING_URL rather than the dead sandbox host, since the constant it used is being deleted.
Verification
TDD, red before green:
- Rewrote
checkCreditsAvailable.test.tsand addedbuildInsufficientCreditsResponse.test.tsfor the new contract, including a loop that drives 20 consecutive shortfalls and assertscreateCreditsStripeSessionwas called 0 times, plus assertions thatbillingUrlis identical across calls and contains neitherstripenorsandbox. Ran them: RED, 6 failed (expected { … } to not have property "checkoutUrl",expected undefined to be 'https://chat.recoupable.dev', and 3×Cannot read properties of undefined (reading 'url')from the mocked session no longer being reached). - Implemented. GREEN.
- Updated
ensureCreditsOrShortCircuit.test.tsfor the two-field signature, asserting the gate is called with exactly{ accountId, creditsToDeduct }.
Full runs:
| Check | Result |
|---|---|
vitest run lib/credits lib/stripe lib/billing lib/research lib/socials lib/chat app/api/webhooks app/api/credits app/api/accounts | 221 files / 1256 tests passed |
eslint lib/research lib/socials lib/chat lib/credits lib/stripe | clean |
tsc --noEmit | 202 errors, identical to baseline, zero in any file this PR touches |
grep -rn checkoutUrl lib app outside tests | only ensureSongstatsPaymentMethod.ts, the out-of-scope gate above |
Not yet done: the issue's live Done-when check (drive a credit-gated endpoint to 402 twenty times on preview and confirm zero new Checkout Sessions on that account in Stripe, and that open-agents' dialog still renders a decline against POST /api/credits/sessions). The 20-iteration unit test covers the code path but not the live Stripe account. Flagging rather than implying it.
Merge order
docs#299 → chat#1961 → api#835 → this PR.
Summary by cubic
Stops creating Stripe Checkout Sessions on credit‑gated 402s. Previously the gate minted a live session (and could charge a saved card); now it only checks balance and returns a static billingUrl, so unattended calls create nothing and no charge happens without consent.
checkCreditsAvailableis read‑only. It drops Stripe calls and thesuccessUrlparameter.buildInsufficientCreditsResponsereturnsbillingUrland removescheckoutUrland anydeclineReason.ensureCreditsOrShortCircuitno longer acceptssuccessUrl; all call sites inlib/chat,lib/research, andlib/socialsare updated.- Replace deleted
CREDIT_SHORTFALL_*constants withCREDIT_BILLING_URL(https://app.recoupable.dev). POST /api/credits/sessionsis unchanged and remains the only place a Checkout Session is minted.ensureSongstatsPaymentMethodstill mints a per‑denial session (payment‑method gate) and now usesCREDIT_BILLING_URLfor its success URL.
Migration
- Read
billingUrlin 402 bodies instead ofcheckoutUrl. Do not expectdeclineReasonon 402. - Remove the
successUrlargument from allensureCreditsOrShortCircuitcalls. No changes toPOST /api/credits/sessions.