Repository navigation
fix(billing): refuse to mint a duplicate subscription on an org - #3171
Merged
Merged
Conversation
Adds blockIfActiveSubscription, run by the three routes that can mint a Stripe subscription/invoice on an org's behalf: - POST /api/checkout-session - POST /api/invoice-request - POST /api/invite/:token/accept If the org's existing subscription status is active, trialing, or past_due, the route returns 409 with the existing subscription details and a Stripe Customer Portal URL. Tier upgrades and payment-method changes belong in the portal, not these intake routes. Without this guard, two of these routes in sequence produced the duplicate $3K Builder subscription on top of Triton's active $10K Corporate sub in April 2026 — the same incident that drove the issuer-identity lockdown in #3142. The lockdown closed the "wrong identity" door; this closes the "wrong number of subs" door. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
- Privilege escalation: invite route no longer returns a Stripe Customer Portal URL. The recipient gets `member` role on the org (not `admin`), and the portal session would grant admin-equivalent control over the existing subscription. Helper signature now takes BlockOptions, with customerPortalReturnUrl required to opt-in to the URL. Public routes pass the URL (member is verified upstream); the invite route omits it and the 409 message points to finance@ + dashboard instead. - Decimal formatting: render amounts with minimumFractionDigits=2 so $250.50 doesn't display as $250.5. - Reuse TIER_PRESERVING_STATUSES from organization-db.ts instead of a duplicate BLOCKING_STATUSES set — same intent, no drift risk. - Fallback message when portal URL is unavailable (org has no Stripe customer, portal creation fails, or caller suppressed it). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This was referenced Apr 25, 2026
Concurrent intake race: two simultaneous billing intakes can both pass the duplicate-sub guard
#3179
Closed
Contributor
Author
|
Issue #3181 proposes auditing the Stripe Customer Portal configuration for grandfathered-pricing safety ( Triaged by Claude Code. Session: https://claude.ai/code/session_01E33kYH6pf47j9hHiFn5pWr Generated by Claude Code |
Contributor
Author
|
Issue #3179 proposes a Postgres advisory lock on Generated by Claude Code |
This was referenced Apr 25, 2026
bokelley
added a commit
that referenced
this pull request
Apr 26, 2026
* feat(billing): webhook-side dedup on customer.subscription.created (#3184) Closes the cross-path race that the intake-side guards (#3171 blockIfActiveSubscription, #3179/#3183 advisory lock) leave open. Stripe Checkout creates a session URL, not a subscription — the sub gets minted only when the user completes the hosted page. So two concurrent intake paths (e.g., admin invite + member checkout) can both pass their guards before either mints a sub, and the user can complete both within seconds. Triton hit this in April 2026. On customer.subscription.created we re-check the customer's full live-sub inventory. If another live sub (active/trialing/past_due) exists, we cancel the new one with proration refund, alert ops via notifySystemError, and skip the org-row UPDATE so the surviving sub's state stays intact. Lookup or cancel failures fall through to "don't know" — a missed duplicate is caught by the periodic integrity audit (one-active-stripe-sub-per-org). Failing closed during a Stripe blip would block legitimate first-time subscriptions. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(billing): address reviewer feedback on webhook dedup Three concrete reviewer-flagged fixes: 1. (BLOCKER) The follow-up customer.subscription.{updated,deleted} events for the canceled duplicate sub were clobbering the surviving sub's row state — exactly the bug this PR was meant to prevent. The suppressOrgUpdate flag only gates the .created event. Added a structural guard at the top of the .updated/.deleted branches: if the event's sub id isn't the one we currently track AND the event's status is non-live, ignore the event. .created is exempt because that's how we *learn* about a new sub. 2. Stripe webhook retries of customer.subscription.created would re-invoke the helper after we already canceled. Stripe's cancel on an already-canceled sub returns 400, not a silent no-op, which threw and re-fired the ops alert. Added an early-return when the incoming subscription.status is already non-live. 3. subscriptions.list({ status: 'all', limit: 20 }) could miss the live sub on customers with many canceled experiments. Bumped to limit: 100 (Stripe max) and warn when has_more. Also addressed: - Alert message correctly reflects cancel failure ("COULD NOT be canceled — cancel manually") instead of unconditional "was canceled with proration". - Enriched the alert with new sub amount, lookup_key, and collection_method so ops can triage without clicking into Stripe. Test coverage extended to: retry-of-canceled, page overflow, alert content on cancel-success and cancel-failure, alert payload fields. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes the second half of the Triton/Encypher incident. PR #3142 closed the wrong-identity door (caller-supplied emails could become the Stripe customer of record). This PR closes the wrong-number-of-subs door (no path may mint a subscription/invoice on an org that already has a live one).
What changed
New helper
server/src/billing/active-subscription-guard.tsexportingblockIfActiveSubscription(orgId, orgDb, returnUrl). Returnsnullwhen safe; returns a 409 payload (with existing subscription details + a Stripe Customer Portal URL) when blocking.Wired into the three routes that can mint billing on an org's behalf:
POST /api/checkout-session— server/src/routes/billing-public.tsPOST /api/invoice-request— server/src/routes/billing-public.tsPOST /api/invite/:token/accept— server/src/routes/invites.tsBlocking statuses:
active,trialing,past_due. Non-blocking:canceled,unpaid,incomplete_expired,none(those are recoverable by re-subscribing).Why past_due also blocks
Without this, a member whose card got declined could click invoice-request and stack a second past_due sub on top of the first one. The right path for them is the customer portal (update payment method, retry the existing invoice) — which is what the 409 message points them to.
Tier upgrade path
Existing members who want to change tiers or update payment method use the Stripe Customer Portal (already wired up via
createCustomerPortalSessionand Addie'sget_billing_portaltool). The 409 includescustomer_portal_urlso the UI can deep-link them straight to it.Tests
server/tests/unit/active-subscription-guard.test.ts— 10 cases covering all status branches, missing org row, portal-creation failure, and message content.npm run typecheck— cleannpm run test:unit— 834/834npm run test:server-unit— 2208/2208 (10 new)Test plan (manual)
POST /api/checkout-sessionfor any tier → expect 409 withcustomer_portal_urlPOST /api/invoice-requestfor renewal → expect 200 (allowed re-subscribe)Follow-up: direct-link join flow with payment chooser
The next UX iteration (filed separately): replace per-invite tokens with shareable
/joinlinks that include a tier hint, walk WorkOS sign-in/sign-up, render the agreement, then offer card / invoice / wire as payment method choices. See the linked issue.🤖 Generated with Claude Code