Repository navigation
fix(billing): clear subscription state on unlink + filter membership sub on link (#3623 step 4) - #3681
Conversation
…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]>
Security review pass — pushed fix commit (1d5cac7)Three issues found by experts and addressed: HIGH — concurrent webhook re-link race: previous unlink path nulled HIGH — no audit trail on entitlement-affecting admin actions: both 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 — Other expert feedback (deferred): the |
…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]>
…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]>
Summary
Two bugs in the admin Stripe-customer link/unlink endpoints, both surfaced by the Lina/HYPD/Yoshihiko investigation in #3623.
Bug 1:
/unlinkleft orgs showing as paying membersPOST /api/admin/stripe-customers/:customerId/unlink(server/src/routes/billing.ts:798) was:Cleared the customer link but left every other
subscription_*column intact. After an unlink:subscription_statusstill says'active'stripe_subscription_idstill references the now-detached Stripe subeffective_membership.is_memberstill returns trueFix: clear all subscription_* fields in the same UPDATE + invalidate the membership cache.
Bug 2:
/linkhad the samedata[0]bug as/syncLine 726 of the link endpoint had
const subscription = subscriptions.data[0]— same bug as/syncfixed 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 usespickMembershipSubfromserver/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:
/linkpicks the wrong sub for multi-sub customers → wrong state written to new org/unlinkdoesn't clean up state → org left in zombie "member without customer" stateThis PR closes those.
Test plan
npx tsc --noEmitcleanlina_classcustomer → verifysubscription_status,stripe_subscription_id,subscription_amountall NULL; relink → verify state restoredRefs
data[0]bug fixed in/sync), feat(billing): lazy reconcile on certification paywall hit (#3623 step 3) #3663 (lazy reconcile on paywall hit — covers the customer-facing impact at runtime)relinked_at: 2026-04-25on Lina's customer with no source-control trace of the script🤖 Generated with Claude Code