Skip to content

fix(billing): /sync picks membership sub, not subscriptions.data[0] (#3623 step 2) - #3646

Merged
bokelley merged 2 commits into
mainfrom
bokelley/stripe-data0-fix
Apr 30, 2026
Merged

bokelley merged 2 commits into
mainfrom
bokelley/stripe-data0-fix

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Summary

Fixes a latent bug in POST /api/admin/accounts/:orgId/sync where customer.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 sandbox multi_sub fixture from #3643.

The bug

server/src/routes/admin/accounts-billing.ts:144 (now fixed):

const subscription = subscriptions.data[0];

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. /sync would then write the non-membership sub's status, 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)

$ npx tsx -e "<query multi_sub fixture>"
All subs on multi_sub customer:
  sub_1TRr5VH3X7K0BEHzbyxcy0h9  status=trialing  lookup=aao_sandbox_event_ticket
  sub_1TRr5TH3X7K0BEHzBo4qxV1Y  status=trialing  lookup=aao_membership_explorer_50

OLD (subscriptions.data[0]):  picks sub_1TRr5V… lookup=aao_sandbox_event_ticket   ❌
NEW (pickMembershipSub):       picks sub_1TRr5T… lookup=aao_membership_explorer_50  ✓

Stripe returns the non-membership sub first; old data[0] would pick it.

What changed

  1. 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 with aao_membership_ or aao_invoice_
    • isMembershipSub(sub) — true when first item is a membership-priced sub
    • pickMembershipSub(subs) — returns the membership sub, preferring active over other live statuses for stable tiebreak
  2. accounts-billing.ts:/sync now calls pickMembershipSub instead of indexing data[0]. When no membership sub is found, falls through to the existing invoice-fallback branch (preserving prior behavior for invoice-billed orgs).

  3. stripe-sub-reflected-in-org-row invariant (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

  • Doesn't refactor the invoice-fallback branch's inline check (line 202-211). That branch ALSO checks productMetadata.category === 'membership' which the helper doesn't model. Out of scope for this PR — separate cleanup if desired.
  • Doesn't change webhook subscription-update handling in http.ts:3725-3850. That path receives a single subscription from Stripe directly; it doesn't pick from a list.
  • Doesn't address the broader "auto-remediation skips agreement attestation" concern (security review H3 on Stripe-DB subscription reconciliation: catch missing-webhook drift, auto-remediate #3623). That's step 3 of Path B — separate PR after this.

Test plan

  • 21-case unit test on the helper: npx vitest run tests/unit/billing/membership-prices.test.ts
  • Existing integrity invariant tests still pass (46/46): npx vitest run tests/unit/integrity/
  • npx tsc --noEmit clean
  • Pre-commit hook (unit + dynamic imports + typecheck) passes
  • Manual verification against sandbox multi_sub fixture: bug reproduced + fix confirmed

Refs

🤖 Generated with Claude Code

bokelley and others added 2 commits April 30, 2026 06:01
…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]>
@bokelley
bokelley merged commit 56601f0 into main Apr 30, 2026
12 of 13 checks passed
@bokelley
bokelley deleted the bokelley/stripe-data0-fix branch April 30, 2026 11:22
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]>
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