Repository navigation
Description
Problem
PR #3183 closed the millisecond intake race for the two routes that directly mint a Stripe subscription (`POST /api/invoice-request` and `POST /api/invite/:token/accept`) by wrapping them in a per-org Postgres advisory lock.
`POST /api/checkout-session` was deliberately left out because the actual subscription doesn't get created until the user completes Stripe's hosted checkout page. Two concurrent calls produce two session URLs, not two subscriptions. The duplicate-sub case only materializes if the user pays on both sessions.
That's a real (if narrow) gap. The cross-path version is also real:
T+0: user opens dashboard, clicks "Pay by card" → checkout-session #1 minted, no sub yet on Stripe
T+10ms: admin pastes invite-accept link in Slack, user clicks it
T+11ms: invite-accept route takes advisory lock, runs blockIfActiveSubscription
→ Stripe still has no sub (session #1 incomplete)
→ guard passes, mints invoice-driven sub via createAndSendInvoice
T+20ms: user goes back to first tab, completes Stripe Checkout #1 → second sub created
The advisory lock can't see this because the in-flight checkout-session has no Stripe-side state to read until the user pays.
Fix: webhook-side dedup
The right place to close this is in the `customer.subscription.created` webhook handler. By the time the webhook fires, Stripe has already created the second sub on the customer — so we can detect it and act.
`server/src/http.ts:3450` is where the subscription-created event is processed. Add:
case 'customer.subscription.created': {
const subscription = event.data.object as Stripe.Subscription;
const customerId = subscription.customer as string;
// Reject if the customer already has another active subscription. Stripe
// already accepted this one, so we cancel it and refund any charge.
const existing = await stripe.subscriptions.list({
customer: customerId,
status: 'active',
limit: 10,
});
const otherActive = existing.data.filter(s => s.id !== subscription.id);
if (otherActive.length > 0) {
logger.error({
newSubId: subscription.id,
existingSubIds: otherActive.map(s => s.id),
customerId,
}, 'Refusing duplicate subscription on customer that already has active sub');
await stripe.subscriptions.cancel(subscription.id, { prorate: true });
notifySystemError({
source: 'stripe-subscription-dedup',
errorMessage: \`Duplicate subscription \${subscription.id} canceled; existing: \${otherActive.map(s => s.id).join(', ')}\`,
});
return res.status(200).send('ok'); // ack the webhook
}
// ... existing handler logic
}Why this isn't a blocker for #3183
- Triton's actual incident (months apart, sequential intake paths) is closed by the duplicate-sub guard from fix(billing): refuse to mint a duplicate subscription on an org #3171.
- The millisecond same-path race is closed by fix(billing): close intake race with per-org advisory lock (#3179) #3183.
- The remaining cross-path race needs the user to pay on both sessions, which requires entering card details twice on different Stripe Checkout pages within seconds. Realistic but rare.
- A periodic invariants check (separate effort) would catch any escapee.
Acceptance criteria
- `customer.subscription.created` webhook detects when the customer has another active subscription, cancels the new one with proration refund, and logs/alerts.
- The cancellation respects Stripe's webhook retry semantics (idempotent: re-firing the webhook produces the same outcome).
- Test case: simulate two webhook events arriving for the same customer in quick succession; assert second one is canceled.
- Logged + alerted (notifySystemError) so operators know a duplicate was caught.
References
- PR fix(billing): refuse to mint a duplicate subscription on an org #3171 — duplicate-subscription guard
- PR fix(billing): close intake race with per-org advisory lock (#3179) #3183 — advisory-lock follow-up
- security review of fix(billing): close intake race with per-org advisory lock (#3179) #3183 finding M2 (Q6)
Activity
bokelley commentedon Apr 25, 2026
Triage
Classification: Bug (gap in subscription dedup after advisory lock)
Bucket(s): admin / ops tools (
server/src/http.tswebhook handler)Status: ready-for-human
What the experts said:
active(should beTIER_PRESERVING_STATUSES), idempotency gap on webhook retry, wrong placement (new case would shadow the existing 3-event handler),prorate: truedeprecated in SDK v10,res.send('ok')breaks response contract, no testscustomer.subscription.deleted, which the existing DB-update block processes unconditionally, overwritingorganizations.subscription_status → canceledandstripe_subscription_id → duplicateand corrupting the legitimate record. External subscription creation on our Stripe customer (customer ID isn't secret) amplifies the attack surface.My take: Approach is sound, two architectural decisions need your call. Subscriptions our server creates do carry
workos_organization_idmetadata (stripe-client.ts:1129), so an ownership check is viable — but the DB-update guard and the cancel-with-no-proration tradeoff need an explicit choice before a PR can be written cleanly.The DB corruption path: dedup cancels
sub_B→ Stripe firescustomer.subscription.deletedforsub_B→ existing handler runs unconditionally →UPDATE organizations SET subscription_status='canceled', stripe_subscription_id='sub_B'→ org appears dead even thoughsub_Ais still active on Stripe.Option A — Full safe fix: ownership check + DB-update guard
Closes the external-sub and DB-corruption paths. Four files touched + tests.
Option B — Alert-only: detect but do not cancel
Gap stays open; finance catches via alert and cancels manually. No DB corruption risk. Simpler to ship, but leaves the cross-path race partially unresolved.
@bokelley, your call: Option A (full fix — safe to auto-execute once you confirm) or Option B (alert-only, faster to ship)?
Triaged by Claude Code. Session: https://claude.ai/code/cse_01XQiHh6mgiqqwWHGq6yS67q
Generated by Claude Code
feat(billing): webhook-side subscription dedup (#3184) (#3242)