Open source CapCut alternative.
TypeScript
feat(site): read plan terms from su [rebuild]
David Leea0b4bf1ce74
diff --git a/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.ts b/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.tsindex 4a0d8a43..45d78264 100644--- a/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.ts+++ b/site/src/app/[locale]/cut/_components/landing/cutPricingPlans.ts@@ -1,9 +1,10 @@import { useLocale, useTranslations } from "next-intl";import type { PricingPlan } from "@/app/_components/landing/pricingPlans";+import { usePlanTerms } from "@/app/_components/PlanTermsProvider";import type { CardColor } from "@/app/_components/landing/theme";import { promotionCovers, type AllowancePromotion } from "@/lib/billing/allowance-promotion";-import { PAID_PLANS, PLAN_TERMS, RECOMMENDED_PLAN, type PaidPlan } from "@/lib/billing/plans";+import { PAID_PLANS, PLAN_NAMES, RECOMMENDED_PLAN, type PaidPlan, type PlanTerms } from "@/lib/billing/plans";import { formatCreditCount } from "@/lib/credits/format-credits";import { formatUsdPlain } from "@/lib/credits/format-usd";@@ -31,15 +32,17 @@ export type PlanCopy = {export function useCutPlans(): PlanCopy[] {const t = useTranslations("common.plans");const locale = useLocale();+ const table = usePlanTerms();return PAID_PLANS.map((plan, i) => {- const terms = PLAN_TERMS[plan];- const below = i > 0 ? PLAN_TERMS[PAID_PLANS[i - 1]] : null;+ const terms = table[plan];+ const below = i > 0 ? PAID_PLANS[i - 1] : null;+ const belowTerms = below ? table[below] : null;const amount = formatUsdPlain(String(terms.monthlyDollars), locale);const features: PlanFeature[] = [{ kind: "credits", text: t("credits", { credits: formatCreditCount(terms.monthlyCredits, locale) }) },- ...(below ? [{ kind: "inherits" as const, text: t("everythingIn", { plan: below.name }) }] : []),+ ...(below ? [{ kind: "inherits" as const, text: t("everythingIn", { plan: PLAN_NAMES[below] }) }] : []),{ kind: "check", text: t("storage", { gb: terms.storageGb }) },- ...(terms.unlimitedProjects && !below?.unlimitedProjects+ ...(terms.unlimitedProjects && !belowTerms?.unlimitedProjects? [{ kind: "check" as const, text: t("unlimitedProjects") }]: []),...(below ? [{ kind: "check" as const, text: t("renders", { count: terms.rendersPerDay }) }] : []),@@ -47,7 +50,7 @@ export function useCutPlans(): PlanCopy[] {];return {plan,- name: terms.name,+ name: PLAN_NAMES[plan],body: t("body", { plan }),price: t("price", { price: amount }),amount,@@ -63,15 +66,16 @@ export function useCutPlan(plan: PaidPlan): PlanCopy {}// The allowance promotion as the Pro card states it, while a period starting-// now would get it: the multiplied allowance in USD and the last day. Null-// when the plain plan applies.+// now would get it: the multiplied allowance in credits and the last day.+// Null when the plain plan applies.export function activeProPromotion(promotion: AllowancePromotion,+ pro: PlanTerms,now = new Date(),-): { allowanceDollars: number; multiplier: number; lastDay: string | null } | null {+): { allowanceCredits: number; multiplier: number; lastDay: string | null } | null {if (!promotionCovers(promotion, now)) return null;return {- allowanceDollars: PLAN_TERMS.pro.monthlyDollars * promotion.multiplier,+ allowanceCredits: pro.monthlyCredits * promotion.multiplier,multiplier: promotion.multiplier,lastDay: promotion.lastDay,};diff --git a/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsx b/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsxindex 07830bc6..6815608d 100644--- a/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsx+++ b/site/src/app/[locale]/cut/app/(home)/settings/_components/ProCard.tsx@@ -18,20 +18,19 @@ import {CardTitle,} from "@/components/ui/card";import { Skeleton } from "@/components/ui/skeleton";+import { usePlanTerms } from "@/app/_components/PlanTermsProvider";import { activeProPromotion, useCutPlan } from "@/app/[locale]/cut/_components/landing/cutPricingPlans";import { useApiErrorText } from "@/app/[locale]/cut/app/(home)/settings/_components/useApiErrorText";import { useIntroTerms } from "@/cut/components/IntroOffer";import { useCreditLifeClause, useFormatDeadline } from "@/cut/components/SubscribeBonusPill";import { openUpgrade } from "@/cut/lib/upgrade";import { track } from "@/lib/analytics";-import { PAID_PLANS, PLAN_TERMS } from "@/lib/billing/plans";-import { creditCountLabel, creditsFromDollars, creditsPerDollar, formatCreditCount, formatCredits } from "@/lib/credits/format-credits";+import { PAID_PLANS, PLAN_NAMES } from "@/lib/billing/plans";+import { creditCountLabel, creditsFromDollars, formatCreditCount, formatCredits } from "@/lib/credits/format-credits";import type { Locale } from "@/i18n/locales";import { useSubscribeBonus } from "@/queries/credits";import { useAccountConfig } from "@/queries/accountConfig";-// A whole-dollar allowance as the credits it buys: $20 → "20,000 credits".-const allowanceCredits = (dollars: number, locale: Locale) => creditCountLabel(dollars * creditsPerDollar, locale);// The left-over half of "12,300 of 20,000 credits"; the total carries the unit.const leftCount = (dollars: string, locale: Locale) => formatCreditCount(creditsFromDollars(dollars, "down"), locale);@@ -54,7 +53,8 @@ export function ProCard() {const portal = useOpenBillingPortal();const bonus = useSubscribeBonus();const config = useAccountConfig({ enabled: true });- const promotion = config.data ? activeProPromotion(config.data.settings.proAllowancePromotion) : null;+ const terms = usePlanTerms();+ const promotion = config.data ? activeProPromotion(config.data.settings.proAllowancePromotion, terms.pro) : null;const intro = useIntroOffer({ enabled: pro.data?.isActive === false });if (pro.isLoading) {@@ -80,7 +80,7 @@ export function ProCard() {<Card><CardHeader><CardTitle className="flex items-center gap-3">- {plan ? t("titlePlan", { plan: PLAN_TERMS[plan].name }) : t("title")}+ {plan ? t("titlePlan", { plan: PLAN_NAMES[plan] }) : t("title")}{isActive && data ? (<Badge variant="default">{t("status", { status: data.status ?? "" })}</Badge>) : null}@@ -93,14 +93,14 @@ export function ProCard() {? t.rich("promotionUntil", {b: (chunks) => <span className="font-medium">{chunks}</span>,day: lastDayLabel(promotion.lastDay),- allowance: allowanceCredits(promotion.allowanceDollars, locale),+ allowance: creditCountLabel(promotion.allowanceCredits, locale),multiplier: format.number(promotion.multiplier),- usual: allowanceCredits(PLAN_TERMS.pro.monthlyDollars, locale),+ usual: creditCountLabel(terms.pro.monthlyCredits, locale),}): t("promotionOpen", {- allowance: allowanceCredits(promotion.allowanceDollars, locale),+ allowance: creditCountLabel(promotion.allowanceCredits, locale),multiplier: format.number(promotion.multiplier),- usual: allowanceCredits(PLAN_TERMS.pro.monthlyDollars, locale),+ usual: creditCountLabel(terms.pro.monthlyCredits, locale),})}</CardContent>) : null}@@ -129,9 +129,9 @@ export function ProCard() {{promotion.lastDay !== null? t("activePromotionUntil", {day: lastDayLabel(promotion.lastDay),- allowance: allowanceCredits(promotion.allowanceDollars, locale),+ allowance: creditCountLabel(promotion.allowanceCredits, locale),})- : t("activePromotionOpen", { allowance: allowanceCredits(promotion.allowanceDollars, locale) })}+ : t("activePromotionOpen", { allowance: creditCountLabel(promotion.allowanceCredits, locale) })}</div>) : null}{offer?.status === "claimed" ? (diff --git a/site/src/app/[locale]/layout.tsx b/site/src/app/[locale]/layout.tsxindex a3ae0a3b..9f96c479 100644--- a/site/src/app/[locale]/layout.tsx+++ b/site/src/app/[locale]/layout.tsx@@ -13,6 +13,8 @@ import { LOCALES, isLocale } from "@/i18n/locales";import { THEME_HEAD_SCRIPT } from "@/lib/theme";import { QueryProvider } from "@/queries/QueryProvider";import { MetaPageView } from "@/app/_components/MetaPageView";+import { PlanTermsProvider } from "@/app/_components/PlanTermsProvider";+import { cachedPlanTerms } from "@/lib/billing/plan-terms-server";import { PostHogProvider } from "@/app/_components/PostHogProvider";export async function generateMetadata(): Promise<Metadata> {@@ -58,6 +60,8 @@ export default async function RootLayout({if (!isLocale(locale)) {notFound();}+ // Cached, so the terms are in every page's static shell.+ const planTerms = await cachedPlanTerms();return (<htmllang={locale}@@ -71,7 +75,9 @@ export default async function RootLayout({<body className="min-h-full flex flex-col"><PostHogProvider><QueryProvider>- <IntlScope namespaces={["common"]}>{children}</IntlScope>+ <PlanTermsProvider terms={planTerms}>+ <IntlScope namespaces={["common"]}>{children}</IntlScope>+ </PlanTermsProvider></QueryProvider><Suspense fallback={null}><MetaPageView />diff --git a/site/src/app/_components/PlanTermsProvider.tsx b/site/src/app/_components/PlanTermsProvider.tsxnew file mode 100644index 00000000..c9f35f96--- /dev/null+++ b/site/src/app/_components/PlanTermsProvider.tsx@@ -0,0 +1,22 @@+"use client";++import { createContext, useContext, type ReactNode } from "react";++import type { PlanTermsTable } from "@/lib/billing/plans";++// The plan terms the root layout read on the server, handed to every card+// that sells a plan. They arrive in the page's HTML, so nothing waits on a+// fetch and no figure repaints after the first frame.+const PlanTermsContext = createContext<PlanTermsTable | null>(null);++export function PlanTermsProvider({ terms, children }: { terms: PlanTermsTable; children: ReactNode }) {+ return <PlanTermsContext.Provider value={terms}>{children}</PlanTermsContext.Provider>;+}++export function usePlanTerms(): PlanTermsTable {+ const terms = useContext(PlanTermsContext);+ if (!terms) {+ throw new Error("usePlanTerms needs a PlanTermsProvider above it.");+ }+ return terms;+}diff --git a/site/src/app/api/billing/checkout/route.ts b/site/src/app/api/billing/checkout/route.tsindex e94ff074..d089348f 100644--- a/site/src/app/api/billing/checkout/route.ts+++ b/site/src/app/api/billing/checkout/route.ts@@ -7,7 +7,7 @@ import { auth } from "@/lib/auth";import { introCouponId } from "@/lib/billing/intro-offer";import { introCoupon, readIntroOffer } from "@/lib/billing/intro-offer-server";import { metaCheckoutMetadata, trackCheckoutStarted } from "@/lib/billing/meta-checkout";-import { PAID_PLANS, PLAN_TERMS, planRank, type PaidPlan } from "@/lib/billing/plans";+import { PAID_PLANS, PLAN_NAMES, planRank, type PaidPlan } from "@/lib/billing/plans";import { dropIntroDiscount, INTRO_OFFER_METADATA_KEY, liftScheduledCancel, upgradeKey } from "@/lib/billing/plan-upgrade";import {getActiveSubscription,@@ -101,7 +101,7 @@ export const POST = withDonkeyAuth(async (request) => {customer: customerId,line_items: [{ price: priceId, quantity: 1 }],locale: STRIPE_LOCALE[requestLocale(request)],- metadata: { ...metaCheckoutMetadata(request.headers), plan: PLAN_TERMS[plan].name },+ metadata: { ...metaCheckoutMetadata(request.headers), plan: PLAN_NAMES[plan] },mode: "subscription",subscription_data: {metadata: {@@ -120,7 +120,7 @@ export const POST = withDonkeyAuth(async (request) => {);}- trackCheckoutStarted(checkout.id, PLAN_TERMS[plan].name, request.headers, session.user);+ trackCheckoutStarted(checkout.id, PLAN_NAMES[plan], request.headers, session.user);return NextResponse.json({ url: checkout.url });});diff --git a/site/src/app/api/billing/plans/revalidate/route.ts b/site/src/app/api/billing/plans/revalidate/route.tsnew file mode 100644index 00000000..8adc6a56--- /dev/null+++ b/site/src/app/api/billing/plans/revalidate/route.ts@@ -0,0 +1,34 @@+import { timingSafeEqual } from "node:crypto";++import { NextResponse } from "next/server";++import { revalidatePlanTerms } from "@/lib/billing/plan-terms-server";++// su writes the plan terms from a separate deployment, and a cache clears+// only from inside the app that holds it, so su posts here after each save.+// Deliberately not wrapped in withDonkeyAuth — the caller is a machine, not a+// session — and gated by the shared secret su already holds for the site's+// caches (the blog's revalidate route takes the same one).++const HTTP_UNAUTHORIZED = 401;+const HTTP_SERVER_ERROR = 500;++/** Constant-time bearer check: a byte-by-byte `!==` would leak the secret's+ * length and prefix through timing. */+function authorized(header: string, secret: string): boolean {+ const expected = Buffer.from(`Bearer ${secret}`);+ const got = Buffer.from(header);+ return got.length === expected.length && timingSafeEqual(got, expected);+}++export async function POST(request: Request) {+ const secret = process.env.BLOG_REVALIDATE_SECRET;+ if (!secret) {+ return new Response("BLOG_REVALIDATE_SECRET is not set", { status: HTTP_SERVER_ERROR });+ }+ if (!authorized(request.headers.get("authorization") ?? "", secret)) {+ return new Response("Unauthorized", { status: HTTP_UNAUTHORIZED });+ }+ revalidatePlanTerms();+ return NextResponse.json({ ok: true });+}diff --git a/site/src/cut/components/CreditsPill.tsx b/site/src/cut/components/CreditsPill.tsxindex 573598ad..150391d6 100644--- a/site/src/cut/components/CreditsPill.tsx+++ b/site/src/cut/components/CreditsPill.tsx@@ -14,7 +14,7 @@ import { useEngineUser } from "@/cut/lib/backend/hooks";import { useHostedBalance, useInvalidateOnSettle } from "@/cut/lib/hosted";import { openUpgrade } from "@/cut/lib/upgrade";import { track } from "@/lib/analytics";-import { PAID_PLANS, PLAN_TERMS } from "@/lib/billing/plans";+import { PAID_PLANS, PLAN_NAMES } from "@/lib/billing/plans";import { compactCredits, creditsFromDollars, formatCreditCount, formatCredits } from "@/lib/credits/format-credits";import { CREDITS_PILL_FLAG } from "@/lib/feature-flags";import { useProSubscription } from "@/queries/billing";@@ -108,7 +108,7 @@ function PlanCard({ balance }: { balance: string }) {return (<div className="text-sm"><div className="flex items-center justify-between gap-3 px-4 py-3">- <span className="font-semibold">{plan ? PLAN_TERMS[plan].name : t("creditsPill.free")}</span>+ <span className="font-semibold">{plan ? PLAN_NAMES[plan] : t("creditsPill.free")}</span>{subscription.data && plan !== PAID_PLANS[PAID_PLANS.length - 1] ? (<Button size="sm" onClick={() => openUpgrade("plans", "credits_pill")}>{t("creditsPill.upgrade")}diff --git a/site/src/cut/components/UpgradeDialog.tsx b/site/src/cut/components/UpgradeDialog.tsxindex cf01b80e..3b457193 100644--- a/site/src/cut/components/UpgradeDialog.tsx+++ b/site/src/cut/components/UpgradeDialog.tsx@@ -9,7 +9,7 @@ import { useEffect, useState } from "react";import { PlansDialog } from "@/cut/components/PlansDialog";import { onOperationFailure } from "@/cut/lib/operationFailure";import { onUpgrade, openUpgrade, type UpgradeRequest } from "@/cut/lib/upgrade";-import { PAID_PLANS, PLAN_TERMS } from "@/lib/billing/plans";+import { PAID_PLANS, PLAN_NAMES } from "@/lib/billing/plans";import { useProSubscription } from "@/queries/billing";export function UpgradeDialog() {@@ -49,7 +49,7 @@ function OpenDialog({ request, onClose }: { request: UpgradeRequest; onClose: ()if (!plan || !periodEnd) {return { title: t("plans.freeOutTitle") };}- const words = { plan: PLAN_TERMS[plan].name, date: format.dateTime(new Date(periodEnd), { day: "numeric", month: "long" }) };+ const words = { plan: PLAN_NAMES[plan], date: format.dateTime(new Date(periodEnd), { day: "numeric", month: "long" }) };return plan === PAID_PLANS[PAID_PLANS.length - 1]? { title: t("plans.topOutTitle", words) }: { title: t("plans.paidOutTitle"), body: t("plans.paidOutBody", words) };diff --git a/site/src/cut/lib/projectLimit.ts b/site/src/cut/lib/projectLimit.tsindex 83daf708..40c2afc0 100644--- a/site/src/cut/lib/projectLimit.ts+++ b/site/src/cut/lib/projectLimit.ts@@ -5,7 +5,6 @@import type { QueryClient } from "@tanstack/react-query";import { track } from "@/lib/analytics";-import { PLAN_TERMS } from "@/lib/billing/plans";import { countedProjects, projectLimitFull } from "@/lib/billing/project-limit";import { accountConfigQueryKey, fetchAccountConfig } from "@/queries/accountConfig";import { fetchProSubscription, proSubscriptionQueryKey } from "@/queries/billing";@@ -31,7 +30,7 @@ export async function newProjectAllowed(client: QueryClient): Promise<boolean> {// Plus keeps the free limit; Pro and Max lift it.const subscription = await client.ensureQueryData({ queryKey: proSubscriptionQueryKey, queryFn: fetchProSubscription });- if (subscription.plan && PLAN_TERMS[subscription.plan].unlimitedProjects) {+ if (subscription.plan && config.settings.planTerms[subscription.plan].unlimitedProjects) {return true;}diff --git a/site/src/cut/server/cloud/limits.test.ts b/site/src/cut/server/cloud/limits.test.tsindex 44a54723..26d7845a 100644--- a/site/src/cut/server/cloud/limits.test.ts+++ b/site/src/cut/server/cloud/limits.test.ts@@ -1,6 +1,11 @@import { describe, expect, test } from "bun:test";-import { cutLimitsForTier, FREE_STORAGE_BYTES } from "./limits";+import { SETTINGS } from "@/lib/config/registry";++import { cutLimitsForTier as limitsForTier, FREE_STORAGE_BYTES } from "./limits";++const cutLimitsForTier = (tier: { superUser: boolean; plan: string | null }) =>+ limitsForTier(tier, SETTINGS.planTerms.default);const GB = 1024 ** 3;@@ -26,6 +31,11 @@ describe("cutLimitsForTier", () => {);});+ test("a plan's storage and render cap follow its terms", () => {+ const terms = { ...SETTINGS.planTerms.default, plus: { ...SETTINGS.planTerms.default.plus, storageGb: 25, rendersPerDay: 40 } };+ expect(limitsForTier({ superUser: false, plan: "plus" }, terms)).toMatchObject({ storageBytes: 25 * GB, renderJobsPerDay: 40 });+ });+test("super users are unlimited", () => {expect(cutLimitsForTier({ superUser: true, plan: null }).storageBytes).toBeNull();});diff --git a/site/src/cut/server/cloud/limits.ts b/site/src/cut/server/cloud/limits.tsindex 9d79449f..494dae1c 100644--- a/site/src/cut/server/cloud/limits.ts+++ b/site/src/cut/server/cloud/limits.ts@@ -1,5 +1,6 @@-import { PLAN_TERMS, isPaidPlan, type PaidPlan } from "@/lib/billing/plans";+import { isPaidPlan, type PaidPlan, type PlanTermsTable } from "@/lib/billing/plans";import { getActiveSubscription } from "@/lib/billing/pro-subscription";+import { getGlobalSetting } from "@/lib/config/effective";import { isDonkeySuperUser } from "@/lib/super-user";import { prisma } from "@/lib/prisma";@@ -54,27 +55,24 @@ const FREE: CutLimits = {titlesPerDay: 300,};const GB = 1024 ** 3;-// Plus buys credits and storage; its other caps are the free ones.-const PLUS: CutLimits = {- ...FREE,- storageBytes: PLAN_TERMS.plus.storageGb * GB,- renderJobsPerDay: PLAN_TERMS.plus.rendersPerDay,-};-const PRO: CutLimits = {- storageBytes: PLAN_TERMS.pro.storageGb * GB,- renderJobsPerDay: PLAN_TERMS.pro.rendersPerDay,- liveJobs: 32,- liveTurns: 8,- titlesPerDay: 2000,-};-const MAX: CutLimits = {- storageBytes: PLAN_TERMS.max.storageGb * GB,- renderJobsPerDay: PLAN_TERMS.max.rendersPerDay,- liveJobs: 48,- liveTurns: 12,- titlesPerDay: 5000,++// Each plan's storage and render cap come from its terms (the planTerms+// setting); the live caps are engineering bounds.+const PLAN_CAPS: Record<PaidPlan, Pick<CutLimits, "liveJobs" | "liveTurns" | "titlesPerDay">> = {+ // Plus buys credits and storage; its other caps are the free ones.+ plus: { liveJobs: FREE.liveJobs, liveTurns: FREE.liveTurns, titlesPerDay: FREE.titlesPerDay },+ pro: { liveJobs: 32, liveTurns: 8, titlesPerDay: 2000 },+ max: { liveJobs: 48, liveTurns: 12, titlesPerDay: 5000 },};-const PLAN_LIMITS: Record<PaidPlan, CutLimits> = { plus: PLUS, pro: PRO, max: MAX };++function planLimits(plan: PaidPlan, terms: PlanTermsTable): CutLimits {+ return {+ ...PLAN_CAPS[plan],+ storageBytes: terms[plan].storageGb * GB,+ renderJobsPerDay: terms[plan].rendersPerDay,+ };+}+const UNLIMITED: CutLimits = {storageBytes: null,renderJobsPerDay: null,@@ -86,16 +84,19 @@ const UNLIMITED: CutLimits = {/** The limits an account's tier earns: its plan's, or free's without one.* Super users are unlimited. A row with a plan key this build doesn't know* reads as Pro, the plan every row was before the ladder. */-export function cutLimitsForTier(tier: { superUser: boolean; plan: string | null }): CutLimits {+export function cutLimitsForTier(+ tier: { superUser: boolean; plan: string | null },+ terms: PlanTermsTable,+): CutLimits {if (tier.superUser) return UNLIMITED;if (tier.plan === null) return FREE;- return isPaidPlan(tier.plan) ? PLAN_LIMITS[tier.plan] : PRO;+ return planLimits(isPaidPlan(tier.plan) ? tier.plan : "pro", terms);}export async function cutLimitsFor(userId: string): Promise<CutLimits> {if (await isDonkeySuperUser(userId)) return UNLIMITED;- const subscription = await getActiveSubscription(userId);- return cutLimitsForTier({ superUser: false, plan: subscription?.planKey ?? null });+ const [subscription, terms] = await Promise.all([getActiveSubscription(userId), getGlobalSetting("planTerms")]);+ return cutLimitsForTier({ superUser: false, plan: subscription?.planKey ?? null }, terms);}/** 429 when the account already has as many asked-for jobs in flight as itsdiff --git a/site/src/cut/worker/db.test.ts b/site/src/cut/worker/db.test.tsindex 78afde73..9e5b51aa 100644--- a/site/src/cut/worker/db.test.ts+++ b/site/src/cut/worker/db.test.ts@@ -5,7 +5,8 @@ import { stubModule } from "@/lib/testing/stubModule";// The account the charge point weighs every object against: free tier, no Pro.const prisma = {cutRenderJob: { findMany: mock(async (args: unknown): Promise<QueueRow[]> => { void args; return []; }) },- settingOverride: { findUnique: mock(async () => ({ value: { maxAttempts: 3 } })) },+ // No overrides: the plan terms read their defaults.+ settingOverride: { findUnique: mock(async () => ({ value: { maxAttempts: 3 } })), findMany: mock(async () => []) },user: { findUnique: mock(async () => ({ superUser: false })) },proSubscription: { findUnique: mock(async () => null) },$transaction: mock(async (diff --git a/site/src/lib/billing/meta-checkout.ts b/site/src/lib/billing/meta-checkout.tsindex 2b7669ef..8091ef08 100644--- a/site/src/lib/billing/meta-checkout.ts+++ b/site/src/lib/billing/meta-checkout.ts@@ -1,7 +1,7 @@import type Stripe from "stripe";import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";-import type { PlanTerms } from "@/lib/billing/plans";+import type { PLAN_NAMES } from "@/lib/billing/plans";import { metaBrowser, type MetaBrowser, trackMetaEvent } from "@/lib/meta/conversions";// A purchase completes in Stripe's webhook, far from the browser that paid.@@ -30,7 +30,7 @@ const CENTS_PER_DOLLAR = 100;const CONVERTED: ReadonlySet<Stripe.Checkout.Session["payment_status"]> = new Set(["paid", "no_payment_required"]);// The plan a checkout sells, by its display name.-export type CheckoutProduct = PlanTerms["name"];+export type CheckoutProduct = (typeof PLAN_NAMES)[keyof typeof PLAN_NAMES];/** The browser behind a checkout request, as checkout session metadata. */export function metaCheckoutMetadata(headers: Headers): Record<string, string> {diff --git a/site/src/lib/billing/plan-terms-server.ts b/site/src/lib/billing/plan-terms-server.tsnew file mode 100644index 00000000..e085f745--- /dev/null+++ b/site/src/lib/billing/plan-terms-server.ts@@ -0,0 +1,30 @@+// The plan terms as pages read them. The server's own checks read the+// planTerms setting fresh; pages read it from a cache scope, so the terms are part of each+// page's static HTML and every card paints with its numbers at once. A su+// save posts the revalidate route, which expires the scope and renders the+// landing again before anyone asks for it.+import { cacheLife, cacheTag, revalidateTag } from "next/cache";+import { after } from "next/server";++import { CUT_HOSTED_ORIGIN } from "@/cut/lib/hosts";+import type { PlanTermsTable } from "@/lib/billing/plans";+import { getGlobalSetting } from "@/lib/config/effective";++const PLAN_TERMS_TAG = "plan-terms";++/** The terms a page renders into its HTML. */+export async function cachedPlanTerms(): Promise<PlanTermsTable> {+ "use cache";+ cacheTag(PLAN_TERMS_TAG);+ cacheLife("max");+ return getGlobalSetting("planTerms");+}++/** Drop every page's copy of the terms now and render the landing again+ * once the response has gone out. A route handler cannot use updateTag, and+ * the stale-while-revalidate profile would show the next visitor the old+ * terms. */+export function revalidatePlanTerms(): void {+ revalidateTag(PLAN_TERMS_TAG, { expire: 0 });+ after(() => fetch(`${CUT_HOSTED_ORIGIN}/`, { cache: "no-store" }).catch(() => {}));+}diff --git a/site/src/lib/billing/plans.ts b/site/src/lib/billing/plans.tsindex 83bf54c9..5fad65cc 100644--- a/site/src/lib/billing/plans.ts+++ b/site/src/lib/billing/plans.ts@@ -1,15 +1,21 @@-// The paid plans and what each one buys, in one place: checkout, the webhook-// grant, the storage and project limits, and every card that sells a plan-// read these, so a price can't say two things in two parts of the product.-// Client-safe: no server imports.+// The paid plans: their order, their names and the shape of what each one+// sells. Checkout, the webhook grant, the storage and project limits, and+// every card that sells a plan read the terms from one setting, so a price+// can't say two things in two parts of the product. Client-safe: no server+// imports.// Cheapest first; a plan's place in this list is its rank.export const PAID_PLANS = ["plus", "pro", "max"] as const;export type PaidPlan = (typeof PAID_PLANS)[number];+// The display name of each plan, the same in every language.+export const PLAN_NAMES: Record<PaidPlan, string> = { plus: "Plus", pro: "Pro", max: "Max" };++// What a plan sells. su runs these through the planTerms setting, which+// holds one per plan; the server reads it fresh, the pages read it baked into+// their HTML (plan-terms-server.ts).export type PlanTerms = {- // The display name, the same in every language.- name: string;+ // The monthly price in USD; su checks it against the plan's Stripe price.monthlyDollars: number;// The AI credits each billing period starts with.monthlyCredits: number;@@ -20,14 +26,7 @@ export type PlanTerms = {rendersPerDay: number;};-// Credits are charged at provider cost plus 30%, so a period's credits cost-// Donkey about 0.77 of their face value when spent in full. Max's 60,000-// credits come to ~$46 of provider cost against its $49 price.-export const PLAN_TERMS: Record<PaidPlan, PlanTerms> = {- plus: { name: "Plus", monthlyDollars: 5, monthlyCredits: 5_000, storageGb: 10, unlimitedProjects: false, rendersPerDay: 10 },- pro: { name: "Pro", monthlyDollars: 20, monthlyCredits: 20_000, storageGb: 100, unlimitedProjects: true, rendersPerDay: 200 },- max: { name: "Max", monthlyDollars: 49, monthlyCredits: 60_000, storageGb: 500, unlimitedProjects: true, rendersPerDay: 500 },-};+export type PlanTermsTable = Record<PaidPlan, PlanTerms>;// The plan every upsell marks as the best value.export const RECOMMENDED_PLAN: PaidPlan = "pro";diff --git a/site/src/lib/billing/pro-subscription.test.ts b/site/src/lib/billing/pro-subscription.test.tsindex 2e39c8f9..a3135072 100644--- a/site/src/lib/billing/pro-subscription.test.ts+++ b/site/src/lib/billing/pro-subscription.test.ts@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";import type Stripe from "stripe";import { planAllowanceMicros, scheduledProEnd, subscriptionCancelAt, subscriptionPlan } from "@/lib/billing/pro-subscription";+import { SETTINGS } from "@/lib/config/registry";const PERIOD_START = 1_767_225_600; // 2026-01-01T00:00:00Zconst PERIOD_END = 1_769_904_000; // 2026-02-01T00:00:00Z@@ -94,8 +95,9 @@ describe("subscriptionPlan", () => {describe("planAllowanceMicros", () => {// 1,000 credits a dollar; a dollar is a million micros.test("grants each plan's credits", () => {- expect(planAllowanceMicros("plus")).toBe(BigInt(5_000_000));- expect(planAllowanceMicros("pro")).toBe(BigInt(20_000_000));- expect(planAllowanceMicros("max")).toBe(BigInt(60_000_000));+ const terms = SETTINGS.planTerms.default;+ expect(planAllowanceMicros(terms.plus)).toBe(BigInt(5_000_000));+ expect(planAllowanceMicros(terms.pro)).toBe(BigInt(20_000_000));+ expect(planAllowanceMicros(terms.max)).toBe(BigInt(60_000_000));});});diff --git a/site/src/lib/billing/pro-subscription.ts b/site/src/lib/billing/pro-subscription.tsindex afbd2263..d4424384 100644--- a/site/src/lib/billing/pro-subscription.ts+++ b/site/src/lib/billing/pro-subscription.ts@@ -7,7 +7,7 @@ import {} from "@/lib/billing/stripe";import { promotedAllowanceMicros } from "@/lib/billing/allowance-promotion";import { getGlobalSetting } from "@/lib/config/effective";-import { isPaidPlan, PAID_PLANS, PLAN_TERMS, type PaidPlan } from "@/lib/billing/plans";+import { isPaidPlan, PAID_PLANS, PLAN_NAMES, type PaidPlan, type PlanTerms } from "@/lib/billing/plans";import { creditStringToMicros, zeroCreditMicros } from "@/lib/credits/amounts";import { creditsPerDollar } from "@/lib/credits/format-credits";import { grantCredits } from "@/lib/credits/inference";@@ -64,8 +64,8 @@ export async function planPriceId(plan: PaidPlan): Promise<string | null> {}// The credits a plan's billing period starts with, as ledger micros.-export function planAllowanceMicros(plan: PaidPlan): bigint {- return creditStringToMicros(String(PLAN_TERMS[plan].monthlyCredits / creditsPerDollar));+export function planAllowanceMicros(terms: PlanTerms): bigint {+ return creditStringToMicros(String(terms.monthlyCredits / creditsPerDollar));}// The account's running subscription, whichever plan it is on; null for a@@ -156,13 +156,10 @@ export async function syncProSubscription(const periodEnd = unixToDate(item.current_period_end);const cancelAt = subscriptionCancelAt(subscription);const endedAt = unixToDate(subscription.ended_at);+ const plainMicros = planAllowanceMicros((await getGlobalSetting("planTerms"))[plan]);const allowanceMicros = periodStart- ? promotedAllowanceMicros(- planAllowanceMicros(plan),- await getGlobalSetting("proAllowancePromotion"),- periodStart,- )- : planAllowanceMicros(plan);+ ? promotedAllowanceMicros(plainMicros, await getGlobalSetting("proAllowancePromotion"), periodStart)+ : plainMicros;await prisma.proSubscription.upsert({create: {@@ -211,7 +208,7 @@ export async function syncProSubscription() {await grantCredits({amountMicros: allowanceMicros,- description: `Donkey ${PLAN_TERMS[plan].name} monthly allowance`,+ description: `Donkey ${PLAN_NAMES[plan]} monthly allowance`,expiresAt: periodEnd,metadata: { plan },periodEnd,diff --git a/site/src/lib/billing/project-limit-server.ts b/site/src/lib/billing/project-limit-server.tsindex c6701fd9..72136944 100644--- a/site/src/lib/billing/project-limit-server.ts+++ b/site/src/lib/billing/project-limit-server.ts@@ -1,7 +1,7 @@import { starterProjectId } from "@/cut/lib/starter";-import { PLAN_TERMS, isPaidPlan } from "@/lib/billing/plans";+import { isPaidPlan } from "@/lib/billing/plans";import { getActiveSubscription } from "@/lib/billing/pro-subscription";-import { contextForUser, getSetting } from "@/lib/config/effective";+import { contextForUser, getGlobalSetting, getSetting } from "@/lib/config/effective";import { prisma } from "@/lib/prisma";import { projectLimitFull } from "./project-limit";@@ -14,7 +14,7 @@ export async function cloudProjectsFull(userId: string): Promise<boolean> {return false;}const subscription = await getActiveSubscription(userId);- if (subscription && isPaidPlan(subscription.planKey) && PLAN_TERMS[subscription.planKey].unlimitedProjects) {+ if (subscription && isPaidPlan(subscription.planKey) && (await getGlobalSetting("planTerms"))[subscription.planKey].unlimitedProjects) {return false;}diff --git a/site/src/lib/config/audienceFacts.ts b/site/src/lib/config/audienceFacts.tsindex b6b1b42f..2c6eda32 100644--- a/site/src/lib/config/audienceFacts.ts+++ b/site/src/lib/config/audienceFacts.ts@@ -1,5 +1,6 @@import { cutLimitsForTier } from "@/cut/server/cloud/limits";import type { AudienceFact, AudienceFacts } from "@donkeycut/abexp";+import type { PlanTermsTable } from "@/lib/billing/plans";import { ACTIVE_PRO_STATUSES } from "@/lib/billing/pro-subscription";import { PURCHASE_SOURCES } from "@/lib/config/purchases";import { prisma } from "@/lib/prisma";@@ -14,9 +15,11 @@ const clampPercent = (x: number) => Math.min(100, Math.max(0, x));export type KnownUser = { id: string; country: string | null; createdAt: Date };+// `terms` sizes each plan's storage quota for storageUsedPercent.export async function collectFactsFor(users: KnownUser[],needs: Set<AudienceFact>,+ terms: PlanTermsTable,): Promise<Map<string, AudienceFacts>> {const facts = new Map<string, AudienceFacts>();for (const user of users) {@@ -73,7 +76,7 @@ export async function collectFactsFor(const bytesBy = new Map(usage.map((row) => [row.userId, Number(row.bytes)]));for (const tier of tiers) {const fact = facts.get(tier.id)!;- const quota = cutLimitsForTier({ superUser: tier.superUser, plan: planBy.get(tier.id) ?? null }).storageBytes;+ const quota = cutLimitsForTier({ superUser: tier.superUser, plan: planBy.get(tier.id) ?? null }, terms).storageBytes;fact.storageUsedPercent = quota === null ? null : clampPercent((100 * (bytesBy.get(tier.id) ?? 0)) / quota);}}@@ -90,7 +93,8 @@ export async function collectFacts(userId: string,known: { country: string | null; createdAt: Date },needs: Set<AudienceFact>,+ terms: PlanTermsTable,): Promise<AudienceFacts> {- const facts = await collectFactsFor([{ id: userId, ...known }], needs);+ const facts = await collectFactsFor([{ id: userId, ...known }], needs, terms);return facts.get(userId)!;}diff --git a/site/src/lib/config/effective.ts b/site/src/lib/config/effective.tsindex e71c5fea..8b10a15e 100644--- a/site/src/lib/config/effective.ts+++ b/site/src/lib/config/effective.ts@@ -112,7 +112,8 @@ export async function getEffectiveConfig(ctx: ConfigContext): Promise<EffectiveCconst needs = new Set<AudienceFact>();for (const e of candidates) for (const fact of audienceNeeds(e.audience)) needs.add(fact);const now = new Date();- const facts = await collectFacts(ctx.userId, { country: ctx.country, createdAt: ctx.createdAt }, needs);+ const terms = resolveSettings(overrides, []).settings.planTerms;+ const facts = await collectFacts(ctx.userId, { country: ctx.country, createdAt: ctx.createdAt }, needs, terms);const assign = { userId: ctx.userId, facts, now };const fresh: Prisma.ExperimentAssignmentCreateManyInput[] = [];for (const experiment of candidates) {diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.tsindex b390c232..1c7834e6 100644--- a/site/src/lib/config/registry.ts+++ b/site/src/lib/config/registry.ts@@ -11,6 +11,17 @@ import { z } from "zod";import { maxCreditGrantDollars, maxCreditGrantExpiryDays } from "@/lib/credits/top-up";+// One paid plan's terms in the planTerms setting (src/lib/billing/plans.ts).+const planTermsSchema = z+ .object({+ monthlyDollars: z.number().multipleOf(0.01).min(0.5).max(10_000),+ monthlyCredits: z.number().int().min(0).max(10_000_000),+ storageGb: z.number().int().min(1).max(100_000),+ rendersPerDay: z.number().int().min(1).max(100_000),+ unlimitedProjects: z.boolean(),+ })+ .strict();+// The settings registry: every lever su runs, declared once// with a schema and a default. A value resolves default < override < variant// (src/lib/config/resolve.ts); a database row holds the override, an@@ -219,6 +230,18 @@ export const SETTINGS = defineSettings({description:"How many projects a free account may hold besides its starter project. Creating one more opens the upgrade dialog.",},+ planTerms: {+ schema: z.object({ plus: planTermsSchema, pro: planTermsSchema, max: planTermsSchema }).strict(),+ default: {+ plus: { monthlyDollars: 5, monthlyCredits: 5_000, storageGb: 10, rendersPerDay: 10, unlimitedProjects: false },+ pro: { monthlyDollars: 20, monthlyCredits: 20_000, storageGb: 100, rendersPerDay: 200, unlimitedProjects: true },+ max: { monthlyDollars: 49, monthlyCredits: 60_000, storageGb: 500, rendersPerDay: 500, unlimitedProjects: true },+ },+ public: true,+ title: "Plan terms",+ description:+ "What each paid plan sells: its monthly USD price, which has to match its Stripe price, the AI credits each period starts with, cloud storage, renders a day, and whether the free project limit is lifted. Credits cost about 0.77 of their face value when spent in full.",+ },planPrices: {schema: z.object({