Skip to content

fix(billing): clear subscription state on unlink + filter membership sub on link (#3623 step 4) - #3681

Merged
bokelley merged 2 commits into
mainfrom
bokelley/relink-sync
Apr 30, 2026
Merged

bokelley merged 2 commits into
mainfrom
bokelley/relink-sync

Conversation

@bokelley

Copy link
Copy Markdown
Contributor

Summary

Two bugs in the admin Stripe-customer link/unlink endpoints, both surfaced by the Lina/HYPD/Yoshihiko investigation in #3623.

Bug 1: /unlink left orgs showing as paying members

POST /api/admin/stripe-customers/:customerId/unlink (server/src/routes/billing.ts:798) was:

UPDATE organizations SET stripe_customer_id = NULL WHERE stripe_customer_id = $1

Cleared the customer link but left every other subscription_* column intact. After an unlink:

  • subscription_status still says 'active'
  • stripe_subscription_id still references the now-detached Stripe sub
  • effective_membership.is_member still returns true
  • Entitlement gates silently grant access until something fires another webhook — which never happens, because the customer is no longer attached

Fix: clear all subscription_* fields in the same UPDATE + invalidate the membership cache.

Bug 2: /link had the same data[0] bug as /sync

Line 726 of the link endpoint had const subscription = subscriptions.data[0] — same bug as /sync fixed in #3646. A customer with a non-membership sub stacked alongside a real membership would get the wrong sub written to the org row. Now uses pickMembershipSub from server/src/billing/membership-prices.ts.

Why this matters

The Stripe diagnosis (in #3663 PR description) showed that the production drift on Lina/HYPD/Yoshihiko wasn't from missed webhooks — it was from a one-off audit script (now gone) that re-linked Stripe customers between orgs without transferring subscription state. That script bypassed these admin endpoints. But the endpoints themselves had bugs that would have produced similar artifacts on any future force-relink-via-UI scenario:

  • /link picks the wrong sub for multi-sub customers → wrong state written to new org
  • /unlink doesn't clean up state → org left in zombie "member without customer" state

This PR closes those.

Test plan

  • npx tsc --noEmit clean
  • 78 unit tests pass (5 test files)
  • Pre-commit hook (unit + dynamic imports + typecheck) passes
  • Manual: in the sandbox, unlink the lina_class customer → verify subscription_status, stripe_subscription_id, subscription_amount all NULL; relink → verify state restored

Refs

🤖 Generated with Claude Code

bokelley and others added 2 commits April 30, 2026 11:35
…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]>
…#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]>
@bokelley

Copy link
Copy Markdown
Contributor Author

Security review pass — pushed fix commit (1d5cac7)

Three issues found by experts and addressed:

HIGH — concurrent webhook re-link race: previous unlink path nulled stripe_customer_id but didn't clear the Stripe customer's metadata.workos_organization_id. resolveOrgForStripeCustomer falls back to that metadata field — so the next webhook for the unlinked customer would silently re-link and re-populate state. An admin's revocation could be undone within minutes. Now mirrors the link path's metadata-clear (billing.ts:697).

HIGH — no audit trail on entitlement-affecting admin actions: both /unlink and the force-replace branch of /link only wrote logger.info. Now writes registry_audit_log entries (admin_stripe_unlink, admin_stripe_link_replace, admin_stripe_link) with prior state (subscription_status, tier, sub_id) and admin email.

MEDIUM — force-replace with no-membership-sub left stale state: when force-replacing a customer where the new customer has no membership sub, the old code skipped the UPDATE entirely — subscription_status etc. stayed populated from the previous customer. Now explicitly clears those fields in that branch.

Other expert feedback (deferred): the stripe_events table I'd planned next was challenged on (a) silent-swallow promotion (handler catch-blocks that don't re-throw would get permanently marked as processed), (b) PII retention of full webhook payloads, (c) misprioritization vs. catch-block audit. Skipping that PR; will replace with a catch-block audit in handle-subscription-created.ts and a customer-relink path test.

@bokelley
bokelley merged commit 72ba4e7 into main Apr 30, 2026
13 checks passed
@bokelley
bokelley deleted the bokelley/relink-sync branch April 30, 2026 15:55
bokelley added a commit that referenced this pull request Apr 30, 2026
…atch (#3691 review fix)

Two issues from expert review of #3691:

M1 — .deleted audit log was not in its own try/catch.
The subscription_cancelled audit_log + org_activities INSERTs at
http.ts:3939+3956 were `await`ed inside the outer try/catch which
swallowed errors. If those INSERTs failed transiently (DB blip, race),
the failure jumped to the outer swallow and no row was ever recorded —
worst-of-both-worlds: subscription_status update committed (separate
write earlier), audit/activity row missing, Stripe sees 200 and never
retries. Wraps each in its own try/catch with notifySystemError so
the gap is observable. The outer swallow stays for the rest of the
non-idempotent side effects.

M2 — admin unlink left step-3 webhook fallback open.
#3681 cleared customer.metadata.workos_organization_id on unlink, but
resolveOrgForStripeCustomer has THREE fallback paths:
  1. DB stripe_customer_id (cleared by the unlink UPDATE)
  2. customer.metadata.workos_organization_id (cleared in #3681)
  3. subscription.metadata.workos_organization_id ← still open
A webhook for one of the customer's subs would walk to step 3 and
silently re-link the org. Unlink now lists active subs and clears
their workos_organization_id metadata too — only the subs that have
the key set, so we don't burn Stripe API calls on subs without it.

Adds an integration test that asserts the metadata-clear is called
on the right subs (and skipped on subs without the key), proving
the wire-up not just for customer.metadata but also subscription.metadata.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
bokelley added a commit that referenced this pull request Apr 30, 2026
…ntegration tests (#3623 step 5) (#3691)

* fix(billing): re-throw on core subscription UPDATE failure (#3623 step 5)

The customer.subscription.* webhook handler in http.ts wrapped the
core column UPDATE plus all downstream side effects in a single
try/catch that returned 200 on any error. If the UPDATE itself
failed (DB outage, constraint violation, race), Stripe never
retried and the org row was left silently stale — the silent-swallow
path js-protocol-expert and security-reviewer warned about during
the #3681 review.

Hoists the core UPDATE outside the swallow-on-error block. UPDATE
on a single row by primary key is idempotent — exception now
propagates so Stripe retries. Downstream side effects (tier-change
enforcement, welcome DMs, autopublish, .deleted audit/activities)
keep their existing log+continue pattern because they're non-idempotent
and a Stripe retry would refire them.

Adds server/tests/integration/admin-stripe-link-unlink.test.ts (5
tests) covering the link/unlink hardening from #3681 + #3692:
- link picks the membership sub when customer has multi-sub
- link writes admin_stripe_link audit log
- unlink clears all subscription_* columns
- unlink clears Stripe customer metadata.workos_organization_id
  (closes the webhook re-link race)
- unlink writes admin_stripe_unlink audit log with prior state

Out-of-scope follow-up identified: the same silent-swallow pattern
exists at http.ts:4195 (revenue_events INSERT in invoice.paid) and
lines 4393, 4469, 4506. revenue_events.stripe_invoice_id already
has a UNIQUE constraint so retries are safe; the right fix is
ON CONFLICT (stripe_invoice_id) DO NOTHING plus re-throw on real
errors. Tracked separately rather than expanding this PR.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(billing): close step-3 webhook re-link fallback + audit-log try/catch (#3691 review fix)

Two issues from expert review of #3691:

M1 — .deleted audit log was not in its own try/catch.
The subscription_cancelled audit_log + org_activities INSERTs at
http.ts:3939+3956 were `await`ed inside the outer try/catch which
swallowed errors. If those INSERTs failed transiently (DB blip, race),
the failure jumped to the outer swallow and no row was ever recorded —
worst-of-both-worlds: subscription_status update committed (separate
write earlier), audit/activity row missing, Stripe sees 200 and never
retries. Wraps each in its own try/catch with notifySystemError so
the gap is observable. The outer swallow stays for the rest of the
non-idempotent side effects.

M2 — admin unlink left step-3 webhook fallback open.
#3681 cleared customer.metadata.workos_organization_id on unlink, but
resolveOrgForStripeCustomer has THREE fallback paths:
  1. DB stripe_customer_id (cleared by the unlink UPDATE)
  2. customer.metadata.workos_organization_id (cleared in #3681)
  3. subscription.metadata.workos_organization_id ← still open
A webhook for one of the customer's subs would walk to step 3 and
silently re-link the org. Unlink now lists active subs and clears
their workos_organization_id metadata too — only the subs that have
the key set, so we don't burn Stripe API calls on subs without it.

Adds an integration test that asserts the metadata-clear is called
on the right subs (and skipped on subs without the key), proving
the wire-up not just for customer.metadata but also subscription.metadata.

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