diff --git a/src/main/billing/billing-client.test.ts b/src/main/billing/billing-client.test.ts index 9945e868426..0668aa56758 100644 --- a/src/main/billing/billing-client.test.ts +++ b/src/main/billing/billing-client.test.ts @@ -1,10 +1,8 @@ import { beforeEach, describe, expect, it } from 'vitest' import { OrcaCloudRequestError } from '../orca-profiles/cloud-auth/profile-cloud-client' import { - BillingServiceError, assertStripeHostedUrl, claimTrial, - createCheckoutUrl, createPortalUrl, BillingOrgMismatchError, fetchEntitlement, @@ -64,10 +62,13 @@ describe('billing client', () => { describe('EP-9: the token is for the team this device shows', () => { beforeEach(() => resetBillingExplicitOrgForTests()) - it('asks auth for this device\'s team explicitly and accepts a token for it', async () => { + it("asks auth for this device's team explicitly and accepts a token for it", async () => { const seen: Seen[] = [] const bt = jwt({ sub: 'u1', org: 'org_paid' }) - const fetchImpl = fakeFetch({ [endpoints.billingTokenEndpoint]: Response.json({ billingToken: bt, expiresAt: 1 }) }, seen) + const fetchImpl = fakeFetch( + { [endpoints.billingTokenEndpoint]: Response.json({ billingToken: bt, expiresAt: 1 }) }, + seen + ) expect(await mintBillingToken(endpoints, 'a', 'org_paid', fetchImpl)).toBe(bt) expect(seen[0]?.init?.body).toBe(JSON.stringify({ orgId: 'org_paid' })) }) @@ -75,15 +76,21 @@ describe('billing client', () => { it('refuses a token auth minted for another team (another device switched the shared active team)', async () => { const fetchImpl: typeof fetch = async () => Response.json({ billingToken: jwt({ sub: 'u1', org: 'org_eval' }), expiresAt: 1 }) - await expect(mintBillingToken(endpoints, 'a', 'org_paid', fetchImpl)).rejects.toBeInstanceOf(BillingOrgMismatchError) + await expect(mintBillingToken(endpoints, 'a', 'org_paid', fetchImpl)).rejects.toBeInstanceOf( + BillingOrgMismatchError + ) // A personal account never accepts a team token either. - await expect(mintBillingToken(endpoints, 'a', null, fetchImpl)).rejects.toBeInstanceOf(BillingOrgMismatchError) + await expect(mintBillingToken(endpoints, 'a', null, fetchImpl)).rejects.toBeInstanceOf( + BillingOrgMismatchError + ) }) it('treats 403 not_a_member as a team-switch error, not a session failure', async () => { const fetchImpl: typeof fetch = async () => new Response(JSON.stringify({ error: 'not_a_member' }), { status: 403 }) - await expect(mintBillingToken(endpoints, 'a', 'org_gone', fetchImpl)).rejects.toBeInstanceOf(BillingOrgMismatchError) + await expect(mintBillingToken(endpoints, 'a', 'org_gone', fetchImpl)).rejects.toBeInstanceOf( + BillingOrgMismatchError + ) }) it('falls back to the empty body on an older auth (400), still checking the claim', async () => { @@ -114,48 +121,6 @@ describe('billing client', () => { await expect(call).rejects.toBeInstanceOf(OrcaCloudRequestError) }) - it('reports billing refusals as BillingServiceError, never as a session failure', async () => { - const call = createCheckoutUrl( - endpoints, - 'bt', - { plan: 'team', interval: 'month', seats: 1 }, - fakeFetch({ - 'https://billing.example.test/v1/billing/checkout': Response.json( - { error: 'already_subscribed' }, - { status: 409 } - ) - }) - ) - await expect(call).rejects.toMatchObject({ - statusCode: 409, - errorCode: 'already_subscribed' - }) - await expect(call).rejects.toBeInstanceOf(BillingServiceError) - }) - - it('sends plan, interval and seats and returns the hosted Checkout URL', async () => { - const seen: Seen[] = [] - const url = await createCheckoutUrl( - endpoints, - 'bt', - { plan: 'team', interval: 'year', seats: 3 }, - fakeFetch( - { - 'https://billing.example.test/v1/billing/checkout': Response.json({ - url: 'https://checkout.stripe.com/c/pay/cs_test_1' - }) - }, - seen - ) - ) - expect(url).toBe('https://checkout.stripe.com/c/pay/cs_test_1') - expect(JSON.parse(String(seen[0]?.init?.body))).toEqual({ - plan: 'team', - interval: 'year', - seats: 3 - }) - }) - it('only opens Stripe-hosted pages', async () => { expect(assertStripeHostedUrl('https://billing.stripe.com/p/session/x')).toBe( 'https://billing.stripe.com/p/session/x' @@ -255,8 +220,13 @@ describe('billing client', () => { expect(unsafe.offers).toBeNull() // A portal cancel's end date (cancel_at) comes through; older services omit it. expect( - (await fetchEntitlement(endpoints, 'bt', response({ cancelAtPeriodEnd: true, cancelAt: 1797167516000 }))) - .cancelAt + ( + await fetchEntitlement( + endpoints, + 'bt', + response({ cancelAtPeriodEnd: true, cancelAt: 1797167516000 }) + ) + ).cancelAt ).toBe(1797167516000) expect((await fetchEntitlement(endpoints, 'bt', response({}))).cancelAt).toBeNull() // A plan this desktop doesn't know (a newer service) is still a plan, never "no plan". diff --git a/src/main/billing/billing-client.ts b/src/main/billing/billing-client.ts index c38521d3b35..08f14fee3ba 100644 --- a/src/main/billing/billing-client.ts +++ b/src/main/billing/billing-client.ts @@ -2,7 +2,6 @@ // then call the billing service with it. Pure (fetch injected) so it is testable without Electron. import { z } from 'zod' import type { - OrcaBillingCheckoutArgs, OrcaBillingEntitlement, OrcaBillingOverageArgs, OrcaBillingTeamPlan @@ -183,28 +182,6 @@ export async function fetchEntitlement( ) } -export async function createCheckoutUrl( - endpoints: BillingEndpoints, - token: string, - args: OrcaBillingCheckoutArgs, - fetchImpl: typeof fetch = fetch -): Promise { - const body = await billingRequest( - endpoints, - token, - 'POST', - 'v1/billing/checkout', - { - plan: args.plan, - interval: args.interval, - seats: args.seats, - ...(args.setupSessionId ? { setupSessionId: args.setupSessionId } : {}) - }, - fetchImpl - ) - return assertStripeHostedUrl(UrlBody.safeParse(body).data?.url) -} - export async function createPortalUrl( endpoints: BillingEndpoints, token: string, diff --git a/src/main/billing/billing-config.test.ts b/src/main/billing/billing-config.test.ts index de153033268..e0381009f68 100644 --- a/src/main/billing/billing-config.test.ts +++ b/src/main/billing/billing-config.test.ts @@ -3,10 +3,7 @@ import { describe, expect, it, vi } from 'vitest' vi.mock('electron', () => ({ app: { isPackaged: false } })) import { getBillingEndpoints } from './billing-config' -import { - billingCheckoutArgsFromUnknown, - billingOverageArgsFromUnknown -} from '../ipc/profiles/orca-profile-billing-handlers' +import { billingOverageArgsFromUnknown } from '../ipc/profiles/orca-profile-billing-handlers' const authConfig = { apiBaseUrl: 'https://login.onorca.dev' } @@ -32,29 +29,6 @@ describe('billing config', () => { }) describe('billing IPC args', () => { - it('accepts a catalog plan id with an interval and 1..500 seats', () => { - expect(billingCheckoutArgsFromUnknown({ plan: 'team', interval: 'year', seats: 5 })).toEqual({ - plan: 'team', - interval: 'year', - seats: 5 - }) - // Billing's catalog names the plans (billing decides what it sells); the shape is checked here. - expect(billingCheckoutArgsFromUnknown({ plan: 'pro', interval: 'month', seats: 1 }).plan).toBe( - 'pro' - ) - for (const bad of [ - { plan: 'Pro Plan', interval: 'month', seats: 1 }, - { plan: '', interval: 'month', seats: 1 }, - { plan: 'team', interval: 'week', seats: 1 }, - { plan: 'team', interval: 'month', seats: 0 }, - { plan: 'team', interval: 'month', seats: 501 }, - { plan: 'team', interval: 'month', seats: 1, extra: true }, - null - ]) { - expect(() => billingCheckoutArgsFromUnknown(bad)).toThrow('invalid_orca_billing_checkout') - } - }) - it('accepts overage toggles with an optional whole-cent cap', () => { expect(billingOverageArgsFromUnknown({ enabled: false })).toEqual({ enabled: false }) expect(billingOverageArgsFromUnknown({ enabled: true, spendCapCents: 5000 })).toEqual({ diff --git a/src/main/billing/billing-service-link.test.ts b/src/main/billing/billing-service-link.test.ts deleted file mode 100644 index 2313cace95d..00000000000 --- a/src/main/billing/billing-service-link.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' - -vi.mock('electron', () => ({ app: { isPackaged: false }, shell: { openExternal: vi.fn() } })) - -import { withSetupSessionFallback } from './billing-setup-session-fallback' -import type { OrcaBillingCheckoutArgs, OrcaBillingLinkResult } from '../../shared/orca-billing' - -const ARGS: OrcaBillingCheckoutArgs = { - plan: 'team', - interval: 'month', - seats: 3, - setupSessionId: 'cs_x' -} - -describe('checkout "Copy link" setup-session fallback', () => { - it('retries without the setup session when billing says it is for someone else', async () => { - const run = vi.fn(async (args: OrcaBillingCheckoutArgs): Promise => - args.setupSessionId - ? { status: 'failed', error: 'setup_session_mismatch' } - : { status: 'ok', url: 'https://checkout.stripe.com/c/pay/cs_live_1' } - ) - await expect(withSetupSessionFallback(ARGS, run)).resolves.toEqual({ - status: 'ok', - url: 'https://checkout.stripe.com/c/pay/cs_live_1' - }) - expect(run).toHaveBeenCalledTimes(2) - expect(run.mock.calls[1][0]).not.toHaveProperty('setupSessionId') - }) - - it('keeps any other refusal as it is', async () => { - const run = vi.fn(async (): Promise => ({ status: 'forbidden' })) - await expect(withSetupSessionFallback(ARGS, run)).resolves.toEqual({ status: 'forbidden' }) - expect(run).toHaveBeenCalledTimes(1) - }) -}) diff --git a/src/main/billing/billing-service.ts b/src/main/billing/billing-service.ts index 2b4f0befc56..20eb0af3dee 100644 --- a/src/main/billing/billing-service.ts +++ b/src/main/billing/billing-service.ts @@ -6,27 +6,23 @@ import { appendFile } from 'node:fs/promises' import { join } from 'node:path' import { app, shell } from 'electron' import type { - OrcaBillingCheckoutArgs, OrcaBillingLinkResult, OrcaBillingOpenResult, OrcaBillingOverageArgs, OrcaBillingOverageResult, OrcaBillingStatusResult, OrcaBillingTeamPlansResult, - OrcaBillingTrialClaimResult, - OrcaBillingUsageHistoryResult + OrcaBillingTrialClaimResult } from '../../shared/orca-billing' import type { OrcaPlanCatalogResult } from '../../shared/orca-billing-plans' import { loadPlanCatalog } from './plan-catalog-client' import { openResultForError } from './billing-open-result' -import { withSetupSessionFallback } from './billing-setup-session-fallback' import { getOrcaCloudAuthConfig } from '../orca-profiles/cloud-auth/profile-cloud-auth-config' import { runWithFreshOrcaCloudSession } from '../orca-profiles/cloud-session/profile-cloud-session-refresh' import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store' import { BillingServiceError, claimTrial, - createCheckoutUrl, createPortalUrl, fetchEntitlement, fetchTeamPlans, @@ -35,7 +31,6 @@ import { type BillingEndpoints } from './billing-client' import { getBillingEndpoints } from './billing-config' -import { fetchUsageHistory } from './billing-usage-client' import { getBillingDevKeyFile, mintDevBillingToken } from './billing-dev-token' import { cleanCloudServiceUrl } from '../../shared/cloud-service-url' import { listOrcaProfileOrgMembers } from '../orca-profiles/cloud-org/profile-cloud-org-members-service' @@ -117,7 +112,11 @@ function prepare(userDataPath: string): Ready { // The team this device shows, from the same profile whose session this is (a local // profile switch mid-call must not pair one profile's session with another's team); // never auth's shared "active team" (EP-9). - await mintBillingToken(endpoints, session.accessToken, active.profile.cloud?.activeOrgId ?? null), + await mintBillingToken( + endpoints, + session.accessToken, + active.profile.cloud?.activeOrgId ?? null + ), endpoints ) ) @@ -187,25 +186,6 @@ export async function getOrcaBillingStatus(userDataPath: string): Promise { - const ready = prepare(userDataPath) - if (!ready.ok) { - return { status: ready.status } - } - try { - const history = await ready.run((token, endpoints) => - fetchUsageHistory(endpoints, token, utcOffsetMinutes) - ) - return history === 'signed-out' ? { status: 'signed-out' } : { status: 'ok', history } - } catch (error) { - return { status: 'failed', error: message(error) } - } -} - /** Plan state for other teams the signed-in user is on (cloud start B2); never switches teams. */ export async function getOrcaBillingTeamPlans( userDataPath: string, @@ -268,17 +248,6 @@ async function openHosted( } } -export function openOrcaBillingCheckout( - userDataPath: string, - args: OrcaBillingCheckoutArgs -): Promise { - return withSetupSessionFallback(args, (checkoutArgs) => - openHosted(userDataPath, (token, endpoints) => - createCheckoutUrl(endpoints, token, checkoutArgs) - ) - ) -} - export function openOrcaBillingPortal(userDataPath: string): Promise { return openHosted(userDataPath, (token, endpoints) => createPortalUrl(endpoints, token)) } diff --git a/src/main/billing/billing-setup-session-fallback.ts b/src/main/billing/billing-setup-session-fallback.ts deleted file mode 100644 index d29a0244a09..00000000000 --- a/src/main/billing/billing-setup-session-fallback.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { OrcaBillingCheckoutArgs } from '../../shared/orca-billing' - -/** A setup session for another team or user (or an expired one) must not block buying. */ -export async function withSetupSessionFallback( - args: OrcaBillingCheckoutArgs, - run: (args: OrcaBillingCheckoutArgs) => Promise -): Promise { - const result = await run(args) - if ( - args.setupSessionId && - result.status === 'failed' && - /setup_session_mismatch/.test(result.error ?? '') - ) { - const { setupSessionId: _dropped, ...plain } = args - return run(plain) - } - return result -} diff --git a/src/main/billing/billing-usage-client.test.ts b/src/main/billing/billing-usage-client.test.ts deleted file mode 100644 index 342838d7cb7..00000000000 --- a/src/main/billing/billing-usage-client.test.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { fetchUsageHistory } from './billing-usage-client' - -const endpoints = { - billingApiUrl: 'https://billing.example.test', - billingTokenEndpoint: 'https://login.example.test/v1/desktop/auth/billing-token' -} - -type Seen = { url: string; init: RequestInit | undefined } - -function fakeFetch(responses: Record, seen: Seen[] = []): typeof fetch { - return async (input, init) => { - const url = String(input) - seen.push({ url, init }) - const response = responses[url] - if (!response) { - throw new Error(`unexpected ${url}`) - } - return response - } -} - -describe('fetchUsageHistory', () => { - const url = 'https://billing.example.test/v1/billing/usage?utcOffset=-480' - const body = { - days: [{ start: 1, seconds: 3600 }], - totalSeconds: 3600, - yourSeconds: 1800, - members: { top: [{ userId: 'u1', seconds: 3600 }], otherCount: 0, otherSeconds: 0 }, - sandboxes: { top: [{ sandboxId: 'sbx_1', seconds: 3600 }], otherCount: 0, otherSeconds: 0 } - } - - it('sends the local offset and maps both breakdowns to one row shape', async () => { - const seen: Seen[] = [] - const history = await fetchUsageHistory( - endpoints, - 'bt', - -480, - fakeFetch({ [url]: Response.json(body) }, seen) - ) - expect(seen[0]!.init?.method).toBe('GET') - expect(history.members).toEqual({ - top: [{ id: 'u1', seconds: 3600 }], - otherCount: 0, - otherSeconds: 0 - }) - expect(history.sandboxes?.top).toEqual([{ id: 'sbx_1', seconds: 3600 }]) - }) - - it('accepts a member’s view and rejects malformed rows', async () => { - const member = await fetchUsageHistory( - endpoints, - 'bt', - -480, - fakeFetch({ [url]: Response.json({ ...body, members: null, sandboxes: null }) }) - ) - expect(member.members).toBeNull() - await expect( - fetchUsageHistory( - endpoints, - 'bt', - -480, - fakeFetch({ - [url]: Response.json({ - ...body, - members: { top: [{ userId: '