Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-5852: 新增 Workspace Billing summary/prices proxy 与 Stripe 回跳落点 (#6912)

Multica Eve2d711afdd51e
diff --git a/.env.example b/.env.example
index 4061d3f345..5eb030d34b 100644
--- a/.env.example
+++ b/.env.example
@@ -121,6 +121,13 @@ MULTICA_FEATURE_FLAGS_FILE=
# Workspace subscription Checkout/Portal/entitlement proxying is fail-closed;
# enable it only after multica-cloud billing.subscriptions is configured:
# FF_BILLING_WORKSPACE_SUBSCRIPTIONS=true
+#
+# Point multica-cloud's three subscription return URLs at this app's
+# /billing/return page (checkout_success_url, checkout_cancel_url,
+# portal_return_url). Cloud appends the workspace it authorized plus a result
+# marker, and that page resolves them to the workspace's Billing settings.
+# Configuring a workspace-specific URL instead would strand every other
+# workspace on someone else's page.
# Self-host image channel
# Default stable release channel. Pin to an exact release like v0.2.4 if you
diff --git a/apps/web/app/billing/return/page.tsx b/apps/web/app/billing/return/page.tsx
new file mode 100644
index 0000000000..44992faa91
--- /dev/null
+++ b/apps/web/app/billing/return/page.tsx
@@ -0,0 +1,18 @@
+import { BillingReturnPage } from "@multica/views/billing";
+
+/**
+ * `/billing/return` — where Stripe Checkout and Billing Portal send the browser.
+ *
+ * Deliberately a top-level route, not workspace-scoped: a deployment configures
+ * one set of return URLs in cloud, so they cannot carry a workspace slug. Cloud
+ * appends the workspace it authorized and this page resolves it to the slug
+ * before forwarding to Workspace Settings → Billing. `billing` is already a
+ * reserved slug, so this cannot shadow a real workspace.
+ *
+ * Desktop has no route of its own here: Stripe opens in the system browser, so
+ * the return always lands on the web app. The desktop Billing tab picks the new
+ * state up when its window regains focus.
+ */
+export default function BillingReturnRoute() {
+ return <BillingReturnPage />;
+}
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 3090c80805..356a2b3edc 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -185,6 +185,9 @@ import type {
CreateBillingCheckoutSessionResponse,
BillingCheckoutSessionStatus,
CreateBillingPortalSessionResponse,
+ WorkspaceSubscriptionEntitlements,
+ WorkspaceSubscriptionSummary,
+ WorkspaceSubscriptionPrices,
} from "../types";
import type { OnboardingCompletionPath } from "../onboarding/types";
import type {
@@ -287,6 +290,9 @@ import {
CreateBillingCheckoutSessionResponseSchema,
BillingCheckoutSessionStatusSchema,
CreateBillingPortalSessionResponseSchema,
+ WorkspaceSubscriptionEntitlementsSchema,
+ WorkspaceSubscriptionSummarySchema,
+ WorkspaceSubscriptionPricesSchema,
DingTalkInstallationSchema,
DingTalkGroupRouteSchema,
ListDingTalkGroupRoutesResponseSchema,
@@ -1556,6 +1562,50 @@ export class ApiClient {
);
}
+ // ---------------------------------------------------------------------
+ // Workspace subscriptions — the server resolves the workspace from the
+ // authenticated request context, so no caller names one.
+ //
+ // Two distinct failure paths, both of which a caller must render as
+ // "unavailable" and neither of which may look like Free:
+ //
+ // - non-2xx (older cloud without the route, 403, 503) throws ApiError from
+ // `fetch`, so a React Query caller sees `isError`;
+ // - a 2xx body that does not match the contract returns null here.
+ // ---------------------------------------------------------------------
+
+ async getWorkspaceSubscriptionEntitlements(): Promise<WorkspaceSubscriptionEntitlements | null> {
+ const raw = await this.fetch<unknown>(
+ "/api/cloud-subscriptions/entitlements",
+ );
+ return parseWithFallback<WorkspaceSubscriptionEntitlements | null>(
+ raw,
+ WorkspaceSubscriptionEntitlementsSchema,
+ null,
+ { endpoint: "GET /api/cloud-subscriptions/entitlements" },
+ );
+ }
+
+ async getWorkspaceSubscriptionSummary(): Promise<WorkspaceSubscriptionSummary | null> {
+ const raw = await this.fetch<unknown>("/api/cloud-subscriptions/summary");
+ return parseWithFallback<WorkspaceSubscriptionSummary | null>(
+ raw,
+ WorkspaceSubscriptionSummarySchema,
+ null,
+ { endpoint: "GET /api/cloud-subscriptions/summary" },
+ );
+ }
+
+ async getWorkspaceSubscriptionPrices(): Promise<WorkspaceSubscriptionPrices | null> {
+ const raw = await this.fetch<unknown>("/api/cloud-subscriptions/prices");
+ return parseWithFallback<WorkspaceSubscriptionPrices | null>(
+ raw,
+ WorkspaceSubscriptionPricesSchema,
+ null,
+ { endpoint: "GET /api/cloud-subscriptions/prices" },
+ );
+ }
+
async deleteRuntime(runtimeId: string): Promise<void> {
await this.fetch(`/api/runtimes/${runtimeId}`, { method: "DELETE" });
}
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 069b56442b..b98a361161 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -704,3 +704,151 @@ describe("parseWithFallback", () => {
expect(out).toBe(fallback);
});
});
+
+// Workspace subscription reads carry a specific hazard the wallet schemas do
+// not: the fallback for a paid workspace must never be a shape that reads as
+// Free. An older cloud, a 503, or a renamed field has to surface as "unknown"
+// so the UI shows "unavailable" instead of quietly downgrading a paying team.
+describe("workspace subscription contract", () => {
+ const entitlement = {
+ workspace_id: "11111111-1111-1111-1111-111111111111",
+ plan: "pro",
+ status: "active",
+ seats: 3,
+ issue_window: null,
+ autopilot_runs: null,
+ current_period_end: "2026-09-01T00:00:00Z",
+ snapshot_expires_at: null,
+ version: 7,
+ };
+
+ it("maps a full summary to camelCase without inventing values", async () => {
+ stubFetchJson({
+ entitlement,
+ billing_interval: "year",
+ actual_seats: 3,
+ billed_seats: 5,
+ pending_seat_quantity: 3,
+ cancel_at_period_end: true,
+ grace_until: "2026-09-08T00:00:00Z",
+ has_stripe_customer: true,
+ });
+ const client = new ApiClient("https://api.example.test");
+ const summary = await client.getWorkspaceSubscriptionSummary();
+
+ expect(summary).not.toBeNull();
+ expect(summary?.entitlement.plan).toBe("pro");
+ expect(summary?.entitlement.version).toBe(7);
+ expect(summary?.billingInterval).toBe("year");
+ expect(summary?.billedSeats).toBe(5);
+ expect(summary?.pendingSeatQuantity).toBe(3);
+ expect(summary?.cancelAtPeriodEnd).toBe(true);
+ expect(summary?.graceUntil).toBe("2026-09-08T00:00:00Z");
+ expect(summary?.hasStripeCustomer).toBe(true);
+ });
+
+ it("keeps a paid summary readable when optional fields are absent", async () => {
+ // A cloud that predates the optional seat/cancellation fields still has to
+ // produce a usable Pro summary rather than failing the whole read.
+ stubFetchJson({ entitlement, actual_seats: 3 });
+ const client = new ApiClient("https://api.example.test");
+ const summary = await client.getWorkspaceSubscriptionSummary();
+
+ expect(summary?.entitlement.plan).toBe("pro");
+ expect(summary?.billingInterval).toBeNull();
+ expect(summary?.billedSeats).toBeNull();
+ expect(summary?.pendingSeatQuantity).toBeNull();
+ expect(summary?.cancelAtPeriodEnd).toBe(false);
+ expect(summary?.graceUntil).toBeNull();
+ // Absent means "no Stripe customer known", which is the safe reading: the
+ // caller hides Portal rather than offering a control that would 404.
+ expect(summary?.hasStripeCustomer).toBe(false);
+ });
+
+ it("preserves unknown plans and statuses instead of coercing them", async () => {
+ stubFetchJson({
+ entitlement: { ...entitlement, plan: "business", status: "paused" },
+ actual_seats: 9,
+ });
+ const client = new ApiClient("https://api.example.test");
+ const summary = await client.getWorkspaceSubscriptionSummary();
+
+ expect(summary?.entitlement.plan).toBe("business");
+ expect(summary?.entitlement.status).toBe("paused");
+ });
+
+ it("returns null — never a Free-looking shape — for a malformed summary", async () => {
+ stubFetchJson({ entitlement: { plan: "pro" }, actual_seats: "many" });
+ const client = new ApiClient("https://api.example.test");
+ expect(await client.getWorkspaceSubscriptionSummary()).toBeNull();
+ });
+
+ it("throws ApiError for a non-2xx summary so the caller reports unavailable", async () => {
+ // An older cloud without the route, a 403, or a 503 never reaches schema
+ // parsing: fetch rejects first and a React Query caller sees isError. What
+ // matters for both paths is the same — no snapshot is produced, so nothing
+ // can be mistaken for a Free workspace.
+ for (const status of [404, 503]) {
+ stubFetchJson({ error: "unavailable" }, status);
+ const client = new ApiClient("https://api.example.test");
+ await expect(client.getWorkspaceSubscriptionSummary()).rejects.toThrow();
+ }
+ });
+
+ it("returns null for a 2xx body that does not match the contract", async () => {
+ // The other half of the contract: a response that arrives successfully but
+ // does not conform degrades to null rather than throwing into React.
+ stubFetchJson({ unexpected: "shape" });
+ const client = new ApiClient("https://api.example.test");
+ expect(await client.getWorkspaceSubscriptionSummary()).toBeNull();
+ });
+
+ it("accepts additive cloud fields on summary and prices", async () => {
+ stubFetchJson({
+ entitlement: { ...entitlement, trial_ends_at: "2026-10-01T00:00:00Z" },
+ actual_seats: 3,
+ future_field: { nested: true },
+ });
+ const client = new ApiClient("https://api.example.test");
+ expect(
+ (await client.getWorkspaceSubscriptionSummary())?.entitlement.plan,
+ ).toBe("pro");
+ });
+
+ it("maps validated prices and rejects a non-positive amount", async () => {
+ stubFetchJson({
+ month: { currency: "usd", unit_amount: 2000, interval: "month", interval_count: 1 },
+ year: { currency: "usd", unit_amount: 20000, interval: "year", interval_count: 1 },
+ });
+ const client = new ApiClient("https://api.example.test");
+ const prices = await client.getWorkspaceSubscriptionPrices();
+ expect(prices?.month.unitAmount).toBe(2000);
+ expect(prices?.year.interval).toBe("year");
+
+ // A zero or missing amount must not be rendered next to a purchase button.
+ stubFetchJson({
+ month: { currency: "usd", unit_amount: 0, interval: "month", interval_count: 1 },
+ year: { currency: "usd", unit_amount: 20000, interval: "year", interval_count: 1 },
+ });
+ expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();
+ });
+
+ it("rejects a prices response whose interval does not match its slot", async () => {
+ const client = new ApiClient("https://api.example.test");
+
+ // An interval outside the contract.
+ stubFetchJson({
+ month: { currency: "usd", unit_amount: 2000, interval: "month", interval_count: 1 },
+ year: { currency: "usd", unit_amount: 20000, interval: "week", interval_count: 1 },
+ });
+ expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();
+
+ // Valid intervals in the wrong slots. Accepting this would let the UI quote
+ // a yearly amount as the monthly price.
+ stubFetchJson({
+ month: { currency: "usd", unit_amount: 20000, interval: "year", interval_count: 1 },
+ year: { currency: "usd", unit_amount: 2000, interval: "month", interval_count: 1 },
+ });
+ expect(await client.getWorkspaceSubscriptionPrices()).toBeNull();
+ });
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index cf5c1e928e..5b94446f0c 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -21,6 +21,10 @@ import type {
Comment,
CreateBillingCheckoutSessionResponse,
CreateBillingPortalSessionResponse,
+ WorkspaceSubscriptionEntitlements,
+ WorkspaceSubscriptionSummary,
+ WorkspaceSubscriptionPrice,
+ WorkspaceSubscriptionPrices,
CronPreviewResponse,
DingTalkGroupRoute,
DingTalkInstallation,
@@ -2157,6 +2161,118 @@ export const EMPTY_CREATE_BILLING_PORTAL_SESSION_RESPONSE: CreateBillingPortalSe
url: "",
};
+// ---------------------------------------------------------------------------
+// Workspace subscriptions (`/api/cloud-subscriptions/*`)
+//
+// These schemas are the compatibility boundary with multica-cloud. Three rules
+// hold for all of them:
+//
+// 1. There is no fallback value. Callers get `null` on any parse failure and
+// must render "unavailable" — never a synthetic Free plan, because that
+// turns an upstream outage or an older cloud into a silent downgrade of a
+// paying workspace.
+// 2. `.loose()` keeps unknown keys, so a cloud that adds fields does not break
+// an older client.
+// 3. `plan` and `status` stay open strings. A new plan or Stripe status must
+// surface as unknown rather than be coerced into a known one.
+
+const WorkspaceSubscriptionIntervalSchema = z.enum(["month", "year"]);
+
+export const WorkspaceSubscriptionEntitlementsSchema = z
+ .object({
+ workspace_id: z.string(),
+ plan: z.string(),
+ status: z.string(),
+ // Cloud documents seats as >= 1, but accepting 0 costs nothing and keeps a
+ // workspace that momentarily reports no human members readable instead of
+ // failing the whole snapshot.
+ seats: z.number().int().nonnegative(),
+ issue_window: z.number().int().nonnegative().nullable(),
+ autopilot_runs: z.number().int().nonnegative().nullable(),
+ current_period_end: z.string().nullable().optional(),
+ snapshot_expires_at: z.string().nullable().optional(),
+ version: z.number().int().nonnegative(),
+ })
+ .loose()
+ .transform(
+ (value): WorkspaceSubscriptionEntitlements => ({
+ workspaceId: value.workspace_id,
+ plan: value.plan,
+ status: value.status,
+ seats: value.seats,
+ issueWindow: value.issue_window,
+ autopilotRuns: value.autopilot_runs,
+ currentPeriodEnd: value.current_period_end ?? null,
+ snapshotExpiresAt: value.snapshot_expires_at ?? null,
+ version: value.version,
+ }),
+ );
+
+export const WorkspaceSubscriptionSummarySchema = z
+ .object({
+ entitlement: WorkspaceSubscriptionEntitlementsSchema,
+ billing_interval: WorkspaceSubscriptionIntervalSchema.nullable().optional(),
+ actual_seats: z.number().int().nonnegative(),
+ billed_seats: z.number().int().nonnegative().nullable().optional(),
+ pending_seat_quantity: z.number().int().nonnegative().nullable().optional(),
+ cancel_at_period_end: z.boolean().optional(),
+ grace_until: z.string().nullable().optional(),
+ has_stripe_customer: z.boolean().optional(),
+ })
+ .loose()
+ .transform(
+ (value): WorkspaceSubscriptionSummary => ({
+ entitlement: value.entitlement,
+ billingInterval: value.billing_interval ?? null,
+ actualSeats: value.actual_seats,
+ billedSeats: value.billed_seats ?? null,
+ pendingSeatQuantity: value.pending_seat_quantity ?? null,
+ cancelAtPeriodEnd: value.cancel_at_period_end ?? false,
+ graceUntil: value.grace_until ?? null,
+ hasStripeCustomer: value.has_stripe_customer ?? false,
+ }),
+ );
+
+const WorkspaceSubscriptionPriceSchema = (
+ expected: "month" | "year",
+) =>
+ z
+ .object({
+ currency: z.string().min(1),
+ // Reject 0 and negatives: a free or malformed Price must read as
+ // "price unavailable", not as a real amount shown next to a purchase
+ // button.
+ unit_amount: z.number().int().positive(),
+ // Pinned to the slot it arrived in. Cloud validates this too, but a
+ // schema that accepted a yearly Price under `month` would let the UI
+ // quote a yearly amount as a monthly one — the schema is an independent
+ // boundary, so it checks the correspondence itself.
+ interval: z.literal(expected),
+ interval_count: z.number().int().positive(),
+ })
+ .loose()
+ .transform(
+ (value): WorkspaceSubscriptionPrice => ({
+ currency: value.currency,
+ unitAmount: value.unit_amount,
+ interval: value.interval,
+ intervalCount: value.interval_count,
+ }),
+ );
+
+export const WorkspaceSubscriptionPricesSchema = z
+ .object({
+ month: WorkspaceSubscriptionPriceSchema("month"),
+ year: WorkspaceSubscriptionPriceSchema("year"),
+ })
+ .loose()
+ .transform(
+ (value): WorkspaceSubscriptionPrices => ({
+ month: value.month,
+ year: value.year,
+ }),
+ );
+
// ---------------------------------------------------------------------------
// Runtime model discovery (`POST /api/runtimes/:id/models`,
// `GET /api/runtimes/:id/models/:requestId`). Both endpoints return the same
diff --git a/packages/core/billing/index.ts b/packages/core/billing/index.ts
index 868bf87e53..03d1544ff8 100644
--- a/packages/core/billing/index.ts
+++ b/packages/core/billing/index.ts
@@ -1,2 +1,3 @@
export * from "./queries";
export * from "./mutations";
+export * from "./workspace-subscription-queries";
diff --git a/packages/core/billing/workspace-subscription-queries.ts b/packages/core/billing/workspace-subscription-queries.ts
new file mode 100644
index 0000000000..d64920da61
--- /dev/null
+++ b/packages/core/billing/workspace-subscription-queries.ts
@@ -0,0 +1,68 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+
+/**
+ * Workspace subscription reads.
+ *
+ * Unlike the account-level wallet keys in `./queries`, these ARE scoped by
+ * workspace ID: the server resolves the workspace from the request context, so
+ * two workspaces produce different data from the same URL. Keying on the
+ * workspace is what stops a cached snapshot from one workspace being shown for
+ * another after a switch.
+ */
+export const workspaceSubscriptionKeys = {
+ all: (wsId: string) => ["workspace-subscriptions", wsId] as const,
+ entitlements: (wsId: string) =>
+ [...workspaceSubscriptionKeys.all(wsId), "entitlements"] as const,
+ summary: (wsId: string) =>
+ [...workspaceSubscriptionKeys.all(wsId), "summary"] as const,
+ prices: (wsId: string) =>
+ [...workspaceSubscriptionKeys.all(wsId), "prices"] as const,
+};
+
+export function workspaceSubscriptionEntitlementsOptions(wsId: string) {
+ return queryOptions({
+ queryKey: workspaceSubscriptionKeys.entitlements(wsId),
+ queryFn: () => api.getWorkspaceSubscriptionEntitlements(),
+ enabled: wsId.length > 0,
+ staleTime: 60 * 1000,
+ refetchOnWindowFocus: true,
+ });
+}
+
+/**
+ * The Billing page's primary read. Short stale time plus refetch on focus: a
+ * user returning from Stripe in another tab or the system browser should see the
+ * new state without a manual reload, and cloud serves this without calling
+ * Stripe so refetching is cheap.
+ */
+export function workspaceSubscriptionSummaryOptions(wsId: string) {
+ return queryOptions({
+ queryKey: workspaceSubscriptionKeys.summary(wsId),
+ queryFn: () => api.getWorkspaceSubscriptionSummary(),
+ enabled: wsId.length > 0,
+ staleTime: 30 * 1000,
+ refetchOnWindowFocus: true,
+ });
+}
+
+/**
+ * Prices are deployment configuration, not workspace state: they change only
+ * when an operator repoints a Stripe Price. Cache them for much longer than the
+ * summary and do not refetch on focus — cloud already caches them and each miss
+ * costs a Stripe round trip.
+ *
+ * Retry is disabled because the failure mode here is a misconfigured or
+ * unvalidatable Price, which retrying cannot fix; the caller shows "price
+ * confirmed at Checkout" instead.
+ */
+export function workspaceSubscriptionPricesOptions(wsId: string) {
+ return queryOptions({
+ queryKey: workspaceSubscriptionKeys.prices(wsId),
+ queryFn: () => api.getWorkspaceSubscriptionPrices(),
+ enabled: wsId.length > 0,
+ staleTime: 10 * 60 * 1000,
+ refetchOnWindowFocus: false,
+ retry: false,
+ });
+}
diff --git a/packages/core/types/billing.ts b/packages/core/types/billing.ts
index 401779d8b7..9fbb610cd7 100644
--- a/packages/core/types/billing.ts
+++ b/packages/core/types/billing.ts
@@ -180,3 +180,68 @@ export interface BillingCheckoutSessionStatus {
export interface CreateBillingPortalSessionResponse {
url: string;
}
+
+// ---------------------------------------------------------------------------
+// Workspace subscriptions (`/api/cloud-subscriptions/*`)
+//
+// Workspace-scoped, unlike the account-level wallet types above. The server
+// injects the workspace from the authenticated request context, so no client
+// ever names a workspace, an amount, a Price ID, or a seat quantity.
+//
+// Every field the server may not know is nullable rather than defaulted. A
+// missing value has to stay visibly unknown: rendering an absent plan as Free
+// would turn an upstream outage into a silent downgrade of a paying workspace.
+
+export type WorkspaceSubscriptionInterval = "month" | "year";
+
+export interface WorkspaceSubscriptionEntitlements {
+ workspaceId: string;
+ // Deliberately open strings: cloud may add plans and Stripe statuses without
+ // a client release, and an unknown value must read as unknown, not as Free.
+ plan: string;
+ status: string;
+ seats: number;
+ issueWindow: number | null;
+ autopilotRuns: number | null;
+ currentPeriodEnd: string | null;
+ snapshotExpiresAt: string | null;
+ version: number;
+}
+
+/**
+ * Everything the workspace Billing settings page needs about the current
+ * subscription, served from cloud's own database — never a synchronous Stripe
+ * call, so it stays readable while Stripe is degraded.
+ */
+export interface WorkspaceSubscriptionSummary {
+ entitlement: WorkspaceSubscriptionEntitlements;
+ billingInterval: WorkspaceSubscriptionInterval | null;
+ /** Authoritative current human-member count. Agents never take a seat. */
+ actualSeats: number;
+ /** Persisted Stripe seat high-water; null when no subscription exists yet. */
+ billedSeats: number | null;
+ /** A lower quantity already scheduled for the next period, if any. */
+ pendingSeatQuantity: number | null;
+ cancelAtPeriodEnd: boolean;
+ graceUntil: string | null;
+ /**
+ * Whether a local Stripe customer exists for this workspace. It is a fact,
+ * NOT a permission: Billing Portal still requires owner/admin, so a caller
+ * must gate that control on the member's role as well.
+ */
+ hasStripeCustomer: boolean;
+}
+
+/** Display-safe subset of a configured Stripe Price. IDs stay server-side. */
+export interface WorkspaceSubscriptionPrice {
+ currency: string;
+ /** Minor currency units per licensed seat, e.g. 2000 for $20.00. */
+ unitAmount: number;
+ interval: WorkspaceSubscriptionInterval;
+ intervalCount: number;
+}
+
+export interface WorkspaceSubscriptionPrices {
+ month: WorkspaceSubscriptionPrice;
+ year: WorkspaceSubscriptionPrice;
+}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 2f4d0b0907..17731a2ef6 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -280,4 +280,9 @@ export type {
CreateBillingCheckoutSessionResponse,
BillingCheckoutSessionStatus,
CreateBillingPortalSessionResponse,
+ WorkspaceSubscriptionInterval,
+ WorkspaceSubscriptionEntitlements,
+ WorkspaceSubscriptionSummary,
+ WorkspaceSubscriptionPrice,
+ WorkspaceSubscriptionPrices,
} from "./billing";
diff --git a/packages/views/billing/billing-return-page.test.tsx b/packages/views/billing/billing-return-page.test.tsx
new file mode 100644
index 0000000000..21c02470d5
--- /dev/null
+++ b/packages/views/billing/billing-return-page.test.tsx
@@ -0,0 +1,332 @@
+import type { ReactNode } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enBilling from "../locales/en/billing.json";
+
+const mockReplace = vi.hoisted(() => vi.fn());
+const searchRef = vi.hoisted(() => ({ current: new URLSearchParams() }));
+const authRef = vi.hoisted(() => ({
+ current: { user: { id: "user-1" } as { id: string } | null, isLoading: false },
+}));
+const mockRefetchWorkspaces = vi.hoisted(() => vi.fn());
+const workspacesRef = vi.hoisted(() => ({
+ current: {
+ data: [
+ { id: "11111111-1111-1111-1111-111111111111", slug: "acme" },
+ { id: "22222222-2222-2222-2222-222222222222", slug: "globex" },
+ ] as { id: string; slug: string }[] | undefined,
+ isPending: false,
+ isError: false,
+ refetch: mockRefetchWorkspaces,
+ },
+}));
+
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: () => workspacesRef.current,
+}));
+
+vi.mock("@multica/core/workspace/queries", () => ({
+ workspaceListOptions: () => ({ queryKey: ["workspaces"], queryFn: vi.fn() }),
+}));
+
+vi.mock("@multica/core/auth", () => {
+ const useAuthStore = Object.assign(
+ (selector?: (state: typeof authRef.current) => unknown) =>
+ selector ? selector(authRef.current) : authRef.current,
+ { getState: () => authRef.current },
+ );
+ return { useAuthStore };
+});
+
+vi.mock("../navigation", () => ({
+ useNavigation: () => ({
+ replace: mockReplace,
+ searchParams: searchRef.current,
+ pathname: "/billing/return",
+ }),
+}));
+
+import { BillingReturnPage } from "./billing-return-page";
+
+function Wrapper({ children }: { children: ReactNode }) {
+ return (
+ <I18nProvider locale="en" resources={{ en: { billing: enBilling } }}>
+ {children}
+ </I18nProvider>
+ );
+}
+
+function renderReturn(search: string) {
+ searchRef.current = new URLSearchParams(search);
+ return render(<BillingReturnPage />, { wrapper: Wrapper });
+}
+
+/**
+ * The one claim this page must never make is that anything was saved. `cancel`
+ * means the user backed out, `portal` may have been opened and closed, and even
+ * `success` only means Stripe finished — the subscription is not recorded until
+ * the webhook lands.
+ */
+function expectNoOutcomeClaim() {
+ const text = screen.getByRole("alert").textContent ?? "";
+ expect(text).not.toMatch(/saved|success|upgraded|activated|subscribed/i);
+}
+
+describe("BillingReturnPage", () => {
+ beforeEach(() => {
+ authRef.current = { user: { id: "user-1" }, isLoading: false };
+ workspacesRef.current = {
+ data: [
+ { id: "11111111-1111-1111-1111-111111111111", slug: "acme" },
+ { id: "22222222-2222-2222-2222-222222222222", slug: "globex" },
+ ],
+ isPending: false,
+ isError: false,
+ refetch: mockRefetchWorkspaces,
+ };
+ });
+
+ afterEach(() => {
+ mockReplace.mockReset();
+ mockRefetchWorkspaces.mockReset();
+ });
+
+ it("resolves the workspace id cloud authorized into its slug", async () => {
+ renderReturn("workspace_id=22222222-2222-2222-2222-222222222222&result=success&session_id=cs_test_123");
+
+ await waitFor(() =>
+ expect(mockReplace).toHaveBeenCalledWith(
+ "/globex/settings?tab=billing&result=success",
+ ),
+ );
+ });
+
+ it("forwards cancel and portal results and drops the Stripe session id", async () => {
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=cancel&session_id=cs_test_9");
+ await waitFor(() =>
+ expect(mockReplace).toHaveBeenCalledWith(
+ "/acme/settings?tab=billing&result=cancel",
+ ),
+ );
+
+ mockReplace.mockReset();
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=portal");
+ await waitFor(() =>
+ expect(mockReplace).toHaveBeenCalledWith(
+ "/acme/settings?tab=billing&result=portal",
+ ),
+ );
+ });
+
+ // Only `workspace_id` and `result` are read, and the destination is rebuilt
+ // from paths — so a hand-crafted return link cannot redirect off-app.
+ it("ignores an unrecognized result instead of forwarding it", async () => {
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=https://evil.example/steal");
+
+ await waitFor(() =>
+ expect(mockReplace).toHaveBeenCalledWith("/acme/settings?tab=billing"),
+ );
+ });
+
+ // Paying and then landing somewhere unexplained is worse than a short
+ // message, so an unresolvable workspace is explained rather than redirected.
+ it("explains an unresolvable workspace instead of silently redirecting", async () => {
+ renderReturn("workspace_id=33333333-3333-3333-3333-333333333333&result=success");
+
+ await waitFor(() =>
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "Could not find that workspace",
+ ),
+ );
+ // The page cannot know the outcome, so it must not claim one.
+ expectNoOutcomeClaim();
+ expect(mockReplace).not.toHaveBeenCalled();
+
+ await userEvent.click(screen.getByRole("button", { name: "Go to Multica" }));
+ expect(mockReplace).toHaveBeenCalledWith("/");
+ });
+
+ it("explains a missing workspace id the same way", async () => {
+ renderReturn("result=success");
+
+ await waitFor(() =>
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "Could not find that workspace",
+ ),
+ );
+ expectNoOutcomeClaim();
+ expect(mockReplace).not.toHaveBeenCalled();
+ });
+
+ // A session can expire while the user is on Stripe, so this is a normal path.
+ // Losing the return context here would leave the user on their default
+ // workspace with no idea whether the payment landed.
+ it("carries the return context through login when the session expired", async () => {
+ authRef.current = { user: null, isLoading: false };
+ renderReturn(
+ "workspace_id=11111111-1111-1111-1111-111111111111&result=success&session_id=cs_test_1",
+ );
+
+ await waitFor(() => {
+ expect(mockReplace).toHaveBeenCalledWith(
+ "/login?next=" +
+ encodeURIComponent(
+ "/billing/return?workspace_id=11111111-1111-1111-1111-111111111111&result=success",
+ ),
+ );
+ });
+ // Relative path only — the login page's sanitizer rejects anything else, so
+ // this cannot become an off-site redirect.
+ const target = mockReplace.mock.calls[0]?.[0] as string;
+ expect(decodeURIComponent(target.split("next=")[1] ?? "")).toMatch(
+ /^\/billing\/return\?/,
+ );
+ });
+
+ it("offers a retry instead of spinning forever when the workspace list fails", async () => {
+ workspacesRef.current = {
+ data: undefined,
+ isPending: false,
+ isError: true,
+ refetch: mockRefetchWorkspaces,
+ };
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=success");
+
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "Could not open workspace billing",
+ );
+ expectNoOutcomeClaim();
+ expect(mockReplace).not.toHaveBeenCalled();
+
+ await userEvent.click(screen.getByRole("button", { name: "Try again" }));
+ expect(mockRefetchWorkspaces).toHaveBeenCalledTimes(1);
+ });
+
+ it("waits for auth and the workspace list before deciding", async () => {
+ authRef.current = { user: null, isLoading: true };
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=success");
+ expect(mockReplace).not.toHaveBeenCalled();
+
+ authRef.current = { user: { id: "user-1" }, isLoading: false };
+ workspacesRef.current = {
+ data: undefined,
+ isPending: true,
+ isError: false,
+ refetch: mockRefetchWorkspaces,
+ };
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=success");
+ expect(mockReplace).not.toHaveBeenCalled();
+ });
+
+ it("shows a polite status while redirecting", () => {
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=success");
+
+ expect(screen.getByRole("status")).toHaveTextContent(
+ "Returning you to workspace billing",
+ );
+ });
+});
+
+describe("BillingReturnPage outcome-neutral failure copy", () => {
+ beforeEach(() => {
+ authRef.current = { user: { id: "user-1" }, isLoading: false };
+ workspacesRef.current = {
+ data: [{ id: "11111111-1111-1111-1111-111111111111", slug: "acme" }],
+ isPending: false,
+ isError: false,
+ refetch: mockRefetchWorkspaces,
+ };
+ });
+
+ afterEach(() => {
+ mockReplace.mockReset();
+ mockRefetchWorkspaces.mockReset();
+ });
+
+ // A canceled Checkout changed nothing, so the failure screen must not imply a
+ // billing change happened.
+ it.each([
+ ["cancel", "result=cancel"],
+ ["portal", "result=portal"],
+ ["missing result", ""],
+ ["invalid result", "result=not-a-result"],
+ ])("claims no outcome for %s", async (_label, query) => {
+ const search = ["workspace_id=99999999-9999-9999-9999-999999999999", query]
+ .filter(Boolean)
+ .join("&");
+ renderReturn(search);
+
+ await waitFor(() =>
+ expect(screen.getByRole("alert")).toHaveTextContent(
+ "Could not find that workspace",
+ ),
+ );
+ expectNoOutcomeClaim();
+ });
+
+ it("claims no outcome when the workspace list itself fails", () => {
+ workspacesRef.current = {
+ data: undefined,
+ isPending: false,
+ isError: true,
+ refetch: mockRefetchWorkspaces,
+ };
+ renderReturn("workspace_id=11111111-1111-1111-1111-111111111111&result=success");
+
+ expectNoOutcomeClaim();
+ });
+});
+
+describe("BillingReturnPage login continuation", () => {
+ beforeEach(() => {
+ authRef.current = { user: null, isLoading: false };
+ workspacesRef.current = {
+ data: undefined,
+ isPending: false,
+ isError: false,
+ refetch: mockRefetchWorkspaces,
+ };
+ });
+
+ afterEach(() => {
+ mockReplace.mockReset();
+ });
+
+ function nextParamFrom(call: string): string {
+ return decodeURIComponent(call.split("next=")[1] ?? "");
+ }
+
+ // The login page embeds `next` verbatim in the Google OAuth state, so anything
+ // carried here reaches a third party. Only the two values this page uses to
+ // resume may travel; Stripe's session id and unknown params must be dropped.
+ it("carries only workspace_id and result into the login continuation", async () => {
+ renderReturn(
+ "workspace_id=11111111-1111-1111-1111-111111111111&result=success" +
+ "&session_id=cs_test_secret&utm_source=stripe&anything=else",
+ );
+
+ await waitFor(() => expect(mockReplace).toHaveBeenCalledOnce());
+ const next = nextParamFrom(mockReplace.mock.calls[0]?.[0] as string);
+
+ expect(next).toBe(
+ "/billing/return?workspace_id=11111111-1111-1111-1111-111111111111&result=success",
+ );
+ expect(next).not.toContain("session_id");
+ expect(next).not.toContain("cs_test_secret");
+ expect(next).not.toContain("utm_source");
+ expect(next).not.toContain("anything");
+ });
+
+ it("drops an invalid result and a malformed workspace id from the continuation", async () => {
+ renderReturn("workspace_id=not-a-uuid&result=javascript:alert(1)&session_id=cs_x");
+
+ await waitFor(() => expect(mockReplace).toHaveBeenCalledOnce());
+ const next = nextParamFrom(mockReplace.mock.calls[0]?.[0] as string);
+
+ expect(next).toBe("/billing/return");
+ expect(next).not.toContain("javascript");
+ expect(next).not.toContain("not-a-uuid");
+ });
+});
diff --git a/packages/views/billing/billing-return-page.tsx b/packages/views/billing/billing-return-page.tsx
new file mode 100644
index 0000000000..086140c7dd
--- /dev/null
+++ b/packages/views/billing/billing-return-page.tsx
@@ -0,0 +1,200 @@
+"use client";
+
+import { useEffect } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { AlertCircle, Loader2, RefreshCw } from "lucide-react";
+import { useAuthStore } from "@multica/core/auth";
+import { paths } from "@multica/core/paths";
+import { workspaceListOptions } from "@multica/core/workspace/queries";
+import { Button } from "@multica/ui/components/ui/button";
+import { useNavigation } from "../navigation";
+import { useT } from "../i18n";
+
+/**
+ * Landing page for Stripe Checkout and Billing Portal returns.
+ *
+ * Stripe only knows the return URLs a deployment configured, and a deployment
+ * has exactly one set of them — so they cannot contain a workspace slug. Cloud
+ * therefore appends the workspace it already authorized (`workspace_id`) plus
+ * `result`, and this page turns that into the slug-based Settings URL the user
+ * actually needs. Hardcoding one workspace's slug in the Stripe configuration
+ * would strand every other workspace.
+ *
+ * Three things this page deliberately does NOT do:
+ *
+ * - It never trusts a redirect target from the query string. Only
+ * `workspace_id` and `result` are read, and the destination is rebuilt from
+ * `paths`, so a crafted return link cannot become an open redirect.
+ * - It does not report success on its own. `result=success` means Stripe
+ * finished, not that the subscription is recorded; the destination page is
+ * what waits for the webhook. This page only forwards the marker.
+ * - It does not silently drop the user somewhere else when something is
+ * wrong. Paying and then landing on an unexplained page is worse than a
+ * short message, so the failure states below say what happened.
+ */
+
+const RESULT_VALUES = new Set(["success", "cancel", "portal"]);
+// Same shape check the rest of core uses for route UUIDs. Only a well-formed ID
+// is worth carrying anywhere, and this one can end up in a third-party OAuth
+// state on the login detour below.
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export function BillingReturnPage() {
+ const { t } = useT("billing");
+ const navigation = useNavigation();
+ const user = useAuthStore((s) => s.user);
+ const isAuthLoading = useAuthStore((s) => s.isLoading);
+
+ const workspaceIdRaw = navigation.searchParams.get("workspace_id");
+ const workspaceIdParam =
+ workspaceIdRaw && UUID_RE.test(workspaceIdRaw) ? workspaceIdRaw : null;
+ const resultParam = navigation.searchParams.get("result");
+ const result = resultParam && RESULT_VALUES.has(resultParam) ? resultParam : null;
+
+ const {
+ data: workspaces,
+ isPending: isWorkspacesPending,
+ isError: isWorkspacesError,
+ refetch: refetchWorkspaces,
+ } = useQuery({
+ ...workspaceListOptions(),
+ enabled: !!user,
+ });
+
+ const match =
+ workspaceIdParam && workspaces
+ ? workspaces.find((ws) => ws.id === workspaceIdParam)
+ : undefined;
+ // Only after the list has actually arrived can "not found" mean anything.
+ const isUnresolvable = !!workspaces && !match;
+
+ useEffect(() => {
+ if (isAuthLoading) return;
+ // Checkout can take long enough for a session to expire, so an
+ // unauthenticated return is a normal case rather than an error. Carry enough
+ // to resume the return so the user does not land on their default workspace
+ // with no idea whether the payment took.
+ //
+ // Rebuilt from the two values this page actually uses, NOT forwarded whole:
+ // the login page embeds `next` verbatim in the Google OAuth `state`, so
+ // anything left in here — Stripe's `session_id`, any future cloud param —
+ // would be handed to a third party for no functional reason.
+ // sanitizeNextUrl on the login side also accepts relative paths only, so
+ // this cannot become an off-site redirect.
+ if (!user) {
+ const resume = new URLSearchParams();
+ if (workspaceIdParam) resume.set("workspace_id", workspaceIdParam);
+ if (result) resume.set("result", result);
+ const query = resume.toString();
+ const returnTo = query
+ ? `${navigation.pathname}?${query}`
+ : navigation.pathname;
+ navigation.replace(`${paths.login()}?next=${encodeURIComponent(returnTo)}`);
+ return;
+ }
+ if (isWorkspacesPending || isWorkspacesError || !workspaces) return;
+ if (!match) return;
+
+ const destination = `${paths.workspace(match.slug).settings()}?tab=billing${
+ result ? `&result=${result}` : ""
+ }`;
+ // replace(), not push(): the Stripe hop should not sit in history where a
+ // back navigation would re-run this redirect.
+ navigation.replace(destination);
+ }, [
+ isAuthLoading,
+ isWorkspacesError,
+ isWorkspacesPending,
+ match,
+ navigation,
+ result,
+ user,
+ workspaceIdParam,
+ workspaces,
+ ]);
+
+ // The workspace list is what turns an ID into a slug, so without it there is
+ // no destination to send anyone to. Retrying beats an endless spinner.
+ //
+ // The copy below deliberately claims nothing about the outcome. This page
+ // cannot know it: `cancel` means the user backed out, `portal` may have been
+ // opened and closed, and even `success` only means Stripe finished — the
+ // subscription is not recorded until the webhook lands. Asserting "saved" on a
+ // payment result screen is the one thing worse than saying "check Billing".
+ if (isWorkspacesError) {
+ return (
+ <ReturnMessage
+ title={t(($) => $.return_page.load_failed_title)}
+ description={t(($) => $.return_page.load_failed_description)}
+ action={
+ <Button
+ className="h-11"
+ variant="outline"
+ onClick={() => void refetchWorkspaces()}
+ >
+ <RefreshCw />
+ {t(($) => $.return_page.retry)}
+ </Button>
+ }
+ />
+ );
+ }
+
+ // Deleted workspace, revoked membership, a missing or malformed workspace_id,
+ // or a hand-edited link.
+ if (isUnresolvable) {
+ return (
+ <ReturnMessage
+ title={t(($) => $.return_page.workspace_missing_title)}
+ description={t(($) => $.return_page.workspace_missing_description)}
+ action={
+ <Button className="h-11" onClick={() => navigation.replace(paths.root())}>
+ {t(($) => $.return_page.go_to_app)}
+ </Button>
+ }
+ />
+ );
+ }
+
+ return (
+ <div
+ className="flex min-h-dvh items-center justify-center bg-background p-6"
+ role="status"
+ aria-live="polite"
+ >
+ <div className="flex items-center gap-3 text-body text-muted-foreground">
+ <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
+ <span>{t(($) => $.return_page.redirecting)}</span>
+ </div>
+ </div>
+ );
+}
+
+function ReturnMessage({
+ title,
+ description,
+ action,
+}: {
+ title: string;
+ description: string;
+ action: React.ReactNode;
+}) {
+ return (
+ <div className="flex min-h-dvh items-center justify-center bg-background p-6">
+ <div
+ className="flex max-w-[60ch] flex-col items-start gap-3"
+ role="alert"
+ aria-live="polite"
+ >
+ <div className="flex items-center gap-2 text-body font-medium">
+ <AlertCircle className="size-4 text-destructive" />
+ <span>{title}</span>
+ </div>
+ <p className="text-caption leading-5 text-muted-foreground">
+ {description}
+ </p>
+ {action}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/billing/index.ts b/packages/views/billing/index.ts
index a52179991a..c87df8153f 100644
--- a/packages/views/billing/index.ts
+++ b/packages/views/billing/index.ts
@@ -1 +1,2 @@
export { BillingTestPage } from "./billing-test-page";
+export { BillingReturnPage } from "./billing-return-page";
diff --git a/packages/views/locales/en/billing.json b/packages/views/locales/en/billing.json
index 1a03364d84..2f181ab3e6 100644
--- a/packages/views/locales/en/billing.json
+++ b/packages/views/locales/en/billing.json
@@ -71,5 +71,14 @@
"refresh": "Refresh",
"paging": "page {{page}} / {{totalPages}} · {{total}} total",
"date_dash": "—"
+ },
+ "return_page": {
+ "redirecting": "Returning you to workspace billing…",
+ "load_failed_title": "Could not open workspace billing",
+ "load_failed_description": "You came back from Stripe, but we could not load your workspace list to open the right billing page. Open Workspace settings → Billing to check the current state.",
+ "workspace_missing_title": "Could not find that workspace",
+ "workspace_missing_description": "You came back from Stripe, but this workspace is no longer available to you — it may have been removed, or your access changed. Open Billing in the workspace you expected to check the current state.",
+ "retry": "Try again",
+ "go_to_app": "Go to Multica"
}
}
diff --git a/packages/views/locales/ja/billing.json b/packages/views/locales/ja/billing.json
index b7c8543442..a133c208ef 100644
--- a/packages/views/locales/ja/billing.json
+++ b/packages/views/locales/ja/billing.json
@@ -71,5 +71,14 @@
"refresh": "更新",
"paging": "{{page}} / {{totalPages}} ページ · 合計 {{total}}件",
"date_dash": "—"
+ },
+ "return_page": {
+ "redirecting": "ワークスペースの請求ページに戻ります…",
+ "load_failed_title": "ワークスペースの請求ページを開けませんでした",
+ "load_failed_description": "Stripe から戻りましたが、ワークスペース一覧を読み込めず該当の請求ページを開けませんでした。「ワークスペース設定 → 請求」で現在の状態を確認してください。",
+ "workspace_missing_title": "ワークスペースが見つかりません",
+ "workspace_missing_description": "Stripe から戻りましたが、このワークスペースは利用できません。削除されたか、アクセス権が変更された可能性があります。対象のワークスペースの請求ページで現在の状態を確認してください。",
+ "retry": "再試行",
+ "go_to_app": "Multica を開く"
}
}
diff --git a/packages/views/locales/ko/billing.json b/packages/views/locales/ko/billing.json
index 7859df28d3..82f87e1a68 100644
--- a/packages/views/locales/ko/billing.json
+++ b/packages/views/locales/ko/billing.json
@@ -71,5 +71,14 @@
"refresh": "새로고침",
"paging": "{{page}} / {{totalPages}} 페이지 · 총 {{total}}개",
"date_dash": "—"
+ },
+ "return_page": {
+ "redirecting": "워크스페이스 결제 페이지로 돌아갑니다…",
+ "load_failed_title": "워크스페이스 결제 페이지를 열 수 없습니다",
+ "load_failed_description": "Stripe에서 돌아왔지만 워크스페이스 목록을 불러오지 못해 해당 결제 페이지를 열 수 없었습니다. 워크스페이스 설정 → 결제에서 현재 상태를 확인해 주세요.",
+ "workspace_missing_title": "워크스페이스를 찾을 수 없습니다",
+ "workspace_missing_description": "Stripe에서 돌아왔지만 이 워크스페이스를 사용할 수 없습니다. 삭제되었거나 접근 권한이 변경되었을 수 있습니다. 원하는 워크스페이스의 결제 페이지에서 현재 상태를 확인해 주세요.",
+ "retry": "다시 시도",
+ "go_to_app": "Multica로 이동"
}
}
diff --git a/packages/views/locales/zh-Hans/billing.json b/packages/views/locales/zh-Hans/billing.json
index 3a213bde49..9ad14cf2f5 100644
--- a/packages/views/locales/zh-Hans/billing.json
+++ b/packages/views/locales/zh-Hans/billing.json
@@ -71,5 +71,14 @@
"refresh": "刷新",
"paging": "第 {{page}} / {{totalPages}} 页 · 共 {{total}} 条",
"date_dash": "—"
+ },
+ "return_page": {
+ "redirecting": "正在返回工作区账单页…",
+ "load_failed_title": "无法打开工作区账单页",
+ "load_failed_description": "你已从 Stripe 返回,但我们无法加载工作区列表来打开对应的账单页。请到「工作区设置 → 账单」确认当前状态。",
+ "workspace_missing_title": "找不到该工作区",
+ "workspace_missing_description": "你已从 Stripe 返回,但该工作区对你已不可用——可能已被删除,或你的访问权限发生了变化。请到你预期的那个工作区的账单页确认当前状态。",
+ "retry": "重试",
+ "go_to_app": "前往 Multica"
}
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index d19e03e7f3..317fc2904e 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1351,14 +1351,20 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Workspace subscriptions use the same cloud transport and Stripe
// webhook as the existing owner-credit billing surface, but every request
- // is workspace-scoped. Entitlements are member-readable; Checkout, seat
- // reconcile, and Portal mutations require owner/admin. The handlers also
- // enforce billing_workspace_subscriptions so a route refactor cannot
+ // is workspace-scoped. Entitlements, summary and prices are
+ // member-readable; Checkout, seat reconcile, and Portal mutations require
+ // owner/admin. The handlers also enforce
+ // billing_workspace_subscriptions so a route refactor cannot
// accidentally bypass the rollout flag.
r.Route("/api/cloud-subscriptions", func(r chi.Router) {
r.Use(handler.RequireHumanActor)
- r.With(middleware.RequireWorkspaceMember(queries)).Get("/entitlements", h.GetCloudWorkspaceEntitlements)
+ r.Group(func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceMember(queries))
+ r.Get("/entitlements", h.GetCloudWorkspaceEntitlements)
+ r.Get("/summary", h.GetCloudWorkspaceSubscriptionSummary)
+ r.Get("/prices", h.GetCloudWorkspaceSubscriptionPrices)
+ })
r.Group(func(r chi.Router) {
r.Use(middleware.RequireWorkspaceRole(queries, "owner", "admin"))
r.Post("/checkout-sessions", h.CreateCloudWorkspaceSubscriptionCheckout)
diff --git a/server/internal/handler/cloud_billing.go b/server/internal/handler/cloud_billing.go
index 4213eb36b0..57ed7cba9d 100644
--- a/server/internal/handler/cloud_billing.go
+++ b/server/internal/handler/cloud_billing.go
@@ -157,6 +157,38 @@ func (h *Handler) GetCloudWorkspaceEntitlements(w http.ResponseWriter, r *http.R
h.proxyCloudSubscription(w, r, http.MethodGet, "/api/v1/entitlements/"+workspaceID, userID, nil, nil)
}
+// GetCloudWorkspaceSubscriptionSummary forwards cloud's Billing-page read:
+// the resolved entitlement plus local subscription facts (seats, interval,
+// cancellation and grace state, Portal availability). Member-readable like
+// entitlements; cloud re-verifies membership against its product database.
+//
+// Cloud serves this from its own database without calling Stripe, so this stays
+// available while Stripe is degraded. A cloud that predates the endpoint
+// answers 404 and the client treats the page as unavailable — never as Free.
+func (h *Handler) GetCloudWorkspaceSubscriptionSummary(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r)
+ if !ok {
+ return
+ }
+ h.proxyCloudSubscription(w, r, http.MethodGet, "/api/v1/subscriptions/"+workspaceID+"/summary", userID, nil, nil)
+}
+
+// GetCloudWorkspaceSubscriptionPrices forwards cloud's validated per-seat price
+// read so the client never hardcodes an amount that Stripe can change.
+//
+// Member-readable: seeing what Pro costs is not a privileged action, and cloud
+// scopes the read to a workspace this caller belongs to. Cloud returns only
+// currency, minor-unit amount and interval — Price and Product IDs stay server
+// side — and answers 503 when a configured Price cannot be validated, which the
+// client renders as "price confirmed at Checkout" rather than a guessed number.
+func (h *Handler) GetCloudWorkspaceSubscriptionPrices(w http.ResponseWriter, r *http.Request) {
+ workspaceID, userID, ok := h.requireCloudSubscriptionWorkspace(w, r)
+ if !ok {
+ return
+ }
+ h.proxyCloudSubscription(w, r, http.MethodGet, "/api/v1/subscriptions/"+workspaceID+"/prices", userID, nil, nil)
+}
+
// CreateCloudWorkspaceSubscriptionCheckout injects the middleware-resolved
// workspace into the upstream body. A caller cannot use a valid role in one
// workspace to smuggle a different workspace_id through JSON.
diff --git a/server/internal/handler/cloud_billing_test.go b/server/internal/handler/cloud_billing_test.go
index d3984d4ef3..f5aaecbd04 100644
--- a/server/internal/handler/cloud_billing_test.go
+++ b/server/internal/handler/cloud_billing_test.go
@@ -254,22 +254,29 @@ func withCloudSubscriptionWorkspace(req *http.Request, role string) *http.Reques
}
func TestCloudWorkspaceSubscriptionsDisabledByDefault(t *testing.T) {
- proxy := &fakeCloudRuntimeProxy{enabled: true}
- useCloudRuntimeProxy(t, proxy)
withFeatureFlag(t, testHandler, featureflags.BillingWorkspaceSubscriptions, false)
- req := withCloudSubscriptionWorkspace(
- newRequest(http.MethodGet, "/api/cloud-subscriptions/entitlements", nil),
- "member",
- )
- w := httptest.NewRecorder()
- testHandler.GetCloudWorkspaceEntitlements(w, req)
-
- if w.Code != http.StatusServiceUnavailable {
- t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
+ reads := map[string]func(http.ResponseWriter, *http.Request){
+ "/api/cloud-subscriptions/entitlements": testHandler.GetCloudWorkspaceEntitlements,
+ "/api/cloud-subscriptions/summary": testHandler.GetCloudWorkspaceSubscriptionSummary,
+ "/api/cloud-subscriptions/prices": testHandler.GetCloudWorkspaceSubscriptionPrices,
}
- if proxy.called {
- t.Fatal("upstream must not be called while the feature flag is off")
+ for path, invoke := range reads {
+ t.Run(path, func(t *testing.T) {
+ proxy := &fakeCloudRuntimeProxy{enabled: true}
+ useCloudRuntimeProxy(t, proxy)
+
+ req := withCloudSubscriptionWorkspace(newRequest(http.MethodGet, path, nil), "member")
+ w := httptest.NewRecorder()
+ invoke(w, req)
+
+ if w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, body = %s", w.Code, w.Body.String())
+ }
+ if proxy.called {
+ t.Fatal("upstream must not be called while the feature flag is off")
+ }
+ })
}
}
@@ -294,6 +301,24 @@ func TestCloudWorkspaceSubscriptionReadAndWritesUseScopedPaths(t *testing.T) {
wantPath: "/api/v1/entitlements/" + testWorkspaceID,
invoke: testHandler.GetCloudWorkspaceEntitlements,
},
+ {
+ name: "member reads billing summary",
+ method: http.MethodGet,
+ path: "/api/cloud-subscriptions/summary",
+ role: "member",
+ wantStatus: http.StatusOK,
+ wantPath: "/api/v1/subscriptions/" + testWorkspaceID + "/summary",
+ invoke: testHandler.GetCloudWorkspaceSubscriptionSummary,
+ },
+ {
+ name: "member reads seat prices",
+ method: http.MethodGet,
+ path: "/api/cloud-subscriptions/prices",
+ role: "member",
+ wantStatus: http.StatusOK,
+ wantPath: "/api/v1/subscriptions/" + testWorkspaceID + "/prices",
+ invoke: testHandler.GetCloudWorkspaceSubscriptionPrices,
+ },
{
name: "admin reconciles seats",
method: http.MethodPost,