Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Make billing pages load fast and start checkout before the click (#800)
Ben Senescu5f790336d22a
diff --git a/docs/maintainers/review-guidelines.md b/docs/maintainers/review-guidelines.mdindex 94eda01a..04121a8e 100644--- a/docs/maintainers/review-guidelines.md+++ b/docs/maintainers/review-guidelines.md@@ -56,6 +56,8 @@ Applies to: `src/shared/billing*.ts`, `src/shared/rank-tracking.ts`, `src/serverEvery billable hosted provider path must check organization credits before paid execution and meter provider-reported spend through the established shared credit-spend helper after execution. A failed gate prevents the paid call. A bounded partial-success API may surface a failed billing check as an explicit item-level error, but it must not present the paid operation as successful. Authorization failures terminate the request. Never use a stale-positive cache that can authorize access or spend that a live check would deny, and ensure retries or Workflow replays cannot omit metering or double-charge.+Build every Autumn billing request (attach, subscription updates, the customer portal, customer creation) on the server from fixed plan IDs and server-chosen parameters; a client may supply only narrow validated values such as a bounded top-up amount or a sanitized return path. Never forward a client-supplied request body to an Autumn call made with the secret key: its parameters include ways to change prices, skip payment, or enable a plan before it is paid, and an owner check does not help because every user owns their own organization.+### Untrusted outbound URLsApplies to: `src/server/**`, `src/serverFunctions/**`, `src/routes/api/**`.diff --git a/src/client/features/ai-search/ResearchPageShell.tsx b/src/client/features/ai-search/ResearchPageShell.tsxindex 6b5d04a6..a69e7c07 100644--- a/src/client/features/ai-search/ResearchPageShell.tsx+++ b/src/client/features/ai-search/ResearchPageShell.tsx@@ -2,8 +2,7 @@ import { useEffect, useRef, type ReactNode } from "react";import type { UseQueryResult } from "@tanstack/react-query";import { Link } from "@tanstack/react-router";import { Sparkles, type LucideIcon } from "lucide-react";-import { SUBSCRIBE_ROUTE } from "@/shared/billing";-import type { PlanStatus } from "@/client/features/billing/plan-detection";+import { SUBSCRIBE_ROUTE, type PlanStatus } from "@/shared/billing";import { GateCard } from "@/client/components/GateCard";import { PageHeader } from "@/client/components/PageHeader";import { QueryError } from "@/client/components/QueryState";diff --git a/src/client/features/billing/FreePlanBanner.tsx b/src/client/features/billing/FreePlanBanner.tsxindex c30101fc..38a7a7a0 100644--- a/src/client/features/billing/FreePlanBanner.tsx+++ b/src/client/features/billing/FreePlanBanner.tsx@@ -6,16 +6,11 @@ import { useCanManageBilling } from "@/client/features/team/organizationQueries"import { BILLING_ROUTE, SUBSCRIBE_ROUTE } from "@/shared/billing";export function FreePlanBanner() {- const {- customerQuery,- isFreePlan,- isOutOfCredits,- isLowCredits,- refillDate,- } = useCreditBalance();+ const { accountQuery, isFreePlan, isOutOfCredits, isLowCredits, refillDate } =+ useCreditBalance();const canManageBilling = useCanManageBilling();- if (customerQuery.isLoading || !customerQuery.data) {+ if (!accountQuery.data) {return null;}diff --git a/src/client/features/billing/HostedPlanGate.tsx b/src/client/features/billing/HostedPlanGate.tsxindex 03ef2764..1ca8dd8d 100644--- a/src/client/features/billing/HostedPlanGate.tsx+++ b/src/client/features/billing/HostedPlanGate.tsx@@ -1,10 +1,7 @@-import { useCustomer } from "autumn-js/react";-import { useSession } from "@/lib/auth-client";+import { useQuery } from "@tanstack/react-query";+import { billingAccountQueryOptions } from "@/client/features/billing/billingAccountQuery";import { isHostedClientAuthMode } from "@/lib/auth-mode";-import {- getCustomerPlanStatus,- type PlanStatus,-} from "@/client/features/billing/plan-detection";+import type { PlanStatus } from "@/shared/billing";// The single client-side plan gate. It is a UX layer only: the server enforces// every paid-plan limit before it spends anything.@@ -12,16 +9,13 @@ export function useHostedPlanGate(): "loading" | PlanStatus {// Self-hosted has no Autumn customer and resolves to the paid tier on the// server, so only hosted mode looks up the plan.const isHostedMode = isHostedClientAuthMode();- const { data: session, isPending: isSessionPending } = useSession();- const hasSession = Boolean(session?.user?.id);- const customerQuery = useCustomer({- queryOptions: { enabled: isHostedMode && hasSession },+ const accountQuery = useQuery({+ ...billingAccountQueryOptions(),+ enabled: isHostedMode,});if (!isHostedMode) return "paid";- if (isSessionPending || !hasSession || customerQuery.isLoading) {- return "loading";- }- // Fails closed: a customer that failed to load resolves to "free".- return getCustomerPlanStatus(customerQuery.data);+ if (accountQuery.isPending) return "loading";+ // Fails closed: an account that failed to load resolves to "free".+ return accountQuery.data?.planStatus ?? "free";}diff --git a/src/client/features/billing/InsufficientCreditsError.tsx b/src/client/features/billing/InsufficientCreditsError.tsxindex 7b28367c..5098e9a5 100644--- a/src/client/features/billing/InsufficientCreditsError.tsx+++ b/src/client/features/billing/InsufficientCreditsError.tsx@@ -23,11 +23,11 @@ export function InsufficientCreditsError({variant?: "inline" | "card" | "page";title?: string;}) {- const { customerQuery, isFreePlan, refillDate } = useCreditBalance();+ const { accountQuery, isFreePlan, refillDate } = useCreditBalance();let message: string;let action: ReactElement;- if (!customerQuery.data) {+ if (!accountQuery.data) {message = getStandardErrorMessage(new Error("INSUFFICIENT_CREDITS"));action = (<CreditsButton link={<Link to={BILLING_ROUTE} />} label="Go to Billing" />diff --git a/src/client/features/billing/billingAccountQuery.ts b/src/client/features/billing/billingAccountQuery.tsnew file mode 100644index 00000000..d06918cb--- /dev/null+++ b/src/client/features/billing/billingAccountQuery.ts@@ -0,0 +1,30 @@+import { queryOptions } from "@tanstack/react-query";+import { queryClient } from "@/client/tanstack-db";+import { isHostedClientAuthMode } from "@/lib/auth-mode";++/**+ * The organization's plan and credits. Every billing surface reads this one+ * query, so a page opened from anywhere in the app renders from the cache.+ */+export const billingAccountQueryOptions = () =>+ queryOptions({+ queryKey: ["billing", "account"],+ // Imported when the query runs: QueryState's out-of-credits message reads+ // this query on every page, and a static import would pull the server+ // function's middleware into every module (and test) that renders it.+ queryFn: async () => {+ const { getBillingAccount } = await import("@/serverFunctions/billing");+ return getBillingAccount();+ },+ // Balances move with every paid call.+ staleTime: 60_000,+ // The SDK doesn't retry Autumn errors on this read (it fails open and the+ // server turns that into an error), so try once more here.+ retry: 1,+ });++/** Starts loading the billing account without waiting for it. Hosted only. */+export function prefetchBillingAccount() {+ if (!isHostedClientAuthMode()) return;+ void queryClient.prefetchQuery(billingAccountQueryOptions());+}diff --git a/src/client/features/billing/checkout-url.ts b/src/client/features/billing/checkout-url.tsdeleted file mode 100644index d5907bb9..00000000--- a/src/client/features/billing/checkout-url.ts+++ /dev/null@@ -1,11 +0,0 @@-import { SUBSCRIBE_ROUTE } from "@/shared/billing";--// Success URL for plan checkouts: land on /subscribe's finalizing screen,-// which polls until Autumn reflects the new subscription, then forwards to-// redirectTo.-export function buildCheckoutSuccessUrl(redirectTo: string) {- const url = new URL(SUBSCRIBE_ROUTE, window.location.origin);- url.searchParams.set("checkout", "success");- url.searchParams.set("redirect", redirectTo);- return url.toString();-}diff --git a/src/client/features/billing/checkout.ts b/src/client/features/billing/checkout.tsnew file mode 100644index 00000000..919fc2f7--- /dev/null+++ b/src/client/features/billing/checkout.ts@@ -0,0 +1,69 @@+import { queryOptions } from "@tanstack/react-query";+import { billingAccountQueryOptions } from "@/client/features/billing/billingAccountQuery";+import { organizationContextQueryOptions } from "@/client/features/team/organizationQueries";+import { captureClientEvent } from "@/client/lib/posthog";+import { queryClient } from "@/client/tanstack-db";+import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { hasOrgPermission } from "@/lib/org-permissions";+import { createPlanCheckout } from "@/serverFunctions/billing";+import { AUTUMN_PAID_PLAN_ID, type CheckoutPlanId } from "@/shared/billing";++const planCheckoutQueryOptions = (planId: CheckoutPlanId, redirectTo: string) =>+ queryOptions({+ queryKey: ["billing", "checkout-url", planId, redirectTo],+ queryFn: () => createPlanCheckout({ data: { planId, redirectTo } }),+ // Autumn's checkout sessions last an hour; start over after 10 minutes.+ staleTime: 10 * 60_000,+ gcTime: 10 * 60_000,+ retry: false,+ });++// Autumn keeps one open Stripe checkout per customer and expires it when a+// checkout with different details is requested. Every upgrade link returns to+// the app home, so the paywall, Billing and other tabs all get the same live+// session back instead of cancelling each other's.+const UPGRADE_REDIRECT = "/";++/**+ * Starts creating the upgrade checkout link before the click, since Autumn+ * takes a few seconds to make one. Nothing is billed until the customer+ * confirms at checkout, so an unused link only costs the call; skip orgs that+ * can't use it.+ */+export function prefetchUpgradeCheckout() {+ if (!isHostedClientAuthMode()) return;+ void Promise.all([+ queryClient.ensureQueryData(billingAccountQueryOptions()),+ queryClient.ensureQueryData(organizationContextQueryOptions()),+ ])+ .then(([account, organization]) => {+ if (+ account.planStatus !== "free" ||+ !hasOrgPermission(organization.role, { billing: ["manage"] })+ ) {+ return;+ }+ return queryClient.prefetchQuery(+ planCheckoutQueryOptions(AUTUMN_PAID_PLAN_ID, UPGRADE_REDIRECT),+ );+ })+ // The click creates the link itself if this didn't.+ .catch(() => undefined);+}++/** Sends the browser to checkout, using the link made ahead of time if any. */+export async function openPlanCheckout(+ planId: CheckoutPlanId,+ redirectTo: string,+) {+ const options = planCheckoutQueryOptions(planId, redirectTo);+ captureClientEvent("billing:checkout_start", {+ planId,+ link_ready: queryClient.getQueryData(options.queryKey) !== undefined,+ });+ window.location.assign(await queryClient.fetchQuery(options));+}++export function openUpgradeCheckout() {+ return openPlanCheckout(AUTUMN_PAID_PLAN_ID, UPGRADE_REDIRECT);+}diff --git a/src/client/features/billing/plan-detection.test.ts b/src/client/features/billing/plan-detection.test.tsdeleted file mode 100644index db1999f1..00000000--- a/src/client/features/billing/plan-detection.test.ts+++ /dev/null@@ -1,31 +0,0 @@-import { describe, expect, it } from "vitest";-import { AUTUMN_PAID_PLAN_FEATURE_ID } from "@/shared/billing";-import { getCustomerPaidPlan, getCustomerPlanStatus } from "./plan-detection";--describe("getCustomerPlanStatus", () => {- it("treats any plan granting the paid entitlement as paid, everything else as free", () => {- expect(getCustomerPlanStatus(undefined)).toBe("free");- expect(getCustomerPlanStatus({ flags: {} })).toBe("free");- expect(- getCustomerPlanStatus({- flags: {- [AUTUMN_PAID_PLAN_FEATURE_ID]: {- planId: "friends_and_family_2",- },- },- }),- ).toBe("paid");- });-});--describe("getCustomerPaidPlan", () => {- it("reads the name from the expanded subscription and credits from balances", () => {- expect(- getCustomerPaidPlan({- flags: { [AUTUMN_PAID_PLAN_FEATURE_ID]: { planId: "yc-plan" } },- subscriptions: [{ planId: "yc-plan", plan: { name: "YC Plan" } }],- balances: { usage_credits: { granted: 50000 } },- }),- ).toEqual({ id: "yc-plan", name: "YC Plan", monthlyCreditsUsd: 50 });- });-});diff --git a/src/client/features/billing/plan-detection.ts b/src/client/features/billing/plan-detection.tsdeleted file mode 100644index 37f179c5..00000000--- a/src/client/features/billing/plan-detection.ts+++ /dev/null@@ -1,47 +0,0 @@-import {- AUTUMN_PAID_PLAN_FEATURE_ID,- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- autumnSeoDataCreditsToUsd,-} from "@/shared/billing";--export type PlanStatus = "free" | "paid";--// The slice of the Autumn customer we read. Structural so tests and both-// the SDK's React and server shapes fit without casts.-type CustomerLike = {- flags?: Record<string, { planId?: string | null } | undefined>;- subscriptions?: Array<{ planId: string; plan?: { name: string } }>;- balances?: Record<string, { granted: number } | undefined>;-};--export function getCustomerPlanStatus(- customer: CustomerLike | undefined,-): PlanStatus {- return customer?.flags?.[AUTUMN_PAID_PLAN_FEATURE_ID] ? "paid" : "free";-}--// Autumn records which plan granted the paid entitlement, so any plan that-// grants paid_plan is recognized without listing plan IDs here.-export function getCustomerPaidPlanId(- customer: CustomerLike | undefined,-): string | null {- return customer?.flags?.[AUTUMN_PAID_PLAN_FEATURE_ID]?.planId ?? null;-}--// Display details for the plan a paid customer is on. `name` needs the-// customer fetched with `expand: ["subscriptions.plan"]`; it falls back to-// the plan ID otherwise.-export function getCustomerPaidPlan(customer: CustomerLike | undefined) {- const planId = getCustomerPaidPlanId(customer);- if (!planId) return null;- const subscription = customer?.subscriptions?.find(- (s) => s.planId === planId,- );- return {- id: planId,- name: subscription?.plan?.name ?? planId,- monthlyCreditsUsd: autumnSeoDataCreditsToUsd(- customer?.balances?.[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID]?.granted ?? 0,- ),- };-}diff --git a/src/client/features/billing/plan-offers.ts b/src/client/features/billing/plan-offers.tsindex c703dff5..37633e3a 100644--- a/src/client/features/billing/plan-offers.ts+++ b/src/client/features/billing/plan-offers.ts@@ -1,19 +1,18 @@import {- AUTUMN_CHECKOUT_SESSION_PARAMS,AUTUMN_PAID_PLAN_ID,- AUTUMN_YC_CHECKOUT_SESSION_PARAMS,AUTUMN_YC_PLAN_ID,+ type CheckoutPlanId,} from "@/shared/billing";// What a checkout page advertises before the customer holds the plan. Once-// they do, the Autumn customer is the source of truth (see plan-detection.ts),-// so these numbers only need to match the Autumn plan they sell.+// they do, status and credits come from the Autumn customer (see+// billing-account.ts) and only the name is read from here (getPlanName), so+// these only need to match the Autumn plans they sell.export type PlanOffer = {- planId: string;+ planId: CheckoutPlanId;name: string;priceUsd: number;monthlyCreditsUsd: number;- checkoutSessionParams: Record<string, unknown>;};export const BASE_PLAN_OFFER: PlanOffer = {@@ -21,7 +20,6 @@ export const BASE_PLAN_OFFER: PlanOffer = {name: "Base Plan",priceUsd: 10,monthlyCreditsUsd: 10,- checkoutSessionParams: AUTUMN_CHECKOUT_SESSION_PARAMS,};export const YC_PLAN_OFFER: PlanOffer = {@@ -29,9 +27,17 @@ export const YC_PLAN_OFFER: PlanOffer = {name: "YC Plan",priceUsd: 50,monthlyCreditsUsd: 50,- checkoutSessionParams: AUTUMN_YC_CHECKOUT_SESSION_PARAMS,};+/** A plan's display name. Plans without an offer here (friends and family)+ * show their ID, which is also their name in Autumn. */+export function getPlanName(planId: string) {+ return (+ [BASE_PLAN_OFFER, YC_PLAN_OFFER].find((offer) => offer.planId === planId)+ ?.name ?? planId+ );+}+export function monthlyCreditsFeature(offer: PlanOffer) {return `Includes $${offer.monthlyCreditsUsd.toFixed(2)} of Usage Credits each month`;}diff --git a/src/client/features/billing/route-state.test.ts b/src/client/features/billing/route-state.test.tsindex e1e2c098..bca43c5f 100644--- a/src/client/features/billing/route-state.test.ts+++ b/src/client/features/billing/route-state.test.ts@@ -1,11 +1,10 @@import { describe, expect, it } from "vitest";-import { getBillingRouteState, getSubscribeRouteState } from "./route-state";+import { getSubscribeRouteState } from "./route-state";describe("getSubscribeRouteState", () => {// hasManagedAccess is true for essentially every hosted customer: the free// plan is the Autumn default and grants managed_service_access too.const base = {- hasSession: true,isCustomerLoading: false,isCustomerError: false,hasCustomerData: true,@@ -79,21 +78,3 @@ describe("getSubscribeRouteState", () => {).toBe("redirectToApp");});});--describe("getBillingRouteState", () => {- it("keeps the loaded page when a customer refetch fails", () => {- const failed = {- hasSession: true,- isSessionPending: false,- isCustomerLoading: false,- isCustomerError: true,- };-- expect(getBillingRouteState({ ...failed, hasCustomerData: true })).toBe(- "ready",- );- expect(getBillingRouteState({ ...failed, hasCustomerData: false })).toBe(- "error",- );- });-});diff --git a/src/client/features/billing/route-state.ts b/src/client/features/billing/route-state.tsindex 5b2651cb..6d9214c0 100644--- a/src/client/features/billing/route-state.ts+++ b/src/client/features/billing/route-state.ts@@ -1,26 +1,6 @@-import type { PlanStatus } from "@/client/features/billing/plan-detection";--export function getBillingRouteState(args: {- hasSession: boolean;- isSessionPending: boolean;- isCustomerLoading: boolean;- isCustomerError: boolean;- hasCustomerData: boolean;-}) {- if (args.isSessionPending || !args.hasSession || args.isCustomerLoading) {- return "loading" as const;- }-- // A failed refetch keeps the loaded page; the caller shows the error inline.- if (args.isCustomerError && !args.hasCustomerData) {- return "error" as const;- }-- return "ready" as const;-}+import type { PlanStatus } from "@/shared/billing";export function getSubscribeRouteState(args: {- hasSession: boolean;isCustomerLoading: boolean;isCustomerError: boolean;hasCustomerData: boolean;@@ -30,7 +10,7 @@ export function getSubscribeRouteState(args: {checkoutCompleted: boolean;finalizingTimedOut: boolean;}) {- if (!args.hasSession || args.isCustomerLoading) {+ if (args.isCustomerLoading) {return "loading" as const;}diff --git a/src/client/features/billing/useBillingUsageEvents.ts b/src/client/features/billing/useBillingUsageEvents.tsindex 7ee78a4e..68b5fc5c 100644--- a/src/client/features/billing/useBillingUsageEvents.ts+++ b/src/client/features/billing/useBillingUsageEvents.ts@@ -1,12 +1,11 @@-import { useQuery } from "@tanstack/react-query";+import { queryOptions, useQuery } from "@tanstack/react-query";import { getBillingUsageEvents } from "@/serverFunctions/billing";export const BILLING_USAGE_DAYS = 30;const DAY_MS = 24 * 60 * 60 * 1000;-/** The usage events of the last 30 days, for the usage chart and the per-feature breakdown. */-export function useBillingUsageEvents() {- return useQuery({+export const billingUsageEventsQueryOptions = () =>+ queryOptions({queryKey: ["billing", "usage-events", `${BILLING_USAGE_DAYS}d`],queryFn: () => {const end = Date.now();@@ -16,4 +15,8 @@ export function useBillingUsageEvents() {},staleTime: 60_000,});++/** The usage events of the last 30 days, for the usage chart and the per-feature breakdown. */+export function useBillingUsageEvents() {+ return useQuery(billingUsageEventsQueryOptions());}diff --git a/src/client/features/billing/useCreditBalance.ts b/src/client/features/billing/useCreditBalance.tsindex e1fc9db9..7a607600 100644--- a/src/client/features/billing/useCreditBalance.ts+++ b/src/client/features/billing/useCreditBalance.ts@@ -1,63 +1,31 @@-import { useCustomer } from "autumn-js/react";-import { useSession } from "@/lib/auth-client";-import {- getCustomerPaidPlanId,- getCustomerPlanStatus,-} from "@/client/features/billing/plan-detection";-import {- AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- LOW_CREDITS_THRESHOLD_USD,- autumnSeoDataCreditsToUsd,-} from "@/shared/billing";+import { useQuery } from "@tanstack/react-query";+import { billingAccountQueryOptions } from "@/client/features/billing/billingAccountQuery";+import { LOW_CREDITS_THRESHOLD_USD } from "@/shared/billing";-type CustomerParams = NonNullable<Parameters<typeof useCustomer>[0]>;+/** The signed-in organization's plan and remaining credits in USD. */+export function useCreditBalance() {+ const accountQuery = useQuery(billingAccountQueryOptions());+ const account = accountQuery.data;-/** The signed-in organization's Autumn customer, plan, and remaining credits in USD. */-export function useCreditBalance({- expand,-}: { expand?: CustomerParams["expand"] } = {}) {- const session = useSession();- const customerQuery = useCustomer({- expand,- queryOptions: {- enabled: Boolean(session.data?.user?.id),- },- });-- const customer = customerQuery.data;- const balances = customer?.balances;- const monthlyBalance = balances?.[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID];- const monthlyRemaining = autumnSeoDataCreditsToUsd(- monthlyBalance?.remaining ?? 0,- );- const topUpRemaining = autumnSeoDataCreditsToUsd(- balances?.[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]?.remaining ?? 0,- );+ const monthlyRemaining = account?.monthlyRemainingUsd ?? 0;+ const topUpRemaining = account?.topUpRemainingUsd ?? 0;const totalRemaining = monthlyRemaining + topUpRemaining;- // A paid plan canceled at period end ends then instead of refilling.- const paidSubscription = customer?.subscriptions?.find(- (subscription) => subscription.planId === getCustomerPaidPlanId(customer),- );const isOutOfCredits = totalRemaining <= 0;return {- session,- customerQuery,- isFreePlan: getCustomerPlanStatus(customer) === "free",+ accountQuery,+ isFreePlan: account?.planStatus !== "paid",monthlyRemaining,topUpRemaining,totalRemaining,isOutOfCredits,isLowCredits: !isOutOfCredits && totalRemaining < LOW_CREDITS_THRESHOLD_USD,- // When monthly credits refill, e.g. "Oct 12". Null for the free plan's- // one-time credits and for a canceled plan, which never refill.- refillDate:- monthlyBalance?.nextResetAt && !paidSubscription?.canceledAt- ? new Date(monthlyBalance.nextResetAt).toLocaleDateString(undefined, {- month: "short",- day: "numeric",- })- : null,+ // When monthly credits refill, e.g. "Oct 12".+ refillDate: account?.monthlyRefillsAt+ ? new Date(account.monthlyRefillsAt).toLocaleDateString(undefined, {+ month: "short",+ day: "numeric",+ })+ : null,};}diff --git a/src/lib/auth-redirect.test.ts b/src/lib/auth-redirect.test.tsindex 798542f0..c8c5890e 100644--- a/src/lib/auth-redirect.test.ts+++ b/src/lib/auth-redirect.test.ts@@ -50,6 +50,11 @@ describe("auth redirect helpers", () => {expect(normalizeAuthRedirect("/path\\..\\evil")).toBe("/");});+ it("rejects tab and newline redirects that URL parsers strip into //", () => {+ expect(normalizeAuthRedirect("/\t/evil.test")).toBe("/");+ expect(normalizeAuthRedirect("/\n/evil.test")).toBe("/");+ });+it("builds sign-in links with the redirect query only when needed", () => {expect(getSignInHref("/")).toBe("/sign-in");expect(getSignInHref("/oauth-consent?client_id=abc")).toBe(diff --git a/src/lib/auth-redirect.ts b/src/lib/auth-redirect.tsindex 398123ff..44b8fa73 100644--- a/src/lib/auth-redirect.ts+++ b/src/lib/auth-redirect.ts@@ -3,14 +3,16 @@ const OAUTH_SIGNED_QUERY_END = "sig";const OAUTH_AUTHORIZE_MARKERS = ["response_type", "client_id", "redirect_uri"];export function normalizeAuthRedirect(value: string | null | undefined) {- // Backslashes are rejected because URL parsers treat them as slashes:- // "/\evil.com" resolves cross-origin, an open redirect via+ // Backslashes are rejected because URL parsers treat them as slashes, and+ // tabs and newlines because URL parsers strip them: "/\evil.com" and+ // "/\t/evil.com" both resolve cross-origin, an open redirect via// window.location sinks.if (!value ||!value.startsWith("/") ||value.startsWith("//") ||- value.includes("\\")+ value.includes("\\") ||+ /[\t\n\r]/.test(value)) {return "/";}diff --git a/src/routes/__root.tsx b/src/routes/__root.tsxindex 5690d4da..d9121348 100644--- a/src/routes/__root.tsx+++ b/src/routes/__root.tsx@@ -9,7 +9,6 @@ import {import { TanStackRouterDevtoolsPanel } from "@tanstack/react-router-devtools";import { TanStackDevtools } from "@tanstack/react-devtools";import { QueryClientProvider } from "@tanstack/react-query";-import { AutumnProvider } from "autumn-js/react";import * as React from "react";import { DefaultCatchBoundary } from "@/client/components/DefaultCatchBoundary";import { captureGoogleLinkError } from "@/client/features/integrations/googleLinkError";@@ -141,37 +140,27 @@ function RootDocument({ children }: { children: React.ReactNode }) {</head><body><ClientOnly>- {/* Keep this the ONLY AutumnProvider. Each provider creates its own- customer cache (autumn-js bundles a private react-query, so it- never shares the app QueryClient), and every extra provider mount- pays its own ~1s getOrCreateCustomer round trip. It only provides- context — nothing fetches until a useCustomer consumer mounts. */}- <AutumnProvider>- <QueryClientProvider client={queryClient}>- <TooltipProvider>- <PostHogBootstrap />- {children}- <ExportToSheetsModal />- <Toaster- position="bottom-right"- mobileOffset={{ bottom: 100 }}+ <QueryClientProvider client={queryClient}>+ <TooltipProvider>+ <PostHogBootstrap />+ {children}+ <ExportToSheetsModal />+ <Toaster position="bottom-right" mobileOffset={{ bottom: 100 }} />+ {showDevtools ? (+ <TanStackDevtools+ config={{ position: "bottom-right" }}+ eventBusConfig={{ connectToServerBus: true }}+ plugins={[+ {+ name: "TanStack Router",+ render: <TanStackRouterDevtoolsPanel />,+ defaultOpen: true,+ },+ ]}/>- {showDevtools ? (- <TanStackDevtools- config={{ position: "bottom-right" }}- eventBusConfig={{ connectToServerBus: true }}- plugins={[- {- name: "TanStack Router",- render: <TanStackRouterDevtoolsPanel />,- defaultOpen: true,- },- ]}- />- ) : null}- </TooltipProvider>- </QueryClientProvider>- </AutumnProvider>+ ) : null}+ </TooltipProvider>+ </QueryClientProvider></ClientOnly><Scripts /></body>diff --git a/src/routes/_app/billing.tsx b/src/routes/_app/billing.tsxindex 8389b697..8b3190ad 100644--- a/src/routes/_app/billing.tsx+++ b/src/routes/_app/billing.tsx@@ -3,7 +3,6 @@ import { useState } from "react";import { ErrorState } from "@/client/components/ErrorState";import { PageHeader } from "@/client/components/PageHeader";import { QueryError } from "@/client/components/QueryState";-import { SkeletonPage } from "@/client/components/SkeletonPresets";import { Button } from "@/client/components/ui/button";import {Card,@@ -18,35 +17,48 @@ import {InputGroupAddon,InputGroupInput,} from "@/client/components/ui/input-group";+import { Skeleton } from "@/client/components/ui/skeleton";+import { queryClient } from "@/client/tanstack-db";import { isHostedClientAuthMode } from "@/lib/auth-mode";import { useCanManageBilling } from "@/client/features/team/organizationQueries";-import { captureClientEvent } from "@/client/lib/posthog";import { getStandardErrorMessage } from "@/client/lib/error-messages";-import { buildCheckoutSuccessUrl } from "@/client/features/billing/checkout-url";+import { prefetchBillingAccount } from "@/client/features/billing/billingAccountQuery";+import {+ openUpgradeCheckout,+ prefetchUpgradeCheckout,+} from "@/client/features/billing/checkout";import { BillingUsageChart } from "@/client/features/billing/BillingUsageChart";import { BillingFeatureBreakdown } from "@/client/features/billing/BillingFeatureBreakdown";import { parseTopUpAmount } from "@/client/features/billing/HostedBillingContentUtils";-import { getBillingRouteState } from "@/client/features/billing/route-state";-import { getCustomerPaidPlan } from "@/client/features/billing/plan-detection";+import { billingUsageEventsQueryOptions } from "@/client/features/billing/useBillingUsageEvents";import { useCreditBalance } from "@/client/features/billing/useCreditBalance";import {BASE_PLAN_OFFER,+ getPlanName,monthlyCreditsFeature,} from "@/client/features/billing/plan-offers";import {- AUTUMN_CHECKOUT_SESSION_PARAMS,- BILLING_ROUTE,- AUTUMN_SEO_DATA_CREDITS_PER_USD,- AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,- AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,-} from "@/shared/billing";+ createBillingPortalSession,+ createTopUpCheckout,+} from "@/serverFunctions/billing";+import { BILLING_ROUTE } from "@/shared/billing";export const Route = createFileRoute("/_app/billing")({+ // The loader fills the module-scoped query client, so keep it out of server+ // requests: one worker isolate must not cache another account's billing.+ ssr: false,beforeLoad: () => {if (!isHostedClientAuthMode()) {throw notFound();}},+ // Start both reads, and a free plan's checkout link, on link intent and on+ // a full load alongside the session check, without holding up navigation.+ loader: () => {+ prefetchBillingAccount();+ void queryClient.prefetchQuery(billingUsageEventsQueryOptions());+ prefetchUpgradeCheckout();+ },component: BillingPage,});@@ -54,15 +66,16 @@ type BillingAction = "plan" | "topUp";function BillingPage() {const [topUpAmount, setTopUpAmount] = useState("20");- const [isPending, setIsPending] = useState(false);+ const [pendingAction, setPendingAction] = useState<BillingAction | null>(+ null,+ );const [error, setError] = useState<{action: BillingAction;message: string;} | null>(null);const {- session: { data: session, isPending: isSessionPending },- customerQuery,+ accountQuery,isFreePlan,monthlyRemaining,topUpRemaining,@@ -70,296 +83,269 @@ function BillingPage() {isOutOfCredits,isLowCredits,refillDate,- } = useCreditBalance({- // Expanded so the plan card can show the subscribed plan's name.- expand: ["subscriptions.plan"],- });+ } = useCreditBalance();+ const account = accountQuery.data;// Subscription changes are owner-only; other members see balances but are// pointed at the owner instead of checkout (the server enforces this too).const canManageBilling = useCanManageBilling();- const paidPlan = getCustomerPaidPlan(customerQuery.data);- const billingRouteState = getBillingRouteState({- hasSession: Boolean(session?.user?.id),- isSessionPending,- isCustomerLoading: customerQuery.isLoading,- isCustomerError: customerQuery.isError,- hasCustomerData: customerQuery.data != null,- });-const { isValid: isValidTopUp, parsed: parsedTopUpAmount } =parseTopUpAmount(topUpAmount);const showTopUpError = topUpAmount.trim() !== "" && !isValidTopUp;- if (billingRouteState === "loading") {- return <SkeletonPage />;- }-- if (billingRouteState === "error") {- return (- <div className="mx-auto box-content max-w-7xl space-y-4 px-4 py-4 pb-24 md:px-6 md:py-6 md:pb-8">- <PageHeader title="Billing unavailable" />- <QueryError- error={customerQuery.error}- fallback="We couldn't load your billing details right now. Please try again."- onRetry={() => void customerQuery.refetch()}- isRetrying={customerQuery.isFetching}- />- </div>- );- }-- function startUpgradeCheckout() {- captureClientEvent("billing:checkout_start");- return customerQuery.attach({- planId: BASE_PLAN_OFFER.planId,- redirectMode: "always",- successUrl: buildCheckoutSuccessUrl(BILLING_ROUTE),- checkoutSessionParams: BASE_PLAN_OFFER.checkoutSessionParams,- });- }-+ // Each action ends by sending the browser to Stripe, so the button stays+ // pending unless it fails.async function runAction(action: BillingAction,- callback: () => Promise<unknown>,+ callback: () => Promise<void>,fallbackMessage: string,) {setError(null);- setIsPending(true);+ setPendingAction(action);try {await callback();- await customerQuery.refetch();} catch (err) {setError({action,message: getStandardErrorMessage(err, fallbackMessage),});- } finally {- setIsPending(false);+ setPendingAction(null);}}+ async function startTopUpCheckout() {+ window.location.assign(+ await createTopUpCheckout({ data: { amountUsd: parsedTopUpAmount } }),+ );+ }++ async function openPortal() {+ window.location.assign(+ await createBillingPortalSession({ data: { returnTo: BILLING_ROUTE } }),+ );+ }+function actionError(action: BillingAction) {return error?.action === action ? (<ErrorState message={error.message} />) : null;}- if (isPending) {- return (- <div className="flex h-full items-center justify-center">- <p className="text-sm text-muted-foreground">- Redirecting to Stripe...- </p>- </div>- );- }-return (<div className="mx-auto box-content max-w-7xl space-y-5 px-4 py-4 pb-24 md:px-6 md:py-6 md:pb-8"><PageHeader title="Billing" />- {customerQuery.isError ? (+ {accountQuery.isPending ? (+ <div className="grid gap-5 md:grid-cols-2">+ <SubscriptionCardSkeleton />+ </div>+ ) : !account ? (<QueryError- error={customerQuery.error}- fallback="Failed to refresh billing details"- onRetry={() => void customerQuery.refetch()}- isRetrying={customerQuery.isFetching}+ cause={accountQuery.error}+ fallback="We couldn't load your billing details right now. Please try again."+ onRetry={() => void accountQuery.refetch()}+ isRetrying={accountQuery.isFetching}/>- ) : null}+ ) : (+ <>+ {accountQuery.isError ? (+ <QueryError+ cause={accountQuery.error}+ fallback="Failed to refresh billing details"+ onRetry={() => void accountQuery.refetch()}+ isRetrying={accountQuery.isFetching}+ />+ ) : null}- <div className="grid gap-5 md:grid-cols-2">- {/* Subscription card */}- <Card>- <CardContent className="flex h-full flex-col justify-between gap-4">- <div>- <div className="text-2xl font-semibold tabular-nums">- ${totalRemaining.toFixed(2)}{" "}- <span className="text-sm font-normal text-muted-foreground">- remaining- </span>- </div>- {!isFreePlan ? (- <div className="mt-1 flex gap-3 text-xs text-muted-foreground">- <span className="tabular-nums">- Monthly ${monthlyRemaining.toFixed(2)}- </span>- <span>·</span>- <span className="tabular-nums">- Top-ups ${topUpRemaining.toFixed(2)}- </span>+ <div className="grid gap-5 md:grid-cols-2">+ {/* Subscription card */}+ <Card>+ <CardContent className="flex h-full flex-col justify-between gap-4">+ <div>+ <div className="text-2xl font-semibold tabular-nums">+ ${totalRemaining.toFixed(2)}{" "}+ <span className="text-sm font-normal text-muted-foreground">+ remaining+ </span>+ </div>+ {!isFreePlan ? (+ <div className="mt-1 flex gap-3 text-xs text-muted-foreground">+ <span className="tabular-nums">+ Monthly ${monthlyRemaining.toFixed(2)}+ </span>+ <span>·</span>+ <span className="tabular-nums">+ Top-ups ${topUpRemaining.toFixed(2)}+ </span>+ </div>+ ) : null}+ {isOutOfCredits ? (+ <p className="mt-2 text-xs text-destructive">+ {isFreePlan+ ? "You’ve used your free credits. Upgrade your plan to continue."+ : `You’ve used this month’s credits. Buy more below to keep going${+ refillDate+ ? `, or wait for them to refill on ${refillDate}`+ : ""+ }.`}+ </p>+ ) : isLowCredits ? (+ <p className="mt-2 text-xs text-amber-600">+ You’re running low on credits.{" "}+ {isFreePlan+ ? `Upgrade to get $${BASE_PLAN_OFFER.monthlyCreditsUsd}/month.`+ : "Buy more credits below."}+ </p>+ ) : null}</div>- ) : null}- {isOutOfCredits ? (- <p className="mt-2 text-xs text-destructive">- {isFreePlan- ? "You’ve used your free credits. Upgrade your plan to continue."- : `You’ve used this month’s credits. Buy more below to keep going${- refillDate- ? `, or wait for them to refill on ${refillDate}`- : ""- }.`}- </p>- ) : isLowCredits ? (- <p className="mt-2 text-xs text-amber-600">- You’re running low on credits.{" "}- {isFreePlan- ? `Upgrade to get $${BASE_PLAN_OFFER.monthlyCreditsUsd}/month.`- : "Buy more credits below."}- </p>- ) : null}- </div>- <div className="text-sm">- <span className="font-medium">Plan</span>{" "}- <span className="text-muted-foreground">- {paidPlan?.name ?? "Free Plan"}- </span>- {paidPlan ? (- <span className="text-muted-foreground">- {" "}- · ${paidPlan.monthlyCreditsUsd.toFixed(2)} of Usage- Credits each month- </span>- ) : null}- </div>-- {!canManageBilling ? (- <p className="border-t border-border pt-3 text-sm text-muted-foreground">- Only the organization owner can change the plan or buy credits.- Ask them if you need more.- </p>- ) : isFreePlan ? (- <div className="space-y-3 border-t border-border pt-3">- <div className="flex items-baseline justify-between gap-4">- <span className="text-sm font-medium">- {BASE_PLAN_OFFER.name}- </span>- <span className="text-sm font-medium tabular-nums">- ${BASE_PLAN_OFFER.priceUsd}/month+ <div className="text-sm">+ <span className="font-medium">Plan</span>{" "}+ <span className="text-muted-foreground">+ {account.paidPlanId+ ? getPlanName(account.paidPlanId)+ : "Free Plan"}</span>+ {account.paidPlanId ? (+ <span className="text-muted-foreground">+ {" "}+ · ${account.monthlyCreditsUsd.toFixed(2)} of Usage+ Credits each month+ </span>+ ) : null}</div>- <ul className="space-y-1.5">- {[- "Access to all OpenSEO features",- monthlyCreditsFeature(BASE_PLAN_OFFER),- ].map((item) => (- <li- key={item}- className="flex gap-2 text-xs text-muted-foreground"- >- <span className="mt-[1px] shrink-0 text-muted-foreground/60">- —++ {!canManageBilling ? (+ <p className="border-t border-border pt-3 text-sm text-muted-foreground">+ Only the organization owner can change the plan or buy+ credits. Ask them if you need more.+ </p>+ ) : isFreePlan ? (+ <div className="space-y-3 border-t border-border pt-3">+ <div className="flex items-baseline justify-between gap-4">+ <span className="text-sm font-medium">+ {BASE_PLAN_OFFER.name}+ </span>+ <span className="text-sm font-medium tabular-nums">+ ${BASE_PLAN_OFFER.priceUsd}/month</span>- {item}- </li>- ))}- </ul>- <Button- variant="secondary"- className="w-full"- onClick={() =>- void runAction(- "plan",- startUpgradeCheckout,- "We couldn't start the checkout. Please try again.",- )- }- >- Upgrade Plan- </Button>- {actionError("plan")}- </div>- ) : (- <div className="space-y-3">- <Button- variant="secondary"- className="w-full"- onClick={() =>- void runAction(- "plan",- () =>- customerQuery.openCustomerPortal({- returnUrl: window.location.href,- }),- "We couldn't open the billing portal. Please try again.",- )- }- >- Manage subscription- </Button>- {actionError("plan")}- </div>- )}- </CardContent>- </Card>+ </div>+ <ul className="space-y-1.5">+ {[+ "Access to all OpenSEO features",+ monthlyCreditsFeature(BASE_PLAN_OFFER),+ ].map((item) => (+ <li+ key={item}+ className="flex gap-2 text-xs text-muted-foreground"+ >+ <span className="mt-[1px] shrink-0 text-muted-foreground/60">+ —+ </span>+ {item}+ </li>+ ))}+ </ul>+ <Button+ variant="secondary"+ className="w-full"+ pending={pendingAction === "plan"}+ disabled={pendingAction !== null}+ onClick={() =>+ void runAction(+ "plan",+ openUpgradeCheckout,+ "We couldn't start the checkout. Please try again.",+ )+ }+ >+ {pendingAction === "plan"+ ? "Redirecting to Stripe..."+ : "Upgrade Plan"}+ </Button>+ {actionError("plan")}+ </div>+ ) : (+ <div className="space-y-3">+ <Button+ variant="secondary"+ className="w-full"+ pending={pendingAction === "plan"}+ disabled={pendingAction !== null}+ onClick={() =>+ void runAction(+ "plan",+ openPortal,+ "We couldn't open the billing portal. Please try again.",+ )+ }+ >+ {pendingAction === "plan"+ ? "Opening Stripe..."+ : "Manage subscription"}+ </Button>+ {actionError("plan")}+ </div>+ )}+ </CardContent>+ </Card>- {/* Buy credits card — paid plan only, owner-only */}- {!isFreePlan && canManageBilling ? (- <Card>- <CardHeader>- <CardTitle>Buy credits</CardTitle>- <CardDescription>- Top-up credits never expire and are used after your monthly- credits.- </CardDescription>- </CardHeader>- <CardContent className="space-y-3">- <Field data-invalid={showTopUpError}>- <InputGroup>- <InputGroupAddon>$</InputGroupAddon>- <InputGroupInput- type="number"- min={10}- max={99}- step={1}- inputMode="numeric"- aria-label="Top-up amount in USD"- aria-invalid={showTopUpError}- value={topUpAmount}- onChange={(e) => setTopUpAmount(e.target.value)}- />- </InputGroup>- {showTopUpError ? (- <FieldError>Enter between $10–$99.</FieldError>- ) : null}- </Field>+ {/* Buy credits card — paid plan only, owner-only */}+ {!isFreePlan && canManageBilling ? (+ <Card>+ <CardHeader>+ <CardTitle>Buy credits</CardTitle>+ <CardDescription>+ Top-up credits never expire and are used after your monthly+ credits.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-3">+ <Field data-invalid={showTopUpError}>+ <InputGroup>+ <InputGroupAddon>$</InputGroupAddon>+ <InputGroupInput+ type="number"+ min={10}+ max={99}+ step={1}+ inputMode="numeric"+ aria-label="Top-up amount in USD"+ aria-invalid={showTopUpError}+ value={topUpAmount}+ onChange={(e) => setTopUpAmount(e.target.value)}+ />+ </InputGroup>+ {showTopUpError ? (+ <FieldError>Enter between $10–$99.</FieldError>+ ) : null}+ </Field>- <Button- variant="secondary"- className="w-full"- disabled={!isValidTopUp}- onClick={() =>- void runAction(- "topUp",- () =>- customerQuery.attach({- planId: AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,- redirectMode: "always",- successUrl: window.location.href,- checkoutSessionParams: AUTUMN_CHECKOUT_SESSION_PARAMS,- featureQuantities: [- {- featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,- quantity: Math.round(- parsedTopUpAmount *- AUTUMN_SEO_DATA_CREDITS_PER_USD,- ),- },- ],- }),- "We couldn't start the checkout. Please try again.",- )- }- >- Buy credits- </Button>- {actionError("topUp")}- </CardContent>- </Card>- ) : null}- </div>+ <Button+ variant="secondary"+ className="w-full"+ pending={pendingAction === "topUp"}+ disabled={!isValidTopUp || pendingAction !== null}+ onClick={() =>+ void runAction(+ "topUp",+ startTopUpCheckout,+ "We couldn't start the checkout. Please try again.",+ )+ }+ >+ {pendingAction === "topUp"+ ? "Redirecting to Stripe..."+ : "Buy credits"}+ </Button>+ {actionError("topUp")}+ </CardContent>+ </Card>+ ) : null}+ </div>+ </>+ )}<BillingUsageChart />@@ -371,3 +357,16 @@ function BillingPage() {</div>);}++/** The subscription card's shape while the billing account loads. */+function SubscriptionCardSkeleton() {+ return (+ <Card aria-busy>+ <CardContent className="space-y-4">+ <Skeleton className="h-8 w-40" />+ <Skeleton className="h-4 w-56" />+ <Skeleton className="h-9 w-full" />+ </CardContent>+ </Card>+ );+}diff --git a/src/routes/_app/billing_.fix-payment.tsx b/src/routes/_app/billing_.fix-payment.tsxindex e8c4dda5..01ad8bf1 100644--- a/src/routes/_app/billing_.fix-payment.tsx+++ b/src/routes/_app/billing_.fix-payment.tsx@@ -1,7 +1,5 @@import { createFileRoute, Link, notFound } from "@tanstack/react-router";-import { useCustomer } from "autumn-js/react";import { useEffect, useRef, useState, type ReactNode } from "react";-import { useSession } from "@/lib/auth-client";import { isHostedClientAuthMode } from "@/lib/auth-mode";import { useQuery } from "@tanstack/react-query";import {@@ -10,22 +8,31 @@ import {} from "@/client/features/team/organizationQueries";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { captureClientError, captureClientEvent } from "@/client/lib/posthog";-import { getBillingRouteState } from "@/client/features/billing/route-state";+import {+ billingAccountQueryOptions,+ prefetchBillingAccount,+} from "@/client/features/billing/billingAccountQuery";+import { createBillingPortalSession } from "@/serverFunctions/billing";import { BILLING_ROUTE } from "@/shared/billing";import { QueryError } from "@/client/components/QueryState";+import { SkeletonPage } from "@/client/components/SkeletonPresets";import { Spinner } from "@/client/components/Spinner";import { Button } from "@/client/components/ui/button";const SUPPORT_EMAIL = "[email protected]";// How long the post-portal "checking" screen polls Autumn before telling the-// user the retry is still pending.+// user the retry is still pending, and how often it polls.const CHECKING_TIMEOUT_MS = 30_000;+const CHECKING_POLL_MS = 1000;// Linked from the payment-failed email. Deliberately narrower than /billing:// one problem, one fix. The Stripe portal both saves the new card as the// default and lets the customer pay the open invoice, so it is the only action.export const Route = createFileRoute("/_app/billing_/fix-payment")({+ // The loader fills the module-scoped query client, so keep it out of server+ // requests: one worker isolate must not cache another account's billing.+ ssr: false,validateSearch: (search: Record<string, unknown>): { returned?: true } => ({returned:search.returned === true || search.returned === "true" ? true : undefined,@@ -35,47 +42,43 @@ export const Route = createFileRoute("/_app/billing_/fix-payment")({throw notFound();}},+ // Most visits are full loads from the payment-failed email: start the+ // billing read alongside the session check, not after it.+ loader: () => prefetchBillingAccount(),component: FixPaymentPage,});function FixPaymentPage() {const { returned } = Route.useSearch();- const { data: session, isPending: isSessionPending } = useSession();const [isOpeningPortal, setIsOpeningPortal] = useState(false);const [error, setError] = useState<string | null>(null);const [checkingTimedOut, setCheckingTimedOut] = useState(false);const viewCaptured = useRef(false);- const customerQuery = useCustomer({- queryOptions: { enabled: Boolean(session?.user?.id) },+ const accountQuery = useQuery({+ ...billingAccountQueryOptions(),+ // Stripe retries the invoice with the new card and Autumn relays the+ // result a few seconds later; poll until the subscription is no longer+ // past due. An interval never cancels a read in flight, unlike refetch().+ refetchInterval: (query) =>+ returned && !checkingTimedOut && query.state.data?.isPastDue+ ? CHECKING_POLL_MS+ : false,});+ const account = accountQuery.data;+const canManageBilling = useCanManageBilling();// The hook above reports true while the role loads (a UI choice); the// telemetry waits for the real role.const roleResolved =useQuery(organizationContextQueryOptions()).data !== undefined;- const routeState = getBillingRouteState({- hasSession: Boolean(session?.user?.id),- isSessionPending,- isCustomerLoading: customerQuery.isLoading,- isCustomerError: customerQuery.isError,- hasCustomerData: customerQuery.data != null,- });- const isPastDue =- customerQuery.data?.subscriptions?.some((s) => s.pastDue) ?? false;- const isChecking =- Boolean(returned) &&- routeState === "ready" &&- isPastDue &&- !checkingTimedOut;-- // Stripe retries the invoice with the new card and Autumn relays the result- // a few seconds later; poll until the subscription is no longer past due.- const { refetch: refetchCustomer } = customerQuery;+ const isLoaded = account !== undefined;+ const isPastDue = account?.isPastDue ?? false;+ const isChecking = Boolean(returned) && isPastDue && !checkingTimedOut;+useEffect(() => {if (!isChecking) return;- const interval = setInterval(() => void refetchCustomer(), 2000);const timeout = setTimeout(() => {setCheckingTimedOut(true);// The user did the right thing and we could not confirm it worked.@@ -85,37 +88,36 @@ function FixPaymentPage() {{ context: "fix_payment_check_timeout" },);}, CHECKING_TIMEOUT_MS);- return () => {- clearInterval(interval);- clearTimeout(timeout);- };- }, [isChecking, refetchCustomer]);+ return () => clearTimeout(timeout);+ }, [isChecking]);// Funnel: viewed -> portal_opened -> returned -> payment_fixed. Each fires// once per page load; `returned` is a full navigation back from Stripe.useEffect(() => {- if (routeState !== "ready" || !roleResolved || viewCaptured.current) return;+ if (!isLoaded || !roleResolved || viewCaptured.current) return;viewCaptured.current = true;captureClientEvent(returned ? "billing:fix_payment_returned" : "billing:fix_payment_viewed",{ past_due: isPastDue, can_manage_billing: canManageBilling },);- }, [routeState, roleResolved, returned, isPastDue, canManageBilling]);+ }, [isLoaded, roleResolved, returned, isPastDue, canManageBilling]);useEffect(() => {- if (returned && routeState === "ready" && !isPastDue) {+ if (returned && isLoaded && !isPastDue) {captureClientEvent("billing:payment_fixed");}- }, [returned, routeState, isPastDue]);+ }, [returned, isLoaded, isPastDue]);async function openPortal() {setError(null);setIsOpeningPortal(true);captureClientEvent("billing:fix_payment_portal_opened");try {- const returnUrl = new URL(window.location.href);- returnUrl.searchParams.set("returned", "true");- await customerQuery.openCustomerPortal({ returnUrl: returnUrl.href });+ window.location.assign(+ await createBillingPortalSession({+ data: { returnTo: "/billing/fix-payment?returned=true" },+ }),+ );} catch (err) {captureClientError(err, { context: "fix_payment_open_portal" });setError(@@ -128,18 +130,19 @@ function FixPaymentPage() {}}- if (routeState === "loading") {- return null;+ if (accountQuery.isPending) {+ return <SkeletonPage />;}- if (routeState === "error") {+ // A failed refetch keeps the loaded page; only a failed first read stops.+ if (!isLoaded) {return (<Page title="Billing unavailable"><QueryError- error={customerQuery.error}+ cause={accountQuery.error}fallback="We couldn't load your billing details right now. Please try again."- onRetry={() => void customerQuery.refetch()}- isRetrying={customerQuery.isFetching}+ onRetry={() => void accountQuery.refetch()}+ isRetrying={accountQuery.isFetching}/></Page>);diff --git a/src/routes/_app/route.tsx b/src/routes/_app/route.tsxindex 893a04f7..db5d9311 100644--- a/src/routes/_app/route.tsx+++ b/src/routes/_app/route.tsx@@ -1,5 +1,7 @@import { Outlet, createFileRoute, useParams } from "@tanstack/react-router";+import { useEffect } from "react";import { useHostedAuthRouteGuard } from "@/client/features/auth/useHostedAuthRouteGuard";+import { prefetchBillingAccount } from "@/client/features/billing/billingAccountQuery";import { FreePlanBanner } from "@/client/features/billing/FreePlanBanner";import { SkeletonPage } from "@/client/components/SkeletonPresets";import { AuthenticatedAppLayout } from "@/client/layout/AppShell";@@ -20,6 +22,12 @@ function AppRouteLayout() {// so a full load shows the sidebar and a page skeleton instead of a spinner.const ready = authGate.canRenderAuthenticatedContent;+ // Billing, fix-payment, and the upgrade page all read this one cached+ // account, so loading it once here lets them open without waiting.+ useEffect(() => {+ if (ready) prefetchBillingAccount();+ }, [ready]);+return (<AuthenticatedAppLayoutprojectId={projectId}diff --git a/src/routes/_authenticated.subscribe.tsx b/src/routes/_authenticated.subscribe.tsxindex eaeb92c1..7b698cef 100644--- a/src/routes/_authenticated.subscribe.tsx+++ b/src/routes/_authenticated.subscribe.tsx@@ -1,9 +1,17 @@+import { useQuery } from "@tanstack/react-query";import { createFileRoute, useNavigate } from "@tanstack/react-router";-import { useCustomer } from "autumn-js/react";import { useEffect, useState } from "react";import { ArrowRight } from "lucide-react";import { QueryError } from "@/client/components/QueryState";import { StatusScreen } from "@/client/components/StatusScreen";+import {+ billingAccountQueryOptions,+ prefetchBillingAccount,+} from "@/client/features/billing/billingAccountQuery";+import {+ openUpgradeCheckout,+ prefetchUpgradeCheckout,+} from "@/client/features/billing/checkout";import { PlanPageAccountMenu } from "@/client/features/billing/PlanPageAccountMenu";import { PlanOfferCard } from "@/client/features/billing/PlanOfferCard";import {@@ -14,10 +22,8 @@ import { captureClientEvent } from "@/client/lib/posthog";import { useSession } from "@/lib/auth-client";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { getSubscribeRouteState } from "@/client/features/billing/route-state";-import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection";import { normalizeAuthRedirect } from "@/lib/auth-redirect";import { useCanManageBilling } from "@/client/features/team/organizationQueries";-import { AUTUMN_MANAGED_ACCESS_FEATURE_ID } from "@/shared/billing";import { SUPPORT_EMAIL } from "@/client/lib/support";import { Button } from "@/client/components/ui/button";@@ -29,10 +35,14 @@ const PLAN_FEATURES = [];// How long the post-checkout "finalizing" screen polls Autumn before giving-// up and letting the user through anyway.+// up and letting the user through anyway, and how often it polls.const FINALIZING_TIMEOUT_MS = 30_000;+const FINALIZING_POLL_MS = 1000;export const Route = createFileRoute("/_authenticated/subscribe")({+ // The loader fills the module-scoped query client, so keep it out of server+ // requests: one worker isolate must not cache another account's billing.+ ssr: false,validateSearch: (search: Record<string, unknown>,): { upgrade?: true; redirect?: string; checkout?: "success" } => ({@@ -44,6 +54,16 @@ export const Route = createFileRoute("/_authenticated/subscribe")({: undefined,checkout: search.checkout === "success" ? "success" : undefined,}),+ loaderDeps: ({ search: { upgrade, checkout } }) => ({ upgrade, checkout }),+ // Start the billing read alongside the session check, not after it. Upgrade+ // links outside Billing land here with ?upgrade=true, and hovering one+ // preloads this route, so the checkout link starts before the click.+ loader: ({ deps }) => {+ prefetchBillingAccount();+ if (deps.upgrade && deps.checkout !== "success") {+ prefetchUpgradeCheckout();+ }+ },component: SubscribePage,});@@ -56,48 +76,35 @@ function SubscribePage() {const [finalizingTimedOut, setFinalizingTimedOut] = useState(false);const checkoutCompleted = checkout === "success";- const hasSession = Boolean(session?.user?.id);- const customerQuery = useCustomer({- queryOptions: {- enabled: hasSession,- },+ const accountQuery = useQuery({+ ...billingAccountQueryOptions(),+ // Autumn can lag Stripe by a few seconds after checkout; poll until the+ // subscription shows up so the just-paid user isn't shown the paywall+ // again. An interval never cancels a read in flight, unlike refetch().+ refetchInterval: (query) =>+ checkoutCompleted &&+ !finalizingTimedOut &&+ query.state.data?.planStatus !== "paid"+ ? FINALIZING_POLL_MS+ : false,});+ const account = accountQuery.data;// Checkout is owner-only; other members hitting the paywall are pointed at// their organization owner instead of a Subscribe button that would 403.const canManageBilling = useCanManageBilling();- // Read managed access from the already-loaded Autumn customer (local, no API- // call) instead of a separate server round-trip.- const hasManagedAccess = customerQuery.check({- featureId: AUTUMN_MANAGED_ACCESS_FEATURE_ID,- }).allowed;-- const planStatus = getCustomerPlanStatus(customerQuery.data);const subscribeRouteState = getSubscribeRouteState({- hasSession,- isCustomerLoading: customerQuery.isLoading,- isCustomerError: customerQuery.isError,- hasCustomerData: customerQuery.data != null,- hasManagedAccess,- planStatus,+ isCustomerLoading: accountQuery.isPending,+ isCustomerError: accountQuery.isError,+ hasCustomerData: account !== undefined,+ hasManagedAccess: account?.hasManagedAccess ?? false,+ planStatus: account?.planStatus ?? "free",isUpgradeFlow: isUpgradeFlow === true,checkoutCompleted,finalizingTimedOut,});- // Autumn can lag Stripe by a few seconds after checkout; poll until the- // subscription shows up so the just-paid user isn't shown the paywall again.- const isFinalizing = subscribeRouteState === "finalizing";- const { refetch: refetchCustomer } = customerQuery;- useEffect(() => {- if (!isFinalizing) return;- const interval = setInterval(() => {- void refetchCustomer();- }, 2000);- return () => clearInterval(interval);- }, [refetchCustomer, isFinalizing]);-// Armed once on landing with checkout=success (not on the finalizing state,// which a refetch with no cached data can leave for "loading" and re-enter)// so the deadline is a hard bound from arrival.@@ -160,10 +167,10 @@ function SubscribePage() {return (<StatusScreen logo title="Billing unavailable" size="sm"><QueryError- error={customerQuery.error}+ cause={accountQuery.error}fallback="We couldn't verify your billing status right now. Please try again."- onRetry={() => void customerQuery.refetch()}- isRetrying={customerQuery.isFetching}+ onRetry={() => void accountQuery.refetch()}+ isRetrying={accountQuery.isFetching}/></StatusScreen>);@@ -174,15 +181,7 @@ function SubscribePage() {setIsAttaching(true);try {- captureClientEvent("billing:checkout_start");- const successUrl = new URL(window.location.href);- successUrl.searchParams.set("checkout", "success");- await customerQuery.attach({- planId: BASE_PLAN_OFFER.planId,- redirectMode: "always",- successUrl: successUrl.toString(),- checkoutSessionParams: BASE_PLAN_OFFER.checkoutSessionParams,- });+ await openUpgradeCheckout();} catch (err) {setError(getStandardErrorMessage(diff --git a/src/routes/_authenticated.yc.tsx b/src/routes/_authenticated.yc.tsxindex 264c43d3..ff538ea7 100644--- a/src/routes/_authenticated.yc.tsx+++ b/src/routes/_authenticated.yc.tsx@@ -1,25 +1,24 @@+import { useQuery } from "@tanstack/react-query";import { Link, createFileRoute, notFound } from "@tanstack/react-router";-import { useCustomer } from "autumn-js/react";import { useState } from "react";import { ArrowRight, Tag } from "lucide-react";import { QueryError } from "@/client/components/QueryState";import { StatusScreen } from "@/client/components/StatusScreen";import { Button } from "@/client/components/ui/button";+import { Skeleton } from "@/client/components/ui/skeleton";+import {+ billingAccountQueryOptions,+ prefetchBillingAccount,+} from "@/client/features/billing/billingAccountQuery";import { PlanPageAccountMenu } from "@/client/features/billing/PlanPageAccountMenu";import { PlanOfferCard } from "@/client/features/billing/PlanOfferCard";import {YC_PLAN_OFFER,monthlyCreditsFeature,} from "@/client/features/billing/plan-offers";-import { buildCheckoutSuccessUrl } from "@/client/features/billing/checkout-url";-import {- getCustomerPaidPlanId,- getCustomerPlanStatus,-} from "@/client/features/billing/plan-detection";-import { getBillingRouteState } from "@/client/features/billing/route-state";+import { openPlanCheckout } from "@/client/features/billing/checkout";import { useCanManageBilling } from "@/client/features/team/organizationQueries";import { getStandardErrorMessage } from "@/client/lib/error-messages";-import { captureClientEvent } from "@/client/lib/posthog";import { useSession } from "@/lib/auth-client";import { isHostedClientAuthMode } from "@/lib/auth-mode";import { BILLING_ROUTE } from "@/shared/billing";@@ -33,54 +32,43 @@ const PLAN_FEATURES = [];export const Route = createFileRoute("/_authenticated/yc")({+ // The loader fills the module-scoped query client, so keep it out of server+ // requests: one worker isolate must not cache another account's billing.+ ssr: false,beforeLoad: () => {if (!isHostedClientAuthMode()) {throw notFound();}},+ // Start the billing read alongside the session check, not after it.+ loader: () => prefetchBillingAccount(),component: YcPlanPage,});function YcPlanPage() {- const { data: session, isPending: isSessionPending } = useSession();+ const { data: session } = useSession();const [isAttaching, setIsAttaching] = useState(false);const [error, setError] = useState<string | null>(null);- const hasSession = Boolean(session?.user?.id);- const customerQuery = useCustomer({- queryOptions: {- enabled: hasSession,- },- });+ const accountQuery = useQuery(billingAccountQueryOptions());+ const account = accountQuery.data;// Checkout is owner-only; other members are pointed at their organization// owner instead of a button that would 403.const canManageBilling = useCanManageBilling();- const routeState = getBillingRouteState({- hasSession,- isSessionPending,- isCustomerLoading: customerQuery.isLoading,- isCustomerError: customerQuery.isError,- hasCustomerData: customerQuery.data != null,- });-- const isPaid = getCustomerPlanStatus(customerQuery.data) === "paid";- const isOnYcPlan =- getCustomerPaidPlanId(customerQuery.data) === YC_PLAN_OFFER.planId;+ const isPaid = account?.planStatus === "paid";+ const isOnYcPlan = account?.paidPlanId === YC_PLAN_OFFER.planId;- if (routeState === "loading") {- return null;- }-- if (routeState === "error") {+ // A failed refetch keeps the loaded page; only a failed first read stops.+ if (accountQuery.isError && !account) {return (<StatusScreen logo title="Billing unavailable" size="sm"><QueryError- error={customerQuery.error}+ cause={accountQuery.error}fallback="We couldn't verify your billing status right now. Please try again."- onRetry={() => void customerQuery.refetch()}- isRetrying={customerQuery.isFetching}+ onRetry={() => void accountQuery.refetch()}+ isRetrying={accountQuery.isFetching}/></StatusScreen>);@@ -91,17 +79,12 @@ function YcPlanPage() {setIsAttaching(true);try {- captureClientEvent("billing:checkout_start", {- planId: YC_PLAN_OFFER.planId,- });// Existing subscribers switching plans land on Billing so they can see// the new plan; new subscribers go into the app.- await customerQuery.attach({- planId: YC_PLAN_OFFER.planId,- redirectMode: "always",- successUrl: buildCheckoutSuccessUrl(isPaid ? BILLING_ROUTE : "/"),- checkoutSessionParams: YC_PLAN_OFFER.checkoutSessionParams,- });+ await openPlanCheckout(+ YC_PLAN_OFFER.planId,+ isPaid ? BILLING_ROUTE : "/",+ );} catch (err) {setError(getStandardErrorMessage(@@ -148,7 +131,10 @@ function YcPlanPage() {</p>) : null}- {isOnYcPlan ? (+ {!account ? (+ // The offer is static; only the button depends on the current plan.+ <Skeleton className="h-9 w-full" />+ ) : isOnYcPlan ? (<p className="text-sm text-muted-foreground">You’re already on the {YC_PLAN_OFFER.name}.{" "}<Linkdiff --git a/src/routes/api/autumn/$.ts b/src/routes/api/autumn/$.tsindex ebb58b5b..9bf20c1e 100644--- a/src/routes/api/autumn/$.ts+++ b/src/routes/api/autumn/$.ts@@ -1,57 +1,13 @@import { createFileRoute } from "@tanstack/react-router";-import type { autumnHandler } from "autumn-js/fetch";import { env } from "cloudflare:workers";import { isHostedAuthMode } from "@/lib/auth-mode";-import { hasOrgPermission } from "@/lib/org-permissions";import { resolveHostedContext } from "@/middleware/ensure-user/hosted";-import type { EnsuredUserContext } from "@/middleware/ensure-user/types";--// Autumn routes any org member may call: balance/customer reads that power-// credit meters and usage views. Every other route (attach, updateSubscription,-// openCustomerPortal, setupPayment, referrals, previews, ...) changes the-// org's subscription or payment state and is owner-only — unknown/new routes-// fail closed into the owner-only branch.-const MEMBER_READABLE_AUTUMN_ROUTES = new Set([- "getOrCreateCustomer",- "getEntity",- "listPlans",- "listEvents",- "aggregateEvents",-]);--// The caller's context is resolved exactly once per request, in-// handleAutumnRequest, and shared with Autumn's identify callback through this-// map. Resolving twice (identify re-reads the same headers) would let an-// active-org switch or membership change between the two reads authorize-// against one organization but bill another.-const contextByRequest = new WeakMap<Request, EnsuredUserContext>();--let handlerPromise: Promise<ReturnType<typeof autumnHandler>> | undefined;--// Lazy: keeps autumn-js/fetch out of the eager isolate startup graph;-// resolves instantly after the first request.-function loadHandler() {- return (handlerPromise ??= import("autumn-js/fetch").then(- ({ autumnHandler }) =>- autumnHandler({- identify: async (request) => {- const context = contextByRequest.get(request);- // identify is only reachable via handleAutumnRequest, which resolves- // first — fail closed rather than re-resolving if that ever breaks.- if (!context) {- throw new Error(- "Autumn identify called without a resolved context",- );- }-- return {- customerId: context.organizationId,- };- },- }),- ));-}+import { autumn } from "@/server/billing/autumn";+// The backend of the autumn-js browser client, which the app no longer uses:+// billing reads, checkout and the portal go through server functions. Tabs+// opened before that change still read their customer here; every other+// route asks them to reload. Delete this once those tabs are gone.async function handleAutumnRequest(request: Request) {if (!isHostedAuthMode(env.AUTH_MODE)) {return new Response("Not found", {@@ -59,6 +15,18 @@ async function handleAutumnRequest(request: Request) {});}+ if (+ new URL(request.url).pathname.split("/").pop() !== "getOrCreateCustomer"+ ) {+ return Response.json(+ {+ message: "Billing has changed. Reload the page and try again.",+ code: "reload_required",+ },+ { status: 410 },+ );+ }+let context;try {context = await resolveHostedContext(request.headers);@@ -68,23 +36,16 @@ async function handleAutumnRequest(request: Request) {{ status: 401 },);}- contextByRequest.set(request, context);-- const route = new URL(request.url).pathname.split("/").pop() ?? "";- if (- !MEMBER_READABLE_AUTUMN_ROUTES.has(route) &&- !hasOrgPermission(context.role, { billing: ["manage"] })- ) {- return Response.json(- {- message: "Only the organization owner can manage billing.",- code: "billing_owner_required",- },- { status: 403 },- );- }- return (await loadHandler())(request);+ // Nothing from the request body is passed on. The expand covers what those+ // tabs use: features for the client's local checks and plan names.+ return Response.json(+ await autumn.customers.getOrCreate({+ customerId: context.organizationId,+ email: context.userEmail,+ expand: ["balances.feature", "subscriptions.plan"],+ }),+ );}export const Route = createFileRoute("/api/autumn/$")({diff --git a/src/server/billing/autumn.ts b/src/server/billing/autumn.tsindex cc646c97..70241f76 100644--- a/src/server/billing/autumn.ts+++ b/src/server/billing/autumn.ts@@ -60,6 +60,14 @@ export const autumn = {finalize: (...args: Parameters<Autumn["balances"]["finalize"]>) =>loadAutumn().then((client) => client.balances.finalize(...args)),},+ billing: {+ attach: (...args: Parameters<Autumn["billing"]["attach"]>) =>+ loadAutumn().then((client) => client.billing.attach(...args)),+ openCustomerPortal: (+ ...args: Parameters<Autumn["billing"]["openCustomerPortal"]>+ ) =>+ loadAutumn().then((client) => client.billing.openCustomerPortal(...args)),+ },};// track() has no idempotency key, so replaying a deduction Autumn alreadydiff --git a/src/server/billing/billing-account.test.ts b/src/server/billing/billing-account.test.tsnew file mode 100644index 00000000..2792c638--- /dev/null+++ b/src/server/billing/billing-account.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it, vi } from "vitest";+import {+ AUTUMN_MANAGED_ACCESS_FEATURE_ID,+ AUTUMN_PAID_PLAN_FEATURE_ID,+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+} from "@/shared/billing";++const { getOrCreateMock } = vi.hoisted(() => ({ getOrCreateMock: vi.fn() }));++vi.mock("@/server/billing/autumn", () => ({+ autumn: { customers: { getOrCreate: getOrCreateMock } },+}));++import { getOrganizationBillingAccount } from "./billing-account";++const context = {+ organizationId: "org_1",+ userEmail: "[email protected]",+ userId: "user_1",+};++describe("getOrganizationBillingAccount", () => {+ it("follows the paid entitlement for the plan and reads credits in USD", async () => {+ getOrCreateMock.mockResolvedValueOnce({+ id: "org_1",+ flags: {+ [AUTUMN_PAID_PLAN_FEATURE_ID]: { planId: "friends_and_family_2" },+ [AUTUMN_MANAGED_ACCESS_FEATURE_ID]: {},+ },+ balances: {+ [AUTUMN_SEO_DATA_BALANCE_FEATURE_ID]: {+ granted: 20000,+ remaining: 1500,+ nextResetAt: 1_790_000_000_000,+ },+ [AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]: { remaining: 2500 },+ },+ subscriptions: [{ planId: "friends_and_family_2", pastDue: true }],+ });++ await expect(getOrganizationBillingAccount(context)).resolves.toEqual({+ planStatus: "paid",+ paidPlanId: "friends_and_family_2",+ monthlyCreditsUsd: 20,+ monthlyRemainingUsd: 1.5,+ topUpRemainingUsd: 2.5,+ hasManagedAccess: true,+ isPastDue: true,+ monthlyRefillsAt: 1_790_000_000_000,+ });+ // The organization is the billing identity.+ expect(getOrCreateMock).toHaveBeenCalledWith({+ customerId: "org_1",+ email: "[email protected]",+ });++ getOrCreateMock.mockResolvedValueOnce({+ id: "org_1",+ flags: { [AUTUMN_MANAGED_ACCESS_FEATURE_ID]: {} },+ balances: {},+ subscriptions: [{ pastDue: false }],+ });++ await expect(getOrganizationBillingAccount(context)).resolves.toMatchObject(+ { planStatus: "free", paidPlanId: null, hasManagedAccess: true },+ );+ });++ it("gives no refill date for a paid plan canceled at period end", async () => {+ getOrCreateMock.mockResolvedValueOnce({+ id: "org_1",+ flags: { [AUTUMN_PAID_PLAN_FEATURE_ID]: { planId: "base-plan" } },+ balances: {+ [AUTUMN_SEO_DATA_BALANCE_FEATURE_ID]: {+ nextResetAt: 1_790_000_000_000,+ },+ },+ subscriptions: [{ planId: "base-plan", canceledAt: 1_789_000_000_000 }],+ });++ await expect(getOrganizationBillingAccount(context)).resolves.toMatchObject(+ { monthlyRefillsAt: null },+ );+ });++ it("fails instead of showing the empty customer Autumn returns when it fails open", async () => {+ vi.spyOn(console, "warn").mockImplementation(() => {});+ getOrCreateMock.mockResolvedValueOnce({+ id: null,+ flags: {},+ balances: {},+ subscriptions: [],+ });++ await expect(getOrganizationBillingAccount(context)).rejects.toMatchObject({+ code: "UPSTREAM_UNAVAILABLE",+ });+ });+});diff --git a/src/server/billing/billing-account.ts b/src/server/billing/billing-account.tsnew file mode 100644index 00000000..798435fb--- /dev/null+++ b/src/server/billing/billing-account.ts@@ -0,0 +1,74 @@+import {+ AUTUMN_MANAGED_ACCESS_FEATURE_ID,+ AUTUMN_PAID_PLAN_FEATURE_ID,+ AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ autumnSeoDataCreditsToUsd,+ type PlanStatus,+} from "@/shared/billing";+import { autumn } from "@/server/billing/autumn";+import type { BillingCustomerContext } from "@/server/billing/subscription";+import { AppError } from "@/server/lib/errors";++/** The organization's plan and credits, as the billing screens show them. */+type BillingAccount = {+ planStatus: PlanStatus;+ /** The plan that granted the paid entitlement. Null on the free plan and+ * for paid access granted by hand. */+ paidPlanId: string | null;+ /** What the plan grants each month, in USD. */+ monthlyCreditsUsd: number;+ monthlyRemainingUsd: number;+ topUpRemainingUsd: number;+ hasManagedAccess: boolean;+ isPastDue: boolean;+ /** When the monthly credits refill, in epoch ms. Null for the free plan's+ * one-time credits and for a paid plan canceled at period end, which ends+ * then instead of refilling. */+ monthlyRefillsAt: number | null;+};++export async function getOrganizationBillingAccount(+ context: BillingCustomerContext,+): Promise<BillingAccount> {+ // No expand: every field read below is on the bare customer.+ const customer = await autumn.customers.getOrCreate({+ customerId: context.organizationId,+ email: context.userEmail,+ });++ // The SDK fails open on Autumn 5xx and network errors with an empty customer+ // that has no id. Showing it would tell a paying customer they are on the+ // free plan with $0, so surface the outage instead.+ if (!customer.id) {+ console.warn("billing.account: Autumn returned no customer", {+ organizationId: context.organizationId,+ });+ throw new AppError(+ "UPSTREAM_UNAVAILABLE",+ "Autumn returned no billing customer",+ );+ }++ const paidFlag = customer.flags[AUTUMN_PAID_PLAN_FEATURE_ID];+ const paidSubscription = customer.subscriptions.find(+ (s) => s.planId === paidFlag?.planId,+ );+ const monthly = customer.balances[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID];+ const topUp = customer.balances[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID];++ return {+ // Autumn names the plan that granted `paid_plan`, so every plan configured+ // to grant it counts as paid without listing plan IDs here.+ planStatus: paidFlag ? "paid" : "free",+ paidPlanId: paidFlag?.planId ?? null,+ monthlyCreditsUsd: autumnSeoDataCreditsToUsd(monthly?.granted ?? 0),+ monthlyRemainingUsd: autumnSeoDataCreditsToUsd(monthly?.remaining ?? 0),+ topUpRemainingUsd: autumnSeoDataCreditsToUsd(topUp?.remaining ?? 0),+ hasManagedAccess: Boolean(customer.flags[AUTUMN_MANAGED_ACCESS_FEATURE_ID]),+ isPastDue: customer.subscriptions.some((s) => s.pastDue),+ monthlyRefillsAt: paidSubscription?.canceledAt+ ? null+ : (monthly?.nextResetAt ?? null),+ };+}diff --git a/src/server/billing/checkout.test.ts b/src/server/billing/checkout.test.tsnew file mode 100644index 00000000..39beb527--- /dev/null+++ b/src/server/billing/checkout.test.ts@@ -0,0 +1,103 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import {+ AUTUMN_CHECKOUT_SESSION_PARAMS,+ AUTUMN_PAID_PLAN_ID,+ AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+} from "@/shared/billing";++const { attachMock, portalMock } = vi.hoisted(() => ({+ attachMock: vi.fn(),+ portalMock: vi.fn(),+}));++vi.mock("@/server/billing/autumn", () => ({+ autumn: {+ billing: { attach: attachMock, openCustomerPortal: portalMock },+ },+}));++import {+ createBillingPortalUrl,+ createPlanCheckoutUrl,+ createTopUpCheckoutUrl,+} from "./checkout";++const origin = "https://app.example.com";+const owner = { organizationId: "org_1", role: "owner" };++beforeEach(() => {+ attachMock.mockResolvedValue({ paymentUrl: "https://checkout/session" });+ portalMock.mockResolvedValue({ url: "https://portal/session" });+});++describe("billing checkout links", () => {+ it("create a plan checkout that bills only after the customer confirms", async () => {+ await expect(+ createPlanCheckoutUrl(owner, {+ planId: AUTUMN_PAID_PLAN_ID,+ // An off-site redirect falls back to the app home.+ redirectTo: "//evil.example",+ origin,+ }),+ ).resolves.toBe("https://checkout/session");+ expect(attachMock).toHaveBeenCalledWith({+ customerId: "org_1",+ planId: AUTUMN_PAID_PLAN_ID,+ // Links are created before the click, which is only safe because+ // "always" returns a link instead of charging a saved card.+ redirectMode: "always",+ successUrl: `${origin}/subscribe?checkout=success&redirect=%2F`,+ checkoutSessionParams: AUTUMN_CHECKOUT_SESSION_PARAMS,+ });+ });++ it("buys the chosen dollars of top-up credits", async () => {+ await createTopUpCheckoutUrl(owner, { amountUsd: 25, origin });++ expect(attachMock).toHaveBeenCalledWith(+ expect.objectContaining({+ planId: AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,+ redirectMode: "always",+ featureQuantities: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ quantity: 25_000,+ },+ ],+ }),+ );+ });++ it("returns from the portal to the app page that opened it", async () => {+ await createBillingPortalUrl(owner, {+ returnTo: "/billing/fix-payment?returned=true",+ origin,+ });++ expect(portalMock).toHaveBeenCalledWith({+ customerId: "org_1",+ returnUrl: `${origin}/billing/fix-payment?returned=true`,+ });+ });++ it("only lets the owner start a checkout or open the portal", async () => {+ const member = { organizationId: "org_1", role: "member" };++ await expect(+ createPlanCheckoutUrl(member, {+ planId: AUTUMN_PAID_PLAN_ID,+ redirectTo: "/",+ origin,+ }),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ await expect(+ createTopUpCheckoutUrl(member, { amountUsd: 25, origin }),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ await expect(+ createBillingPortalUrl(member, { returnTo: "/billing", origin }),+ ).rejects.toMatchObject({ code: "FORBIDDEN" });+ expect(attachMock).not.toHaveBeenCalled();+ expect(portalMock).not.toHaveBeenCalled();+ });+});diff --git a/src/server/billing/checkout.ts b/src/server/billing/checkout.tsnew file mode 100644index 00000000..15fc107b--- /dev/null+++ b/src/server/billing/checkout.ts@@ -0,0 +1,100 @@+import { normalizeAuthRedirect } from "@/lib/auth-redirect";+import type { EnsuredUserContext } from "@/middleware/ensure-user/types";+import { requireOrgPermission } from "@/server/auth/org-gate";+import { autumn } from "@/server/billing/autumn";+import { AppError } from "@/server/lib/errors";+import {+ AUTUMN_CHECKOUT_SESSION_PARAMS,+ AUTUMN_PAID_PLAN_ID,+ AUTUMN_SEO_DATA_CREDITS_PER_USD,+ AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,+ AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ AUTUMN_YC_CHECKOUT_SESSION_PARAMS,+ AUTUMN_YC_PLAN_ID,+ BILLING_ROUTE,+ SUBSCRIBE_ROUTE,+ type CheckoutPlanId,+} from "@/shared/billing";++type BillingCaller = Pick<EnsuredUserContext, "organizationId" | "role">;++// The Stripe Checkout options each plan sells with.+const PLAN_CHECKOUT_SESSION_PARAMS: Record<+ CheckoutPlanId,+ Record<string, unknown>+> = {+ [AUTUMN_PAID_PLAN_ID]: AUTUMN_CHECKOUT_SESSION_PARAMS,+ [AUTUMN_YC_PLAN_ID]: AUTUMN_YC_CHECKOUT_SESSION_PARAMS,+};++// redirectMode "always" makes Autumn return a link instead of billing: Stripe+// Checkout, or Autumn's own confirmation page for a customer who already+// subscribes. Nothing is charged until the customer confirms there, which is+// what makes it safe to create these links before the click.+async function createCheckoutUrl(+ caller: BillingCaller,+ params: Omit<+ Parameters<typeof autumn.billing.attach>[0],+ "customerId" | "redirectMode"+ >,+) {+ requireOrgPermission(caller, { billing: ["manage"] });+ const { paymentUrl } = await autumn.billing.attach({+ ...params,+ customerId: caller.organizationId,+ redirectMode: "always",+ });+ if (!paymentUrl) {+ throw new AppError("INTERNAL_ERROR", "Autumn returned no checkout link");+ }+ return paymentUrl;+}++export function createPlanCheckoutUrl(+ caller: BillingCaller,+ args: { planId: CheckoutPlanId; redirectTo: string; origin: string },+) {+ // /subscribe waits for Autumn to show the new plan, then forwards to+ // redirectTo.+ const successUrl = new URL(SUBSCRIBE_ROUTE, args.origin);+ successUrl.searchParams.set("checkout", "success");+ successUrl.searchParams.set(+ "redirect",+ normalizeAuthRedirect(args.redirectTo),+ );++ return createCheckoutUrl(caller, {+ planId: args.planId,+ successUrl: successUrl.href,+ checkoutSessionParams: PLAN_CHECKOUT_SESSION_PARAMS[args.planId],+ });+}++export function createTopUpCheckoutUrl(+ caller: BillingCaller,+ args: { amountUsd: number; origin: string },+) {+ return createCheckoutUrl(caller, {+ planId: AUTUMN_SEO_DATA_TOP_UP_PLAN_ID,+ successUrl: new URL(BILLING_ROUTE, args.origin).href,+ checkoutSessionParams: AUTUMN_CHECKOUT_SESSION_PARAMS,+ featureQuantities: [+ {+ featureId: AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ quantity: args.amountUsd * AUTUMN_SEO_DATA_CREDITS_PER_USD,+ },+ ],+ });+}++export async function createBillingPortalUrl(+ caller: BillingCaller,+ args: { returnTo: string; origin: string },+) {+ requireOrgPermission(caller, { billing: ["manage"] });+ const { url } = await autumn.billing.openCustomerPortal({+ customerId: caller.organizationId,+ returnUrl: new URL(normalizeAuthRedirect(args.returnTo), args.origin).href,+ });+ return url;+}diff --git a/src/serverFunctions/billing.ts b/src/serverFunctions/billing.tsindex 51ccd38e..6c577513 100644--- a/src/serverFunctions/billing.ts+++ b/src/serverFunctions/billing.ts@@ -1,16 +1,67 @@import { createServerFn } from "@tanstack/react-start";+import { getRequest } from "@tanstack/react-start/server";import { z } from "zod";import {AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,+ CHECKOUT_PLAN_IDS,} from "@/shared/billing";+import { getOrganizationBillingAccount } from "@/server/billing/billing-account";+import {+ createBillingPortalUrl,+ createPlanCheckoutUrl,+ createTopUpCheckoutUrl,+} from "@/server/billing/checkout";import { AppError } from "@/server/lib/errors";import {getRequiredEnvValue,isHostedServerAuthMode,} from "@/server/lib/runtime-env";+import { getPublicOrigin } from "@/server/mcp/public-origin";import { requireAuthenticatedContext } from "@/serverFunctions/middleware";+export const getBillingAccount = createServerFn({ method: "POST" })+ .middleware(requireAuthenticatedContext)+ .handler(({ context }) => getOrganizationBillingAccount(context));++// Each returns a URL for the browser to open: Stripe or Autumn checkout, or+// the Stripe billing portal.++export const createPlanCheckout = createServerFn({ method: "POST" })+ .middleware(requireAuthenticatedContext)+ .validator(+ z.object({+ planId: z.enum(CHECKOUT_PLAN_IDS),+ redirectTo: z.string(),+ }),+ )+ .handler(({ data, context }) =>+ createPlanCheckoutUrl(context, {+ ...data,+ origin: getPublicOrigin(getRequest()),+ }),+ );++export const createTopUpCheckout = createServerFn({ method: "POST" })+ .middleware(requireAuthenticatedContext)+ .validator(z.object({ amountUsd: z.number().int().min(10).max(99) }))+ .handler(({ data, context }) =>+ createTopUpCheckoutUrl(context, {+ ...data,+ origin: getPublicOrigin(getRequest()),+ }),+ );++export const createBillingPortalSession = createServerFn({ method: "POST" })+ .middleware(requireAuthenticatedContext)+ .validator(z.object({ returnTo: z.string() }))+ .handler(({ data, context }) =>+ createBillingPortalUrl(context, {+ ...data,+ origin: getPublicOrigin(getRequest()),+ }),+ );+const AUTUMN_EVENTS_LIST_URL = "https://api.useautumn.com/v1/events.list";const EVENT_PAGE_LIMIT = 1000;// Autumn rate-limits events.list; back off on 429 before giving up.diff --git a/src/shared/billing.ts b/src/shared/billing.tsindex 0be8f47d..319feadd 100644--- a/src/shared/billing.ts+++ b/src/shared/billing.ts@@ -1,9 +1,17 @@export const BILLING_ROUTE = "/billing";export const SUBSCRIBE_ROUTE = "/subscribe";+export type PlanStatus = "free" | "paid";+export const AUTUMN_PAID_PLAN_ID = "base-plan";// YC deal: same entitlements as the base plan with $50 of monthly credits.export const AUTUMN_YC_PLAN_ID = "yc-plan";+/** The plans the app sells through checkout. */+export const CHECKOUT_PLAN_IDS = [+ AUTUMN_PAID_PLAN_ID,+ AUTUMN_YC_PLAN_ID,+] as const;+export type CheckoutPlanId = (typeof CHECKOUT_PLAN_IDS)[number];export const AUTUMN_SEO_DATA_TOP_UP_PLAN_ID = "credit-top-up";export const AUTUMN_PAID_PLAN_FEATURE_ID = "paid_plan";// Granted by both the free plan (now the Autumn Default, so every non-paiddiff --git a/vite-plugin-lean-worker-bundle.ts b/vite-plugin-lean-worker-bundle.tsindex a3e3929f..60d17e3a 100644--- a/vite-plugin-lean-worker-bundle.ts+++ b/vite-plugin-lean-worker-bundle.ts@@ -20,9 +20,7 @@ const WORKERS_AI_PROVIDER_STUB = fileURLToPath(const EAGER_DENYLIST: Array<{ pattern: RegExp; expected: string }> = [{pattern: /node_modules\/autumn-js\//,- expected:- "lazy-loaded behind the facade in src/server/billing/autumn.ts and " +- "the /api/autumn route's lazy handler",+ expected: "lazy-loaded behind the facade in src/server/billing/autumn.ts",},{pattern: