Skip to content

Commit 09c0b11

Browse files
authored
fix(billing): refuse plan changes during a pro trial (#10520)
* fix(billing): refuse plan changes during a pro trial A trial's fixed allowance is counted per billing period, and a price change restarts Stripe's period, so switching monthly/yearly during a trial started the cap over each time. Refuse switch-plan (checked against the row and Stripe) and any personal /subscription/upgrade while a Pro trial runs. * fix(billing): scope the trial guard to personal pro, cover the stripe check * chore(tests): shrink the test-types baseline for the switch-plan route test
1 parent fb7d9e5 commit 09c0b11

6 files changed

Lines changed: 145 additions & 26 deletions

File tree

‎apps/sim/app/api/billing/switch-plan/route.test.ts‎

Lines changed: 110 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,26 @@ import { authMockFns, createMockRequest, resetEnvFlagsMock, setEnvFlags } from '
22
import { billingAccessMock, billingAccessMockFns } from '@sim/testing/mocks/billing-access.mock'
33
import { billingCoreMock, billingCoreMockFns } from '@sim/testing/mocks/billing-core.mock'
44
import { billingOrganizationMock } from '@sim/testing/mocks/billing-organization.mock'
5-
import { billingPlanMock } from '@sim/testing/mocks/billing-plan.mock'
5+
import { billingPlanMock, billingPlanMockFns } from '@sim/testing/mocks/billing-plan.mock'
66
import { billingSubscriptionMock } from '@sim/testing/mocks/billing-subscription.mock'
77
import { posthogServerMock } from '@sim/testing/mocks/posthog-server.mock'
8+
import { stripeClientMock } from '@sim/testing/mocks/stripe.mock'
89
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
910

10-
const { mockCanManageWorkspaceBilling, mockGetWorkspaceHostContextForViewer } = vi.hoisted(() => ({
11+
const {
12+
mockCanManageWorkspaceBilling,
13+
mockGetWorkspaceHostContextForViewer,
14+
mockClaimCheckoutAdmission,
15+
mockReleaseCheckoutAdmission,
16+
mockReadSwitchBasis,
17+
mockRecordPlanSwitch,
18+
} = vi.hoisted(() => ({
1119
mockCanManageWorkspaceBilling: vi.fn(),
1220
mockGetWorkspaceHostContextForViewer: vi.fn(),
21+
mockClaimCheckoutAdmission: vi.fn(),
22+
mockReleaseCheckoutAdmission: vi.fn(),
23+
mockReadSwitchBasis: vi.fn(),
24+
mockRecordPlanSwitch: vi.fn(),
1325
}))
1426

1527
vi.mock('@/lib/billing/core/access', () => billingAccessMock)
@@ -22,6 +34,26 @@ vi.mock('@/lib/billing/core/plan', () => billingPlanMock)
2234

2335
vi.mock('@/lib/billing/core/subscription', () => billingSubscriptionMock)
2436

37+
vi.mock('@/lib/billing/stripe-client', () => stripeClientMock)
38+
39+
vi.mock('@/lib/billing/checkout-admission', () => ({
40+
claimCheckoutAdmission: mockClaimCheckoutAdmission,
41+
releaseCheckoutAdmission: mockReleaseCheckoutAdmission,
42+
}))
43+
44+
vi.mock('@/lib/billing/plans', () => ({
45+
getPlanByName: (name: string) => ({
46+
name,
47+
priceId: 'price-month',
48+
annualDiscountPriceId: 'price-year',
49+
}),
50+
}))
51+
52+
vi.mock('@/lib/billing/core/plan-switch', () => ({
53+
readSwitchBasis: mockReadSwitchBasis,
54+
recordPlanSwitch: mockRecordPlanSwitch,
55+
}))
56+
2557
vi.mock('@/lib/billing/workspace-permissions', () => ({
2658
canManageWorkspaceBilling: mockCanManageWorkspaceBilling,
2759
}))
@@ -34,7 +66,9 @@ vi.mock('@/lib/workspaces/host-context', () => ({
3466

3567
import { POST } from '@/app/api/billing/switch-plan/route'
3668

37-
const { mockGetOrganizationSubscription } = billingCoreMockFns
69+
const { mockGetOrganizationSubscription, mockIsSubscriptionOrgScoped } = billingCoreMockFns
70+
71+
const routeContext = { params: Promise.resolve({}) }
3872

3973
const { mockGetEffectiveBillingStatus } = billingAccessMockFns
4074

@@ -96,7 +130,8 @@ describe('POST /api/billing/switch-plan', () => {
96130
createMockRequest('POST', {
97131
targetPlanName: 'enterprise',
98132
workspaceId: 'workspace-1',
99-
})
133+
}),
134+
routeContext
100135
)
101136

102137
expect(response.status).toBe(400)
@@ -105,4 +140,75 @@ describe('POST /api/billing/switch-plan', () => {
105140
})
106141
expect(mockGetEffectiveBillingStatus).not.toHaveBeenCalled()
107142
})
143+
144+
describe('during a Pro free trial', () => {
145+
const personalPro = (status: string) => ({
146+
id: 'subscription-1',
147+
referenceId: 'viewer-1',
148+
plan: 'pro_6000',
149+
status,
150+
stripeSubscriptionId: 'stripe-subscription-1',
151+
})
152+
const mockStripeUpdate = vi.fn()
153+
154+
beforeEach(() => {
155+
mockGetEffectiveBillingStatus.mockResolvedValue({
156+
billingBlocked: false,
157+
billingBlockedReason: null,
158+
blockedByOrgOwner: false,
159+
})
160+
mockIsSubscriptionOrgScoped.mockResolvedValue(false)
161+
mockClaimCheckoutAdmission.mockResolvedValue({ claimToken: 'claim-1' })
162+
stripeClientMock.requireStripeClient.mockReturnValue({
163+
subscriptions: {
164+
retrieve: vi.fn().mockResolvedValue({
165+
status: 'trialing',
166+
items: {
167+
data: [{ id: 'item-1', price: { id: 'price-1', recurring: { interval: 'month' } } }],
168+
},
169+
}),
170+
update: mockStripeUpdate,
171+
},
172+
})
173+
})
174+
175+
it.each([
176+
{ label: 'a tier change', targetPlanName: 'pro_25000', interval: undefined },
177+
{ label: 'an interval change', targetPlanName: 'pro_6000', interval: 'year' },
178+
])('refuses $label before touching Stripe', async (switchCase) => {
179+
billingPlanMockFns.mockGetHighestPrioritySubscription.mockResolvedValue(
180+
personalPro('trialing')
181+
)
182+
183+
const response = await POST(
184+
createMockRequest('POST', {
185+
targetPlanName: switchCase.targetPlanName,
186+
interval: switchCase.interval,
187+
}),
188+
routeContext
189+
)
190+
191+
expect(response.status).toBe(409)
192+
await expect(response.json()).resolves.toMatchObject({
193+
error: expect.stringContaining('free trial ends'),
194+
})
195+
expect(stripeClientMock.requireStripeClient).not.toHaveBeenCalled()
196+
})
197+
198+
it('refuses a switch Stripe still holds in trial while the row has moved on', async () => {
199+
const subscription = personalPro('active')
200+
billingPlanMockFns.mockGetHighestPrioritySubscription.mockResolvedValue(subscription)
201+
mockReadSwitchBasis.mockResolvedValue({ subscription, pool: undefined })
202+
203+
const response = await POST(
204+
createMockRequest('POST', { targetPlanName: 'pro_6000', interval: 'year' }),
205+
routeContext
206+
)
207+
208+
expect(response.status).toBe(409)
209+
expect(mockStripeUpdate).not.toHaveBeenCalled()
210+
expect(mockRecordPlanSwitch).not.toHaveBeenCalled()
211+
expect(mockReleaseCheckoutAdmission).toHaveBeenCalledWith({ claimToken: 'claim-1' })
212+
})
213+
})
108214
})

‎apps/sim/app/api/billing/switch-plan/route.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { type NextRequest, NextResponse } from 'next/server'
66
import { billingSwitchPlanContract } from '@/lib/api/contracts/subscription'
77
import { parseRequest } from '@/lib/api/server'
88
import { getSession } from '@/lib/auth'
9+
import { TRIAL_PLAN_CHANGE_MESSAGE } from '@/lib/billing/authorization'
910
import {
1011
type CheckoutAdmissionClaim,
1112
claimCheckoutAdmission,
@@ -19,13 +20,14 @@ import {
1920
getHighestPrioritySubscription,
2021
} from '@/lib/billing/core/plan'
2122
import { readSwitchBasis, recordPlanSwitch } from '@/lib/billing/core/plan-switch'
22-
import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
23+
import { getPlanTierCredits, getPlanType, isEnterprise, isPro } from '@/lib/billing/plan-helpers'
2324
import { getPlanByName } from '@/lib/billing/plans'
2425
import { requireStripeClient } from '@/lib/billing/stripe-client'
2526
import {
2627
hasUsableSubscriptionAccess,
2728
hasUsableSubscriptionStatus,
2829
isOrgScopedSubscription,
30+
isTrialingSubscription,
2931
} from '@/lib/billing/subscriptions/utils'
3032
import { canManageWorkspaceBilling } from '@/lib/billing/workspace-permissions'
3133
import { isBillingEnabled } from '@/lib/core/config/env-flags'
@@ -106,6 +108,13 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
106108
)
107109
}
108110

111+
// A Pro trial's fixed allowance is counted per billing period, and a price change restarts the
112+
// period, so a switch during the trial would start the cap over. Pro is only ever personal.
113+
const isProPlan = isPro(sub.plan)
114+
if (isProPlan && isTrialingSubscription(sub)) {
115+
return NextResponse.json({ error: TRIAL_PLAN_CHANGE_MESSAGE }, { status: 409 })
116+
}
117+
109118
const targetPlan = getPlanByName(targetPlanName)
110119
if (!targetPlan) {
111120
return NextResponse.json({ error: 'Target plan not found' }, { status: 400 })
@@ -156,6 +165,10 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
156165
if (!hasUsableSubscriptionStatus(stripeSubscription.status)) {
157166
return NextResponse.json({ error: 'Stripe subscription is not active' }, { status: 400 })
158167
}
168+
// The row can trail Stripe: a trial whose start webhook has not landed is still a trial.
169+
if (isProPlan && isTrialingSubscription(stripeSubscription)) {
170+
return NextResponse.json({ error: TRIAL_PLAN_CHANGE_MESSAGE }, { status: 409 })
171+
}
159172

160173
const subscriptionItem = stripeSubscription.items.data[0]
161174
if (!subscriptionItem) {

‎apps/sim/lib/auth/auth.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1225,7 +1225,7 @@ export const auth = betterAuth({
12251225
const checkoutAdmissionClaim = await claimCheckoutAdmission(referenceId)
12261226
try {
12271227
if (isPersonalCheckoutRequest(requestBody, sessionUserId)) {
1228-
await assertPersonalCheckoutAllowed(sessionUserId, requestBody.plan)
1228+
await assertPersonalCheckoutAllowed(sessionUserId)
12291229
}
12301230
} catch (error) {
12311231
await releaseCheckoutAdmission(checkoutAdmissionClaim)

‎apps/sim/lib/billing/authorization.ts‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -118,21 +118,27 @@ export function assertSelfServeCheckoutRequest(body: {
118118
}
119119
}
120120

121-
/** Refuse an organization-plan upgrade while the account's own Pro plan is still in its free trial. */
121+
/**
122+
* Refuse any plan change while the account's own Pro plan is in its free trial. A trial's allowance
123+
* is a fixed cap counted per billing period, and a price change restarts Stripe's period, so a
124+
* change during the trial would start the cap over. A Team upgrade would also keep the trial,
125+
* running the team free without the trial's cap.
126+
*/
122127
async function assertNoPersonalTrial(userId: string): Promise<void> {
123128
const trialing = await db
124129
.select({ plan: subscription.plan })
125130
.from(subscription)
126131
.where(and(eq(subscription.referenceId, userId), eq(subscription.status, 'trialing')))
127132
if (!trialing.some((row) => isPro(row.plan))) return
128133

129-
logger.warn('Blocking team upgrade - personal plan is in its free trial', { userId })
130-
throw new APIError('CONFLICT', {
131-
message:
132-
'Your Pro free trial has to end before you can move to a Team plan. End it from Settings > Billing (restore it first if you canceled it), or wait for it to end, then upgrade.',
133-
})
134+
logger.warn('Blocking plan change - personal plan is in its free trial', { userId })
135+
throw new APIError('CONFLICT', { message: TRIAL_PLAN_CHANGE_MESSAGE })
134136
}
135137

138+
/** Why a plan change is refused during a free trial, and how to get past it. */
139+
export const TRIAL_PLAN_CHANGE_MESSAGE =
140+
'Your plan can change once your Pro free trial ends. End the trial from Settings > Billing (restore it first if you canceled it), or wait for it to end, then change your plan.'
141+
136142
/**
137143
* Classify a `/subscription/upgrade` request as a personal checkout using
138144
* the same reference resolution as the Better Auth Stripe plugin
@@ -161,9 +167,8 @@ export function isPersonalCheckoutRequest(
161167
*
162168
* Blocks an account AWS Marketplace bills, a bound, incomplete Stripe
163169
* subscription, a member already covered by an entitled organization
164-
* subscription, and a Team upgrade of a Pro free trial: Stripe keeps the trial
165-
* across the price change, so the team would run free without the trial's
166-
* capped allowance. Throws {@link APIError} with a user-facing message; the
170+
* subscription, and any plan change during a Pro free trial
171+
* ({@link assertNoPersonalTrial}). Throws {@link APIError} with a user-facing message; the
167172
* checkout UI surfaces it as-is.
168173
*
169174
* Called from the Better Auth `hooks.before` middleware, NOT from
@@ -174,12 +179,10 @@ export function isPersonalCheckoutRequest(
174179
* Fails closed: when coverage cannot be determined, the checkout is
175180
* rejected rather than risking a duplicate subscription.
176181
*/
177-
export async function assertPersonalCheckoutAllowed(userId: string, plan?: unknown): Promise<void> {
182+
export async function assertPersonalCheckoutAllowed(userId: string): Promise<void> {
178183
await assertNotBilledThroughMarketplace(userId)
179184
await assertNoBoundIncompleteSubscription(userId)
180-
if (isOrgPlan(normalizeCheckoutPlan(plan))) {
181-
await assertNoPersonalTrial(userId)
182-
}
185+
await assertNoPersonalTrial(userId)
183186

184187
const coverage = await getOrganizationCoverageForMember(userId)
185188

‎apps/sim/lib/billing/trial.integration.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -566,12 +566,12 @@ describe('the usage limit card', () => {
566566
})
567567
})
568568

569-
describe('a Team upgrade during a Pro trial', () => {
570-
it('is refused while the personal Pro plan is still trialing', async () => {
569+
describe('a personal checkout during a Pro trial', () => {
570+
it('is refused while the personal Pro plan is still trialing, so the trial cap never restarts', async () => {
571571
const userId = await createUser()
572572
await addSubscription(userId, { status: 'trialing', trialStart: new Date() })
573573

574-
await expect(assertPersonalCheckoutAllowed(userId, 'team_8000')).rejects.toMatchObject({
574+
await expect(assertPersonalCheckoutAllowed(userId)).rejects.toMatchObject({
575575
status: 'CONFLICT',
576576
})
577577
})
@@ -580,6 +580,6 @@ describe('a Team upgrade during a Pro trial', () => {
580580
const userId = await createUser()
581581
await addSubscription(userId, { status: 'active' })
582582

583-
await expect(assertPersonalCheckoutAllowed(userId, 'team_8000')).resolves.toBeUndefined()
583+
await expect(assertPersonalCheckoutAllowed(userId)).resolves.toBeUndefined()
584584
})
585585
})

‎scripts/check-test-types.baseline.json‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,6 @@
5353
"apps/sim/app/api/billing/route.test.ts": {
5454
"TS2554": 4
5555
},
56-
"apps/sim/app/api/billing/switch-plan/route.test.ts": {
57-
"TS2554": 1
58-
},
5956
"apps/sim/app/api/billing/update-cost/route.test.ts": {
6057
"TS2554": 50
6158
},

0 commit comments

Comments
 (0)