Repository navigation
fix(billing): /sync picks membership sub, not subscriptions.data[0] (#3623 step 2) - #3646
Merged
Merged
Conversation
…3623 step 2) POST /api/admin/accounts/:orgId/sync was reading customer.subscriptions.data[0] to derive the org's subscription state. Stripe doesn't guarantee subscription ordering — when a customer has a non-membership sub (one-off product, future ancillary sub) stacked alongside a real membership, the wrong sub could win and the org row would be overwritten with the non-membership sub's state, including its lookup_key, amount, and status. Verified against the sandbox multi_sub fixture: Stripe returns the non-membership (aao_sandbox_event_ticket) sub first in customer.subscriptions.data; old data[0] picks it; new pickMembershipSub picks aao_membership_explorer_50 regardless of order. Extracts pickMembershipSub + isMembershipLookupKey into server/src/billing/membership-prices.ts so the integrity invariant (stripe-sub-reflected-in-org-row, merged in #3627) and /sync now share one predicate. Future cron auto-remediator will reuse the same module. Tests: 21-case unit test on the helper covering isMembershipLookupKey predicate (including null/empty), isMembershipSub on Stripe.Subscription shape, and pickMembershipSub order-independence + active-over-trialing tiebreak. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The fixture's mock subscription was missing `lookup_key` on its price. Now that /sync filters subs by membership lookup_key prefix (#3623 step 2), a sub without one falls through to the invoice-fallback branch — which the existing test scenarios don't exercise. Real Stripe membership prices always carry a lookup_key (the checkout flow creates them via products with `aao_membership_*` keys), so the fixture was under-spec. Adds `lookup_key: 'aao_membership_professional_250'` so the four revenue_events backfill tests reach the subscription-update branch the fixture was originally written for. No behavior change to /sync. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
This was referenced Apr 30, 2026
bokelley
added a commit
that referenced
this pull request
Apr 30, 2026
…sub on link (#3623 step 4) (#3681) * fix(billing): clear subscription state on unlink + filter membership sub on link (#3623 step 4) Two bugs in admin Stripe-customer link/unlink endpoints surfaced by the Lina/HYPD/Yoshihiko investigation in #3623: 1. POST /api/admin/stripe-customers/:customerId/unlink was setting stripe_customer_id = NULL but leaving every other subscription_* column intact. After unlink, the org row continued to show as a paying member with no Stripe link — entitlement gates would silently grant access on stale state until a webhook fired (which never does, since the customer is no longer attached). Now clears all subscription_* fields and invalidates the membership cache. 2. POST /api/admin/stripe-customers/:customerId/link had the same subscriptions.data[0] bug as /sync (fixed in #3646) — picks the first sub regardless of whether it's a membership sub. A customer with a non-membership sub stacked alongside a real membership would have its row overwritten with the wrong sub's state. Now uses pickMembershipSub to filter to the membership sub before passing to buildSubscriptionUpdate. Both fixes harden the customer-relink admin path that produced the production drift (Lina's customer was relinked between orgs by an audit script that didn't transfer subscription state). Future relinks via the admin UI will now do the right thing. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(billing): close webhook re-link race + audit trail on link/unlink (#3681 review fix) Security review of #3681 found two HIGH-severity issues: 1. Concurrent webhook re-creates state the unlink just cleared. The previous version nulled stripe_customer_id + subscription_* columns but didn't clear the Stripe customer's metadata.workos_organization_id. resolveOrgForStripeCustomer falls back to the metadata field on cache miss — so the next webhook for the unlinked customer would silently re-link the org we just unlinked, then re-populate subscription state from the upstream sub. Net: an admin who unlinks to revoke entitlement watches the org silently re-acquire it within minutes. Now mirrors the link path's metadata-clear at billing.ts:697. 2. No audit trail on entitlement-affecting admin actions. Both /unlink and the force-replace branch of /link only wrote logger.info. A compromised admin token could mass-unlink paying members with no DB-side forensic record. Now writes registry_audit_log entries (admin_stripe_unlink, admin_stripe_link_replace, admin_stripe_link) including prior subscription_status, prior tier, prior subscription_id, and admin email in details. Audit write failures log but don't fail the action — forensic record is best-effort. Plus one MEDIUM from javascript-protocol-expert: 3. Force-replace with no-membership-sub leaves stale state. When force-replacing a customer where the new customer has no membership sub, the old code skipped the UPDATE entirely — so subscription_status etc. stayed populated from the previous customer. Now explicitly clears subscription_* columns and membership_tier in that branch. All three issues stem from "the unlink/link admin endpoints don't fully transfer or clear billing state when ownership of a Stripe customer changes" — same root pattern as the original Lina drift, just on the admin side instead of the audit-script side. 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
Fixes a latent bug in
POST /api/admin/accounts/:orgId/syncwherecustomer.subscriptions.data[0]could pick a non-membership sub stacked alongside a real membership and overwrite the org row with the wrong state. Verified end-to-end against the sandboxmulti_subfixture from #3643.The bug
server/src/routes/admin/accounts-billing.ts:144(now fixed):Stripe doesn't guarantee subscription ordering. A customer who pays for a membership AND has any non-membership sub (one-off product, future ancillary sub) can end up with the wrong sub at index 0.
/syncwould then write the non-membership sub'sstatus,amount,lookup_key, etc. to the org row — clobbering a paying member with a one-off product's state.Reproduction (against the sandbox shipped in #3643)
Stripe returns the non-membership sub first; old
data[0]would pick it.What changed
New module
server/src/billing/membership-prices.ts— single source of truth for "is this a membership lookup_key" + sub-picker. Replaces the inline prefix-list in the integrity invariant and is called from/sync.isMembershipLookupKey(key)— true when key starts withaao_membership_oraao_invoice_isMembershipSub(sub)— true when first item is a membership-priced subpickMembershipSub(subs)— returns the membership sub, preferringactiveover other live statuses for stable tiebreakaccounts-billing.ts:/syncnow callspickMembershipSubinstead of indexingdata[0]. When no membership sub is found, falls through to the existing invoice-fallback branch (preserving prior behavior for invoice-billed orgs).stripe-sub-reflected-in-org-rowinvariant (merged in audit: detect Stripe→DB drift (Lina-class missed-webhook) (closes detect path of #3623) #3627) refactored to import the shared helper. Behavior unchanged; just DRYs up the prefix list.What it deliberately doesn't do
productMetadata.category === 'membership'which the helper doesn't model. Out of scope for this PR — separate cleanup if desired.http.ts:3725-3850. That path receives a single subscription from Stripe directly; it doesn't pick from a list.Test plan
npx vitest run tests/unit/billing/membership-prices.test.tsnpx vitest run tests/unit/integrity/npx tsc --noEmitcleanmulti_subfixture: bug reproduced + fix confirmedRefs
multi_subfixture this PR validates against)🤖 Generated with Claude Code