Skip to content

fix(billing): refuse to mint a duplicate subscription on an org - #3171

Merged
bokelley merged 2 commits into
mainfrom
bokelley/dup-sub-guard
Apr 25, 2026
Merged

bokelley merged 2 commits into
mainfrom
bokelley/dup-sub-guard

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

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.ts exporting blockIfActiveSubscription(orgId, orgDb, returnUrl). Returns null when 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.ts
  • POST /api/invoice-request — server/src/routes/billing-public.ts
  • POST /api/invite/:token/accept — server/src/routes/invites.ts

Blocking 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 createCustomerPortalSession and Addie's get_billing_portal tool). The 409 includes customer_portal_url so 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 — clean
  • npm run test:unit — 834/834
  • npm run test:server-unit — 2208/2208 (10 new)

Test plan (manual)

  • As an existing active member, hit POST /api/checkout-session for any tier → expect 409 with customer_portal_url
  • As an existing active member, click an invite link from another tier and accept → expect 409 (would have created Triton-style duplicate)
  • As a canceled member, hit POST /api/invoice-request for renewal → expect 200 (allowed re-subscribe)
  • As a brand-new prospect, accept an invite → expect 200 (unchanged behavior)

Follow-up: direct-link join flow with payment chooser

The next UX iteration (filed separately): replace per-invite tokens with shareable /join links 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

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]>
@bokelley

Copy link
Copy Markdown
Contributor Author

Issue #3181 proposes auditing the Stripe Customer Portal configuration for grandfathered-pricing safety (subscription_update exposure, possible createCustomerPortalSession product-list restriction) — same billing surface as this PR; consider folding before merge or confirm follow-up.


Triaged by Claude Code. Session: https://claude.ai/code/session_01E33kYH6pf47j9hHiFn5pWr


Generated by Claude Code

@bokelley

Copy link
Copy Markdown
Contributor Author

Issue #3179 proposes a Postgres advisory lock on hashtext(orgId) to close a millisecond-scale concurrent intake race on the same guard — same surface as this PR (active-subscription-guard.ts); consider folding before merge or confirm follow-up.


Generated by Claude Code

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant