diff --git a/cloud/apps/billing/src/catalog-sync.ts b/cloud/apps/billing/src/catalog-sync.ts new file mode 100644 index 00000000000..78cf50c6808 --- /dev/null +++ b/cloud/apps/billing/src/catalog-sync.ts @@ -0,0 +1,224 @@ +// Stripe is the only price authority. This module +// - syncs plan_prices from the Stripe Prices holding each plan's lookup keys (cron, and on +// price.* / product.* webhooks): what Checkout sells and GET /v1/plans shows; +// - records every seat price a subscription is seen on (price history), so a subscriber on an +// older price keeps mapping to its plan after the lookup key moves to a new price; +// - maps a subscription item's price to a plan + interval: the configured env ids, any price we +// have seen for the plan, a price holding the plan's lookup key, or one on the plan's product. +import { invalidateCatalog, loadCatalog, type Catalog, type PlanPriceRow } from './catalog' +import type { Env } from './env' +import { BILLING_INTERVALS, PLAN_IDS, planForPrice, type BillingInterval, type PlanId } from './plans' +import { StripeError, type StripeClient, type StripePrice } from './stripe' + +export type PriceMatch = { plan: PlanId; interval: BillingInterval } + +function productId(price: StripePrice): string | null { + const product = price.product + if (typeof product === 'string') { + return product + } + return product && typeof product === 'object' && typeof product.id === 'string' ? product.id : null +} + +function asInterval(value: unknown): BillingInterval | null { + return (BILLING_INTERVALS as readonly unknown[]).includes(value) ? (value as BillingInterval) : null +} + +function asPlan(value: unknown): PlanId | null { + return (PLAN_IDS as readonly unknown[]).includes(value) ? (value as PlanId) : null +} + +/** The catalog when one was applied; null otherwise (the env price ids still work). */ +export async function catalogIfApplied(db: D1Database, now: number): Promise { + try { + return await loadCatalog(db, now) + } catch { + return null + } +} + +/** Is this item the metered overage price (the current env one, or any overage price we synced)? */ +export function isOveragePrice(env: Pick, catalog: Catalog | null, price: StripePrice): boolean { + if (price.id === env.STRIPE_PRICE_OVERAGE) { + return true + } + return catalog?.prices.some((row) => row.stripe_price_id === price.id && row.role === 'overage') ?? false +} + +/** Which plan and interval a seat price sells, or null when it isn't one of ours. */ +export function seatPriceMatch(env: Env, catalog: Catalog | null, price: StripePrice): PriceMatch | null { + const configured = planForPrice(env, price.id) + if (configured) { + return configured + } + if (!catalog || isOveragePrice(env, catalog, price) || price.recurring?.usage_type === 'metered') { + return null + } + const known = catalog.prices.find((row) => row.stripe_price_id === price.id && row.role === 'seat') + if (known) { + const plan = asPlan(known.plan_id) + const interval = asInterval(known.interval) + return plan && interval ? { plan, interval } : null + } + const interval = asInterval(price.recurring?.interval) + if (!interval) { + return null + } + for (const plan of catalog.plans.values()) { + const id = asPlan(plan.id) + if (!id || plan.kind !== 'self_serve') { + continue + } + if (price.lookup_key && plan.config.stripe?.seatLookupKeys[interval] === price.lookup_key) { + return { plan: id, interval } + } + } + // A new price on a plan's product (the lookup key moved before we ever saw this price). + const product = productId(price) + if (product) { + const owner = catalog.prices.find((row) => row.role === 'seat' && row.stripe_product_id === product) + const plan = owner ? asPlan(owner.plan_id) : null + if (plan) { + return { plan, interval } + } + } + return null +} + +const UPSERT_PRICE = `INSERT INTO plan_prices (stripe_price_id, plan_id, plan_version, role, interval, lookup_key, unit_amount, + unit_amount_decimal, currency, active, is_checkout_price, stripe_product_id, synced_at) + VALUES (?1, ?2, NULL, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12) + ON CONFLICT (stripe_price_id) DO UPDATE SET + lookup_key = excluded.lookup_key, unit_amount = excluded.unit_amount, unit_amount_decimal = excluded.unit_amount_decimal, + currency = excluded.currency, active = excluded.active, + is_checkout_price = CASE WHEN ?13 = 1 THEN excluded.is_checkout_price ELSE plan_prices.is_checkout_price END, + stripe_product_id = COALESCE(excluded.stripe_product_id, plan_prices.stripe_product_id), synced_at = excluded.synced_at` + +function priceStatement( + db: D1Database, + args: { price: StripePrice; planId: string; role: 'seat' | 'overage'; interval: string | null; checkout: boolean; setCheckout: boolean; now: number } +): D1PreparedStatement { + const { price } = args + return db + .prepare(UPSERT_PRICE) + .bind( + price.id, + args.planId, + args.role, + args.interval, + price.lookup_key ?? null, + typeof price.unit_amount === 'number' ? price.unit_amount : null, + typeof price.unit_amount_decimal === 'string' ? price.unit_amount_decimal : null, + price.currency ?? null, + price.active === false ? 0 : 1, + args.checkout ? 1 : 0, + productId(price), + args.now, + args.setCheckout ? 1 : 0 + ) +} + +/** Remembers the seat prices a subscription is on (never changes which price Checkout sells). */ +export async function recordSubscriptionPrices( + db: D1Database, + catalog: Catalog, + items: Array<{ price: StripePrice; match: PriceMatch }>, + now: number +): Promise { + const fresh = items.filter(({ price }) => { + const row = catalog.prices.find((entry) => entry.stripe_price_id === price.id) + return !row || row.unit_amount !== (price.unit_amount ?? null) || row.active !== (price.active === false ? 0 : 1) + }) + if (fresh.length === 0) { + return + } + await db.batch( + fresh.map(({ price, match }) => + priceStatement(db, { price, planId: match.plan, role: 'seat', interval: match.interval, checkout: false, setCheckout: false, now }) + ) + ) + invalidateCatalog(db) +} + +/** + * Refreshes the prices holding each plan's lookup keys. The holder of a key becomes the checkout + * price for its plan/role/interval; any other price there stops being one (it stays as history). + */ +export async function syncCatalogPrices( + env: Env, + stripe: StripeClient, + now: number +): Promise<{ synced: number; missing: string[]; error?: string }> { + const catalog = await catalogIfApplied(env.BILLING_DB, now) + if (!catalog) { + return { synced: 0, missing: [], error: 'catalog_unavailable' } + } + const wanted: Array<{ key: string; planId: string; role: 'seat' | 'overage'; interval: string | null }> = [] + for (const plan of catalog.plans.values()) { + const stripeConfig = plan.config.stripe + if (!stripeConfig) { + continue + } + for (const interval of BILLING_INTERVALS) { + const key = stripeConfig.seatLookupKeys[interval] + if (key) { + wanted.push({ key, planId: plan.id, role: 'seat', interval }) + } + } + if (stripeConfig.overageLookupKey) { + wanted.push({ key: stripeConfig.overageLookupKey, planId: plan.id, role: 'overage', interval: 'month' }) + } + } + if (wanted.length === 0) { + return { synced: 0, missing: [] } + } + let prices: StripePrice[] + try { + prices = (await stripe.listPricesByLookupKeys([...new Set(wanted.map((entry) => entry.key))])).data + } catch (error) { + // A restricted key without Prices read answers 403: keep the prices we have, and say so. + const message = error instanceof StripeError ? `stripe_${error.status}` : 'stripe_unreachable' + console.error(JSON.stringify({ error: 'catalog_price_sync', message })) + return { synced: 0, missing: wanted.map((entry) => entry.key), error: message } + } + if (prices.some((price) => price.livemode === true) && env.STRIPE_ALLOW_LIVEMODE !== 'true') { + return { synced: 0, missing: [], error: 'livemode_price' } + } + const db = env.BILLING_DB + const statements: D1PreparedStatement[] = [] + const missing: string[] = [] + for (const entry of wanted) { + const price = prices.find((candidate) => candidate.lookup_key === entry.key) + if (!price) { + missing.push(entry.key) + continue + } + statements.push( + priceStatement(db, { price, planId: entry.planId, role: entry.role, interval: entry.interval, checkout: true, setCheckout: true, now }), + // The key moved: the previous holder stays as history only. + db + .prepare( + `UPDATE plan_prices SET is_checkout_price = 0 + WHERE plan_id = ?1 AND role = ?2 AND interval IS ?3 AND stripe_price_id <> ?4 AND is_checkout_price = 1` + ) + .bind(entry.planId, entry.role, entry.interval, price.id) + ) + } + if (statements.length > 0) { + await db.batch(statements) + invalidateCatalog(db) + } + if (missing.length > 0) { + console.error(JSON.stringify({ error: 'catalog_price_missing', lookupKeys: missing })) + } + return { synced: wanted.length - missing.length, missing } +} + +/** The price Checkout sells for a plan and interval: the current lookup-key holder. */ +export function checkoutPrice(catalog: Catalog, planId: string, interval: BillingInterval): PlanPriceRow | null { + return ( + catalog.prices.find( + (row) => row.plan_id === planId && row.role === 'seat' && row.interval === interval && row.is_checkout_price === 1 && row.active === 1 + ) ?? null + ) +} diff --git a/cloud/apps/billing/src/checkout.ts b/cloud/apps/billing/src/checkout.ts index 5fddb7396f5..e770579de2c 100644 --- a/cloud/apps/billing/src/checkout.ts +++ b/cloud/apps/billing/src/checkout.ts @@ -3,10 +3,14 @@ import { z } from 'zod' import type { BillingCaller } from './auth' import type { Env } from './env' import { BILLING_INTERVALS, PLAN_IDS, priceForPlan, type BillingInterval, type PlanId } from './plans' -import { StripeError, type StripeClient } from './stripe' +import { StripeError, assertKeyMode, type StripeClient } from './stripe' import { currentSubscription, customerFor, ensureAccount, linkCustomer } from './store' import { orgIdOf, type MembershipSource } from './membership' import { setupCheckoutReturnUrls } from './cloud-setup-urls' +import { accountTerms } from './entitlements' +import { entitlementsMode } from './entitlements-mode' +import { loadCatalog } from './catalog' +import { checkoutPrice } from './catalog-sync' export const MAX_TEAM_SEATS = 500 @@ -71,6 +75,18 @@ export async function createCheckout( const orgId = orgIdOf(caller.accountId) const live = orgId ? await membership(orgId) : null const seats = Math.max(1, live ?? request.seats) + const terms = await accountTerms(env, caller.accountId, now) + if (seats > terms.maxSeats) { + return { ok: false, status: 400, error: 'too_many_seats' } + } + // A misconfigured (live) key fails first, whatever the catalog says. + assertKeyMode(env) + const price = await seatPriceFor(env, request.plan, request.interval, now) + if (!price) { + // ENTITLEMENTS_MODE=on and Stripe has no price holding this plan's lookup key (yet): never + // sell at a guessed price. + return { ok: false, status: 409, error: 'plan_unavailable' } + } const customer = await ensureCustomer(env, stripe, caller, now) // One live Checkout per account: a reopened or retried checkout expires the earlier page, so // two browser tabs can never both be paid into two subscriptions. A session that can no longer @@ -102,7 +118,7 @@ export async function createCheckout( // Seats only. Overage is opt-in later; its metered item is added then (overage.ts). line_items: [ // Seats then follow org membership automatically (seats.ts); not editable on the page. - { price: priceForPlan(env, request.interval), quantity: seats } + { price, quantity: seats } ], payment_method_collection: 'always', allow_promotion_codes: true, @@ -121,6 +137,15 @@ export async function createCheckout( return { ok: true, url: session.url } } +/** The seat price Checkout sells: the catalog's lookup-key holder when on, else the env price id. */ +async function seatPriceFor(env: Env, plan: PlanId, interval: BillingInterval, now: number): Promise { + if (entitlementsMode(env) !== 'on') { + return priceForPlan(env, interval) + } + const catalog = await loadCatalog(env.BILLING_DB, now) + return checkoutPrice(catalog, plan, interval)?.stripe_price_id ?? null +} + export async function createPortal(env: Env, stripe: StripeClient, caller: BillingCaller): Promise { if (!caller.canManage) { return { ok: false, status: 403, error: 'billing_admin_required' } diff --git a/cloud/apps/billing/src/entitlements.ts b/cloud/apps/billing/src/entitlements.ts index 0c41ddeab84..be4d89b4d8e 100644 --- a/cloud/apps/billing/src/entitlements.ts +++ b/cloud/apps/billing/src/entitlements.ts @@ -26,6 +26,7 @@ import { ORCA_CLOUD_OVERAGE_CENTS_PER_HOUR } from '../../../../src/shared/hosted import { CatalogUnavailableError, loadCatalog, planVersion, policyFor, type Catalog, type PlanPolicy } from './catalog' import { aggregateGrants, isEntitlementKey, type GrantValue } from './entitlement-keys' import { entitlementsMode } from './entitlements-mode' +import { MAX_TEAM_SEATS } from './checkout' import { grantsForSubject, liveAt, projectSubscription, projectTrial, type GrantRow } from './grants' export type DenyReason = @@ -113,6 +114,9 @@ export type AccountTerms = { maxSpendCapCents: number overageCentsPerHour: number idleSleepMinutes: number + /** Seat bounds for Checkout and membership sync, and how close to renewal seats come down. */ + maxSeats: number + seatTrueDownHours: number } type AccountState = { @@ -150,6 +154,8 @@ function legacyTerms(env: Pick, state: AccountState): Acco maxSpendCapCents: team.maxSpendCapCents, overageCentsPerHour: team.overageCentsPerHour, idleSleepMinutes: team.idleSleepMinutes, + maxSeats: MAX_TEAM_SEATS, + seatTrueDownHours: team.seatTrueDownHours, ungranted: false } if (state.subscription) { @@ -271,6 +277,8 @@ async function grantTerms(env: EntitlementEnv, state: AccountState, now: number) overageCentsPerHour: catalogOverageCentsPerHour(catalog, overagePlan), // Product config, not a plan term: the control plane enforces it (GET /v1/config). idleSleepMinutes: planCatalog(env).team.idleSleepMinutes, + maxSeats: policy.seats.max, + seatTrueDownHours: policy.seatTrueDownHours, ungranted } if (subscription) { diff --git a/cloud/apps/billing/src/env.ts b/cloud/apps/billing/src/env.ts index 3905cc2a0a7..1e798845dde 100644 --- a/cloud/apps/billing/src/env.ts +++ b/cloud/apps/billing/src/env.ts @@ -4,7 +4,12 @@ export type Env = { BILLING_DB: D1Database // Stripe. Use a RESTRICTED key (rk_test_...) scoped to: Customers write, Checkout Sessions - // write, Customer portal write, Subscriptions read, Billing meter events write. Nothing else. + // write, Customer portal write, Subscriptions read, Billing meter events write, and (plans & + // entitlements: catalog price sync, reconciliation) Prices read and Events read. Nothing else. + // Without Prices/Events read the catalog keeps its last prices and only the rolling re-sync runs. + // Webhook endpoint events: checkout.session.completed, customer.subscription.{created,updated, + // deleted,paused,resumed}, invoice.{paid,payment_failed}, customer.deleted, price.{created,updated, + // deleted}, product.updated (webhook.ts HANDLED_EVENT_TYPES). STRIPE_SECRET_KEY: string // Webhook endpoint signing secret(s), comma-separated during rotation (whsec_...). STRIPE_WEBHOOK_SECRET: string diff --git a/cloud/apps/billing/src/index.ts b/cloud/apps/billing/src/index.ts index 54804acdff3..f3aa1dd5725 100644 --- a/cloud/apps/billing/src/index.ts +++ b/cloud/apps/billing/src/index.ts @@ -1,6 +1,9 @@ // Orca billing Worker: Stripe Checkout/Portal, Stripe webhooks, entitlements and usage. // +// Public: +// GET /v1/plans plan catalog: Stripe prices, entitlements, features (ETag) // Desktop (Orca Cloud billing JWT): +// GET /v1/entitlements effective entitlements, access and the grants behind them // GET /v1/billing/entitlements current plan, hours used/remaining, can-start // POST /v1/billing/checkout {plan,interval,seats} -> { url } hosted Stripe Checkout // POST /v1/billing/overage {enabled, spendCapCents?} opt in/out of overage, set the cap @@ -47,6 +50,8 @@ import { CheckoutRequestSchema, createCheckout, createPortal } from './checkout' import { checkStart, computeEntitlement, entitlementsMode } from './entitlements' import { CatalogUnavailableError, loadCatalog, policyFor } from './catalog' import { backfillGrants } from './entitlements-backfill' +import { entitlementsView, offersFor, plansView } from './plans-api' +import { reconcile } from './reconcile' import type { Env } from './env' import { MACHINE_SIZES, PlanConfigError, planCatalog, publicOffers } from './plans' import { OverageRequestSchema, updateOverage } from './overage' @@ -114,7 +119,7 @@ function trialInput(caller: BillingCaller, request: Request): TrialInput { /** The desktop's entitlement body: the account's state plus what this caller is offered. */ async function desktopEntitlement(env: Env, caller: BillingCaller, request: Request, now: number) { const entitlement = await computeEntitlement(env, caller.accountId, now, 'desktop') - const offers = publicOffers(planCatalog(env)) + const offers = await offersFor(env, now) const neverHadPlan = entitlement.reason === 'no_subscription' const trial = neverHadPlan ? await trialOffer(env, trialInput(caller, request), now) : null // A team that never had a plan but can't get a trial (one already used by this user, email, @@ -166,7 +171,7 @@ async function handleCloudSetup( if (route === 'GET /v1/cloud-setup/offers') { // Public: the setup pages show the trial and prices before anyone has signed in. const offered = await deps.trial.offeredSeconds(env, now) - return json({ ...publicOffers(planCatalog(env)), trial: offered ? { includedSeconds: offered } : null }) + return json({ ...(await offersFor(env, now)), trial: offered ? { includedSeconds: offered } : null }) } if (route === 'POST /v1/cloud-setup/sessions') { const caller = await authenticateDesktop(env, request) @@ -245,7 +250,7 @@ async function handleCloudSetup( return json({ error: 'invalid_request' }, 400) } const session = await readSetupSessionForPages(env, deps.trial, id, query.data.userId, now) - return session ? json({ ...session, offers: publicOffers(planCatalog(env)) }) : json({ error: 'not_found' }, 404) + return session ? json({ ...session, offers: await offersFor(env, now) }) : json({ error: 'not_found' }, 404) } if (request.method !== 'POST' || !action) { return json({ error: 'not_found' }, 404) @@ -320,6 +325,29 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo case 'POST /v1/stripe/webhook': return await handleStripeWebhook(env, stripe, request, now) + case 'GET /v1/plans': { + // Public catalog (desktop, setup pages, marketing): cacheable, revalidated by ETag. + const catalog = await loadCatalog(env.BILLING_DB, now) + const headers = { + 'cache-control': 'public, max-age=300', + etag: catalog.etag, + 'access-control-allow-origin': '*' + } + if (request.headers.get('if-none-match') === catalog.etag) { + return new Response(null, { status: 304, headers }) + } + return Response.json(plansView(catalog), { headers }) + } + + case 'GET /v1/entitlements': { + const caller = await authenticateDesktop(env, request) + if (!caller) { + return json({ error: 'unauthorized' }, 401) + } + const view = await entitlementsView(env, caller.accountId, caller.canManage, now) + return Response.json(view, { headers: { 'cache-control': 'private, no-cache' } }) + } + case 'GET /v1/billing/entitlements': { const caller = await authenticateDesktop(env, request) if (!caller) { @@ -533,9 +561,11 @@ export default { ctx.waitUntil(flushMeterReports(env, stripe, Date.now()).then(() => undefined)) // Seat drift from a missed membership push heals here (needs AUTH_INTERNAL_URL). ctx.waitUntil(reconcileSeats(env, stripe, authMembershipSource(env), Date.now()).then(() => undefined)) - // Entitlement grants: backfill and heal (no-op while ENTITLEMENTS_MODE is off). + // Stripe -> billing reconciliation: event replay, rolling re-sync, catalog prices (reconcile.ts), + // then entitlement grant backfill/heal. Both are no-ops while ENTITLEMENTS_MODE is off. ctx.waitUntil( - backfillGrants(env, Date.now()) + reconcile(env, stripe, Date.now()) + .then(() => backfillGrants(env, Date.now())) .then((result) => { if (result.subscriptions + result.trials + result.failed > 0) { console.log(JSON.stringify({ event: 'entitlements_backfill', ...result })) diff --git a/cloud/apps/billing/src/overage.ts b/cloud/apps/billing/src/overage.ts index 73d63b06018..f0ae0fb604f 100644 --- a/cloud/apps/billing/src/overage.ts +++ b/cloud/apps/billing/src/overage.ts @@ -91,10 +91,11 @@ export async function retireOverageItem(env: Env, stripe: StripeClient, subscrip } /** A metered item that is not a seat price and not the current overage price: an older overage price. */ -function isStaleOverageItem(env: Env, item: StripeSubscription['items']['data'][number]): boolean { +function isStaleOverageItem(env: Env, subscription: SubscriptionRow, item: StripeSubscription['items']['data'][number]): boolean { return ( item.price.id !== env.STRIPE_PRICE_OVERAGE && planForPrice(env, item.price.id) === null && + item.price.id !== subscription.seat_price_id && item.price.recurring?.usage_type === 'metered' ) } @@ -104,7 +105,7 @@ async function ensureOverageItem(env: Env, stripe: StripeClient, subscription: S // Stripe is the source of truth for the items: the stored id can be missing or on an old price. const live = await stripe.retrieveSubscription(subscription.stripe_subscription_id) const current = live.items.data.find((item) => item.price.id === env.STRIPE_PRICE_OVERAGE) - const stale = live.items.data.filter((item) => isStaleOverageItem(env, item)) + const stale = live.items.data.filter((item) => isStaleOverageItem(env, subscription, item)) if (current) { // Never leave a second metered item on the same meter. for (const item of stale) { diff --git a/cloud/apps/billing/src/plans-api.ts b/cloud/apps/billing/src/plans-api.ts new file mode 100644 index 00000000000..ae0182476d4 --- /dev/null +++ b/cloud/apps/billing/src/plans-api.ts @@ -0,0 +1,171 @@ +// The catalog and an account's entitlements as clients read them: +// GET /v1/plans public plan catalog: prices (Stripe's), entitlements, features, policy +// GET /v1/entitlements the caller's effective entitlements, access, and the grants behind them +// plus `offers`, the older shape inside GET /v1/billing/entitlements and the setup pages, built +// from the same catalog when ENTITLEMENTS_MODE is on (from plans.ts otherwise). +import { checkoutPrice } from './catalog-sync' +import { defaultSelfServePlan, loadCatalog, planVersion, policyFor, type Catalog, type CatalogPlan } from './catalog' +import { catalogOverageCentsPerHour, computeEntitlement, entitlementsMode, type Entitlement } from './entitlements' +import type { Env } from './env' +import { grantsForSubject, liveAt } from './grants' +import { MACHINE_SIZE_WEIGHT, planCatalog, publicOffers, type BillingInterval } from './plans' + +export const PLANS_SCHEMA_VERSION = 1 + +/** "$50", "$480", "$12.50": whole units without decimals, like the legacy labels. */ +export function formatPrice(cents: number, currency: string): string { + const whole = cents % 100 === 0 + return new Intl.NumberFormat('en-US', { + style: 'currency', + currency: currency.toUpperCase(), + minimumFractionDigits: whole ? 0 : 2, + maximumFractionDigits: 2 + }).format(cents / 100) +} + +function seatPrice(catalog: Catalog, plan: CatalogPlan, interval: BillingInterval) { + const row = checkoutPrice(catalog, plan.id, interval) + return row && typeof row.unit_amount === 'number' ? { cents: row.unit_amount, currency: row.currency ?? 'usd' } : null +} + +function perSeatValue(plan: CatalogPlan, key: 'sandbox_hours_monthly' | 'max_concurrent_sandboxes'): number { + const entry = planVersion(plan, plan.currentVersion).entitlements[key] + return typeof entry?.value === 'number' ? entry.value : 0 +} + +/** The legacy `offers` shape, from the D1 catalog and Stripe's prices. A missing price is null/''. */ +export function catalogOffers(catalog: Catalog, idleSleepMinutes: number) { + const team = defaultSelfServePlan(catalog) + const policy = policyFor(catalog, team, team.currentVersion) + const monthly = seatPrice(catalog, team, 'month') + const annual = seatPrice(catalog, team, 'year') + const enterprise = [...catalog.plans.values()].find((plan) => plan.kind === 'contact_sales' && plan.public) + return { + team: { + label: team.name, + monthlyPriceLabel: monthly ? `${formatPrice(monthly.cents, monthly.currency)} per seat per month` : '', + annualPriceLabel: annual ? `${formatPrice(annual.cents, annual.currency)} per seat, billed yearly` : '', + monthlyPriceCentsPerSeat: monthly?.cents ?? null, + annualPriceCentsPerSeat: annual?.cents ?? null, + largeMachineWeight: MACHINE_SIZE_WEIGHT.large, + includedHoursPerSeat: perSeatValue(team, 'sandbox_hours_monthly'), + concurrentSandboxesPerSeat: perSeatValue(team, 'max_concurrent_sandboxes'), + idleSleepMinutes, + overageCentsPerHour: catalogOverageCentsPerHour(catalog, team.id), + defaultSpendCapCents: policy.overage.defaultSpendCapCents, + maxSpendCapCents: policy.overage.maxSpendCapCents, + // Additive (older desktops ignore it): the levels owners and admins are alerted at. + warnAtPercent: policy.warnAtPercent + }, + enterprise: enterprise + ? { label: enterprise.name, priceLabel: enterprise.config.priceLabel ?? '', contactUrl: enterprise.config.contactUrl ?? '' } + : { label: '', priceLabel: '', contactUrl: '' } + } +} + +/** `offers` for the desktop and the setup pages, from whichever catalog the mode serves. */ +export async function offersFor(env: Env, now: number) { + if (entitlementsMode(env) !== 'on') { + return publicOffers(planCatalog(env)) + } + return catalogOffers(await loadCatalog(env.BILLING_DB, now), planCatalog(env).team.idleSleepMinutes) +} + +/** GET /v1/plans: the public catalog. Prices only ever come from Stripe (no price, no checkout). */ +export function plansView(catalog: Catalog) { + const plans = [...catalog.plans.values()] + .filter((plan) => plan.public) + .sort((a, b) => a.sort - b.sort) + .map((plan) => { + const version = planVersion(plan, plan.currentVersion) + const base = { + id: plan.id, + kind: plan.kind, + name: plan.name, + version: plan.currentVersion, + entitlements: version.entitlements, + features: version.features + } + if (plan.kind === 'contact_sales') { + return { ...base, contactUrl: plan.config.contactUrl ?? null, priceLabel: plan.config.priceLabel ?? null } + } + if (plan.kind !== 'self_serve') { + return base + } + const policy = policyFor(catalog, plan, plan.currentVersion) + const prices = (['month', 'year'] as const).flatMap((interval) => { + const price = seatPrice(catalog, plan, interval) + return price ? [{ interval, unitAmountCents: price.cents, currency: price.currency }] : [] + }) + return { + ...base, + billing: 'per_seat' as const, + prices, + overage: { + centsPerHour: catalogOverageCentsPerHour(catalog, plan.id), + billedPer: 'minute' as const, + defaultSpendCapCents: policy.overage.defaultSpendCapCents, + maxSpendCapCents: policy.overage.maxSpendCapCents + }, + seats: policy.seats, + warnAtPercent: policy.warnAtPercent, + checkout: { available: prices.length > 0, intervals: prices.map((price) => price.interval) } + } + }) + return { schemaVersion: PLANS_SCHEMA_VERSION, catalogVersion: catalog.etag.replaceAll('"', ''), plans } +} + +/** GET /v1/entitlements: effective values (the mode's resolver), access, and the live grants. */ +export async function entitlementsView(env: Env, accountId: string, canManageBilling: boolean, now: number) { + const entitlement: Entitlement = await computeEntitlement(env, accountId, now, 'entitlements_v1') + const mode = entitlementsMode(env) + const grants = mode === 'off' ? [] : (await grantsForSubject(env.BILLING_DB, accountId)).filter((row) => liveAt(row, now) || row.state === 'held') + return { + schemaVersion: PLANS_SCHEMA_VERSION, + subject: accountId, + asOf: now, + source: mode === 'on' ? 'grants' : 'legacy', + plan: entitlement.plan + ? { + id: entitlement.plan, + name: entitlement.planLabel, + status: entitlement.status, + interval: entitlement.interval, + seats: entitlement.seats, + period: entitlement.period, + cancelAtPeriodEnd: entitlement.cancelAtPeriodEnd + } + : null, + trial: entitlement.trial, + effective: { + sandboxSeconds: { + included: entitlement.includedSeconds, + used: entitlement.usedSeconds, + remaining: entitlement.remainingIncludedSeconds, + window: entitlement.usageWindow, + resets: entitlement.trial ? 'never' : entitlement.usageWindow ? 'monthly' : null + }, + maxConcurrentSandboxes: entitlement.limits.maxConcurrentSandboxes, + maxConcurrentSandboxesPerMember: entitlement.limits.maxConcurrentSandboxesPerMember, + machineSizes: entitlement.limits.machineSizes, + overage: entitlement.overage, + overageSeconds: entitlement.overageSeconds, + usageWarningPercent: entitlement.usageWarningPercent + }, + access: { canStartSandbox: entitlement.canStartSandbox, reason: entitlement.reason, suspendRunning: entitlement.suspendRunning }, + payment: { pastDueSince: entitlement.payment.pastDueSince, graceEndsAt: entitlement.payment.graceEndsAt }, + grants: grants.map((row) => ({ + key: row.entitlement_key, + value: JSON.parse(row.value_json) as unknown, + perSeat: row.per_seat === 1, + seats: row.seat_quantity, + source: row.source_type, + state: row.state, + ...(row.hold_reason ? { holdReason: row.hold_reason } : {}), + plan: row.plan_id && row.source_type !== 'manual' && row.source_type !== 'promo' ? { id: row.plan_id, version: row.plan_version } : null, + startsAt: row.starts_at, + endsAt: row.ends_at + })), + canManageBilling + } +} diff --git a/cloud/apps/billing/src/reconcile.ts b/cloud/apps/billing/src/reconcile.ts new file mode 100644 index 00000000000..b584d09a0c2 --- /dev/null +++ b/cloud/apps/billing/src/reconcile.ts @@ -0,0 +1,149 @@ +// Reconciliation (cron): a missed or failed webhook can't leave stale access behind. +// 1. Replays Stripe's event log (GET /v1/events, kept 30 days) from a cursor: every event billing +// acts on that isn't already processed goes through the webhook's own path. +// 2. Re-reads a rolling slice of the subscriptions we hold that still matter (open in Stripe, or +// holding live grants), oldest first, so even an event Stripe never sent heals within hours. +// 3. Refreshes the catalog's Stripe prices. +// Off while ENTITLEMENTS_MODE is off (the legacy service had no reconciliation). +import { syncCatalogPrices } from './catalog-sync' +import type { Env } from './env' +import { entitlementsMode } from './entitlements-mode' +import { StripeError, type StripeClient } from './stripe' +import type { SubscriptionRow } from './store' +import { HANDLED_EVENT_TYPES, processStripeEvent, resyncSubscription, type StripeEvent } from './webhook' + +const CURSOR_KEY = 'events_cursor' +/** A subscription is re-read at most this often by the rolling sweep. */ +export const RESYNC_AFTER_MS = 6 * 3600 * 1000 + +async function readCursor(db: D1Database): Promise { + const row = await db.prepare('SELECT value FROM stripe_sync_state WHERE key = ?1').bind(CURSOR_KEY).first<{ value: string }>() + return row?.value ?? null +} + +async function writeCursor(db: D1Database, value: string, now: number): Promise { + await db + .prepare( + `INSERT INTO stripe_sync_state (key, value, updated_at) VALUES (?1, ?2, ?3) + ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at` + ) + .bind(CURSOR_KEY, value, now) + .run() +} + +/** + * Applies events newer than the cursor, oldest first, a page at a time. The first run only sets + * the cursor to the newest event (history before that was delivered by webhooks, and step 2 + * covers anything that wasn't). A failed event stops the replay there, to be retried next run. + */ +export async function replayStripeEvents( + env: Env, + stripe: StripeClient, + now: number, + options: { pages?: number; pageSize?: number } = {} +): Promise<{ replayed: number; applied: number; failed: number; error?: string }> { + const db = env.BILLING_DB + const pageSize = options.pageSize ?? 100 + let cursor = await readCursor(db) + let replayed = 0 + let applied = 0 + try { + if (!cursor) { + const newest = await stripe.listEvents({ types: HANDLED_EVENT_TYPES, limit: 1 }) + if (newest.data[0]) { + await writeCursor(db, newest.data[0].id, now) + } + return { replayed: 0, applied: 0, failed: 0 } + } + for (let page = 0; page < (options.pages ?? 5); page++) { + const result = await stripe.listEvents({ types: HANDLED_EVENT_TYPES, endingBefore: cursor, limit: pageSize }) + // Stripe lists newest first; apply oldest first. + const events = [...result.data].reverse() + for (const event of events) { + replayed++ + const outcome = await processStripeEvent(env, stripe, event as StripeEvent, now) + if (outcome.status >= 500) { + return { replayed, applied, failed: 1 } + } + if (outcome.body.received === true) { + applied++ + console.log(JSON.stringify({ event: 'reconcile_fixed', source: 'event_replay', stripeEvent: event.id, type: event.type })) + } + cursor = event.id + await writeCursor(db, cursor, now) + } + if (!result.has_more || events.length === 0) { + break + } + } + return { replayed, applied, failed: 0 } + } catch (error) { + // A restricted key without Events read answers 403: the rolling re-sync still runs. + const message = error instanceof StripeError ? `stripe_${error.status}` : error instanceof Error ? error.message.slice(0, 120) : 'unknown' + console.error(JSON.stringify({ error: 'reconcile_events', message })) + return { replayed, applied, failed: 0, error: message } + } +} + +/** Re-reads the subscriptions that still matter and haven't been read for RESYNC_AFTER_MS. */ +export async function resyncStaleSubscriptions( + env: Env, + stripe: StripeClient, + now: number, + limit = 25 +): Promise<{ checked: number; changed: number; canceledMissing: number; failed: number }> { + const db = env.BILLING_DB + const rows = ( + await db + .prepare( + `SELECT s.* FROM subscriptions s + WHERE s.updated_at < ?1 + AND (s.status NOT IN ('canceled', 'incomplete_expired') + OR EXISTS (SELECT 1 FROM entitlement_grants g WHERE g.source_type = 'subscription' + AND g.source_id = s.stripe_subscription_id AND g.state <> 'revoked')) + ORDER BY s.updated_at LIMIT ?2` + ) + .bind(now - RESYNC_AFTER_MS, limit) + .all() + ).results + let changed = 0 + let canceledMissing = 0 + let failed = 0 + for (const row of rows) { + try { + const outcome = await resyncSubscription(env, stripe, row, now) + const after = await db + .prepare('SELECT status, seats, cancel_at_period_end, current_period_end FROM subscriptions WHERE stripe_subscription_id = ?1') + .bind(row.stripe_subscription_id) + .first>() + if (outcome === 'canceled_missing') { + canceledMissing++ + } + if ( + after && + (after.status !== row.status || after.seats !== row.seats || after.cancel_at_period_end !== row.cancel_at_period_end || after.current_period_end !== row.current_period_end) + ) { + changed++ + console.log(JSON.stringify({ event: 'reconcile_fixed', source: 'resync', subscription: row.stripe_subscription_id, from: row.status, to: after.status })) + } + } catch (error) { + failed++ + console.error(JSON.stringify({ error: 'reconcile_resync', subscription: row.stripe_subscription_id, message: error instanceof Error ? error.message.slice(0, 160) : '' })) + } + } + return { checked: rows.length, changed, canceledMissing, failed } +} + +export async function reconcile(env: Env, stripe: StripeClient, now: number) { + if (entitlementsMode(env) === 'off') { + return null + } + const prices = await syncCatalogPrices(env, stripe, now) + const events = await replayStripeEvents(env, stripe, now) + const subscriptions = await resyncStaleSubscriptions(env, stripe, now) + const summary = { event: 'billing_reconcile', prices, events, subscriptions } + if (events.applied + subscriptions.changed + subscriptions.failed + events.failed > 0 || prices.error || events.error) { + console.log(JSON.stringify(summary)) + } + return summary +} diff --git a/cloud/apps/billing/src/seats.ts b/cloud/apps/billing/src/seats.ts index ee2ef38e174..f824299059c 100644 --- a/cloud/apps/billing/src/seats.ts +++ b/cloud/apps/billing/src/seats.ts @@ -12,10 +12,11 @@ // Membership is owned by Orca Cloud auth (pull: /v1/internal/billing/org-members; push: // /v1/internal/seats). Seats are never below 1. See cloud/docs/accounts-billing-design.md. import { z } from 'zod' -import { MAX_TEAM_SEATS, OPEN_STATUSES } from './checkout' +import { OPEN_STATUSES } from './checkout' +import { accountTerms } from './entitlements' +import { catalogIfApplied, seatPriceMatch } from './catalog-sync' import type { Env } from './env' import { orgIdOf, type MembershipSource } from './membership' -import { planCatalog, planForPrice } from './plans' import type { StripeClient } from './stripe' import { currentSubscription, openOrgAccounts, setMemberCount } from './store' import { syncSubscription } from './webhook' @@ -50,7 +51,8 @@ export async function syncSeats( return { status: 'no_subscription' } } const desired = Math.max(1, members) - if (desired > MAX_TEAM_SEATS) { + const terms = await accountTerms(env, accountId, now) + if (desired > terms.maxSeats) { return { status: 'too_many_seats' } } // Remembered so the reconcile cron can apply a deferred decrease without a fresh push. @@ -59,14 +61,17 @@ export async function syncSeats( return { status: 'unchanged', seats: desired } } const periodEnd = subscription.current_period_end - const trueDownFrom = periodEnd - planCatalog(env).team.seatTrueDownHours * 3600_000 + const trueDownFrom = periodEnd - terms.seatTrueDownHours * 3600_000 if (desired < subscription.seats && now < trueDownFrom) { return { status: 'deferred', seats: subscription.seats, members: desired, effectiveAt: periodEnd } } // Read the live item: the mirror can lag a webhook, and the item id is not stored. const live = await stripe.retrieveSubscription(subscription.stripe_subscription_id) - const seatItem = live.items.data.find((item) => planForPrice(env, item.price.id)) + const catalog = await catalogIfApplied(db, now) + const seatItem = live.items.data.find( + (item) => seatPriceMatch(env, catalog, item.price) !== null || item.price.id === subscription.seat_price_id + ) if (!seatItem) { return { status: 'no_subscription' } } diff --git a/cloud/apps/billing/src/store.ts b/cloud/apps/billing/src/store.ts index 0542bbf56a7..a301777c035 100644 --- a/cloud/apps/billing/src/store.ts +++ b/cloud/apps/billing/src/store.ts @@ -83,6 +83,10 @@ export async function subscriptionById(db: D1Database, subscriptionId: string): return db.prepare('SELECT * FROM subscriptions WHERE stripe_subscription_id = ?1').bind(subscriptionId).first() } +export async function subscriptionsForCustomer(db: D1Database, customerId: string): Promise { + return (await db.prepare('SELECT * FROM subscriptions WHERE stripe_customer_id = ?1').bind(customerId).all()).results +} + export async function upsertSubscription(db: D1Database, row: SubscriptionRow): Promise { await db .prepare( @@ -100,7 +104,9 @@ export async function upsertSubscription(db: D1Database, row: SubscriptionRow): past_due_since = CASE WHEN excluded.past_due_since IS NULL THEN NULL ELSE COALESCE(subscriptions.past_due_since, excluded.past_due_since) END, member_count = COALESCE(excluded.member_count, subscriptions.member_count), - seat_price_id = COALESCE(excluded.seat_price_id, subscriptions.seat_price_id)` + seat_price_id = COALESCE(excluded.seat_price_id, subscriptions.seat_price_id) + -- updated_at is the time of the Stripe read (or local change): an older read never wins. + WHERE subscriptions.updated_at <= excluded.updated_at` ) .bind( row.stripe_subscription_id, diff --git a/cloud/apps/billing/src/stripe.ts b/cloud/apps/billing/src/stripe.ts index 30b89ef0b15..aed96504e96 100644 --- a/cloud/apps/billing/src/stripe.ts +++ b/cloud/apps/billing/src/stripe.ts @@ -183,6 +183,21 @@ export function createStripeClient(env: Env, fetchImpl: typeof fetch = fetch) { args.idempotencyKey ) }, + /** Active prices holding these lookup keys (the catalog's checkout prices). */ + listPricesByLookupKeys(lookupKeys: string[]) { + return request<{ data: StripePrice[] }>('GET', '/v1/prices', { lookup_keys: lookupKeys, active: 'true', limit: '100' }) + }, + /** + * Events of these types newer than `endingBefore` (the page right after it), or the newest when + * absent. Stripe lists newest first; Stripe keeps events for 30 days. + */ + listEvents(args: { types: string[]; endingBefore?: string; limit: number }) { + return request<{ data: StripeEventObject[]; has_more: boolean }>('GET', '/v1/events', { + types: args.types, + ending_before: args.endingBefore, + limit: String(args.limit) + }) + }, retrieveSubscription(id: string) { return request('GET', `/v1/subscriptions/${encodeURIComponent(id)}`) }, @@ -220,7 +235,28 @@ export type StripeSubscription = { quantity?: number current_period_start?: number current_period_end?: number - price: { id: string; recurring?: { usage_type?: string } | null } + price: StripePrice }> } } + +/** The Price fields billing reads (subscription items embed the whole Price object). */ +export type StripePrice = { + id: string + active?: boolean + livemode?: boolean + currency?: string + unit_amount?: number | null + unit_amount_decimal?: string | null + lookup_key?: string | null + product?: string | { id: string } | null + recurring?: { interval?: string; usage_type?: string } | null +} + +export type StripeEventObject = { + id: string + type: string + created?: number + livemode: boolean + data: { object: Record } +} diff --git a/cloud/apps/billing/src/webhook.ts b/cloud/apps/billing/src/webhook.ts index b64a014abc2..0a29a52b881 100644 --- a/cloud/apps/billing/src/webhook.ts +++ b/cloud/apps/billing/src/webhook.ts @@ -1,18 +1,29 @@ // Stripe webhook: verify the signature over the raw body, dedupe by event id, then re-read the // subscription from the API instead of trusting the (possibly stale, possibly out-of-order) payload. import type { Env } from './env' -import { planForPrice } from './plans' -import { allowsLiveMode, type StripeClient, type StripeSubscription } from './stripe' -import { accountForCustomer, claimEvent, currentSubscription, customerFor, finishEvent, subscriptionById, upsertSubscription } from './store' +import { StripeError, allowsLiveMode, type StripeClient, type StripeSubscription } from './stripe' +import { + accountForCustomer, + claimEvent, + currentSubscription, + customerFor, + finishEvent, + subscriptionById, + subscriptionsForCustomer, + upsertSubscription, + type SubscriptionRow +} from './store' import { entitlementsMode } from './entitlements-mode' import { loadCatalog } from './catalog' import { projectSubscription } from './grants' +import { catalogIfApplied, isOveragePrice, recordSubscriptionPrices, seatPriceMatch, syncCatalogPrices, type PriceMatch } from './catalog-sync' +import type { StripePrice } from './stripe' import { retireOverageItem } from './overage' import { splitSecrets, verifyStripeSignature } from './webhook-signature' const MAX_BODY_BYTES = 512 * 1024 -type StripeEvent = { +export type StripeEvent = { id: string type: string livemode: boolean @@ -27,6 +38,18 @@ const SUBSCRIPTION_EVENTS = new Set([ 'customer.subscription.resumed' ]) const INVOICE_EVENTS = new Set(['invoice.paid', 'invoice.payment_failed']) +// The catalog's prices changed in Stripe: re-sync plan_prices (catalog-sync.ts). +const CATALOG_EVENTS = new Set(['price.created', 'price.updated', 'price.deleted', 'product.updated']) +const CUSTOMER_DELETED = 'customer.deleted' + +/** Every event type billing acts on (the webhook endpoint's list and the reconciliation replay). */ +export const HANDLED_EVENT_TYPES = [ + 'checkout.session.completed', + ...SUBSCRIPTION_EVENTS, + ...INVOICE_EVENTS, + ...CATALOG_EVENTS, + CUSTOMER_DELETED +] function idOf(value: unknown): string | null { if (typeof value === 'string' && value) { @@ -76,29 +99,46 @@ export async function syncSubscription(env: Env, stripe: StripeClient, subscript if (!accountId) { throw new IgnoredSubscription('unknown_customer') } - let match: ReturnType = null - let seatPriceId: string | null = null + const catalog = await catalogIfApplied(db, now) + let match: PriceMatch | null = null + let seatPrice: StripePrice | null = null let seats = 1 let overageItemId: string | null = null let periodStart = subscription.current_period_start let periodEnd = subscription.current_period_end for (const item of subscription.items.data) { - if (item.price.id === env.STRIPE_PRICE_OVERAGE) { + if (isOveragePrice(env, catalog, item.price)) { overageItemId = item.id continue } - const itemPlan = planForPrice(env, item.price.id) + const itemPlan = seatPriceMatch(env, catalog, item.price) if (itemPlan) { match = itemPlan - seatPriceId = item.price.id + seatPrice = item.price seats = Math.max(1, item.quantity ?? 1) periodStart = item.current_period_start ?? periodStart periodEnd = item.current_period_end ?? periodEnd } } + const known = await subscriptionById(db, subscription.id) + if (!match && known) { + // A subscriber we already bill, on a price we can't map (it was replaced in Stripe before we + // ever saw it): never freeze them on stale Stripe state. Status, period and cancellation still + // apply, so a cancel still revokes; plan, interval and seats stay as last known. + console.error(JSON.stringify({ error: 'unrecognized_subscription_items', subscription: subscription.id, known: true })) + match = { plan: known.plan, interval: known.billing_interval } + seats = known.seats + periodStart = periodStart ?? subscription.items.data[0]?.current_period_start ?? known.current_period_start / 1000 + periodEnd = periodEnd ?? subscription.items.data[0]?.current_period_end ?? known.current_period_end / 1000 + } if (!match || !periodStart || !periodEnd) { throw new IgnoredSubscription('unrecognized_subscription_items') } + if (catalog && seatPrice) { + await recordSubscriptionPrices(db, catalog, [{ price: seatPrice, match }], now).catch((error: unknown) => { + console.error(JSON.stringify({ error: 'record_subscription_price', message: error instanceof Error ? error.message.slice(0, 200) : '' })) + }) + } await upsertSubscription(db, { stripe_subscription_id: subscription.id, account_id: accountId, @@ -117,7 +157,7 @@ export async function syncSubscription(env: Env, stripe: StripeClient, subscript past_due_since: PAYMENT_FAILED_STATUSES.has(subscription.status) ? now : null, // Membership comes from auth, not Stripe: keep the stored count. member_count: null, - seat_price_id: seatPriceId + seat_price_id: seatPrice?.id ?? null }) await projectGrants(env, subscription.id, now) if (overageItemId) { @@ -178,29 +218,101 @@ export async function handleStripeWebhook(env: Env, stripe: StripeClient, reques if (typeof event.id !== 'string' || typeof event.type !== 'string' || !event.data?.object) { return Response.json({ error: 'invalid_event' }, { status: 400 }) } + const outcome = await processStripeEvent(env, stripe, event, now) + return Response.json(outcome.body, { status: outcome.status }) +} + +/** + * Applies one Stripe event: the webhook's path and the reconciliation replay's. Deduped by event + * id; the subscription (or customer, or catalog) is re-read from Stripe, never taken from the payload. + */ +export async function processStripeEvent( + env: Env, + stripe: StripeClient, + event: StripeEvent, + now: number +): Promise<{ status: number; body: Record }> { // Acknowledged (so Stripe stops retrying) but never applied. if (event.livemode && !allowsLiveMode(env)) { - return Response.json({ ignored: 'livemode' }) + return { status: 200, body: { ignored: 'livemode' } } } const subscriptionId = subscriptionIdFor(event) - if (!subscriptionId) { - return Response.json({ ignored: 'event_type' }) + const customerId = event.type === CUSTOMER_DELETED ? idOf(event.data.object.id) : null + const catalogEvent = CATALOG_EVENTS.has(event.type) + if (!subscriptionId && !customerId && !catalogEvent) { + return { status: 200, body: { ignored: 'event_type' } } } if ((await claimEvent(env.BILLING_DB, event.id, event.type, now)) === 'duplicate') { - return Response.json({ duplicate: true }) + return { status: 200, body: { duplicate: true } } } try { - await syncSubscription(env, stripe, subscriptionId, now) + if (subscriptionId) { + await syncSubscription(env, stripe, subscriptionId, now) + } else if (customerId) { + await endCustomerSubscriptions(env, customerId, now) + } else { + const result = await syncCatalogPrices(env, stripe, now) + if (result.error && result.error !== 'catalog_unavailable') { + throw new Error(`catalog_sync_${result.error}`) + } + } await finishEvent(env.BILLING_DB, event.id, { now }) - return Response.json({ received: true }) + return { status: 200, body: { received: true } } } catch (error) { if (error instanceof IgnoredSubscription) { // Not ours or not recognizable: retrying will not help. Recorded for the audit script. await finishEvent(env.BILLING_DB, event.id, { now, note: error.message }) - return Response.json({ ignored: error.message }) + return { status: 200, body: { ignored: error.message } } } await finishEvent(env.BILLING_DB, event.id, { error: error instanceof Error ? error.message : 'unknown' }) // Non-2xx: Stripe retries with backoff for up to three days. - return Response.json({ error: 'processing_failed' }, { status: 500 }) + return { status: 500, body: { error: 'processing_failed' } } + } +} + +/** + * A deleted Stripe customer takes its subscriptions with it (Stripe cancels them, and a deleted + * subscription can't be read back): mark every one we hold for it canceled and revoke the grants. + */ +export async function endCustomerSubscriptions(env: Env, customerId: string, now: number): Promise { + const rows = await subscriptionsForCustomer(env.BILLING_DB, customerId) + let ended = 0 + for (const row of rows) { + if (row.status === 'canceled') { + continue + } + await markCanceled(env, row, now) + ended++ + } + return ended +} + +async function markCanceled(env: Env, row: SubscriptionRow, now: number): Promise { + await upsertSubscription(env.BILLING_DB, { ...row, status: 'canceled', past_due_since: null, member_count: null, updated_at: now }) + await projectGrants(env, row.stripe_subscription_id, now) +} + +/** + * Re-reads one subscription we hold (reconciliation). A subscription Stripe no longer has (its + * customer was deleted) is canceled here. Returns what happened, for the cron summary. + */ +export async function resyncSubscription( + env: Env, + stripe: StripeClient, + row: SubscriptionRow, + now: number +): Promise<'synced' | 'canceled_missing' | 'ignored'> { + try { + await syncSubscription(env, stripe, row.stripe_subscription_id, now) + return 'synced' + } catch (error) { + if (error instanceof StripeError && error.status === 404) { + await markCanceled(env, row, now) + return 'canceled_missing' + } + if (error instanceof IgnoredSubscription) { + return 'ignored' + } + throw error } } diff --git a/cloud/apps/billing/test/billing-config.test.ts b/cloud/apps/billing/test/billing-config.test.ts index 7c6d6281d6f..1fd0c71f3c7 100644 --- a/cloud/apps/billing/test/billing-config.test.ts +++ b/cloud/apps/billing/test/billing-config.test.ts @@ -23,7 +23,10 @@ describe('config: tax and plan catalog', () => { }) it('takes Team numbers and labels and the Enterprise contact from BILLING_PLANS', async () => { + // BILLING_PLANS is the legacy catalog: with ENTITLEMENTS_MODE=on prices come from Stripe and the + // rest from the D1 catalog (test/plans-api.test.ts). const h = await createHarness({ + ENTITLEMENTS_MODE: 'off', BILLING_PLANS: JSON.stringify({ team: { includedHoursPerSeat: 40, monthlyPriceLabel: '$45 per seat per month', defaultSpendCapCents: 5000 }, enterprise: { contactUrl: 'https://example.test/sales' } diff --git a/cloud/apps/billing/test/harness.ts b/cloud/apps/billing/test/harness.ts index 97ad3c01c80..af6d764b959 100644 --- a/cloud/apps/billing/test/harness.ts +++ b/cloud/apps/billing/test/harness.ts @@ -7,6 +7,7 @@ import { createFakeD1 } from './d1-fake' import { createFakeStripe, signStripePayload } from './stripe-fake' import type { TrialPort } from '../src/cloud-setup-trial' import { applyCatalog } from '../src/catalog' +import { syncCatalogPrices } from '../src/catalog-sync' import { testCatalog } from './catalog-fixture' /** Harnesses created by the current test (the shadow guard checks each one's diff table). */ @@ -41,6 +42,9 @@ export async function createHarness(overrides: Partial = {}) { // The D1 catalog every environment gets from catalog/catalog.json (with any BILLING_PLANS test // override carried over, so the modes agree). await applyCatalog(db, testCatalog(env.BILLING_PLANS), Date.now()) + // ...and its prices, synced from the fake Stripe's lookup keys like the cron does. + await syncCatalogPrices(env, createStripeClient(env, stripe.fetchImpl), Date.now()) + stripe.calls.length = 0 liveHarnesses.push({ raw, env }) let now = Date.now() // Live org member counts from auth; null = not configured (the default). @@ -67,7 +71,11 @@ export async function createHarness(overrides: Partial = {}) { ...(outboundFetch ? { fetch: outboundFetch } : {}) }) await Promise.all(waits.splice(0)) - return { status: response.status, body: (await response.json()) as Record } + const text = await response.text() + const result = { status: response.status, body: (text ? JSON.parse(text) : null) as Record } + // Not enumerable, so `toEqual({ status, body })` assertions stay as they are. + Object.defineProperty(result, 'headers', { value: response.headers, enumerable: false }) + return result as typeof result & { headers: Headers } } return { @@ -102,6 +110,11 @@ export async function createHarness(overrides: Partial = {}) { }, async webhook(event: unknown, secret = WEBHOOK_SECRET) { const rawBody = JSON.stringify(event) + // Stripe logs every event it delivers (GET /v1/events, the reconciliation replay). + const typed = event as { id?: string; type?: string; livemode?: boolean; data?: { object: Record } } + if (typed.id && typed.type && typed.data && !stripe.events.some((entry) => entry.id === typed.id)) { + stripe.recordEvent({ id: typed.id, type: typed.type, created: Math.floor(now / 1000), livemode: typed.livemode ?? false, data: typed.data }) + } return call('POST', '/v1/stripe/webhook', { rawBody, headers: { 'stripe-signature': signStripePayload(rawBody, secret, Math.floor(now / 1000)) } diff --git a/cloud/apps/billing/test/lifecycle.test.ts b/cloud/apps/billing/test/lifecycle.test.ts new file mode 100644 index 00000000000..e8dc7c4a39f --- /dev/null +++ b/cloud/apps/billing/test/lifecycle.test.ts @@ -0,0 +1,171 @@ +// Stripe lifecycle -> grants: price changes can't orphan a subscriber (the planForPrice bug), +// pause/resume, deleted customers, and reconciliation (event replay, rolling re-sync). +import { describe, expect, it } from 'vitest' +import { syncCatalogPrices } from '../src/catalog-sync' +import { reconcile, RESYNC_AFTER_MS } from '../src/reconcile' +import { createStripeClient } from '../src/stripe' +import { syncSubscription } from '../src/webhook' +import { createHarness } from './harness' +import { checkoutCompleted, stripeEvent } from './stripe-fake' + +const HOUR = 3600 +const PERIOD_START = Math.floor(Date.now() / 1000) - 5 * 24 * HOUR +const PERIOD_END = PERIOD_START + 30 * 24 * HOUR + +async function subscribed(mode?: string, basePrice = 'price_team_month') { + const h = await createHarness(mode ? { ENTITLEMENTS_MODE: mode } : {}) + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' }) + const auth = { authorization: `Bearer ${token}` } + await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 2 }, headers: auth }) + const customer = [...h.stripe.customers.keys()][0]! + const subscription = h.stripe.putSubscription({ customer, accountId: 'org:o1', basePrice, quantity: 2, periodStart: PERIOD_START, periodEnd: PERIOD_END }) + const delivered = await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' })) + return { h, auth, customer, subscription, delivered } +} + +function entitlement(h: Awaited>, auth: Record) { + return h.call('GET', '/v1/billing/entitlements', { headers: auth }).then((response) => response.body) +} + +/** Moves the monthly lookup key to a new price and points the env at it (a price change). */ +async function changeMonthlyPrice(h: Awaited>, id: string, product = 'prod_team') { + h.stripe.prices.get('price_team_month')!.lookup_key = null + h.stripe.prices.set(id, { id, active: true, currency: 'usd', unit_amount: 5500, unit_amount_decimal: '5500', lookup_key: 'orca_team_seat_monthly', product, recurring: { interval: 'month', usage_type: 'licensed' } }) + h.env.STRIPE_PRICE_TEAM_MONTHLY = id + await syncCatalogPrices(h.env, createStripeClient(h.env, h.stripe.fetchImpl), Date.now()) +} + +describe('a price change never orphans existing subscribers (planForPrice)', () => { + // Runs in every mode project: the fix doesn't depend on ENTITLEMENTS_MODE. + it('a subscriber on the old price still has their cancel revoke access', async () => { + const { h, auth, subscription } = await subscribed() + expect((await entitlement(h, auth)).canStartSandbox).toBe(true) + await changeMonthlyPrice(h, 'price_team_month_v2') + subscription.status = 'canceled' + expect((await h.webhook(stripeEvent('customer.subscription.deleted', subscription))).body).toEqual({ received: true }) + expect(await entitlement(h, auth)).toMatchObject({ status: 'canceled', canStartSandbox: false, reason: 'subscription_inactive' }) + const start = await h.controlPlane('/v1/internal/entitlements/check', { accountId: 'org:o1', machineSize: 'standard', runningSandboxes: 0 }) + expect(start.body).toMatchObject({ allow: false, reason: 'subscription_inactive' }) + if (h.env.ENTITLEMENTS_MODE === 'on' || h.env.ENTITLEMENTS_MODE === 'shadow') { + const states = h.raw.prepare("SELECT DISTINCT state, revoked_reason FROM entitlement_grants WHERE source_type = 'subscription'").all() + expect(states).toEqual([{ state: 'revoked', revoked_reason: 'stripe_canceled' }]) + } + }) + + it('recognizes a price it never saw that is on the plan\'s product', async () => { + const h = await createHarness({ ENTITLEMENTS_MODE: 'on' }) + await changeMonthlyPrice(h, 'price_team_month_v2') + // The key moves again, to a price created after our last sync. + h.stripe.prices.set('price_team_month_v3', { id: 'price_team_month_v3', active: true, currency: 'usd', unit_amount: 5900, product: 'prod_team', recurring: { interval: 'month', usage_type: 'licensed' } }) + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' }) + const auth = { authorization: `Bearer ${token}` } + await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 1 }, headers: auth }) + const customer = [...h.stripe.customers.keys()][0]! + const subscription = h.stripe.putSubscription({ customer, accountId: 'org:o1', basePrice: 'price_team_month_v3', quantity: 1, periodStart: PERIOD_START, periodEnd: PERIOD_END }) + expect((await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' }))).body).toEqual({ received: true }) + expect(await entitlement(h, auth)).toMatchObject({ plan: 'team', interval: 'month', canStartSandbox: true, includedSeconds: 60 * HOUR }) + // ...and it is now in the price history. + expect(h.raw.prepare("SELECT plan_id, role, interval FROM plan_prices WHERE stripe_price_id = 'price_team_month_v3'").get()).toEqual({ plan_id: 'team', role: 'seat', interval: 'month' }) + }) + + it('still applies status for a known subscriber on an unmappable price', async () => { + const { h, auth, subscription } = await subscribed('on') + subscription.items.data[0]!.price = { id: 'price_mystery', recurring: { usage_type: 'licensed' } } + subscription.status = 'canceled' + expect((await h.webhook(stripeEvent('customer.subscription.deleted', subscription))).body).toEqual({ received: true }) + expect(await entitlement(h, auth)).toMatchObject({ plan: 'team', seats: 2, canStartSandbox: false, reason: 'subscription_inactive' }) + }) + + it('still ignores an unknown subscription on an unknown price', async () => { + const h = await createHarness({ ENTITLEMENTS_MODE: 'on' }) + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' }) + await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team' }, headers: { authorization: `Bearer ${token}` } }) + const customer = [...h.stripe.customers.keys()][0]! + const subscription = h.stripe.putSubscription({ customer, accountId: 'org:o1', basePrice: 'price_other_product', periodStart: PERIOD_START, periodEnd: PERIOD_END }) + expect((await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' }))).body).toEqual({ + ignored: 'unrecognized_subscription_items' + }) + }) +}) + +describe('Stripe states (ENTITLEMENTS_MODE=on)', () => { + it('holds on pause and releases on resume', async () => { + const { h, auth, subscription } = await subscribed('on') + subscription.status = 'paused' + await h.webhook(stripeEvent('customer.subscription.paused', subscription)) + expect(await entitlement(h, auth)).toMatchObject({ canStartSandbox: false, reason: 'subscription_inactive' }) + expect(h.raw.prepare("SELECT DISTINCT state, hold_reason FROM entitlement_grants").all()).toEqual([{ state: 'held', hold_reason: 'paused' }]) + subscription.status = 'active' + await h.webhook(stripeEvent('customer.subscription.resumed', subscription)) + expect((await entitlement(h, auth)).canStartSandbox).toBe(true) + }) + + it('revokes everything when the Stripe customer is deleted', async () => { + const { h, auth, customer } = await subscribed('on') + expect((await h.webhook(stripeEvent('customer.deleted', { id: customer, object: 'customer' }))).body).toEqual({ received: true }) + expect(await entitlement(h, auth)).toMatchObject({ status: 'canceled', canStartSandbox: false }) + expect(h.raw.prepare('SELECT DISTINCT state FROM entitlement_grants').all()).toEqual([{ state: 'revoked' }]) + }) + + it('never lets an older Stripe read overwrite the mirror', async () => { + const { h, auth, subscription } = await subscribed('on') + subscription.status = 'canceled' + await syncSubscription(h.env, createStripeClient(h.env, h.stripe.fetchImpl), subscription.id, Date.now() + 1000) + subscription.status = 'active' + // A slower handler that read Stripe earlier finishes last. + await syncSubscription(h.env, createStripeClient(h.env, h.stripe.fetchImpl), subscription.id, Date.now() - 1000) + expect((await entitlement(h, auth)).status).toBe('canceled') + }) +}) + +describe('reconciliation (ENTITLEMENTS_MODE=on)', () => { + it('replays events whose webhook never arrived', async () => { + const h = await createHarness({ ENTITLEMENTS_MODE: 'on' }) + const stripe = createStripeClient(h.env, h.stripe.fetchImpl) + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' }) + const auth = { authorization: `Bearer ${token}` } + await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 1 }, headers: auth }) + // First run: only sets the cursor at the newest event. + h.stripe.recordEvent({ id: 'evt_old', type: 'invoice.paid', created: 1, livemode: false, data: { object: { id: 'in_1', subscription: 'sub_gone' } } }) + expect((await reconcile(h.env, stripe, Date.now()))!.events).toEqual({ replayed: 0, applied: 0, failed: 0 }) + const customer = [...h.stripe.customers.keys()][0]! + const subscription = h.stripe.putSubscription({ customer, accountId: 'org:o1', basePrice: 'price_team_month', quantity: 1, periodStart: PERIOD_START, periodEnd: PERIOD_END }) + const missed = checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' }) + h.stripe.recordEvent({ id: missed.id, type: missed.type, created: missed.created, livemode: false, data: missed.data }) + expect((await entitlement(h, auth)).canStartSandbox).toBe(false) + expect((await reconcile(h.env, stripe, Date.now()))!.events).toEqual({ replayed: 1, applied: 1, failed: 0 }) + expect((await entitlement(h, auth)).canStartSandbox).toBe(true) + // A delivered-and-processed event is not applied twice. + await h.webhook(missed) + expect((await reconcile(h.env, stripe, Date.now()))!.events).toEqual({ replayed: 0, applied: 0, failed: 0 }) + }) + + it('re-reads stale subscriptions: a cancel Stripe never told us about still revokes', async () => { + const { h, auth, subscription } = await subscribed('on') + const stripe = createStripeClient(h.env, h.stripe.fetchImpl) + subscription.status = 'canceled' + // Not stale yet: nothing re-read. + expect((await reconcile(h.env, stripe, Date.now()))!.subscriptions).toMatchObject({ checked: 0 }) + const later = Date.now() + RESYNC_AFTER_MS + 1000 + h.setNow(later) + expect((await reconcile(h.env, stripe, later))!.subscriptions).toEqual({ checked: 1, changed: 1, canceledMissing: 0, failed: 0 }) + expect(await entitlement(h, auth)).toMatchObject({ status: 'canceled', canStartSandbox: false }) + expect(h.raw.prepare('SELECT DISTINCT state FROM entitlement_grants').all()).toEqual([{ state: 'revoked' }]) + // Done: a canceled subscription with nothing live is not re-read again. + expect((await reconcile(h.env, stripe, later + RESYNC_AFTER_MS * 2))!.subscriptions.checked).toBe(0) + }) + + it('cancels a subscription Stripe no longer has', async () => { + const { h, auth, subscription } = await subscribed('on') + h.stripe.subscriptions.delete(subscription.id) + const later = Date.now() + RESYNC_AFTER_MS + 1000 + h.setNow(later) + expect((await reconcile(h.env, createStripeClient(h.env, h.stripe.fetchImpl), later))!.subscriptions).toMatchObject({ canceledMissing: 1 }) + expect(await entitlement(h, auth)).toMatchObject({ status: 'canceled', canStartSandbox: false }) + }) + + it('does nothing while the mode is off', async () => { + const h = await createHarness({ ENTITLEMENTS_MODE: 'off' }) + expect(await reconcile(h.env, createStripeClient(h.env, h.stripe.fetchImpl), Date.now())).toBeNull() + }) +}) diff --git a/cloud/apps/billing/test/plans-api.test.ts b/cloud/apps/billing/test/plans-api.test.ts new file mode 100644 index 00000000000..5f1bc6604a2 --- /dev/null +++ b/cloud/apps/billing/test/plans-api.test.ts @@ -0,0 +1,199 @@ +// GET /v1/plans, GET /v1/entitlements, catalog prices from Stripe, and the legacy `offers` built +// from the D1 catalog when ENTITLEMENTS_MODE is on. +import { describe, expect, it } from 'vitest' +import { syncCatalogPrices } from '../src/catalog-sync' +import { publicOffers, DEFAULT_PLANS } from '../src/plans' +import { formatPrice } from '../src/plans-api' +import { createStripeClient } from '../src/stripe' +import { createHarness } from './harness' +import { checkoutCompleted } from './stripe-fake' + +const HOUR = 3600 +const PERIOD_START = Math.floor(Date.now() / 1000) - 5 * 24 * HOUR +const PERIOD_END = PERIOD_START + 30 * 24 * HOUR + +async function resyncPrices(h: Awaited>) { + return syncCatalogPrices(h.env, createStripeClient(h.env, h.stripe.fetchImpl), Date.now()) +} + +describe('GET /v1/plans', () => { + it('serves the catalog with Stripe prices, entitlements, features and policy; never price ids', async () => { + const h = await createHarness() + const response = await h.call('GET', '/v1/plans') + expect(response.status).toBe(200) + expect(response.headers.get('cache-control')).toBe('public, max-age=300') + expect(response.headers.get('access-control-allow-origin')).toBe('*') + const body = response.body + expect(body.schemaVersion).toBe(1) + expect(body.plans.map((plan: { id: string }) => plan.id)).toEqual(['trial', 'team', 'enterprise']) + const team = body.plans.find((plan: { id: string }) => plan.id === 'team') + expect(team).toMatchObject({ + kind: 'self_serve', + name: 'Team', + billing: 'per_seat', + prices: [ + { interval: 'month', unitAmountCents: 5000, currency: 'usd' }, + { interval: 'year', unitAmountCents: 48000, currency: 'usd' } + ], + overage: { centsPerHour: 100, billedPer: 'minute', defaultSpendCapCents: 2500, maxSpendCapCents: 500_000 }, + seats: { min: 1, max: 500 }, + warnAtPercent: [75, 90, 100], + entitlements: { sandbox_hours_monthly: { value: 60, perSeat: true }, max_concurrent_sandboxes: { value: 3, perSeat: true } }, + checkout: { available: true, intervals: ['month', 'year'] } + }) + expect(team.features[0]).toEqual({ id: 'included_hours_per_seat', params: { hours: 60 }, text: '60 sandbox hours per seat each month, pooled across your team' }) + expect(body.plans.find((plan: { id: string }) => plan.id === 'enterprise')).toMatchObject({ kind: 'contact_sales', contactUrl: 'https://onorca.dev/contact-sales' }) + expect(body.plans.find((plan: { id: string }) => plan.id === 'trial')).toMatchObject({ kind: 'trial', entitlements: { sandbox_hours_lifetime: { value: 2, perSeat: false } } }) + expect(JSON.stringify(body)).not.toContain('price_') + }) + + it('answers 304 to a matching ETag, and the ETag changes when a Stripe price changes', async () => { + const h = await createHarness() + const first = await h.call('GET', '/v1/plans') + const etag = first.headers.get('etag')! + expect((await h.call('GET', '/v1/plans', { headers: { 'if-none-match': etag } })).status).toBe(304) + h.stripe.prices.get('price_team_month')!.unit_amount = 5500 + await resyncPrices(h) + const second = await h.call('GET', '/v1/plans', { headers: { 'if-none-match': etag } }) + expect(second.status).toBe(200) + expect(second.body.plans.find((plan: { id: string }) => plan.id === 'team').prices[0].unitAmountCents).toBe(5500) + }) + + it('shows no price (and no checkout) for an interval Stripe has no price for: never a guessed one', async () => { + const h = await createHarness({ ENTITLEMENTS_MODE: 'on' }) + h.stripe.prices.get('price_team_year')!.active = false + h.raw.exec("UPDATE plan_prices SET active = 0 WHERE stripe_price_id = 'price_team_year'") + const team = (await h.call('GET', '/v1/plans')).body.plans.find((plan: { id: string }) => plan.id === 'team') + expect(team.prices.map((price: { interval: string }) => price.interval)).toEqual(['month']) + expect(team.checkout).toEqual({ available: true, intervals: ['month'] }) + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' }) + const auth = { authorization: `Bearer ${token}` } + expect(await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', interval: 'year' }, headers: auth })).toEqual({ + status: 409, + body: { error: 'plan_unavailable' } + }) + const offers = (await h.call('GET', '/v1/billing/entitlements', { headers: auth })).body.offers + expect(offers.team).toMatchObject({ annualPriceCentsPerSeat: null, annualPriceLabel: '', monthlyPriceCentsPerSeat: 5000 }) + }) + + it('fails closed (503) before a catalog was ever applied', async () => { + const h = await createHarness() + h.raw.exec('DELETE FROM plan_versions; DELETE FROM plans;') + const { invalidateCatalog } = await import('../src/catalog') + invalidateCatalog(h.env.BILLING_DB) + expect(await h.call('GET', '/v1/plans')).toEqual({ status: 503, body: { error: 'billing_misconfigured' } }) + }) +}) + +describe('catalog prices follow the Stripe lookup keys', () => { + it('sells the new price once the lookup key moves; the old one stays as history', async () => { + const h = await createHarness({ ENTITLEMENTS_MODE: 'on' }) + h.stripe.prices.get('price_team_month')!.lookup_key = null + h.stripe.prices.set('price_team_month_v2', { + id: 'price_team_month_v2', + active: true, + currency: 'usd', + unit_amount: 6000, + unit_amount_decimal: '6000', + lookup_key: 'orca_team_seat_monthly', + product: 'prod_team', + recurring: { interval: 'month', usage_type: 'licensed' } + }) + await resyncPrices(h) + const rows = h.raw.prepare("SELECT stripe_price_id, is_checkout_price FROM plan_prices WHERE role = 'seat' AND interval = 'month' ORDER BY stripe_price_id").all() + expect(rows).toEqual([ + { stripe_price_id: 'price_team_month', is_checkout_price: 0 }, + { stripe_price_id: 'price_team_month_v2', is_checkout_price: 1 } + ]) + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' }) + await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team' }, headers: { authorization: `Bearer ${token}` } }) + const session = h.stripe.calls.find((call) => call.path === '/v1/checkout/sessions' && call.method === 'POST')! + expect(session.form.get('line_items[0][price]')).toBe('price_team_month_v2') + const offers = (await h.call('GET', '/v1/billing/entitlements', { headers: { authorization: `Bearer ${token}` } })).body.offers + expect(offers.team).toMatchObject({ monthlyPriceCentsPerSeat: 6000, monthlyPriceLabel: '$60 per seat per month' }) + }) + + it('refreshes on a price.updated webhook', async () => { + const h = await createHarness({ ENTITLEMENTS_MODE: 'on' }) + h.stripe.prices.get('price_team_year')!.unit_amount = 45000 + const { stripeEvent } = await import('./stripe-fake') + expect((await h.webhook(stripeEvent('price.updated', { id: 'price_team_year', object: 'price' }))).body).toEqual({ received: true }) + const team = (await h.call('GET', '/v1/plans')).body.plans.find((plan: { id: string }) => plan.id === 'team') + expect(team.prices[1]).toEqual({ interval: 'year', unitAmountCents: 45000, currency: 'usd' }) + }) + + it('keeps the prices it has when the key may not read Prices (403), and says so', async () => { + const h = await createHarness({ ENTITLEMENTS_MODE: 'on' }) + const forbidden: typeof fetch = async () => Response.json({ error: { message: 'restricted' } }, { status: 403 }) + const result = await syncCatalogPrices(h.env, createStripeClient(h.env, forbidden), Date.now()) + expect(result.error).toBe('stripe_403') + const team = (await h.call('GET', '/v1/plans')).body.plans.find((plan: { id: string }) => plan.id === 'team') + expect(team.prices).toHaveLength(2) + }) +}) + +describe('offers from the catalog (ENTITLEMENTS_MODE=on)', () => { + it('match the legacy offers for the launch catalog, plus the warning levels', async () => { + const h = await createHarness({ ENTITLEMENTS_MODE: 'on' }) + const token = await h.desktopToken({ sub: 'u1' }) + const offers = (await h.call('GET', '/v1/billing/entitlements', { headers: { authorization: `Bearer ${token}` } })).body.offers + const { trial, ...rest } = offers + expect(trial).toBeNull() + const legacy = publicOffers({ team: DEFAULT_PLANS.team, enterprise: DEFAULT_PLANS.enterprise }) + expect(rest).toEqual({ ...legacy, team: { ...legacy.team, warnAtPercent: [75, 90, 100] } }) + const setup = (await h.call('GET', '/v1/cloud-setup/offers')).body + expect(setup.team.monthlyPriceLabel).toBe('$50 per seat per month') + }) + + it('formats prices like the legacy labels', () => { + expect(formatPrice(5000, 'usd')).toBe('$50') + expect(formatPrice(48000, 'usd')).toBe('$480') + expect(formatPrice(1250, 'usd')).toBe('$12.50') + expect(formatPrice(100000, 'usd')).toBe('$1,000') + }) +}) + +describe('GET /v1/entitlements', () => { + it('returns effective values, access and the grants behind them', async () => { + const h = await createHarness({ ENTITLEMENTS_MODE: 'on' }) + const token = await h.desktopToken({ sub: 'u1', org: 'o1', orgRole: 'owner', email: 'a@example.com' }) + const auth = { authorization: `Bearer ${token}` } + expect((await h.call('GET', '/v1/entitlements')).status).toBe(401) + expect((await h.call('GET', '/v1/entitlements', { headers: auth })).body).toMatchObject({ + schemaVersion: 1, + subject: 'org:o1', + source: 'grants', + plan: null, + access: { canStartSandbox: false, reason: 'no_subscription' }, + grants: [], + canManageBilling: true + }) + await h.call('POST', '/v1/billing/checkout', { body: { plan: 'team', seats: 2 }, headers: auth }) + const customer = [...h.stripe.customers.keys()][0]! + const subscription = h.stripe.putSubscription({ customer, accountId: 'org:o1', basePrice: 'price_team_month', quantity: 2, periodStart: PERIOD_START, periodEnd: PERIOD_END }) + await h.webhook(checkoutCompleted({ customer, subscription: subscription.id, accountId: 'org:o1' })) + const view = await h.call('GET', '/v1/entitlements', { headers: auth }) + expect(view.headers.get('cache-control')).toBe('private, no-cache') + expect(view.body).toMatchObject({ + plan: { id: 'team', name: 'Team', status: 'active', interval: 'month', seats: 2, cancelAtPeriodEnd: false }, + effective: { + sandboxSeconds: { included: 120 * HOUR, used: 0, remaining: 120 * HOUR, resets: 'monthly' }, + maxConcurrentSandboxes: 6, + maxConcurrentSandboxesPerMember: 3, + machineSizes: ['standard', 'large'] + }, + access: { canStartSandbox: true, reason: null, suspendRunning: false } + }) + expect(view.body.grants).toContainEqual({ + key: 'sandbox_hours_monthly', + value: 60, + perSeat: true, + seats: 2, + source: 'subscription', + state: 'active', + plan: { id: 'team', version: 1 }, + startsAt: PERIOD_START * 1000, + endsAt: null + }) + }) +}) diff --git a/cloud/apps/billing/test/stripe-fake.ts b/cloud/apps/billing/test/stripe-fake.ts index 8c6209990b0..3e0e28f296f 100644 --- a/cloud/apps/billing/test/stripe-fake.ts +++ b/cloud/apps/billing/test/stripe-fake.ts @@ -14,12 +14,34 @@ export type FakeSubscription = { items: { object: 'list'; data: FakeItem[] } } +type FakePrice = { + id: string + object?: 'price' + active?: boolean + livemode?: boolean + currency?: string + unit_amount?: number | null + unit_amount_decimal?: string | null + lookup_key?: string | null + product?: string + recurring: { interval?: string; usage_type: 'licensed' | 'metered' } +} + type FakeItem = { id: string quantity?: number current_period_start: number current_period_end: number - price: { id: string; recurring: { usage_type: 'licensed' | 'metered' } } + price: FakePrice +} + +/** The test-mode catalog the harness env names (STRIPE_PRICE_*), like stripe-test-setup.ts makes. */ +export function defaultFakePrices(): FakePrice[] { + return [ + { id: 'price_team_month', active: true, currency: 'usd', unit_amount: 5000, unit_amount_decimal: '5000', lookup_key: 'orca_team_seat_monthly', product: 'prod_team', recurring: { interval: 'month', usage_type: 'licensed' } }, + { id: 'price_team_year', active: true, currency: 'usd', unit_amount: 48000, unit_amount_decimal: '48000', lookup_key: 'orca_team_seat_annual', product: 'prod_team', recurring: { interval: 'year', usage_type: 'licensed' } }, + { id: 'price_overage', active: true, currency: 'usd', unit_amount: null, unit_amount_decimal: '1.666666666667', lookup_key: 'orca_sandbox_overage_per_minute', product: 'prod_overage', recurring: { interval: 'month', usage_type: 'metered' } } + ] } export type RecordedCall = { method: string; path: string; form: URLSearchParams; headers: Headers } @@ -31,7 +53,12 @@ export function createFakeStripe() { const idempotent = new Map() const checkoutSessions = new Map() const meterEvents: Array> = [] + const prices = new Map(defaultFakePrices().map((price) => [price.id, price])) + // Stripe's event log (newest last here; listed newest first like Stripe). + const events: Array<{ id: string; type: string; created: number; livemode: boolean; data: { object: Record } }> = [] let nextId = 1 + const priceFor = (id: string, usage: 'licensed' | 'metered'): FakePrice => + structuredClone(prices.get(id) ?? { id, recurring: { usage_type: usage } }) let failMeterEvents = 0 const fetchImpl: typeof fetch = async (input, init) => { @@ -86,6 +113,28 @@ export function createFakeStripe() { const id = `bps_test_${nextId++}` return respond({ id, url: `https://billing.stripe.com/p/session/${id}` }) } + if (method === 'GET' && url.pathname === '/v1/prices') { + const keys = [...url.searchParams.entries()].filter(([name]) => name.startsWith('lookup_keys')).map(([, value]) => value) + return Response.json({ + object: 'list', + data: [...prices.values()].filter((price) => price.active !== false && price.lookup_key && keys.includes(price.lookup_key)) + }) + } + if (method === 'GET' && url.pathname === '/v1/events') { + const types = [...url.searchParams.entries()].filter(([name]) => name.startsWith('types')).map(([, value]) => value) + const before = url.searchParams.get('ending_before') + const limit = Number(url.searchParams.get('limit') ?? '10') + const matching = events.filter((event) => types.length === 0 || types.includes(event.type)) + let page: typeof matching + if (before) { + const index = matching.findIndex((event) => event.id === before) + // The `limit` events right after the cursor (oldest of the newer ones first), newest first. + page = (index < 0 ? [] : matching.slice(index + 1, index + 1 + limit)).reverse() + return Response.json({ object: 'list', data: page, has_more: index >= 0 && matching.length > index + 1 + limit }) + } + page = matching.slice(-limit).reverse() + return Response.json({ object: 'list', data: page, has_more: matching.length > limit }) + } if (method === 'GET' && url.pathname.startsWith('/v1/subscriptions/')) { const subscription = subscriptions.get(decodeURIComponent(url.pathname.slice('/v1/subscriptions/'.length))) return subscription @@ -97,7 +146,7 @@ export function createFakeStripe() { for (const subscription of subscriptions.values()) { const item = subscription.items.data.find((entry) => entry.id === itemId) if (item && form.has('price')) { - item.price = { id: form.get('price')!, recurring: { usage_type: 'metered' } } + item.price = priceFor(form.get('price')!, 'metered') return respond({ id: item.id, price: item.price }) } if (item) { @@ -126,7 +175,7 @@ export function createFakeStripe() { const base = subscription.items.data[0]! const item: FakeItem = { id: `si_test_${nextId++}`, - price: { id: form.get('price') ?? '', recurring: { usage_type: 'metered' } }, + price: priceFor(form.get('price') ?? '', 'metered'), current_period_start: base.current_period_start, current_period_end: base.current_period_end } @@ -150,6 +199,12 @@ export function createFakeStripe() { customers, subscriptions, meterEvents, + prices, + events, + /** Stripe records an event (whether or not its webhook is delivered). */ + recordEvent(event: { id: string; type: string; created: number; livemode: boolean; data: { object: Record } }) { + events.push(event) + }, failNextMeterEvents(count: number) { failMeterEvents = count }, @@ -169,10 +224,10 @@ export function createFakeStripe() { const id = `sub_test_${nextId++}` const period = { current_period_start: args.periodStart, current_period_end: args.periodEnd } const data: FakeSubscription['items']['data'] = [ - { id: `si_test_${nextId++}`, quantity: args.quantity ?? 1, price: { id: args.basePrice, recurring: { usage_type: 'licensed' } }, ...period } + { id: `si_test_${nextId++}`, quantity: args.quantity ?? 1, price: priceFor(args.basePrice, 'licensed'), ...period } ] for (const price of [args.overagePrice ?? []].flat()) { - data.push({ id: `si_test_${nextId++}`, price: { id: price, recurring: { usage_type: 'metered' } }, ...period }) + data.push({ id: `si_test_${nextId++}`, price: priceFor(price, 'metered'), ...period }) } const subscription: FakeSubscription = { id,