Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: isolate SAML SSO billing from Pro entitlements

Richie McIlroy3ab4601aebf7
diff --git a/apps/web/__tests__/unit/developer-credits-webhook.test.ts b/apps/web/__tests__/unit/developer-credits-webhook.test.ts
index f379b56c8..49a257c20 100644
--- a/apps/web/__tests__/unit/developer-credits-webhook.test.ts
+++ b/apps/web/__tests__/unit/developer-credits-webhook.test.ts
@@ -78,6 +78,12 @@ vi.mock("@cap/utils", () => ({
stripe: () => mockStripe,
}));
+vi.mock("@/lib/sso/billing", () => ({
+ attachSsoCheckout: vi.fn(),
+ getSsoBillingForSubscription: vi.fn(),
+ syncSsoSubscription: vi.fn(),
+}));
+
vi.mock("drizzle-orm", () => ({
and: vi.fn((...args: unknown[]) => args),
eq: vi.fn((a: unknown, b: unknown) => ({ eq: [a, b] })),
diff --git a/apps/web/__tests__/unit/signed-baa-webhook.test.ts b/apps/web/__tests__/unit/signed-baa-webhook.test.ts
index d53f57f1c..07a5ca85c 100644
--- a/apps/web/__tests__/unit/signed-baa-webhook.test.ts
+++ b/apps/web/__tests__/unit/signed-baa-webhook.test.ts
@@ -1,5 +1,6 @@
import { sendEmail } from "@cap/database/emails/config";
import { signedBaas, users } from "@cap/database/schema";
+import { STRIPE_SAML_SSO_LEGACY_PRICE_ID } from "@cap/utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mockDbChain = {
@@ -97,12 +98,15 @@ const mockStripe = {
},
};
-vi.mock("@cap/utils", () => ({
- stripe: () => mockStripe,
- STRIPE_SIGNED_BAA_PRICE_IDS: {
- production: "price_baa",
- development: "price_baa_test",
- },
+vi.mock("@cap/utils", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@cap/utils")>();
+ return { ...actual, stripe: () => mockStripe };
+});
+
+vi.mock("@/lib/sso/billing", () => ({
+ attachSsoCheckout: vi.fn(),
+ getSsoBillingForSubscription: vi.fn(),
+ syncSsoSubscription: vi.fn(),
}));
vi.mock("drizzle-orm", () => ({
@@ -314,7 +318,7 @@ describe("Stripe webhook — Signed BAA", () => {
expect(mockStripe.subscriptions.cancel).not.toHaveBeenCalled();
});
- it("cancels Signed BAA when Pro becomes unpaid", async () => {
+ it("cancels Signed BAA when Pro becomes unpaid even if SSO remains active", async () => {
mockStripe.webhooks.constructEvent.mockReturnValue({
type: "customer.subscription.updated",
data: {
@@ -348,6 +352,16 @@ describe("Stripe webhook — Signed BAA", () => {
metadata: { type: "signed_baa" },
items: { data: [{ quantity: 1 }] },
},
+ {
+ id: "sub_sso",
+ status: "active",
+ metadata: {},
+ items: {
+ data: [
+ { quantity: 1, price: { id: STRIPE_SAML_SSO_LEGACY_PRICE_ID } },
+ ],
+ },
+ },
],
});
mockStripe.subscriptions.cancel.mockResolvedValue({ id: "sub_baa" });
@@ -357,6 +371,52 @@ describe("Stripe webhook — Signed BAA", () => {
expect(res.status).toBe(200);
expect(mockStripe.subscriptions.cancel).toHaveBeenCalledWith("sub_baa");
expect(mockDbChain.set).toHaveBeenCalledWith({ status: "canceled" });
+ expect(mockDbChain.set).toHaveBeenCalledWith(
+ expect.objectContaining({ inviteQuota: 0 }),
+ );
+ });
+
+ it("excludes SSO and BAA from Pro subscription-update seat quotas", async () => {
+ const pro = {
+ ...directProSubscription,
+ items: { data: [{ quantity: 3, price: { id: "price_pro" } }] },
+ };
+ mockStripe.webhooks.constructEvent.mockReturnValue({
+ type: "customer.subscription.updated",
+ data: { object: pro },
+ });
+ mockStripe.customers.retrieve.mockResolvedValue({
+ id: "cus_pro",
+ email: "[email protected]",
+ metadata: { userId: "user-1" },
+ });
+ mockDbChain.limit.mockResolvedValueOnce([{ id: "user-1" }]);
+ mockStripe.subscriptions.list.mockResolvedValue({
+ data: [
+ pro,
+ {
+ ...directProSubscription,
+ id: "sub_sso",
+ items: {
+ data: [
+ { quantity: 1, price: { id: STRIPE_SAML_SSO_LEGACY_PRICE_ID } },
+ ],
+ },
+ },
+ {
+ ...directProSubscription,
+ id: "sub_baa",
+ metadata: { type: "signed_baa" },
+ },
+ ],
+ });
+ expect((await POST(makeWebhookRequest())).status).toBe(200);
+ expect(mockDbChain.set).toHaveBeenCalledWith(
+ expect.objectContaining({
+ stripeSubscriptionId: "sub_pro",
+ inviteQuota: 3,
+ }),
+ );
});
it("keeps Signed BAA while Pro is past_due", async () => {
@@ -537,7 +597,9 @@ describe("Signed BAA Payment Link webhooks", () => {
customer: "cus_link",
status: "active",
metadata: {},
- items: { data: [{ price: { id: "price_baa" }, quantity: 1 }] },
+ items: {
+ data: [{ price: { id: "price_1U6C99FJxA1XpeSsUg1rXHo2" }, quantity: 1 }],
+ },
latest_invoice: { status: "paid" },
};
const session = {
@@ -827,7 +889,9 @@ describe("Signed BAA Payment Link webhooks", () => {
billing_reason: "subscription_cycle",
attempt_count: 1,
next_payment_attempt: null,
- lines: { data: [{ price: { id: "price_baa" } }] },
+ lines: {
+ data: [{ price: { id: "price_1U6C99FJxA1XpeSsUg1rXHo2" } }],
+ },
},
},
});
diff --git a/apps/web/__tests__/unit/sso-billing.test.ts b/apps/web/__tests__/unit/sso-billing.test.ts
new file mode 100644
index 000000000..009468ed5
--- /dev/null
+++ b/apps/web/__tests__/unit/sso-billing.test.ts
@@ -0,0 +1,960 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+import type { organizationSso } from "@cap/database/schema";
+import type Stripe from "stripe";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ stripe: {
+ customers: { create: vi.fn() },
+ subscriptions: { retrieve: vi.fn(), list: vi.fn() },
+ invoices: { retrieve: vi.fn(), list: vi.fn(), listLineItems: vi.fn() },
+ prices: { retrieve: vi.fn() },
+ checkout: {
+ sessions: { create: vi.fn(), retrieve: vi.fn(), expire: vi.fn() },
+ },
+ billingPortal: { sessions: { create: vi.fn() } },
+ },
+ listSubscriptions: vi.fn(),
+ environment: {
+ NODE_ENV: "production",
+ WEB_URL: "https://cap.test",
+ STRIPE_SAML_SSO_PRICE_ID: undefined as string | undefined,
+ },
+}));
+
+vi.mock("@cap/env", () => ({
+ buildEnv: {},
+ serverEnv: () => mocks.environment,
+}));
+vi.mock("@cap/utils", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@cap/utils")>();
+ return { ...actual, stripe: () => mocks.stripe };
+});
+vi.mock("@cap/database", () => ({ db: () => database }));
+vi.mock("@cap/database/schema", () => {
+ const table = (name: string, columns: string[]) => ({
+ _table: name,
+ ...Object.fromEntries(
+ columns.map((column) => [column, `${name}.${column}`]),
+ ),
+ });
+ return {
+ organizations: table("organizations", ["id", "ownerId", "tombstoneAt"]),
+ users: table("users", ["id", "stripeCustomerId"]),
+ organizationSso: table("organizationSso", [
+ "organizationId",
+ "stripeCustomerId",
+ "stripeSubscriptionId",
+ "checkoutAttemptId",
+ "checkoutSessionId",
+ ]),
+ };
+});
+vi.mock("drizzle-orm", () => ({
+ eq: (column: string, value: unknown) => ({ column, value }),
+ and: (...conditions: Condition[]) => ({ conditions }),
+ isNull: (column: string) => ({ column, value: null }),
+}));
+
+import {
+ hasSsoAccess,
+ STRIPE_SAML_SSO_LEGACY_PRICE_ID,
+ STRIPE_SAML_SSO_PRICE_ID,
+ STRIPE_SAML_SSO_PRODUCT_ID,
+} from "@cap/utils";
+import { Organisation, User } from "@cap/web-domain";
+import {
+ attachSsoCheckout,
+ createSsoBillingPortal,
+ createSsoCheckout,
+ getSsoPrices,
+ syncSsoSubscription,
+} from "@/lib/sso/billing";
+
+type BillingRow = typeof organizationSso.$inferSelect;
+type Row = Record<string, unknown>;
+type Table = { _table: string };
+type Condition =
+ | { column: string; value: unknown }
+ | { conditions: Condition[] };
+
+const organizationId = Organisation.OrganisationId.make("org_owner");
+const userId = User.UserId.make("user_owner");
+const periodEnd = Math.floor(new Date("2026-10-02T00:00:00Z").getTime() / 1000);
+const state = {
+ billing: new Map<string, Row>(),
+ organizations: new Map<string, Row>(),
+ users: new Map<string, Row>(),
+ sessions: new Map<string, Stripe.Checkout.Session>(),
+ transactionTail: Promise.resolve(),
+};
+const transactionContext = new AsyncLocalStorage<boolean>();
+
+function rowsFor(table: Table) {
+ if (table._table === "organizationSso") return state.billing;
+ if (table._table === "organizations") return state.organizations;
+ if (table._table === "users") return state.users;
+ throw new Error(`Unexpected table ${table._table}`);
+}
+
+function fieldValue(row: Row, table: Table, column: string) {
+ const [source, key = ""] = column.split(".");
+ if (table._table === "organizations" && source === "users") {
+ return state.users.get(String(row.ownerId))?.[key];
+ }
+ return row[key];
+}
+
+function matches(row: Row, table: Table, condition?: Condition): boolean {
+ if (!condition) return true;
+ if ("conditions" in condition) {
+ return condition.conditions.every((item) => matches(row, table, item));
+ }
+ return fieldValue(row, table, condition.column) === condition.value;
+}
+
+class Query {
+ private table: Table = { _table: "unset" };
+ private condition?: Condition;
+
+ constructor(private projection?: Record<string, string>) {}
+
+ from(table: Table) {
+ this.table = table;
+ return this;
+ }
+ innerJoin() {
+ return this;
+ }
+ where(condition: Condition) {
+ this.condition = condition;
+ return this;
+ }
+ limit(count: number) {
+ const result = Promise.resolve().then(() =>
+ [...rowsFor(this.table).values()]
+ .filter((row) => matches(row, this.table, this.condition))
+ .slice(0, count)
+ .map((row) =>
+ structuredClone(
+ this.projection
+ ? Object.fromEntries(
+ Object.entries(this.projection).map(([key, column]) => [
+ key,
+ fieldValue(row, this.table, column),
+ ]),
+ )
+ : row,
+ ),
+ ),
+ );
+ return Object.assign(result, { for: () => result });
+ }
+}
+
+const database = {
+ select: (projection?: Record<string, string>) => new Query(projection),
+ insert: (table: Table) => ({
+ values: async (row: Row) => {
+ if (table._table !== "organizationSso")
+ throw new Error("Unexpected non-SSO write");
+ const id = String(row.organizationId);
+ if (state.billing.has(id))
+ throw new Error("Duplicate organization billing");
+ state.billing.set(id, { ...billingRow(), ...row });
+ },
+ }),
+ update: (table: Table) => ({
+ set: (fields: Row) => ({
+ where: async (condition: Condition) => {
+ if (
+ table._table === "users" &&
+ (Object.keys(fields).length !== 1 || !fields.stripeCustomerId)
+ ) {
+ throw new Error("Unexpected Pro billing mutation");
+ }
+ for (const [id, row] of rowsFor(table)) {
+ if (matches(row, table, condition))
+ rowsFor(table).set(id, { ...row, ...fields });
+ }
+ },
+ }),
+ }),
+ transaction: async (callback: (tx: unknown) => Promise<unknown>) => {
+ const result = state.transactionTail.then(() =>
+ transactionContext.run(true, () => callback(database)),
+ );
+ state.transactionTail = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ return result;
+ },
+};
+
+function billingRow(overrides: Partial<BillingRow> = {}): BillingRow {
+ return {
+ organizationId,
+ purchasedByUserId: userId,
+ stripeCustomerId: "cus_owner",
+ stripeSubscriptionId: null,
+ stripePriceId: null,
+ status: "unpaid",
+ paidThrough: null,
+ currentPeriodEnd: null,
+ cancelAtPeriodEnd: false,
+ checkoutAttemptId: null,
+ checkoutSessionId: null,
+ checkoutStartedAt: null,
+ checkoutCurrency: null,
+ checkoutPriceId: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...overrides,
+ };
+}
+
+function paidInvoice(priceId = STRIPE_SAML_SSO_PRICE_ID): Stripe.Invoice {
+ return {
+ id: "in_sso",
+ status: "paid",
+ customer: "cus_owner",
+ subscription: "sub_sso",
+ lines: {
+ has_more: false,
+ data: [
+ {
+ type: "subscription",
+ proration: false,
+ amount: 20000,
+ price: { id: priceId },
+ subscription: "sub_sso",
+ subscription_item: "si_sso",
+ period: { start: periodEnd - 30 * 86400, end: periodEnd },
+ },
+ ],
+ },
+ } as unknown as Stripe.Invoice;
+}
+
+function ssoSubscription(
+ overrides: Partial<Stripe.Subscription> = {},
+ priceId = STRIPE_SAML_SSO_PRICE_ID,
+): Stripe.Subscription {
+ return {
+ id: "sub_sso",
+ customer: "cus_owner",
+ status: "active",
+ metadata: { type: "saml_sso", organizationId, userId },
+ current_period_end: periodEnd,
+ cancel_at_period_end: false,
+ items: {
+ has_more: false,
+ data: [
+ {
+ id: "si_sso",
+ quantity: 1,
+ price: {
+ id: priceId,
+ product: STRIPE_SAML_SSO_PRODUCT_ID,
+ recurring: { interval: "month", interval_count: 1 },
+ },
+ },
+ ],
+ },
+ latest_invoice: paidInvoice(priceId),
+ ...overrides,
+ } as Stripe.Subscription;
+}
+
+function checkoutSession(
+ overrides: Partial<Stripe.Checkout.Session> = {},
+): Stripe.Checkout.Session {
+ return {
+ id: "cs_sso",
+ mode: "subscription",
+ status: "complete",
+ payment_status: "paid",
+ currency: "usd",
+ customer: "cus_owner",
+ subscription: "sub_sso",
+ metadata: { type: "saml_sso", organizationId, userId },
+ ...overrides,
+ } as Stripe.Checkout.Session;
+}
+
+function checkoutInput(currency: "usd" | "gbp" | "eur" = "usd") {
+ return {
+ organizationId,
+ purchasedByUserId: userId,
+ stripeCustomerId: "cus_owner",
+ currency,
+ };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(new Date("2026-09-02T00:00:00Z"));
+ vi.clearAllMocks();
+ state.billing.clear();
+ state.organizations.clear();
+ state.users.clear();
+ state.sessions.clear();
+ state.transactionTail = Promise.resolve();
+ state.organizations.set(organizationId, {
+ id: organizationId,
+ ownerId: userId,
+ tombstoneAt: null,
+ });
+ state.users.set(userId, { id: userId, stripeCustomerId: "cus_owner" });
+ mocks.environment.NODE_ENV = "production";
+ mocks.environment.STRIPE_SAML_SSO_PRICE_ID = undefined;
+ mocks.stripe.subscriptions.retrieve.mockImplementation(async () => {
+ expect(transactionContext.getStore()).not.toBe(true);
+ return ssoSubscription();
+ });
+ mocks.listSubscriptions.mockResolvedValue([]);
+ mocks.stripe.subscriptions.list.mockReturnValue({
+ autoPagingToArray: mocks.listSubscriptions,
+ });
+ mocks.stripe.invoices.list.mockResolvedValue({ data: [] });
+ mocks.stripe.customers.create.mockResolvedValue({ id: "cus_created" });
+ mocks.stripe.prices.retrieve.mockResolvedValue({
+ id: STRIPE_SAML_SSO_PRICE_ID,
+ active: true,
+ currency: "usd",
+ unit_amount: 20000,
+ recurring: { interval: "month", interval_count: 1 },
+ currency_options: {
+ usd: { unit_amount: 20000 },
+ gbp: { unit_amount: 20000 },
+ eur: { unit_amount: 20000 },
+ },
+ });
+ mocks.stripe.checkout.sessions.retrieve.mockImplementation(
+ async (id: string) => {
+ expect(transactionContext.getStore()).not.toBe(true);
+ const session = state.sessions.get(id);
+ if (!session) throw new Error("Missing checkout session");
+ return structuredClone(session);
+ },
+ );
+ mocks.stripe.checkout.sessions.create.mockImplementation(
+ async (params: Stripe.Checkout.SessionCreateParams) => {
+ expect(transactionContext.getStore()).not.toBe(true);
+ const existing = [...state.sessions.values()].find(
+ (session) =>
+ session.metadata?.checkoutAttemptId ===
+ params.metadata?.checkoutAttemptId,
+ );
+ if (existing) return existing;
+ const session = checkoutSession({
+ id: `cs_created_${state.sessions.size}`,
+ status: "open",
+ payment_status: "unpaid",
+ subscription: null,
+ url: "https://checkout.stripe.test/sso",
+ metadata: params.metadata as Stripe.Metadata,
+ customer: params.customer,
+ currency: params.currency ?? null,
+ });
+ state.sessions.set(session.id, session);
+ return session;
+ },
+ );
+ mocks.stripe.checkout.sessions.expire.mockImplementation(
+ async (id: string) => {
+ expect(transactionContext.getStore()).not.toBe(true);
+ const session = state.sessions.get(id);
+ if (!session || session.status !== "open") {
+ throw new Error("Checkout is not open");
+ }
+ const expired = { ...session, status: "expired" as const, url: null };
+ state.sessions.set(id, expired);
+ return structuredClone(expired);
+ },
+ );
+ mocks.stripe.billingPortal.sessions.create.mockResolvedValue({
+ url: "https://billing.stripe.test/sso",
+ });
+});
+
+afterEach(() => vi.useRealTimers());
+
+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");
+ expect(record).toMatchObject({
+ organizationId,
+ purchasedByUserId: userId,
+ stripeSubscriptionId: "sub_sso",
+ status: "active",
+ });
+ expect(record?.paidThrough).toEqual(new Date(periodEnd * 1000));
+ expect(hasSsoAccess(record)).toBe(true);
+ expect(state.users.get(userId)).toEqual({
+ id: userId,
+ stripeCustomerId: "cus_owner",
+ });
+ });
+
+ it("retains an explicitly linked legacy price and does not charge again", async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({ stripeSubscriptionId: "sub_sso" }),
+ );
+ state.users.set(userId, {
+ id: userId,
+ stripeCustomerId: "cus_separate_pro",
+ });
+ const subscription = ssoSubscription(
+ { metadata: {} },
+ STRIPE_SAML_SSO_LEGACY_PRICE_ID,
+ );
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(subscription);
+ const record = await syncSsoSubscription("sub_sso");
+ expect(record?.stripePriceId).toBe(STRIPE_SAML_SSO_LEGACY_PRICE_ID);
+ expect(hasSsoAccess(record)).toBe(true);
+ expect(mocks.stripe.checkout.sessions.create).not.toHaveBeenCalled();
+ });
+
+ it("does not guess an organization for an unbound payment without metadata", async () => {
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ metadata: {} }),
+ );
+ expect(await syncSsoSubscription("sub_sso")).toBeNull();
+ expect(state.billing.size).toBe(0);
+ });
+
+ it.each(["active", "past_due", "trialing"] as const)(
+ "does not grant never-paid %s access",
+ async (status) => {
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ status, latest_invoice: null }),
+ );
+ const record = await syncSsoSubscription("sub_sso");
+ expect(record?.paidThrough).toBeNull();
+ expect(hasSsoAccess(record)).toBe(false);
+ },
+ );
+
+ it("does not derive paid-through from an unrelated paid invoice", async () => {
+ const invoice = paidInvoice();
+ invoice.subscription = "sub_other";
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ latest_invoice: invoice }),
+ );
+ expect(hasSsoAccess(await syncSsoSubscription("sub_sso"))).toBe(false);
+ });
+
+ it("rejects metadata-only entitlement on an unapproved product price", async () => {
+ const subscription = ssoSubscription({}, "price_unknown");
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(subscription);
+ await expect(syncSsoSubscription("sub_sso")).rejects.toThrow(
+ "supported SAML SSO price",
+ );
+ expect(state.billing.size).toBe(0);
+ });
+
+ it("revokes access when a linked subscription changes to an unsupported price", async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({
+ stripeSubscriptionId: "sub_sso",
+ status: "active",
+ paidThrough: new Date(periodEnd * 1000),
+ }),
+ );
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({}, "price_unknown"),
+ );
+ const record = await syncSsoSubscription("sub_sso");
+ expect(record?.status).toBe("unpaid");
+ expect(hasSsoAccess(record)).toBe(false);
+ });
+
+ it("rejects a payment bound to another customer's owner", async () => {
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ customer: "cus_other" }),
+ );
+ await expect(syncSsoSubscription("sub_sso")).rejects.toThrow(
+ "different account",
+ );
+ expect(state.billing.size).toBe(0);
+ });
+
+ it("rechecks the billing customer under the organization lock before new association", async () => {
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ latest_invoice: null }),
+ );
+ mocks.stripe.invoices.list.mockImplementationOnce(async () => {
+ state.users.set(userId, { id: userId, stripeCustomerId: "cus_changed" });
+ return { data: [paidInvoice()] };
+ });
+ await expect(syncSsoSubscription("sub_sso")).rejects.toThrow(
+ "billing account changed",
+ );
+ expect(state.billing.size).toBe(0);
+ });
+
+ it("does not replace a different live subscription", async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({ stripeSubscriptionId: "sub_existing", status: "active" }),
+ );
+ await expect(syncSsoSubscription("sub_sso")).rejects.toThrow(
+ "different SAML SSO subscription",
+ );
+ expect(state.billing.get(organizationId)?.stripeSubscriptionId).toBe(
+ "sub_existing",
+ );
+ });
+
+ it("uses fresh cancellation state and preserves later subscription bindings", async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({
+ stripeSubscriptionId: "sub_sso",
+ status: "active",
+ paidThrough: new Date(periodEnd * 1000),
+ }),
+ );
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ status: "canceled" }),
+ );
+ const canceled = await syncSsoSubscription("sub_sso");
+ expect(canceled?.status).toBe("canceled");
+ expect(hasSsoAccess(canceled)).toBe(false);
+ state.billing.set(
+ organizationId,
+ billingRow({ stripeSubscriptionId: "sub_new", status: "active" }),
+ );
+ await syncSsoSubscription("sub_sso");
+ expect(state.billing.get(organizationId)?.stripeSubscriptionId).toBe(
+ "sub_new",
+ );
+ expect(state.billing.get(organizationId)?.status).toBe("active");
+ });
+
+ it("refreshes again when another sync changes billing during the Stripe request", async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({ stripeSubscriptionId: "sub_sso", status: "active" }),
+ );
+ mocks.stripe.subscriptions.retrieve
+ .mockImplementationOnce(async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({ stripeSubscriptionId: "sub_sso", status: "canceled" }),
+ );
+ return ssoSubscription();
+ })
+ .mockResolvedValue(ssoSubscription({ status: "canceled" }));
+ expect((await syncSsoSubscription("sub_sso"))?.status).toBe("canceled");
+ expect(mocks.stripe.subscriptions.retrieve).toHaveBeenCalledTimes(2);
+ });
+
+ it("preserves the confirmed paid period during dunning and advances it after payment", async () => {
+ const oldPaidThrough = new Date("2026-08-31T00:00:00Z");
+ state.billing.set(
+ organizationId,
+ billingRow({
+ stripeSubscriptionId: "sub_sso",
+ status: "active",
+ paidThrough: oldPaidThrough,
+ }),
+ );
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ status: "past_due", latest_invoice: null }),
+ );
+ const overdue = await syncSsoSubscription("sub_sso");
+ expect(overdue?.paidThrough).toEqual(oldPaidThrough);
+ expect(hasSsoAccess(overdue)).toBe(true);
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(ssoSubscription());
+ expect((await syncSsoSubscription("sub_sso"))?.paidThrough).toEqual(
+ new Date(periodEnd * 1000),
+ );
+ });
+
+ it("recognizes a paid overdue invoice when a newer invoice is still open", async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({
+ stripeSubscriptionId: "sub_sso",
+ status: "past_due",
+ paidThrough: new Date("2026-08-01T00:00:00Z"),
+ }),
+ );
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({
+ status: "past_due",
+ latest_invoice: { ...paidInvoice(), id: "in_new", status: "open" },
+ }),
+ );
+ mocks.stripe.invoices.list.mockResolvedValue({ data: [paidInvoice()] });
+ expect((await syncSsoSubscription("sub_sso"))?.paidThrough).toEqual(
+ new Date(periodEnd * 1000),
+ );
+ });
+
+ it("loads remaining invoice lines before deciding the SSO period is unpaid", async () => {
+ const invoice = paidInvoice();
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({
+ latest_invoice: {
+ ...invoice,
+ lines: { ...invoice.lines, data: [], has_more: true },
+ },
+ }),
+ );
+ mocks.stripe.invoices.listLineItems.mockReturnValue({
+ autoPagingToArray: vi.fn().mockResolvedValue(invoice.lines.data),
+ });
+ expect(hasSsoAccess(await syncSsoSubscription("sub_sso"))).toBe(true);
+ expect(mocks.stripe.invoices.listLineItems).toHaveBeenCalledWith("in_sso", {
+ limit: 100,
+ });
+ });
+
+ it("keeps a scheduled cancellation accessible through the paid period", async () => {
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ cancel_at_period_end: true }),
+ );
+ const record = await syncSsoSubscription("sub_sso");
+ expect(record?.cancelAtPeriodEnd).toBe(true);
+ expect(hasSsoAccess(record)).toBe(true);
+ });
+});
+
+describe("SSO checkout ownership and duplicate prevention", () => {
+ it("verifies the current owner before reading checkout data", async () => {
+ await expect(
+ attachSsoCheckout("cs_other", {
+ organizationId,
+ userId: User.UserId.make("user_other"),
+ }),
+ ).rejects.toThrow("Only the organization owner");
+ expect(mocks.stripe.checkout.sessions.retrieve).not.toHaveBeenCalled();
+ });
+
+ it("does not accept another organization's checkout or an unpaid redirect", async () => {
+ state.sessions.set(
+ "cs_sso",
+ checkoutSession({
+ metadata: { type: "saml_sso", organizationId: "org_other", userId },
+ }),
+ );
+ await expect(
+ attachSsoCheckout("cs_sso", { organizationId, userId }),
+ ).rejects.toThrow("different organization or account");
+ expect(state.billing.size).toBe(0);
+ state.sessions.set("cs_sso", checkoutSession({ payment_status: "unpaid" }));
+ expect(
+ await attachSsoCheckout("cs_sso", { organizationId, userId }),
+ ).toBeNull();
+ expect(state.billing.size).toBe(0);
+ });
+
+ it("confirms duplicate checkout delivery idempotently", async () => {
+ state.sessions.set("cs_sso", checkoutSession());
+ await attachSsoCheckout("cs_sso", { organizationId, userId });
+ const second = await attachSsoCheckout("cs_sso", {
+ organizationId,
+ userId,
+ });
+ expect(hasSsoAccess(second)).toBe(true);
+ expect(state.billing.size).toBe(1);
+ expect(mocks.stripe.checkout.sessions.create).not.toHaveBeenCalled();
+ });
+
+ it("creates organization-bound checkout with the displayed currency and fixed quantity", async () => {
+ expect(await createSsoCheckout(checkoutInput("gbp"))).toBe(
+ "https://checkout.stripe.test/sso",
+ );
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ currency: "gbp",
+ customer: "cus_owner",
+ mode: "subscription",
+ line_items: [{ price: STRIPE_SAML_SSO_PRICE_ID, quantity: 1 }],
+ metadata: expect.objectContaining({
+ type: "saml_sso",
+ organizationId,
+ userId,
+ }),
+ subscription_data: {
+ metadata: expect.objectContaining({
+ type: "saml_sso",
+ organizationId,
+ userId,
+ }),
+ },
+ success_url: expect.stringContaining(
+ "/security?organizationId=org_owner&sso_checkout=",
+ ),
+ }),
+ { idempotencyKey: expect.stringContaining("saml-sso-checkout-") },
+ );
+ });
+
+ it("creates a billing customer idempotently when the owner does not have one", async () => {
+ state.users.set(userId, { id: userId, stripeCustomerId: null });
+ await createSsoCheckout({ ...checkoutInput(), stripeCustomerId: null });
+ expect(mocks.stripe.customers.create).toHaveBeenCalledWith(
+ { metadata: { userId } },
+ { idempotencyKey: `cap-sso-customer-${userId}` },
+ );
+ expect(state.users.get(userId)).toEqual({
+ id: userId,
+ stripeCustomerId: "cus_created",
+ });
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenCalledWith(
+ expect.objectContaining({ customer: "cus_created" }),
+ expect.any(Object),
+ );
+ });
+
+ it("preserves a Pro customer attached concurrently while creating the SSO customer", async () => {
+ state.users.set(userId, { id: userId, stripeCustomerId: null });
+ mocks.stripe.customers.create.mockImplementationOnce(async () => {
+ state.users.set(userId, { id: userId, stripeCustomerId: "cus_new_pro" });
+ return { id: "cus_created" };
+ });
+ await createSsoCheckout({ ...checkoutInput(), stripeCustomerId: null });
+ expect(state.users.get(userId)?.stripeCustomerId).toBe("cus_new_pro");
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenCalledWith(
+ expect.objectContaining({ customer: "cus_new_pro" }),
+ expect.any(Object),
+ );
+ });
+
+ it("reopens an existing session without starting another purchase", async () => {
+ await createSsoCheckout(checkoutInput("eur"));
+ await createSsoCheckout(checkoutInput("eur"));
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenCalledTimes(1);
+ expect(state.billing.get(organizationId)?.checkoutCurrency).toBe("eur");
+ });
+
+ it("confirms expiration before replacing an open checkout with the selected currency", async () => {
+ await createSsoCheckout(checkoutInput("usd"));
+ const previous = state.billing.get(organizationId);
+ await createSsoCheckout(checkoutInput("gbp"));
+ expect(mocks.stripe.checkout.sessions.expire).toHaveBeenCalledWith(
+ previous?.checkoutSessionId,
+ {},
+ { idempotencyKey: `saml-sso-expire-${previous?.checkoutAttemptId}` },
+ );
+ expect(
+ state.sessions.get(String(previous?.checkoutSessionId))?.status,
+ ).toBe("expired");
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenCalledTimes(2);
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenLastCalledWith(
+ expect.objectContaining({ currency: "gbp" }),
+ expect.any(Object),
+ );
+ expect(state.billing.get(organizationId)?.checkoutCurrency).toBe("gbp");
+ });
+
+ it("retains the same attempt until an ambiguous currency-switch expiration is reconciled", async () => {
+ await createSsoCheckout(checkoutInput("usd"));
+ const previous = structuredClone(state.billing.get(organizationId));
+ mocks.stripe.checkout.sessions.expire.mockImplementationOnce(
+ async (id: string) => {
+ const session = state.sessions.get(id);
+ if (!session) throw new Error("Missing checkout fixture");
+ state.sessions.set(id, { ...session, status: "expired", url: null });
+ throw new Error("Expiration response interrupted");
+ },
+ );
+ await expect(createSsoCheckout(checkoutInput("gbp"))).rejects.toThrow(
+ "Expiration response interrupted",
+ );
+ expect(state.billing.get(organizationId)).toEqual(previous);
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenCalledTimes(1);
+ await createSsoCheckout(checkoutInput("gbp"));
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenCalledTimes(2);
+ expect(state.billing.get(organizationId)?.checkoutCurrency).toBe("gbp");
+ });
+
+ it("reuses identical parameters and the same key after an ambiguous response", async () => {
+ mocks.stripe.checkout.sessions.create.mockRejectedValueOnce(
+ new Error("Connection interrupted"),
+ );
+ await expect(createSsoCheckout(checkoutInput("gbp"))).rejects.toThrow(
+ "Connection interrupted",
+ );
+ await createSsoCheckout(checkoutInput("eur"));
+ expect(mocks.stripe.checkout.sessions.create.mock.calls[1]).toEqual(
+ mocks.stripe.checkout.sessions.create.mock.calls[0],
+ );
+ });
+
+ it("reserves one stable purchase attempt for concurrent clicks", async () => {
+ await Promise.all([
+ createSsoCheckout(checkoutInput()),
+ createSsoCheckout(checkoutInput()),
+ ]);
+ const keys = mocks.stripe.checkout.sessions.create.mock.calls.map(
+ (call) => call[1].idempotencyKey,
+ );
+ expect(new Set(keys).size).toBe(1);
+ expect(state.billing.size).toBe(1);
+ });
+
+ it("does not reuse an ambiguous key beyond Stripe's retention window", async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({
+ checkoutAttemptId: "attempt_old",
+ checkoutCurrency: "usd",
+ checkoutPriceId: STRIPE_SAML_SSO_PRICE_ID,
+ checkoutStartedAt: new Date("2026-08-30T00:00:00Z"),
+ }),
+ );
+ await expect(createSsoCheckout(checkoutInput())).rejects.toThrow(
+ "could not be confirmed",
+ );
+ expect(mocks.stripe.checkout.sessions.create).not.toHaveBeenCalled();
+ });
+
+ it("allows a new attempt only after a prior session is confirmed expired", async () => {
+ await createSsoCheckout(checkoutInput());
+ const first = state.sessions.values().next().value;
+ if (!first) throw new Error("Missing checkout fixture");
+ state.sessions.set(first.id, { ...first, status: "expired" });
+ await createSsoCheckout(checkoutInput());
+ const keys = mocks.stripe.checkout.sessions.create.mock.calls.map(
+ (call) => call[1].idempotencyKey,
+ );
+ expect(new Set(keys).size).toBe(2);
+ });
+
+ it("allows repurchase after a paid subscription has actually ended", async () => {
+ await createSsoCheckout(checkoutInput());
+ const first = state.sessions.values().next().value;
+ if (!first) throw new Error("Missing checkout fixture");
+ state.sessions.set(first.id, {
+ ...first,
+ status: "complete",
+ payment_status: "paid",
+ subscription: "sub_sso",
+ });
+ await attachSsoCheckout(first.id, { organizationId, userId });
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ status: "canceled" }),
+ );
+ expect(await createSsoCheckout(checkoutInput())).toBe(
+ "https://checkout.stripe.test/sso",
+ );
+ expect(mocks.stripe.checkout.sessions.create).toHaveBeenCalledTimes(2);
+ expect(state.billing.get(organizationId)?.checkoutSessionId).not.toBe(
+ first.id,
+ );
+ });
+
+ it("blocks another charge when an external SSO payment needs association", async () => {
+ mocks.listSubscriptions.mockResolvedValue([
+ ssoSubscription({ metadata: {} }),
+ ]);
+ await expect(createSsoCheckout(checkoutInput())).rejects.toThrow(
+ "existing SAML SSO payment",
+ );
+ expect(mocks.stripe.checkout.sessions.create).not.toHaveBeenCalled();
+ });
+
+ it("blocks another purchase while an existing subscription can recover payment", async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({ stripeSubscriptionId: "sub_sso" }),
+ );
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ status: "unpaid", latest_invoice: null }),
+ );
+ await expect(createSsoCheckout(checkoutInput())).rejects.toThrow(
+ "existing billing",
+ );
+ expect(mocks.stripe.checkout.sessions.create).not.toHaveBeenCalled();
+ });
+
+ it("preserves an ended legacy binding when repurchase would change its billing customer", async () => {
+ const existing = billingRow({
+ stripeSubscriptionId: "sub_sso",
+ status: "canceled",
+ stripePriceId: STRIPE_SAML_SSO_LEGACY_PRICE_ID,
+ });
+ state.billing.set(organizationId, existing);
+ state.users.set(userId, { id: userId, stripeCustomerId: "cus_pro" });
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription(
+ { status: "canceled", metadata: {} },
+ STRIPE_SAML_SSO_LEGACY_PRICE_ID,
+ ),
+ );
+ await expect(
+ createSsoCheckout({ ...checkoutInput(), stripeCustomerId: "cus_pro" }),
+ ).rejects.toThrow("different billing account");
+ expect(state.billing.get(organizationId)?.stripeCustomerId).toBe(
+ "cus_owner",
+ );
+ expect(mocks.stripe.checkout.sessions.create).not.toHaveBeenCalled();
+ });
+});
+
+describe("SSO prices and billing management", () => {
+ it("reads USD, GBP, and EUR amounts from the single multi-currency price", async () => {
+ expect(await getSsoPrices()).toEqual([
+ { currency: "usd", unitAmount: 20000 },
+ { currency: "gbp", unitAmount: 20000 },
+ { currency: "eur", unitAmount: 20000 },
+ ]);
+ expect(mocks.stripe.prices.retrieve).toHaveBeenCalledWith(
+ STRIPE_SAML_SSO_PRICE_ID,
+ { expand: ["currency_options"] },
+ );
+ });
+
+ it("does not use a live price by default outside production", async () => {
+ mocks.environment.NODE_ENV = "development";
+ await expect(getSsoPrices()).rejects.toThrow("not configured");
+ expect(mocks.stripe.prices.retrieve).not.toHaveBeenCalled();
+ mocks.environment.STRIPE_SAML_SSO_PRICE_ID = "price_test_sso";
+ await getSsoPrices();
+ expect(mocks.stripe.prices.retrieve).toHaveBeenCalledWith(
+ "price_test_sso",
+ { expand: ["currency_options"] },
+ );
+ });
+
+ it("manages the exact linked billing customer without rewriting Pro", async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({ stripeSubscriptionId: "sub_sso" }),
+ );
+ state.users.set(userId, {
+ id: userId,
+ stripeCustomerId: "cus_separate_pro",
+ });
+ expect(await createSsoBillingPortal(organizationId)).toBe(
+ "https://billing.stripe.test/sso",
+ );
+ expect(mocks.stripe.billingPortal.sessions.create).toHaveBeenCalledWith({
+ customer: "cus_owner",
+ return_url:
+ "https://cap.test/dashboard/settings/organization/security?organizationId=org_owner",
+ });
+ });
+
+ it("does not expose the previous purchaser's portal after ownership changes", async () => {
+ state.billing.set(
+ organizationId,
+ billingRow({
+ stripeSubscriptionId: "sub_sso",
+ purchasedByUserId: User.UserId.make("user_old_owner"),
+ }),
+ );
+ await expect(createSsoBillingPortal(organizationId)).rejects.toThrow(
+ "current owner",
+ );
+ expect(mocks.stripe.billingPortal.sessions.create).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/__tests__/unit/sso-webhook.test.ts b/apps/web/__tests__/unit/sso-webhook.test.ts
new file mode 100644
index 000000000..502a3c24a
--- /dev/null
+++ b/apps/web/__tests__/unit/sso-webhook.test.ts
@@ -0,0 +1,227 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ constructEvent: vi.fn(),
+ retrieveSubscription: vi.fn(),
+ retrieveCustomer: vi.fn(),
+ dbUpdate: vi.fn(),
+ sendEmail: vi.fn(),
+ attachSsoCheckout: vi.fn(),
+ getSsoBillingForSubscription: vi.fn(),
+ syncSsoSubscription: vi.fn(),
+}));
+
+vi.mock("@cap/database", () => ({ db: () => ({ update: mocks.dbUpdate }) }));
+vi.mock("@cap/database/emails/config", () => ({ sendEmail: mocks.sendEmail }));
+vi.mock("@cap/database/schema", () => ({
+ developerCreditTransactions: {},
+ signedBaas: {},
+ users: {},
+ organizations: {},
+}));
+vi.mock("@cap/env", () => ({
+ buildEnv: {},
+ serverEnv: () => ({ STRIPE_WEBHOOK_SECRET: "whsec_test" }),
+}));
+vi.mock("@cap/utils", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@cap/utils")>();
+ return {
+ ...actual,
+ stripe: () => ({
+ webhooks: { constructEvent: mocks.constructEvent },
+ subscriptions: { retrieve: mocks.retrieveSubscription },
+ customers: { retrieve: mocks.retrieveCustomer },
+ }),
+ };
+});
+vi.mock("@/lib/developer-credits", () => ({ addCreditsToAccount: vi.fn() }));
+vi.mock("@/lib/server-analytics", () => ({ trackServerEvent: vi.fn() }));
+vi.mock("@/lib/sso/billing", () => ({
+ attachSsoCheckout: mocks.attachSsoCheckout,
+ getSsoBillingForSubscription: mocks.getSsoBillingForSubscription,
+ syncSsoSubscription: mocks.syncSsoSubscription,
+}));
+
+import {
+ STRIPE_SAML_SSO_LEGACY_PRICE_ID,
+ STRIPE_SAML_SSO_PRICE_ID,
+ STRIPE_SAML_SSO_PRODUCT_ID,
+} from "@cap/utils";
+import { POST } from "@/app/api/webhooks/stripe/route";
+
+function subscription(priceId = STRIPE_SAML_SSO_PRICE_ID) {
+ return {
+ id: "sub_sso",
+ customer: "cus_owner",
+ status: "active",
+ metadata: {},
+ items: { data: [{ price: { id: priceId }, quantity: 1 }] },
+ };
+}
+
+async function deliver(type: string, object: Record<string, unknown>) {
+ mocks.constructEvent.mockReturnValue({ type, data: { object } });
+ return POST(
+ new Request("https://cap.test/api/webhooks/stripe", {
+ method: "POST",
+ headers: { "Stripe-Signature": "sig_test" },
+ body: "{}",
+ }),
+ );
+}
+
+function expectProUntouched() {
+ expect(mocks.retrieveCustomer).not.toHaveBeenCalled();
+ expect(mocks.dbUpdate).not.toHaveBeenCalled();
+ expect(mocks.sendEmail).not.toHaveBeenCalled();
+}
+
+describe("organization-scoped SAML SSO webhooks", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.attachSsoCheckout.mockResolvedValue(null);
+ mocks.getSsoBillingForSubscription.mockResolvedValue(null);
+ mocks.syncSsoSubscription.mockResolvedValue(null);
+ });
+
+ it.each([
+ "customer.subscription.created",
+ "customer.subscription.updated",
+ "customer.subscription.deleted",
+ ])("routes %s without overwriting Pro", async (eventType) => {
+ for (const priceId of [
+ STRIPE_SAML_SSO_PRICE_ID,
+ STRIPE_SAML_SSO_LEGACY_PRICE_ID,
+ ]) {
+ const response = await deliver(eventType, subscription(priceId));
+ expect(response.status).toBe(200);
+ expect(mocks.syncSsoSubscription).toHaveBeenLastCalledWith("sub_sso");
+ }
+ expectProUntouched();
+ });
+
+ it("isolates an SSO product even when its price is not approved for access", async () => {
+ const response = await deliver("customer.subscription.updated", {
+ ...subscription(),
+ items: {
+ data: [
+ { price: { id: "price_other", product: STRIPE_SAML_SSO_PRODUCT_ID } },
+ ],
+ },
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.syncSsoSubscription).toHaveBeenCalledWith("sub_sso");
+ expectProUntouched();
+ });
+
+ it("isolates metadata-only SSO without granting Pro", async () => {
+ const response = await deliver("customer.subscription.updated", {
+ ...subscription("price_unknown"),
+ metadata: { type: "saml_sso" },
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.syncSsoSubscription).toHaveBeenCalledWith("sub_sso");
+ expectProUntouched();
+ });
+
+ it.each(["customer.subscription.updated", "customer.subscription.deleted"])(
+ "keeps a persisted SSO binding out of Pro handling after price removal during %s",
+ async (eventType) => {
+ mocks.getSsoBillingForSubscription.mockResolvedValue({
+ organizationId: "org_owner",
+ });
+ const response = await deliver(eventType, subscription("price_changed"));
+ expect(response.status).toBe(200);
+ expect(mocks.syncSsoSubscription).toHaveBeenCalledWith("sub_sso");
+ expectProUntouched();
+ },
+ );
+
+ it.each([STRIPE_SAML_SSO_PRICE_ID, STRIPE_SAML_SSO_LEGACY_PRICE_ID])(
+ "recognizes an externally paid checkout by SSO price %s",
+ async (priceId) => {
+ mocks.retrieveSubscription.mockResolvedValue(subscription(priceId));
+ const response = await deliver("checkout.session.completed", {
+ id: "cs_external",
+ subscription: "sub_sso",
+ customer: "cus_owner",
+ payment_status: "paid",
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.attachSsoCheckout).toHaveBeenCalledWith("cs_external");
+ expectProUntouched();
+ },
+ );
+
+ it.each([
+ "checkout.session.completed",
+ "checkout.session.async_payment_succeeded",
+ ])(
+ "reconciles org-bound %s through payment verification",
+ async (eventType) => {
+ const response = await deliver(eventType, {
+ id: "cs_sso",
+ subscription: "sub_sso",
+ metadata: { type: "saml_sso", organizationId: "org_owner" },
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.attachSsoCheckout).toHaveBeenCalledWith("cs_sso");
+ expectProUntouched();
+ },
+ );
+
+ it.each(["invoice.paid", "invoice.payment_failed"])(
+ "synchronizes %s without Pro dunning",
+ async (eventType) => {
+ const response = await deliver(eventType, {
+ id: "in_sso",
+ subscription: "sub_sso",
+ billing_reason: "subscription_cycle",
+ attempt_count: 1,
+ next_payment_attempt: null,
+ lines: { data: [{ price: { id: STRIPE_SAML_SSO_LEGACY_PRICE_ID } }] },
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.syncSsoSubscription).toHaveBeenCalledWith("sub_sso");
+ expectProUntouched();
+ },
+ );
+
+ it("does not send Pro dunning for a persisted SSO binding after price removal", async () => {
+ mocks.getSsoBillingForSubscription.mockResolvedValue({
+ organizationId: "org_owner",
+ });
+ const response = await deliver("invoice.payment_failed", {
+ id: "in_sso",
+ subscription: "sub_sso",
+ billing_reason: "subscription_cycle",
+ attempt_count: 1,
+ lines: { data: [{ price: { id: "price_changed" } }] },
+ });
+ expect(response.status).toBe(200);
+ expect(mocks.syncSsoSubscription).toHaveBeenCalledWith("sub_sso");
+ expectProUntouched();
+ });
+
+ it("preserves retries when SSO reconciliation fails", async () => {
+ mocks.syncSsoSubscription.mockRejectedValue(
+ new Error("Database unavailable"),
+ );
+ const response = await deliver(
+ "customer.subscription.updated",
+ subscription(),
+ );
+ expect(response.status).toBeGreaterThanOrEqual(400);
+ expectProUntouched();
+ });
+
+ it("does not acknowledge a malformed SSO invoice as synchronized", async () => {
+ const response = await deliver("invoice.paid", {
+ id: "in_missing_subscription",
+ subscription_details: { metadata: { type: "saml_sso" } },
+ });
+ expect(response.status).toBeGreaterThanOrEqual(400);
+ expect(mocks.syncSsoSubscription).not.toHaveBeenCalled();
+ expectProUntouched();
+ });
+});
diff --git a/apps/web/__tests__/unit/update-seat-quantity.test.ts b/apps/web/__tests__/unit/update-seat-quantity.test.ts
index 233826a96..542045bc9 100644
--- a/apps/web/__tests__/unit/update-seat-quantity.test.ts
+++ b/apps/web/__tests__/unit/update-seat-quantity.test.ts
@@ -48,9 +48,10 @@ vi.mock("@cap/env", () => ({
buildEnv: { NEXT_PUBLIC_IS_CAP: true },
}));
-vi.mock("@cap/utils", () => ({
- stripe: () => mockStripe,
-}));
+vi.mock("@cap/utils", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@cap/utils")>();
+ return { ...actual, stripe: () => mockStripe };
+});
vi.mock("drizzle-orm", () => ({
eq: vi.fn((field: unknown, value: unknown) => ({ field, value })),
@@ -109,6 +110,7 @@ function mockSeatLookup({
.mockResolvedValueOnce([]);
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_1",
+ customer: "cus_1",
cancel_at_period_end: false,
items: {
data: [{ id: "si_1", quantity: currentQuantity }],
@@ -126,6 +128,51 @@ describe("updateSeatQuantity", () => {
});
});
+ it.each([
+ "price_1UBJpTFJxA1XpeSsQmAOhibr",
+ "price_1UBJQuFJxA1XpeSsnxL2KhP7",
+ "price_1U6C99FJxA1XpeSsUg1rXHo2",
+ ])(
+ "never changes an add-on quantity through a contaminated Pro pointer: %s",
+ async (priceId) => {
+ mockSeatLookup({ currentQuantity: 1 });
+ mockStripe.subscriptions.retrieve.mockResolvedValue({
+ id: "sub_1",
+ customer: "cus_1",
+ items: {
+ data: [{ id: "si_addon", price: { id: priceId }, quantity: 1 }],
+ },
+ });
+ const { updateSeatQuantity } = await import(
+ "@/actions/organization/update-seat-quantity"
+ );
+ await expect(updateSeatQuantity("org-1" as never, 2)).rejects.toThrow(
+ "No matching Cap Pro subscription",
+ );
+ expect(mockStripe.subscriptions.update).not.toHaveBeenCalled();
+ expect(mockDb.set).not.toHaveBeenCalled();
+ },
+ );
+
+ it("refuses to change a subscription belonging to a different customer", async () => {
+ mockSeatLookup({ currentQuantity: 1 });
+ mockStripe.subscriptions.retrieve.mockResolvedValue({
+ id: "sub_1",
+ customer: "cus_other",
+ items: {
+ data: [{ id: "si_pro", price: { id: "price_pro" }, quantity: 1 }],
+ },
+ });
+ const { updateSeatQuantity } = await import(
+ "@/actions/organization/update-seat-quantity"
+ );
+ await expect(updateSeatQuantity("org-1" as never, 2)).rejects.toThrow(
+ "No matching Cap Pro subscription",
+ );
+ expect(mockStripe.subscriptions.update).not.toHaveBeenCalled();
+ expect(mockDb.set).not.toHaveBeenCalled();
+ });
+
it("immediately invoices seat increases and only stores the quota after Stripe applies the update", async () => {
mockSeatLookup({ currentQuantity: 1 });
const { updateSeatQuantity } = await import(
@@ -181,6 +228,7 @@ describe("updateSeatQuantity", () => {
mockSeatLookup({ currentQuantity: 3 });
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_1",
+ customer: "cus_1",
cancel_at_period_end: true,
items: {
data: [{ id: "si_1", quantity: 3 }],
@@ -204,6 +252,7 @@ describe("updateSeatQuantity", () => {
mockSeatLookup({ currentQuantity: 1 });
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_1",
+ customer: "cus_1",
cancel_at_period_end: true,
items: {
data: [{ id: "si_1", quantity: 1 }],
@@ -240,6 +289,7 @@ describe("updateSeatQuantity", () => {
mockSeatLookup({ currentQuantity: 1 });
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_1",
+ customer: "cus_1",
cancel_at_period_end: true,
items: {
data: [{ id: "si_1", quantity: 1 }],
@@ -271,6 +321,7 @@ describe("updateSeatQuantity", () => {
mockSeatLookup({ currentQuantity: 1 });
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_1",
+ customer: "cus_1",
cancel_at_period_end: true,
items: {
data: [{ id: "si_1", quantity: 1 }],
@@ -300,6 +351,7 @@ describe("updateSeatQuantity", () => {
mockSeatLookup({ currentQuantity: 1 });
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_1",
+ customer: "cus_1",
cancel_at_period_end: true,
items: {
data: [{ id: "si_1", quantity: 1 }],
@@ -325,6 +377,7 @@ describe("updateSeatQuantity", () => {
mockSeatLookup({ currentQuantity: 1 });
mockStripe.subscriptions.retrieve.mockResolvedValue({
id: "sub_1",
+ customer: "cus_1",
cancel_at_period_end: true,
items: {
data: [{ id: "si_1", quantity: 1 }],
diff --git a/apps/web/actions/organization/get-subscription-details.ts b/apps/web/actions/organization/get-subscription-details.ts
index f8ae39e24..e58eae387 100644
--- a/apps/web/actions/organization/get-subscription-details.ts
+++ b/apps/web/actions/organization/get-subscription-details.ts
@@ -3,7 +3,7 @@
import { db } from "@cap/database";
import { getCurrentUser } from "@cap/database/auth/session";
import { organizations, users } from "@cap/database/schema";
-import { stripe } from "@cap/utils";
+import { isProSubscription, stripe } from "@cap/utils";
import type { Organisation } from "@cap/web-domain";
import { eq } from "drizzle-orm";
@@ -37,6 +37,7 @@ export async function getSubscriptionDetails(
const [owner] = await db()
.select({
stripeSubscriptionId: users.stripeSubscriptionId,
+ stripeCustomerId: users.stripeCustomerId,
})
.from(users)
.where(eq(users.id, user.id))
@@ -49,6 +50,12 @@ export async function getSubscriptionDetails(
const subscription = await stripe().subscriptions.retrieve(
owner.stripeSubscriptionId,
);
+ const customerId =
+ typeof subscription.customer === "string"
+ ? subscription.customer
+ : subscription.customer.id;
+ if (!isProSubscription(subscription) || customerId !== owner.stripeCustomerId)
+ return null;
// past_due renders as a payment-failed state in the billing card rather
// than falling through to the "Upgrade to Pro" card.
diff --git a/apps/web/actions/organization/signed-baa.ts b/apps/web/actions/organization/signed-baa.ts
index 98a26f8d1..2b0076317 100644
--- a/apps/web/actions/organization/signed-baa.ts
+++ b/apps/web/actions/organization/signed-baa.ts
@@ -7,7 +7,11 @@ import { SignedBaa } from "@cap/database/emails/signed-baa";
import { nanoId } from "@cap/database/helpers";
import { organizations, signedBaas } from "@cap/database/schema";
import { serverEnv } from "@cap/env";
-import { STRIPE_SIGNED_BAA_PRICE_IDS, stripe } from "@cap/utils";
+import {
+ isProSubscription,
+ STRIPE_SIGNED_BAA_PRICE_IDS,
+ stripe,
+} from "@cap/utils";
import type { Organisation } from "@cap/web-domain";
import { and, eq, isNull, lt, ne, or } from "drizzle-orm";
import { revalidatePath } from "next/cache";
@@ -424,7 +428,7 @@ async function completeSignedBaa(
}
if (
!CAP_PRO_STATUSES.has(liveProSubscription.status) ||
- isSignedBaaSubscription(liveProSubscription)
+ !isProSubscription(liveProSubscription)
) {
throw new Error(
"Your organization needs an active Cap Pro subscription before adding the Signed BAA add-on.",
diff --git a/apps/web/actions/organization/update-seat-quantity.ts b/apps/web/actions/organization/update-seat-quantity.ts
index 4abeec566..657fadc72 100644
--- a/apps/web/actions/organization/update-seat-quantity.ts
+++ b/apps/web/actions/organization/update-seat-quantity.ts
@@ -7,7 +7,7 @@ import {
organizations,
users,
} from "@cap/database/schema";
-import { stripe } from "@cap/utils";
+import { isProSubscription, stripe } from "@cap/utils";
import type { Organisation } from "@cap/web-domain";
import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
@@ -46,6 +46,16 @@ async function getOwnerSubscription(
const subscription = await stripe().subscriptions.retrieve(
owner.stripeSubscriptionId,
);
+ const customerId =
+ typeof subscription.customer === "string"
+ ? subscription.customer
+ : subscription.customer.id;
+ if (
+ !isProSubscription(subscription) ||
+ customerId !== owner.stripeCustomerId
+ ) {
+ throw new Error("No matching Cap Pro subscription found");
+ }
const subscriptionItem = subscription.items.data[0];
if (!subscriptionItem) {
diff --git a/apps/web/app/api/desktop/[...route]/root.ts b/apps/web/app/api/desktop/[...route]/root.ts
index 8101878a7..9c14a656c 100644
--- a/apps/web/app/api/desktop/[...route]/root.ts
+++ b/apps/web/app/api/desktop/[...route]/root.ts
@@ -9,7 +9,12 @@ import {
users,
} from "@cap/database/schema";
import { serverEnv } from "@cap/env";
-import { STRIPE_AVAILABLE, stripe, userIsPro } from "@cap/utils";
+import {
+ isProSubscription,
+ STRIPE_AVAILABLE,
+ stripe,
+ userIsPro,
+} from "@cap/utils";
import { OrganizationBrandingPatchBody } from "@cap/web-api-contract";
import { ImageUploads } from "@cap/web-backend";
import { type ImageUpload, Organisation } from "@cap/web-domain";
@@ -484,7 +489,7 @@ app.get("/plan", withAuth, async (c) => {
customer: user.stripeCustomerId,
});
const activeSubscription = subscriptions.data.find(
- (sub) => sub.status === "active",
+ (sub) => sub.status === "active" && isProSubscription(sub),
);
if (activeSubscription) {
isSubscribed = true;
diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.ts
index cc734d538..2e34a900a 100644
--- a/apps/web/app/api/webhooks/stripe/route.ts
+++ b/apps/web/app/api/webhooks/stripe/route.ts
@@ -8,7 +8,7 @@ import {
users,
} from "@cap/database/schema";
import { serverEnv } from "@cap/env";
-import { stripe } from "@cap/utils";
+import { isProSubscription, isSsoSubscription, stripe } from "@cap/utils";
import { Organisation, User } from "@cap/web-domain";
import { and, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
import { NextResponse } from "next/server";
@@ -23,6 +23,11 @@ import {
} from "@/lib/baa/billing";
import { addCreditsToAccount } from "@/lib/developer-credits";
import { trackServerEvent } from "@/lib/server-analytics";
+import {
+ attachSsoCheckout,
+ getSsoBillingForSubscription,
+ syncSsoSubscription,
+} from "@/lib/sso/billing";
const relevantEvents = new Set([
"checkout.session.completed",
@@ -30,6 +35,7 @@ const relevantEvents = new Set([
"customer.subscription.created",
"customer.subscription.updated",
"customer.subscription.deleted",
+ "invoice.paid",
"invoice.payment_failed",
]);
@@ -113,8 +119,7 @@ const ENTITLED_SUBSCRIPTION_STATUSES = new Set([
function hasEntitledProSubscription(subscriptions: Stripe.Subscription[]) {
return subscriptions.some(
(sub) =>
- !isSignedBaaSubscription(sub) &&
- ENTITLED_SUBSCRIPTION_STATUSES.has(sub.status),
+ isProSubscription(sub) && ENTITLED_SUBSCRIPTION_STATUSES.has(sub.status),
);
}
@@ -397,12 +402,60 @@ export const POST = async (req: Request) => {
if (relevantEvents.has(event.type)) {
try {
+ if (
+ event.type === "customer.subscription.created" ||
+ event.type === "customer.subscription.updated" ||
+ event.type === "customer.subscription.deleted"
+ ) {
+ const subscription = event.data.object as Stripe.Subscription;
+ if (
+ isSsoSubscription(subscription) ||
+ (await getSsoBillingForSubscription(subscription.id))
+ ) {
+ await syncSsoSubscription(subscription.id);
+ return NextResponse.json({ received: true });
+ }
+ }
+ if (
+ event.type === "invoice.paid" ||
+ event.type === "invoice.payment_failed"
+ ) {
+ const invoice = event.data.object as Stripe.Invoice;
+ const subscriptionId =
+ typeof invoice.subscription === "string"
+ ? invoice.subscription
+ : invoice.subscription?.id;
+ const ssoInvoice = isSsoSubscription({
+ metadata: invoice.subscription_details?.metadata,
+ items: { data: invoice.lines?.data ?? [] },
+ });
+ if (
+ ssoInvoice ||
+ (event.type === "invoice.payment_failed" &&
+ subscriptionId &&
+ (await getSsoBillingForSubscription(subscriptionId)))
+ ) {
+ if (!subscriptionId) {
+ throw new Error("SAML SSO invoice is missing its subscription.");
+ }
+ await syncSsoSubscription(subscriptionId);
+ return NextResponse.json({ received: true });
+ }
+ if (event.type === "invoice.paid") {
+ if (subscriptionId) await syncSsoSubscription(subscriptionId);
+ return NextResponse.json({ received: true });
+ }
+ }
let checkoutSubscription: Stripe.Subscription | undefined;
if (
event.type === "checkout.session.completed" ||
event.type === "checkout.session.async_payment_succeeded"
) {
const session = event.data.object as Stripe.Checkout.Session;
+ if (session.metadata?.type === "saml_sso") {
+ await attachSsoCheckout(session.id);
+ return NextResponse.json({ received: true });
+ }
const subscriptionId =
typeof session.subscription === "string"
? session.subscription
@@ -410,6 +463,13 @@ export const POST = async (req: Request) => {
if (subscriptionId) {
checkoutSubscription =
await stripe().subscriptions.retrieve(subscriptionId);
+ if (
+ isSsoSubscription(checkoutSubscription) ||
+ (await getSsoBillingForSubscription(subscriptionId))
+ ) {
+ await attachSsoCheckout(session.id);
+ return NextResponse.json({ received: true });
+ }
if (isSignedBaaSubscription(checkoutSubscription)) {
const record = await attachPaidBaaCheckout(
session,
@@ -679,7 +739,7 @@ export const POST = async (req: Request) => {
.filter(
(sub) =>
ENTITLED_SUBSCRIPTION_STATUSES.has(sub.status) &&
- !isSignedBaaSubscription(sub),
+ isProSubscription(sub),
)
.reduce((total, sub) => {
return (
diff --git a/apps/web/lib/baa/billing.ts b/apps/web/lib/baa/billing.ts
index 3f4081136..00ebe5faf 100644
--- a/apps/web/lib/baa/billing.ts
+++ b/apps/web/lib/baa/billing.ts
@@ -1,6 +1,10 @@
import { db } from "@cap/database";
import { organizations, signedBaas, users } from "@cap/database/schema";
-import { STRIPE_SIGNED_BAA_PRICE_IDS, stripe } from "@cap/utils";
+import {
+ isProSubscription,
+ STRIPE_SIGNED_BAA_PRICE_IDS,
+ stripe,
+} from "@cap/utils";
import type { Organisation, User } from "@cap/web-domain";
import { and, eq, isNull, ne, or } from "drizzle-orm";
import type Stripe from "stripe";
@@ -81,7 +85,7 @@ export async function ensureBaaHasPro(
if (
proSubscription &&
proCustomerId === owner.stripeCustomerId &&
- !isSignedBaaSubscription(proSubscription) &&
+ isProSubscription(proSubscription) &&
BAA_ENTITLED_STATUSES.has(proSubscription.status)
) {
return true;
diff --git a/apps/web/lib/sso/billing.ts b/apps/web/lib/sso/billing.ts
new file mode 100644
index 000000000..1364fa6ca
--- /dev/null
+++ b/apps/web/lib/sso/billing.ts
@@ -0,0 +1,788 @@
+import { randomUUID } from "node:crypto";
+import { db } from "@cap/database";
+import { organizationSso, organizations, users } from "@cap/database/schema";
+import { serverEnv } from "@cap/env";
+import {
+ isSsoPrice,
+ isSsoSubscription,
+ STRIPE_SAML_SSO_PRICE_ID,
+ stripe,
+} from "@cap/utils";
+import { Organisation, User } from "@cap/web-domain";
+import { and, eq, isNull } from "drizzle-orm";
+import type Stripe from "stripe";
+import {
+ isSupportedCurrency,
+ SUPPORTED_CURRENCIES,
+ type SupportedCurrency,
+} from "@/utils/currency";
+
+type SsoBilling = typeof organizationSso.$inferSelect;
+type Transaction = Parameters<
+ Parameters<ReturnType<typeof db>["transaction"]>[0]
+>[0];
+type CheckoutInput = {
+ organizationId: Organisation.OrganisationId;
+ purchasedByUserId: User.UserId;
+ stripeCustomerId: string | null;
+ currency: SupportedCurrency;
+};
+
+const TERMINAL_STATUSES = new Set(["canceled", "incomplete_expired"]);
+const CHECKOUT_RETRY_LIMIT_MS = 23 * 60 * 60 * 1000;
+
+function stripeId(value: string | { id: string } | null | undefined) {
+ return typeof value === "string" ? value : (value?.id ?? null);
+}
+
+function checkoutPriceId() {
+ const environment = serverEnv();
+ const priceId =
+ environment.STRIPE_SAML_SSO_PRICE_ID ||
+ (environment.NODE_ENV === "production" ? STRIPE_SAML_SSO_PRICE_ID : null);
+ if (!priceId) {
+ throw new Error("SAML SSO billing is not configured. Contact support.");
+ }
+ return priceId;
+}
+
+function isApprovedPrice(priceId: string | undefined) {
+ return Boolean(
+ priceId &&
+ (isSsoPrice(priceId) || priceId === serverEnv().STRIPE_SAML_SSO_PRICE_ID),
+ );
+}
+
+function ssoItem(subscription: Stripe.Subscription) {
+ const item = subscription.items.data[0];
+ if (
+ !item ||
+ subscription.items.has_more ||
+ subscription.items.data.length !== 1 ||
+ item.quantity !== 1 ||
+ !isApprovedPrice(item.price.id) ||
+ item.price.recurring?.interval !== "month" ||
+ item.price.recurring.interval_count !== 1
+ )
+ return null;
+ return item;
+}
+
+function billingUrl(organizationId: Organisation.OrganisationId) {
+ const url = new URL(
+ "/dashboard/settings/organization/security",
+ serverEnv().WEB_URL,
+ );
+ url.searchParams.set("organizationId", organizationId);
+ return url.toString();
+}
+
+async function getOwner(organizationId: Organisation.OrganisationId) {
+ const [owner] = await db()
+ .select({
+ id: users.id,
+ stripeCustomerId: users.stripeCustomerId,
+ tombstoneAt: organizations.tombstoneAt,
+ })
+ .from(organizations)
+ .innerJoin(users, eq(organizations.ownerId, users.id))
+ .where(eq(organizations.id, organizationId))
+ .limit(1);
+ if (!owner || owner.tombstoneAt) {
+ throw new Error("Organization not found.");
+ }
+ return owner;
+}
+
+async function lockOrganization(
+ tx: Transaction,
+ organizationId: Organisation.OrganisationId,
+) {
+ const [organization] = await tx
+ .select({
+ ownerId: organizations.ownerId,
+ tombstoneAt: organizations.tombstoneAt,
+ })
+ .from(organizations)
+ .where(eq(organizations.id, organizationId))
+ .limit(1)
+ .for("update");
+ if (!organization || organization.tombstoneAt) {
+ throw new Error("Organization not found.");
+ }
+ return organization;
+}
+
+export async function getSsoBilling(
+ organizationId: Organisation.OrganisationId,
+): Promise<SsoBilling | null> {
+ const [record] = await db()
+ .select()
+ .from(organizationSso)
+ .where(eq(organizationSso.organizationId, organizationId))
+ .limit(1);
+ return record ?? null;
+}
+
+export async function getSsoBillingForSubscription(subscriptionId: string) {
+ const [record] = await db()
+ .select()
+ .from(organizationSso)
+ .where(eq(organizationSso.stripeSubscriptionId, subscriptionId))
+ .limit(1);
+ return record ?? null;
+}
+
+async function invoicePaidThrough(
+ invoice: Stripe.Invoice,
+ subscription: Stripe.Subscription,
+ item: Stripe.SubscriptionItem,
+) {
+ if (
+ invoice.status !== "paid" ||
+ stripeId(invoice.subscription) !== subscription.id ||
+ stripeId(invoice.customer) !== stripeId(subscription.customer)
+ )
+ return null;
+ const lines = invoice.lines.has_more
+ ? await stripe()
+ .invoices.listLineItems(invoice.id, { limit: 100 })
+ .autoPagingToArray({ limit: 1000 })
+ : invoice.lines.data;
+ const periodEnds = lines
+ .filter(
+ (line) =>
+ line.type === "subscription" &&
+ !line.proration &&
+ line.amount >= 0 &&
+ line.price?.id === item.price.id &&
+ stripeId(line.subscription) === subscription.id &&
+ stripeId(line.subscription_item) === item.id,
+ )
+ .map((line) => line.period.end)
+ .filter(Number.isFinite);
+ if (periodEnds.length === 0) return null;
+ const paidThrough = Math.min(
+ Math.max(...periodEnds),
+ subscription.current_period_end,
+ );
+ return paidThrough > 0 ? new Date(paidThrough * 1000) : null;
+}
+
+async function confirmedPaidThrough(
+ subscription: Stripe.Subscription,
+ item: Stripe.SubscriptionItem,
+ previousPaidThrough: Date | null,
+) {
+ const latestInvoice =
+ typeof subscription.latest_invoice === "string"
+ ? await stripe().invoices.retrieve(subscription.latest_invoice)
+ : subscription.latest_invoice;
+ if (latestInvoice) {
+ const paidThrough = await invoicePaidThrough(
+ latestInvoice,
+ subscription,
+ item,
+ );
+ if (paidThrough) return paidThrough;
+ }
+ if (subscription.status !== "active" && subscription.status !== "past_due")
+ return previousPaidThrough;
+ const invoices = await stripe().invoices.list({
+ subscription: subscription.id,
+ status: "paid",
+ limit: 10,
+ });
+ for (const invoice of invoices.data) {
+ const paidThrough = await invoicePaidThrough(invoice, subscription, item);
+ if (paidThrough) return paidThrough;
+ }
+ return previousPaidThrough;
+}
+
+function sameBillingSnapshot(left: SsoBilling, right: SsoBilling) {
+ return (
+ left.stripeSubscriptionId === right.stripeSubscriptionId &&
+ left.stripeCustomerId === right.stripeCustomerId &&
+ left.purchasedByUserId === right.purchasedByUserId &&
+ left.status === right.status &&
+ left.paidThrough?.getTime() === right.paidThrough?.getTime() &&
+ left.currentPeriodEnd?.getTime() === right.currentPeriodEnd?.getTime() &&
+ left.cancelAtPeriodEnd === right.cancelAtPeriodEnd &&
+ left.stripePriceId === right.stripePriceId
+ );
+}
+
+export async function syncSsoSubscription(
+ subscriptionId: string,
+): Promise<SsoBilling | null> {
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const observed = await getSsoBillingForSubscription(subscriptionId);
+ const subscription = await stripe().subscriptions.retrieve(subscriptionId, {
+ expand: ["latest_invoice"],
+ });
+ if (!isSsoSubscription(subscription) && !observed) return null;
+ const metadata = subscription.metadata;
+ if (
+ !observed &&
+ (metadata.type !== "saml_sso" ||
+ !metadata.organizationId ||
+ !metadata.userId)
+ )
+ return null;
+ const organizationId =
+ observed?.organizationId ??
+ Organisation.OrganisationId.make(metadata.organizationId ?? "");
+ const purchasedByUserId =
+ observed?.purchasedByUserId ?? User.UserId.make(metadata.userId ?? "");
+ const customerId = stripeId(subscription.customer);
+ if (
+ !customerId ||
+ (observed && observed.stripeCustomerId !== customerId) ||
+ (metadata.organizationId && metadata.organizationId !== organizationId) ||
+ (metadata.userId && metadata.userId !== purchasedByUserId) ||
+ (metadata.type && metadata.type !== "saml_sso")
+ ) {
+ throw new Error(
+ "The SAML SSO subscription does not match its organization.",
+ );
+ }
+ const owner = await getOwner(organizationId);
+ if (
+ !observed &&
+ (owner.id !== purchasedByUserId || owner.stripeCustomerId !== customerId)
+ ) {
+ throw new Error("The SAML SSO payment belongs to a different account.");
+ }
+ const item = ssoItem(subscription);
+ if (!item && !observed) {
+ throw new Error(
+ "The subscription does not contain a supported SAML SSO price.",
+ );
+ }
+ const paidThrough = item
+ ? await confirmedPaidThrough(
+ subscription,
+ item,
+ observed?.paidThrough ?? null,
+ )
+ : null;
+ const result = await db().transaction(async (tx) => {
+ const organization = await lockOrganization(tx, organizationId);
+ const [current] = await tx
+ .select()
+ .from(organizationSso)
+ .where(eq(organizationSso.organizationId, organizationId))
+ .limit(1)
+ .for("update");
+ if (
+ (current?.stripeSubscriptionId === subscription.id &&
+ (!observed || !sameBillingSnapshot(observed, current))) ||
+ (observed &&
+ current?.stripeSubscriptionId !== observed.stripeSubscriptionId)
+ )
+ return { retry: true } as const;
+ if (!observed && organization.ownerId !== purchasedByUserId) {
+ throw new Error("The organization owner changed while confirming SSO.");
+ }
+ if (!observed) {
+ const [billingOwner] = await tx
+ .select({ stripeCustomerId: users.stripeCustomerId })
+ .from(users)
+ .where(eq(users.id, purchasedByUserId))
+ .limit(1)
+ .for("update");
+ if (billingOwner?.stripeCustomerId !== customerId) {
+ throw new Error("The billing account changed while confirming SSO.");
+ }
+ }
+ if (
+ current?.stripeSubscriptionId &&
+ current.stripeSubscriptionId !== subscription.id &&
+ TERMINAL_STATUSES.has(subscription.status)
+ )
+ return { retry: false, record: current } as const;
+ if (
+ current?.stripeSubscriptionId &&
+ current.stripeSubscriptionId !== subscription.id &&
+ (!TERMINAL_STATUSES.has(current.status) ||
+ !current.checkoutAttemptId ||
+ current.checkoutAttemptId !== metadata.checkoutAttemptId)
+ ) {
+ throw new Error(
+ "A different SAML SSO subscription is already linked. Contact support; do not pay again.",
+ );
+ }
+ if (
+ current &&
+ (current.purchasedByUserId !== purchasedByUserId ||
+ (current.stripeCustomerId && current.stripeCustomerId !== customerId))
+ ) {
+ throw new Error(
+ "The SAML SSO purchase does not match its billing account.",
+ );
+ }
+ if (
+ current?.stripeSubscriptionId === subscription.id &&
+ TERMINAL_STATUSES.has(current.status) &&
+ !TERMINAL_STATUSES.has(subscription.status)
+ )
+ return { retry: false, record: current } as const;
+ const existingPaidThrough =
+ current?.stripeSubscriptionId === subscription.id
+ ? current.paidThrough
+ : null;
+ const confirmedThrough =
+ paidThrough &&
+ (!existingPaidThrough || paidThrough > existingPaidThrough)
+ ? paidThrough
+ : existingPaidThrough;
+ const fields = {
+ purchasedByUserId,
+ stripeCustomerId: customerId,
+ stripeSubscriptionId: subscription.id,
+ stripePriceId: subscription.items.data[0]?.price.id ?? null,
+ status: item ? subscription.status : "unpaid",
+ paidThrough: confirmedThrough,
+ currentPeriodEnd: new Date(subscription.current_period_end * 1000),
+ cancelAtPeriodEnd: subscription.cancel_at_period_end,
+ };
+ if (current) {
+ await tx
+ .update(organizationSso)
+ .set(fields)
+ .where(eq(organizationSso.organizationId, organizationId));
+ } else {
+ await tx.insert(organizationSso).values({ organizationId, ...fields });
+ }
+ const [record] = await tx
+ .select()
+ .from(organizationSso)
+ .where(eq(organizationSso.organizationId, organizationId))
+ .limit(1);
+ if (!record) throw new Error("The SAML SSO payment could not be saved.");
+ return { retry: false, record } as const;
+ });
+ if (!result.retry) return result.record;
+ }
+ throw new Error(
+ "SAML SSO billing changed while synchronizing. Please retry.",
+ );
+}
+
+export async function attachSsoCheckout(
+ sessionId: string,
+ expected?: {
+ organizationId: Organisation.OrganisationId;
+ userId: User.UserId;
+ },
+): Promise<SsoBilling | null> {
+ if (!sessionId.startsWith("cs_") || sessionId.length > 255) {
+ throw new Error("Invalid SAML SSO payment confirmation.");
+ }
+ if (
+ expected &&
+ (await getOwner(expected.organizationId)).id !== expected.userId
+ ) {
+ throw new Error(
+ "Only the organization owner can confirm SAML SSO billing.",
+ );
+ }
+ const session = await stripe().checkout.sessions.retrieve(sessionId);
+ if (
+ session.mode !== "subscription" ||
+ session.status !== "complete" ||
+ session.payment_status !== "paid"
+ )
+ return null;
+ const subscriptionId = stripeId(session.subscription);
+ if (!subscriptionId) throw new Error("No SAML SSO subscription was found.");
+ const subscription = await stripe().subscriptions.retrieve(subscriptionId);
+ const binding = await getSsoBillingForSubscription(subscriptionId);
+ const organizationId =
+ binding?.organizationId ?? subscription.metadata.organizationId;
+ const purchaserId =
+ binding?.purchasedByUserId ?? subscription.metadata.userId;
+ if (
+ stripeId(session.customer) !== stripeId(subscription.customer) ||
+ (expected &&
+ (organizationId !== expected.organizationId ||
+ purchaserId !== expected.userId)) ||
+ (session.metadata?.organizationId &&
+ session.metadata.organizationId !== organizationId) ||
+ (session.metadata?.userId && session.metadata.userId !== purchaserId) ||
+ (session.metadata?.type && session.metadata.type !== "saml_sso")
+ ) {
+ throw new Error(
+ "This SAML SSO payment belongs to a different organization or account.",
+ );
+ }
+ if (!ssoItem(subscription) && !binding) return null;
+ const record = await syncSsoSubscription(subscriptionId);
+ 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"],
+ });
+ if (
+ !price.active ||
+ price.recurring?.interval !== "month" ||
+ price.recurring.interval_count !== 1
+ ) {
+ throw new Error("SAML SSO billing is not available. Contact support.");
+ }
+ return SUPPORTED_CURRENCIES.flatMap((currency) => {
+ const unitAmount =
+ price.currency_options?.[currency]?.unit_amount ??
+ (price.currency === currency ? price.unit_amount : null);
+ return unitAmount != null && Number.isInteger(unitAmount) && unitAmount > 0
+ ? [{ currency, unitAmount }]
+ : [];
+ });
+}
+
+async function reserveCheckout(
+ input: CheckoutInput & { stripeCustomerId: string },
+ priceId: string,
+) {
+ return db().transaction(async (tx) => {
+ const organization = await lockOrganization(tx, input.organizationId);
+ if (organization.ownerId !== input.purchasedByUserId) {
+ throw new Error("Only the organization owner can purchase SAML SSO.");
+ }
+ const [current] = await tx
+ .select()
+ .from(organizationSso)
+ .where(eq(organizationSso.organizationId, input.organizationId))
+ .limit(1)
+ .for("update");
+ if (
+ current?.stripeSubscriptionId &&
+ !TERMINAL_STATUSES.has(current.status)
+ ) {
+ throw new Error(
+ "SAML SSO already has a subscription. Manage its existing billing instead.",
+ );
+ }
+ if (
+ current?.stripeSubscriptionId &&
+ (current.stripeCustomerId !== input.stripeCustomerId ||
+ current.purchasedByUserId !== input.purchasedByUserId)
+ ) {
+ throw new Error(
+ "The previous SAML SSO subscription used a different billing account. Contact support before purchasing again.",
+ );
+ }
+ if (current?.checkoutAttemptId) {
+ if (
+ current.purchasedByUserId !== input.purchasedByUserId ||
+ current.stripeCustomerId !== input.stripeCustomerId ||
+ !current.checkoutPriceId ||
+ !isSupportedCurrency(current.checkoutCurrency) ||
+ !current.checkoutStartedAt
+ ) {
+ throw new Error(
+ "An earlier SAML SSO checkout needs reconciliation. Contact support.",
+ );
+ }
+ return current;
+ }
+ const fields = {
+ purchasedByUserId: input.purchasedByUserId,
+ stripeCustomerId: input.stripeCustomerId,
+ checkoutAttemptId: randomUUID(),
+ checkoutSessionId: null,
+ checkoutStartedAt: new Date(),
+ checkoutCurrency: input.currency,
+ checkoutPriceId: priceId,
+ };
+ if (current) {
+ await tx
+ .update(organizationSso)
+ .set(fields)
+ .where(eq(organizationSso.organizationId, input.organizationId));
+ } else {
+ await tx
+ .insert(organizationSso)
+ .values({ organizationId: input.organizationId, ...fields });
+ }
+ const [reserved] = await tx
+ .select()
+ .from(organizationSso)
+ .where(eq(organizationSso.organizationId, input.organizationId))
+ .limit(1);
+ if (!reserved)
+ throw new Error("The SAML SSO checkout could not be reserved.");
+ return reserved;
+ });
+}
+
+async function saveCheckoutSession(reserved: SsoBilling, sessionId: string) {
+ await db().transaction(async (tx) => {
+ const organization = await lockOrganization(tx, reserved.organizationId);
+ const [current] = await tx
+ .select()
+ .from(organizationSso)
+ .where(eq(organizationSso.organizationId, reserved.organizationId))
+ .limit(1)
+ .for("update");
+ if (
+ organization.ownerId !== reserved.purchasedByUserId ||
+ current?.checkoutAttemptId !== reserved.checkoutAttemptId ||
+ (current.checkoutSessionId && current.checkoutSessionId !== sessionId)
+ ) {
+ throw new Error(
+ "SAML SSO billing changed during checkout. Refresh before retrying.",
+ );
+ }
+ await tx
+ .update(organizationSso)
+ .set({ checkoutSessionId: sessionId })
+ .where(eq(organizationSso.organizationId, reserved.organizationId));
+ });
+}
+
+async function clearFinishedCheckout(reserved: SsoBilling, sessionId: string) {
+ if (!reserved.checkoutAttemptId) return false;
+ const attemptId = reserved.checkoutAttemptId;
+ return db().transaction(async (tx) => {
+ const organization = await lockOrganization(tx, reserved.organizationId);
+ if (organization.ownerId !== reserved.purchasedByUserId) {
+ throw new Error("The organization owner changed during checkout.");
+ }
+ const [current] = await tx
+ .select()
+ .from(organizationSso)
+ .where(eq(organizationSso.organizationId, reserved.organizationId))
+ .limit(1)
+ .for("update");
+ if (
+ current?.checkoutAttemptId !== attemptId ||
+ current.checkoutSessionId !== sessionId ||
+ (current.stripeSubscriptionId && !TERMINAL_STATUSES.has(current.status))
+ )
+ return false;
+ await tx
+ .update(organizationSso)
+ .set({
+ checkoutAttemptId: null,
+ checkoutSessionId: null,
+ checkoutStartedAt: null,
+ checkoutCurrency: null,
+ checkoutPriceId: null,
+ })
+ .where(
+ and(
+ eq(organizationSso.organizationId, reserved.organizationId),
+ eq(organizationSso.checkoutAttemptId, attemptId),
+ ),
+ );
+ return true;
+ });
+}
+
+export async function createSsoCheckout(
+ request: CheckoutInput,
+): Promise<string> {
+ if (!isSupportedCurrency(request.currency))
+ throw new Error("Unsupported billing currency.");
+ const owner = await getOwner(request.organizationId);
+ if (
+ owner.id !== request.purchasedByUserId ||
+ (request.stripeCustomerId &&
+ owner.stripeCustomerId !== request.stripeCustomerId)
+ ) {
+ throw new Error(
+ "Only the organization owner can purchase SAML SSO on this billing account.",
+ );
+ }
+ let customerId = owner.stripeCustomerId;
+ if (!customerId) {
+ const customer = await stripe().customers.create(
+ { metadata: { userId: owner.id } },
+ { idempotencyKey: `cap-sso-customer-${owner.id}` },
+ );
+ await db()
+ .update(users)
+ .set({ stripeCustomerId: customer.id })
+ .where(and(eq(users.id, owner.id), isNull(users.stripeCustomerId)));
+ const refreshedOwner = await getOwner(request.organizationId);
+ if (refreshedOwner.id !== owner.id || !refreshedOwner.stripeCustomerId) {
+ throw new Error("The billing account changed. Refresh before retrying.");
+ }
+ customerId = refreshedOwner.stripeCustomerId;
+ }
+ const input = { ...request, stripeCustomerId: customerId };
+ const existing = await getSsoBilling(input.organizationId);
+ if (existing?.stripeSubscriptionId) {
+ const current = await syncSsoSubscription(existing.stripeSubscriptionId);
+ if (!current || !TERMINAL_STATUSES.has(current.status)) {
+ throw new Error(
+ "SAML SSO already has a subscription. Manage its existing billing instead.",
+ );
+ }
+ }
+ const subscriptions = await stripe()
+ .subscriptions.list({
+ customer: input.stripeCustomerId,
+ status: "all",
+ limit: 100,
+ })
+ .autoPagingToArray({ limit: 1000 });
+ for (const subscription of subscriptions) {
+ if (
+ !isSsoSubscription(subscription) ||
+ TERMINAL_STATUSES.has(subscription.status)
+ )
+ continue;
+ if (subscription.metadata.organizationId === input.organizationId) {
+ await syncSsoSubscription(subscription.id);
+ throw new Error(
+ "SAML SSO is already purchased for this organization. Refresh its billing settings.",
+ );
+ }
+ if (!subscription.metadata.organizationId) {
+ throw new Error(
+ "An existing SAML SSO payment needs to be linked. Contact support; do not pay again.",
+ );
+ }
+ }
+ const prices = await getSsoPrices();
+ if (!prices.some((price) => price.currency === input.currency)) {
+ throw new Error("SAML SSO is unavailable in the selected currency.");
+ }
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const reserved = await reserveCheckout(input, checkoutPriceId());
+ let session: Stripe.Checkout.Session;
+ if (reserved.checkoutSessionId) {
+ session = await stripe().checkout.sessions.retrieve(
+ reserved.checkoutSessionId,
+ );
+ } else {
+ if (
+ !reserved.checkoutStartedAt ||
+ Date.now() - reserved.checkoutStartedAt.getTime() >=
+ CHECKOUT_RETRY_LIMIT_MS
+ ) {
+ throw new Error(
+ "An earlier SAML SSO payment could not be confirmed. Contact support; do not pay again.",
+ );
+ }
+ if (
+ !reserved.checkoutAttemptId ||
+ !reserved.checkoutPriceId ||
+ !reserved.checkoutCurrency
+ ) {
+ throw new Error(
+ "The SAML SSO checkout is incomplete. Contact support.",
+ );
+ }
+ const metadata = {
+ type: "saml_sso",
+ organizationId: reserved.organizationId,
+ userId: reserved.purchasedByUserId,
+ checkoutAttemptId: reserved.checkoutAttemptId,
+ };
+ const returnUrl = billingUrl(reserved.organizationId);
+ session = await stripe().checkout.sessions.create(
+ {
+ mode: "subscription",
+ customer: input.stripeCustomerId,
+ currency: reserved.checkoutCurrency,
+ line_items: [{ price: reserved.checkoutPriceId, quantity: 1 }],
+ client_reference_id: reserved.organizationId,
+ success_url: `${returnUrl}&sso_checkout={CHECKOUT_SESSION_ID}`,
+ cancel_url: returnUrl,
+ metadata,
+ subscription_data: { metadata },
+ },
+ { idempotencyKey: `saml-sso-checkout-${reserved.checkoutAttemptId}` },
+ );
+ await saveCheckoutSession(reserved, session.id);
+ }
+ if (
+ stripeId(session.customer) !== reserved.stripeCustomerId ||
+ session.currency !== reserved.checkoutCurrency ||
+ session.metadata?.organizationId !== input.organizationId ||
+ session.metadata.userId !== input.purchasedByUserId ||
+ session.metadata.checkoutAttemptId !== reserved.checkoutAttemptId
+ ) {
+ throw new Error(
+ "The SAML SSO checkout does not match this organization.",
+ );
+ }
+ if (
+ session.status === "open" &&
+ reserved.checkoutCurrency !== input.currency
+ ) {
+ const expired = await stripe().checkout.sessions.expire(
+ session.id,
+ {},
+ { idempotencyKey: `saml-sso-expire-${reserved.checkoutAttemptId}` },
+ );
+ if (expired.id !== session.id || expired.status !== "expired") {
+ throw new Error(
+ "The previous currency checkout could not be closed. Refresh before retrying.",
+ );
+ }
+ session = expired;
+ }
+ if (session.status === "open" && session.url) return session.url;
+ if (session.status === "complete") {
+ const record = await attachSsoCheckout(session.id, {
+ organizationId: input.organizationId,
+ userId: input.purchasedByUserId,
+ });
+ if (
+ record &&
+ TERMINAL_STATUSES.has(record.status) &&
+ (await clearFinishedCheckout(reserved, session.id))
+ )
+ continue;
+ return `${billingUrl(input.organizationId)}&sso_checkout=${encodeURIComponent(session.id)}`;
+ }
+ if (session.status !== "expired") {
+ throw new Error(
+ "The SAML SSO checkout is awaiting confirmation. Please retry shortly.",
+ );
+ }
+ await clearFinishedCheckout(reserved, session.id);
+ }
+ throw new Error("The SAML SSO checkout expired. Refresh before retrying.");
+}
+
+export async function createSsoBillingPortal(
+ organizationId: Organisation.OrganisationId,
+): Promise<string> {
+ const owner = await getOwner(organizationId);
+ const record = await getSsoBilling(organizationId);
+ if (
+ !record?.stripeCustomerId ||
+ !record.stripeSubscriptionId ||
+ record.purchasedByUserId !== owner.id
+ ) {
+ throw new Error(
+ "SAML SSO billing needs to be linked to the current owner. Contact support.",
+ );
+ }
+ const subscription = await stripe().subscriptions.retrieve(
+ record.stripeSubscriptionId,
+ );
+ if (
+ !isSsoSubscription(subscription) ||
+ stripeId(subscription.customer) !== record.stripeCustomerId
+ ) {
+ throw new Error(
+ "The SAML SSO subscription does not match its billing account.",
+ );
+ }
+ const session = await stripe().billingPortal.sessions.create({
+ customer: record.stripeCustomerId,
+ return_url: billingUrl(organizationId),
+ });
+ return session.url;
+}