Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: reuse existing subscription currency for SSO

Richie McIlroyc98cb679df41
diff --git a/apps/web/__tests__/unit/sso-billing.test.ts b/apps/web/__tests__/unit/sso-billing.test.ts
index 009468ed5..e984d9f3c 100644
--- a/apps/web/__tests__/unit/sso-billing.test.ts
+++ b/apps/web/__tests__/unit/sso-billing.test.ts
@@ -245,6 +245,7 @@ function ssoSubscription(
id: "sub_sso",
customer: "cus_owner",
status: "active",
+ currency: "usd",
metadata: { type: "saml_sso", organizationId, userId },
current_period_end: periodEnd,
cancel_at_period_end: false,
@@ -292,6 +293,18 @@ function checkoutInput(currency: "usd" | "gbp" | "eur" = "usd") {
};
}
+function proSubscription(overrides: Partial<Stripe.Subscription> = {}) {
+ const subscription = ssoSubscription(
+ { id: "sub_pro", metadata: {}, ...overrides },
+ "price_pro",
+ );
+ const item = subscription.items.data[0];
+ if (!item) throw new Error("Missing Pro subscription item");
+ item.price.product = "prod_pro";
+ item.price.currency = "usd";
+ return subscription;
+}
+
beforeEach(() => {
vi.useFakeTimers({ toFake: ["Date"] });
vi.setSystemTime(new Date("2026-09-02T00:00:00Z"));
@@ -381,6 +394,130 @@ beforeEach(() => {
afterEach(() => vi.useRealTimers());
+describe("existing subscription billing currency", () => {
+ it.each(["usd", "gbp", "eur"] as const)(
+ "uses the actual %s subscription currency for pricing and checkout",
+ async (currency) => {
+ mocks.listSubscriptions.mockResolvedValue([
+ proSubscription({ currency }),
+ ]);
+ expect(await getSsoPrices(organizationId)).toEqual([
+ { currency, unitAmount: 20000 },
+ ]);
+ expect(mocks.stripe.subscriptions.list).toHaveBeenCalledWith({
+ customer: "cus_owner",
+ status: "all",
+ limit: 100,
+ });
+ await createSsoCheckout(checkoutInput(currency));
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenCalledWith(
+ expect.objectContaining({ currency }),
+ expect.any(Object),
+ );
+ },
+ );
+
+ it.each([
+ "active",
+ "trialing",
+ "past_due",
+ "unpaid",
+ "paused",
+ "incomplete",
+ ] as const)(
+ "does not accept another currency for a %s subscription",
+ async (status) => {
+ mocks.listSubscriptions.mockResolvedValue([
+ proSubscription({
+ currency: "gbp",
+ status,
+ cancel_at_period_end: true,
+ }),
+ ]);
+ await expect(createSsoCheckout(checkoutInput("eur"))).rejects.toThrow(
+ "must use your existing billing currency",
+ );
+ expect(mocks.stripe.checkout.sessions.create).not.toHaveBeenCalled();
+ expect(state.billing.size).toBe(0);
+ },
+ );
+
+ it.each(["canceled", "incomplete_expired"] as const)(
+ "allows currency selection after a %s subscription",
+ async (status) => {
+ mocks.listSubscriptions.mockResolvedValue([
+ proSubscription({ currency: "gbp", status }),
+ ]);
+ expect(await getSsoPrices(organizationId)).toHaveLength(3);
+ await createSsoCheckout(checkoutInput("eur"));
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenCalledWith(
+ expect.objectContaining({ currency: "eur" }),
+ expect.any(Object),
+ );
+ },
+ );
+
+ it("keeps the selector for an owner without a billing customer", async () => {
+ state.users.set(userId, { id: userId, stripeCustomerId: null });
+ expect(await getSsoPrices(organizationId)).toHaveLength(3);
+ expect(mocks.stripe.subscriptions.list).not.toHaveBeenCalled();
+ });
+
+ it("does not fall back to another currency when the matching price is unavailable", async () => {
+ mocks.listSubscriptions.mockResolvedValue([
+ proSubscription({ currency: "gbp" }),
+ ]);
+ mocks.stripe.prices.retrieve.mockResolvedValue({
+ active: true,
+ currency: "usd",
+ unit_amount: 20000,
+ recurring: { interval: "month", interval_count: 1 },
+ });
+ expect(await getSsoPrices(organizationId)).toEqual([]);
+ });
+
+ it.each([{ currencies: ["cad"] }, { currencies: ["usd", "gbp"] }])(
+ "blocks unsupported or conflicting subscription currencies $currencies",
+ async ({ currencies }) => {
+ mocks.listSubscriptions.mockResolvedValue(
+ currencies.map((currency) => proSubscription({ currency })),
+ );
+ await expect(getSsoPrices(organizationId)).rejects.toThrow();
+ await expect(createSsoCheckout(checkoutInput())).rejects.toThrow();
+ expect(mocks.stripe.checkout.sessions.create).not.toHaveBeenCalled();
+ expect(state.billing.size).toBe(0);
+ },
+ );
+
+ it("does not create checkout when the subscription lookup fails", async () => {
+ mocks.listSubscriptions.mockRejectedValue(new Error("Stripe unavailable"));
+ await expect(getSsoPrices(organizationId)).rejects.toThrow(
+ "Stripe unavailable",
+ );
+ await expect(createSsoCheckout(checkoutInput())).rejects.toThrow(
+ "Stripe unavailable",
+ );
+ expect(mocks.stripe.checkout.sessions.create).not.toHaveBeenCalled();
+ });
+
+ it("expires a previous checkout before using a newly established billing currency", async () => {
+ await createSsoCheckout(checkoutInput("eur"));
+ const previousSessionId =
+ state.billing.get(organizationId)?.checkoutSessionId;
+ mocks.listSubscriptions.mockResolvedValue([
+ proSubscription({ currency: "gbp" }),
+ ]);
+ await createSsoCheckout(checkoutInput("gbp"));
+ expect(state.sessions.get(String(previousSessionId))?.status).toBe(
+ "expired",
+ );
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenLastCalledWith(
+ expect.objectContaining({ currency: "gbp" }),
+ expect.any(Object),
+ );
+ });
+});
+
describe("verified organization SSO subscription synchronization", () => {
it("binds a paid subscription to its exact organization without touching Pro", async () => {
const record = await syncSsoSubscription("sub_sso");
diff --git a/apps/web/__tests__/unit/sso-settings.test.ts b/apps/web/__tests__/unit/sso-settings.test.ts
index 91dd77672..e28d0011f 100644
--- a/apps/web/__tests__/unit/sso-settings.test.ts
+++ b/apps/web/__tests__/unit/sso-settings.test.ts
@@ -4,7 +4,7 @@ import { Organisation, User } from "@cap/web-domain";
import type { SQL } from "drizzle-orm";
import { type AnyMySqlColumn, MySqlDialect } from "drizzle-orm/mysql-core";
import { redirect } from "next/navigation";
-import { createElement } from "react";
+import { type ComponentProps, createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getOrganizationSSOData } from "@/actions/organization/get-organization-sso-data";
@@ -64,11 +64,21 @@ vi.mock("@cap/env", () => ({
serverEnv: () => mocks.env,
}));
vi.mock("@cap/ui", () => ({
+ Button: ({ children, disabled }: ComponentProps<"button">) =>
+ createElement("button", { disabled, type: "button" }, children),
+ Input: "input",
Card: "section",
CardDescription: "p",
CardHeader: "header",
CardTitle: "h2",
}));
+vi.mock("hooks/useCurrency", () => ({
+ useCurrency: () => ({ currency: "eur" }),
+}));
+vi.mock("next/navigation", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("next/navigation")>()),
+ useRouter: () => ({ refresh: vi.fn(), replace: vi.fn() }),
+}));
vi.mock(
"@/app/(org)/dashboard/settings/organization/components/ComplianceCard",
() => ({
@@ -337,6 +347,18 @@ beforeEach(() => {
});
describe("organization SSO settings authorization", () => {
+ it("keeps paid SSO setup available when billing currency lookup fails", async () => {
+ makeFixture();
+ mocks.getSsoPrices.mockRejectedValue(new Error("Stripe unavailable"));
+ const settings = await getOrganizationSsoSettings(ORGANIZATION_ID);
+ expect(settings.entitled).toBe(true);
+ expect(settings.prices).toEqual([]);
+ expect(settings.connection?.state).toBe("active");
+ await expect(openOrganizationSsoPortal(ORGANIZATION_ID)).resolves.toEqual({
+ url: "https://admin.workos.test/setup",
+ });
+ });
+
it.each(["owner", "admin"] as const)(
"lets a %s read setup status with owner-only billing controls",
async (role) => {
@@ -350,9 +372,48 @@ describe("organization SSO settings authorization", () => {
signInUrl: `https://cap.test/login?organizationId=${ORGANIZATION_ID}`,
});
expect(mocks.syncSsoSubscription).toHaveBeenCalledWith("sub_sso");
+ expect(mocks.getSsoPrices).toHaveBeenCalledWith(ORGANIZATION_ID);
+ },
+ );
+
+ it.each([
+ ["usd", "$200.00"],
+ ["gbp", "£200.00"],
+ ["eur", "€200.00"],
+ ] as const)(
+ "renders only the existing %s currency without asking the owner to choose",
+ async (currency, amount) => {
+ makeFixture({ paid: false, linked: false });
+ mocks.getSsoPrices.mockResolvedValue([{ currency, unitAmount: 20000 }]);
+ const { SsoCard } = await vi.importActual<
+ typeof import("@/app/(org)/dashboard/settings/organization/components/SsoCard")
+ >("@/app/(org)/dashboard/settings/organization/components/SsoCard");
+ const markup = renderToStaticMarkup(
+ createElement(SsoCard, {
+ initialSettings: await getOrganizationSsoSettings(ORGANIZATION_ID),
+ }),
+ );
+ expect(markup).toContain(`Add SAML SSO · ${amount}/month`);
+ expect(markup).not.toContain("Billing currency");
+ expect(markup).not.toContain("<select");
},
);
+ it("keeps the currency picker when the owner has no current subscription", async () => {
+ makeFixture({ paid: false, linked: false });
+ const { SsoCard } = await vi.importActual<
+ typeof import("@/app/(org)/dashboard/settings/organization/components/SsoCard")
+ >("@/app/(org)/dashboard/settings/organization/components/SsoCard");
+ const markup = renderToStaticMarkup(
+ createElement(SsoCard, {
+ initialSettings: await getOrganizationSsoSettings(ORGANIZATION_ID),
+ }),
+ );
+ expect(markup).toContain("Billing currency");
+ expect(markup).toContain("<select");
+ expect(markup).toContain("Add SAML SSO · €190.00/month");
+ });
+
it.each(["member", "stranger", "forged-owner"] as const)(
"denies %s access before opening setup or billing",
async (role) => {
diff --git a/apps/web/actions/organization/sso.ts b/apps/web/actions/organization/sso.ts
index 798d92100..1d24af410 100644
--- a/apps/web/actions/organization/sso.ts
+++ b/apps/web/actions/organization/sso.ts
@@ -91,7 +91,7 @@ export async function getOrganizationSsoSettings(
const ssoAvailable = Boolean(env.WORKOS_API_KEY && env.WORKOS_CLIENT_ID);
const [billing, prices, configuration] = await Promise.all([
refreshSsoBilling(organizationId),
- getSsoPrices().catch(() => []),
+ getSsoPrices(organizationId).catch(() => []),
ssoAvailable ? getSsoConfiguration(organization) : null,
]);
const entitled = hasSsoAccess(billing);
diff --git a/apps/web/lib/sso/billing.ts b/apps/web/lib/sso/billing.ts
index 1364fa6ca..77bfa6465 100644
--- a/apps/web/lib/sso/billing.ts
+++ b/apps/web/lib/sso/billing.ts
@@ -35,6 +35,42 @@ function stripeId(value: string | { id: string } | null | undefined) {
return typeof value === "string" ? value : (value?.id ?? null);
}
+function subscriptionBillingCurrency(subscriptions: Stripe.Subscription[]) {
+ const currencies = new Set(
+ subscriptions
+ .filter((subscription) => !TERMINAL_STATUSES.has(subscription.status))
+ .map((subscription) => subscription.currency),
+ );
+ if (currencies.size > 1) {
+ throw new Error(
+ "Your subscriptions use different billing currencies. Contact support before adding SAML SSO.",
+ );
+ }
+ const currency = currencies.values().next().value;
+ if (currencies.size && !isSupportedCurrency(currency)) {
+ throw new Error(
+ "SAML SSO is unavailable in your existing billing currency.",
+ );
+ }
+ return currency ?? null;
+}
+
+function listCustomerSubscriptions(customerId: string) {
+ return stripe()
+ .subscriptions.list({ customer: customerId, status: "all", limit: 100 })
+ .autoPagingToArray({ limit: 1000 });
+}
+
+async function organizationBillingCurrency(
+ organizationId: Organisation.OrganisationId,
+) {
+ const owner = await getOwner(organizationId);
+ if (!owner.stripeCustomerId) return null;
+ return subscriptionBillingCurrency(
+ await listCustomerSubscriptions(owner.stripeCustomerId),
+ );
+}
+
function checkoutPriceId() {
const environment = serverEnv();
const priceId =
@@ -422,12 +458,15 @@ export async function attachSsoCheckout(
return record?.stripeSubscriptionId === subscriptionId ? record : null;
}
-export async function getSsoPrices(): Promise<
- { currency: SupportedCurrency; unitAmount: number }[]
-> {
- const price = await stripe().prices.retrieve(checkoutPriceId(), {
- expand: ["currency_options"],
- });
+export async function getSsoPrices(
+ organizationId?: Organisation.OrganisationId,
+): Promise<{ currency: SupportedCurrency; unitAmount: number }[]> {
+ const [price, billingCurrency] = await Promise.all([
+ stripe().prices.retrieve(checkoutPriceId(), {
+ expand: ["currency_options"],
+ }),
+ organizationId ? organizationBillingCurrency(organizationId) : null,
+ ]);
if (
!price.active ||
price.recurring?.interval !== "month" ||
@@ -436,6 +475,7 @@ export async function getSsoPrices(): Promise<
throw new Error("SAML SSO billing is not available. Contact support.");
}
return SUPPORTED_CURRENCIES.flatMap((currency) => {
+ if (billingCurrency && currency !== billingCurrency) return [];
const unitAmount =
price.currency_options?.[currency]?.unit_amount ??
(price.currency === currency ? price.unit_amount : null);
@@ -626,13 +666,7 @@ export async function createSsoCheckout(
);
}
}
- const subscriptions = await stripe()
- .subscriptions.list({
- customer: input.stripeCustomerId,
- status: "all",
- limit: 100,
- })
- .autoPagingToArray({ limit: 1000 });
+ const subscriptions = await listCustomerSubscriptions(input.stripeCustomerId);
for (const subscription of subscriptions) {
if (
!isSsoSubscription(subscription) ||
@@ -651,6 +685,12 @@ export async function createSsoCheckout(
);
}
}
+ const billingCurrency = subscriptionBillingCurrency(subscriptions);
+ if (billingCurrency && input.currency !== billingCurrency) {
+ throw new Error(
+ "SAML SSO must use your existing billing currency. Refresh billing settings and try again.",
+ );
+ }
const prices = await getSsoPrices();
if (!prices.some((price) => price.currency === input.currency)) {
throw new Error("SAML SSO is unavailable in the selected currency.");