Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: add self-service SAML SSO setup and billing settings

Richie McIlroya01d1246f41e
diff --git a/apps/web/__tests__/unit/sso-settings.test.ts b/apps/web/__tests__/unit/sso-settings.test.ts
new file mode 100644
index 000000000..91dd77672
--- /dev/null
+++ b/apps/web/__tests__/unit/sso-settings.test.ts
@@ -0,0 +1,917 @@
+import { verifySsoLoginIntent } from "@cap/database/auth/sso-state";
+import { organizations } from "@cap/database/schema";
+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 { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { getOrganizationSSOData } from "@/actions/organization/get-organization-sso-data";
+import {
+ confirmOrganizationSsoCheckout,
+ getOrganizationSsoSettings,
+ manageOrganizationSsoBilling,
+ openOrganizationSsoPortal,
+ startOrganizationSsoCheckout,
+} from "@/actions/organization/sso";
+import OrganizationSecurityPage from "@/app/(org)/dashboard/settings/organization/security/page";
+import {
+ ensureWorkosOrganization,
+ getSsoConfiguration,
+} from "@/lib/sso/workos";
+
+const mocks = vi.hoisted(() => ({
+ db: vi.fn(),
+ getCurrentUser: vi.fn(),
+ getWorkOS: vi.fn(),
+ getRegisteredSsoOrganization: vi.fn(),
+ getOrganization: vi.fn(),
+ getOrganizationByExternalId: vi.fn(),
+ createOrganization: vi.fn(),
+ listOrganizations: vi.fn(),
+ getConnection: vi.fn(),
+ listConnections: vi.fn(),
+ generateLink: vi.fn(),
+ getSsoBilling: vi.fn(),
+ syncSsoSubscription: vi.fn(),
+ getSsoPrices: vi.fn(),
+ createSsoCheckout: vi.fn(),
+ attachSsoCheckout: vi.fn(),
+ createSsoBillingPortal: vi.fn(),
+ setCookie: vi.fn(),
+ revalidatePath: vi.fn(),
+ isRateLimited: vi.fn(),
+ env: {
+ WEB_URL: "https://cap.test",
+ NEXTAUTH_SECRET: "sso-settings-test-secret",
+ WORKOS_API_KEY: "sk_test_fixture",
+ WORKOS_CLIENT_ID: "client_test_fixture",
+ },
+}));
+
+vi.mock("@cap/database", () => ({ db: mocks.db }));
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: mocks.getCurrentUser,
+}));
+vi.mock("@cap/database/auth/sso", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@cap/database/auth/sso")>()),
+ getWorkOS: mocks.getWorkOS,
+ getRegisteredSsoOrganization: mocks.getRegisteredSsoOrganization,
+}));
+vi.mock("@cap/env", () => ({
+ buildEnv: {},
+ serverEnv: () => mocks.env,
+}));
+vi.mock("@cap/ui", () => ({
+ Card: "section",
+ CardDescription: "p",
+ CardHeader: "header",
+ CardTitle: "h2",
+}));
+vi.mock(
+ "@/app/(org)/dashboard/settings/organization/components/ComplianceCard",
+ () => ({
+ ComplianceCard: () =>
+ createElement("section", { "aria-label": "Compliance settings" }),
+ }),
+);
+vi.mock(
+ "@/app/(org)/dashboard/settings/organization/components/SsoCard",
+ () => ({
+ SsoCard: ({
+ initialSettings,
+ checkoutSessionId,
+ }: {
+ initialSettings: { organizationId: string };
+ checkoutSessionId?: string;
+ }) =>
+ createElement("section", {
+ "aria-label": "SSO settings",
+ "data-organization-id": initialSettings.organizationId,
+ "data-checkout-session-id": checkoutSessionId,
+ }),
+ }),
+);
+vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
+vi.mock("next/headers", () => ({
+ cookies: async () => ({ set: mocks.setCookie }),
+}));
+vi.mock("@/lib/rate-limit", () => ({ isRateLimited: mocks.isRateLimited }));
+vi.mock("@/lib/sso/billing", () => ({
+ getSsoBilling: mocks.getSsoBilling,
+ syncSsoSubscription: mocks.syncSsoSubscription,
+ getSsoPrices: mocks.getSsoPrices,
+ createSsoCheckout: mocks.createSsoCheckout,
+ attachSsoCheckout: mocks.attachSsoCheckout,
+ createSsoBillingPortal: mocks.createSsoBillingPortal,
+}));
+
+const ORGANIZATION_ID = Organisation.OrganisationId.make("a".repeat(15));
+const OTHER_ORGANIZATION_ID = Organisation.OrganisationId.make("b".repeat(15));
+const OWNER_ID = User.UserId.make("owner");
+const WORKOS_ORGANIZATION_ID = "org_company";
+const CONNECTION_ID = "conn_company";
+const SETTINGS_PATH = "/dashboard/settings/organization/security";
+const dialect = new MySqlDialect();
+
+type Row = Record<string, unknown>;
+type CapOrganization = typeof organizations.$inferSelect;
+
+function matchesRow(condition: SQL | undefined, row: Row) {
+ if (!condition) return true;
+ const query = dialect.sqlToQuery(condition);
+ let parameterIndex = 0;
+ return query.sql
+ .replaceAll("(", "")
+ .replaceAll(")", "")
+ .split(" and ")
+ .map((clause) => {
+ const match = /^`[^`]+`\.`([^`]+)`( = \?| is null| in [?, ]+)$/.exec(
+ clause,
+ );
+ if (!match?.[1]) throw new Error(`Unsupported predicate: ${clause}`);
+ if (match[2] === " is null") return row[match[1]] == null;
+ if (match[2] === " = ?") {
+ return row[match[1]] === query.params[parameterIndex++];
+ }
+ const count = clause.match(/\?/g)?.length ?? 0;
+ const values = query.params.slice(parameterIndex, parameterIndex + count);
+ parameterIndex += count;
+ return values.includes(row[match[1]]);
+ })
+ .every(Boolean);
+}
+
+function makeFixture({
+ role = "owner",
+ paid = true,
+ linked = true,
+ verified = true,
+}: {
+ role?: "owner" | "admin" | "member" | "stranger" | "forged-owner";
+ paid?: boolean;
+ linked?: boolean;
+ verified?: boolean;
+} = {}) {
+ const actorId = role === "owner" ? OWNER_ID : User.UserId.make(role);
+ const user = {
+ id: actorId,
+ email: "[email protected]",
+ stripeCustomerId: "cus_owner",
+ activeOrganizationId: ORGANIZATION_ID,
+ };
+ const organization: CapOrganization = {
+ id: ORGANIZATION_ID,
+ name: "Company",
+ ownerId: OWNER_ID,
+ metadata: null,
+ tombstoneAt: null,
+ allowedEmailDomain: null,
+ customDomain: null,
+ domainVerified: null,
+ settings: null,
+ iconUrl: null,
+ shareableLinkIconUrl: null,
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ workosOrganizationId: linked ? WORKOS_ORGANIZATION_ID : null,
+ workosConnectionId: null,
+ };
+ const localOrganizations = [organization];
+ const remote = {
+ id: WORKOS_ORGANIZATION_ID,
+ name: "Company",
+ externalId: ORGANIZATION_ID as string,
+ domains: [
+ { domain: "example.com", state: verified ? "verified" : "pending" },
+ ],
+ };
+ const remoteOrganizations = [remote];
+ const connection = {
+ id: CONNECTION_ID,
+ organizationId: WORKOS_ORGANIZATION_ID,
+ name: "Company SAML",
+ state: "active",
+ connectionType: "SAML",
+ };
+ const connections = [connection];
+ const billing = paid
+ ? {
+ stripeSubscriptionId: "sub_sso",
+ status: "active",
+ paidThrough: new Date(Date.now() + 86_400_000),
+ currentPeriodEnd: new Date(Date.now() + 86_400_000),
+ cancelAtPeriodEnd: false,
+ }
+ : null;
+ const hooks: { beforeUpdate?: () => void } = {};
+ const database = {
+ select: vi.fn((columns?: Record<string, AnyMySqlColumn>) => {
+ let joined = false;
+ let condition: SQL | undefined;
+ const selection = {
+ from: (table: unknown) => {
+ if (table !== organizations) throw new Error("Unexpected table");
+ return selection;
+ },
+ leftJoin: () => {
+ joined = true;
+ return selection;
+ },
+ where: (predicate: SQL | undefined) => {
+ condition = predicate;
+ return selection;
+ },
+ limit: async (count: number) => {
+ if (joined) {
+ if (!condition) throw new Error("Missing authorization predicate");
+ const [requestedOrganizationId, requestedUserId] =
+ dialect.sqlToQuery(condition).params;
+ return localOrganizations
+ .filter(
+ (row) =>
+ row.id === requestedOrganizationId &&
+ !row.tombstoneAt &&
+ requestedUserId === actorId &&
+ (row.ownerId === actorId || role !== "stranger"),
+ )
+ .slice(0, count)
+ .map((row) => ({
+ id: row.id,
+ ownerId: row.ownerId,
+ memberId: role === "owner" ? null : "membership",
+ memberRole: role === "forged-owner" ? "owner" : role,
+ }));
+ }
+ return localOrganizations
+ .filter((row) => matchesRow(condition, row))
+ .slice(0, count)
+ .map((row) =>
+ columns
+ ? Object.fromEntries(
+ Object.entries(columns).map(([key, column]) => [
+ key,
+ (row as Row)[column.name],
+ ]),
+ )
+ : { ...row },
+ );
+ },
+ };
+ return selection;
+ }),
+ update: vi.fn(() => ({
+ set: (patch: Row) => ({
+ where: async (condition: SQL | undefined) => {
+ hooks.beforeUpdate?.();
+ for (const row of localOrganizations) {
+ if (matchesRow(condition, row)) Object.assign(row, patch);
+ }
+ },
+ }),
+ })),
+ };
+ mocks.db.mockReturnValue(database);
+ mocks.getCurrentUser.mockResolvedValue(user);
+ mocks.getWorkOS.mockReturnValue({
+ organizations: {
+ getOrganization: mocks.getOrganization,
+ getOrganizationByExternalId: mocks.getOrganizationByExternalId,
+ createOrganization: mocks.createOrganization,
+ listOrganizations: mocks.listOrganizations,
+ },
+ sso: {
+ getConnection: mocks.getConnection,
+ listConnections: mocks.listConnections,
+ },
+ portal: { generateLink: mocks.generateLink },
+ });
+ mocks.getRegisteredSsoOrganization.mockResolvedValue(organization);
+ mocks.getOrganization.mockResolvedValue(remote);
+ mocks.getOrganizationByExternalId.mockResolvedValue(remote);
+ mocks.createOrganization.mockResolvedValue(remote);
+ mocks.listOrganizations.mockResolvedValue({
+ data: remoteOrganizations,
+ listMetadata: { after: null },
+ });
+ mocks.getConnection.mockResolvedValue(connection);
+ mocks.listConnections.mockResolvedValue({
+ data: connections,
+ listMetadata: { after: null },
+ });
+ mocks.generateLink.mockResolvedValue({
+ link: "https://admin.workos.test/setup",
+ });
+ mocks.getSsoBilling.mockResolvedValue(billing);
+ mocks.syncSsoSubscription.mockResolvedValue(billing);
+ mocks.getSsoPrices.mockResolvedValue([
+ { currency: "usd", unitAmount: 20_000 },
+ { currency: "gbp", unitAmount: 16_000 },
+ { currency: "eur", unitAmount: 19_000 },
+ ]);
+ mocks.createSsoCheckout.mockResolvedValue("https://checkout.stripe.test/sso");
+ mocks.attachSsoCheckout.mockResolvedValue(billing);
+ mocks.createSsoBillingPortal.mockResolvedValue(
+ "https://billing.stripe.test/sso",
+ );
+ mocks.isRateLimited.mockResolvedValue(false);
+ return {
+ user,
+ organization,
+ localOrganizations,
+ remote,
+ remoteOrganizations,
+ connection,
+ connections,
+ billing,
+ database,
+ hooks,
+ };
+}
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.env.WORKOS_API_KEY = "sk_test_fixture";
+ mocks.env.WORKOS_CLIENT_ID = "client_test_fixture";
+});
+
+describe("organization SSO settings authorization", () => {
+ it.each(["owner", "admin"] as const)(
+ "lets a %s read setup status with owner-only billing controls",
+ async (role) => {
+ makeFixture({ role });
+ const settings = await getOrganizationSsoSettings(ORGANIZATION_ID);
+ expect(settings).toMatchObject({
+ organizationId: ORGANIZATION_ID,
+ canManageBilling: role === "owner",
+ entitled: true,
+ suggestedDomain: "example.com",
+ signInUrl: `https://cap.test/login?organizationId=${ORGANIZATION_ID}`,
+ });
+ expect(mocks.syncSsoSubscription).toHaveBeenCalledWith("sub_sso");
+ },
+ );
+
+ it.each(["member", "stranger", "forged-owner"] as const)(
+ "denies %s access before opening setup or billing",
+ async (role) => {
+ makeFixture({ role });
+ await expect(
+ getOrganizationSsoSettings(ORGANIZATION_ID),
+ ).rejects.toThrow();
+ await expect(
+ openOrganizationSsoPortal(ORGANIZATION_ID),
+ ).rejects.toThrow();
+ await expect(
+ startOrganizationSsoCheckout(ORGANIZATION_ID, "usd"),
+ ).rejects.toThrow();
+ expect(mocks.getSsoBilling).not.toHaveBeenCalled();
+ expect(mocks.generateLink).not.toHaveBeenCalled();
+ expect(mocks.createSsoCheckout).not.toHaveBeenCalled();
+ },
+ );
+
+ it("rejects signed-out requests and another organization's checkout", async () => {
+ makeFixture();
+ await expect(
+ startOrganizationSsoCheckout(OTHER_ORGANIZATION_ID, "usd"),
+ ).rejects.toThrow("Forbidden");
+ mocks.getCurrentUser.mockResolvedValue(null);
+ await expect(getOrganizationSsoSettings(ORGANIZATION_ID)).rejects.toThrow(
+ "Unauthorized",
+ );
+ await expect(openOrganizationSsoPortal(ORGANIZATION_ID)).rejects.toThrow(
+ "Unauthorized",
+ );
+ expect(mocks.generateLink).not.toHaveBeenCalled();
+ expect(mocks.createSsoCheckout).not.toHaveBeenCalled();
+ });
+
+ it("lets a paid admin configure SSO without creating a charge", async () => {
+ makeFixture({ role: "admin" });
+ await expect(openOrganizationSsoPortal(ORGANIZATION_ID)).resolves.toEqual({
+ url: "https://admin.workos.test/setup",
+ });
+ expect(mocks.generateLink).toHaveBeenCalledWith(
+ expect.objectContaining({
+ organization: WORKOS_ORGANIZATION_ID,
+ intent: "sso",
+ returnUrl: `https://cap.test${SETTINGS_PATH}?organizationId=${ORGANIZATION_ID}`,
+ }),
+ );
+ expect(mocks.createSsoCheckout).not.toHaveBeenCalled();
+ });
+
+ it("keeps checkout, confirmation and billing management owner-only", async () => {
+ makeFixture({ role: "admin" });
+ await expect(
+ startOrganizationSsoCheckout(ORGANIZATION_ID, "usd"),
+ ).rejects.toThrow("Only the owner");
+ await expect(
+ confirmOrganizationSsoCheckout(ORGANIZATION_ID, "cs_paid"),
+ ).rejects.toThrow("Only the owner");
+ await expect(manageOrganizationSsoBilling(ORGANIZATION_ID)).rejects.toThrow(
+ "Only the owner",
+ );
+ expect(mocks.createSsoCheckout).not.toHaveBeenCalled();
+ expect(mocks.attachSsoCheckout).not.toHaveBeenCalled();
+ expect(mocks.createSsoBillingPortal).not.toHaveBeenCalled();
+ });
+
+ it("does not create WorkOS resources or portal links for unpaid organizations", async () => {
+ makeFixture({ paid: false, linked: false });
+ const settings = await getOrganizationSsoSettings(ORGANIZATION_ID);
+ expect(settings.entitled).toBe(false);
+ expect(settings.signInUrl).toBeNull();
+ await expect(
+ openOrganizationSsoPortal(ORGANIZATION_ID, "example.com"),
+ ).rejects.toThrow("active SAML SSO add-on");
+ expect(mocks.createOrganization).not.toHaveBeenCalled();
+ expect(mocks.generateLink).not.toHaveBeenCalled();
+ });
+
+ it("rechecks current billing before opening a previously paid setup", async () => {
+ const fixture = makeFixture();
+ mocks.syncSsoSubscription.mockResolvedValue({
+ ...fixture.billing,
+ status: "canceled",
+ });
+ await expect(openOrganizationSsoPortal(ORGANIZATION_ID)).rejects.toThrow(
+ "active SAML SSO add-on",
+ );
+ expect(mocks.generateLink).not.toHaveBeenCalled();
+ });
+
+ it.each(["usd", "gbp", "eur"])(
+ "binds a %s checkout to the authenticated owner and requested organization",
+ async (currency) => {
+ const fixture = makeFixture({ paid: false });
+ await expect(
+ startOrganizationSsoCheckout(ORGANIZATION_ID, currency),
+ ).resolves.toEqual({ url: "https://checkout.stripe.test/sso" });
+ expect(mocks.createSsoCheckout).toHaveBeenCalledWith({
+ organizationId: ORGANIZATION_ID,
+ purchasedByUserId: fixture.user.id,
+ stripeCustomerId: fixture.user.stripeCustomerId,
+ currency,
+ });
+ },
+ );
+
+ it("rejects an unsupported currency before starting checkout", async () => {
+ makeFixture();
+ await expect(
+ startOrganizationSsoCheckout(ORGANIZATION_ID, "jpy"),
+ ).rejects.toThrow("Unsupported billing currency");
+ expect(mocks.createSsoCheckout).not.toHaveBeenCalled();
+ });
+
+ it.each(["complete", "sso_setup=complete", "cs_", `cs_${"a".repeat(253)}`])(
+ "does not treat %s as a verified payment return",
+ async (sessionId) => {
+ makeFixture({ paid: false });
+ await expect(
+ confirmOrganizationSsoCheckout(ORGANIZATION_ID, sessionId),
+ ).rejects.toThrow("Invalid checkout session");
+ expect(mocks.attachSsoCheckout).not.toHaveBeenCalled();
+ },
+ );
+
+ it("confirms checkout against the expected organization and owner", async () => {
+ makeFixture();
+ const settings = await confirmOrganizationSsoCheckout(
+ ORGANIZATION_ID,
+ "cs_verified",
+ );
+ expect(mocks.attachSsoCheckout).toHaveBeenCalledWith("cs_verified", {
+ organizationId: ORGANIZATION_ID,
+ userId: OWNER_ID,
+ });
+ expect(settings.entitled).toBe(true);
+ expect(mocks.revalidatePath).toHaveBeenCalledWith(SETTINGS_PATH);
+ });
+
+ it("does not unlock setup when a checkout has no paid entitlement", async () => {
+ makeFixture({ paid: false });
+ mocks.attachSsoCheckout.mockResolvedValue({
+ status: "active",
+ paidThrough: null,
+ });
+ await expect(
+ confirmOrganizationSsoCheckout(ORGANIZATION_ID, "cs_pending"),
+ ).rejects.toThrow("payment is still processing");
+ expect(mocks.revalidatePath).not.toHaveBeenCalled();
+ });
+
+ it("preserves checkout ownership errors from Stripe reconciliation", async () => {
+ makeFixture();
+ mocks.attachSsoCheckout.mockRejectedValue(
+ new Error("Checkout belongs to another organization"),
+ );
+ await expect(
+ confirmOrganizationSsoCheckout(ORGANIZATION_ID, "cs_other"),
+ ).rejects.toThrow("another organization");
+ expect(mocks.revalidatePath).not.toHaveBeenCalled();
+ });
+
+ it("does not advertise sign-in until the domain is verified", async () => {
+ makeFixture({ verified: false });
+ const settings = await getOrganizationSsoSettings(ORGANIZATION_ID);
+ expect(settings.entitled).toBe(true);
+ expect(settings.domains).toEqual([
+ { domain: "example.com", state: "pending" },
+ ]);
+ expect(settings.signInUrl).toBeNull();
+ });
+
+ it("opens domain verification before SSO setup and rechecks the live domain state", async () => {
+ const fixture = makeFixture({ verified: false });
+ await openOrganizationSsoPortal(ORGANIZATION_ID);
+ expect(mocks.generateLink).toHaveBeenLastCalledWith({
+ organization: WORKOS_ORGANIZATION_ID,
+ intent: "domain_verification",
+ returnUrl: `https://cap.test${SETTINGS_PATH}?organizationId=${ORGANIZATION_ID}`,
+ successUrl: `https://cap.test${SETTINGS_PATH}?organizationId=${ORGANIZATION_ID}&sso_setup=complete`,
+ });
+ fixture.remote.domains = [{ domain: "example.com", state: "verified" }];
+ await openOrganizationSsoPortal(ORGANIZATION_ID);
+ expect(mocks.generateLink).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ organization: WORKOS_ORGANIZATION_ID,
+ intent: "sso",
+ }),
+ );
+ });
+
+ it("lets a paid admin verify another domain without leaving the organization scope", async () => {
+ const fixture = makeFixture({ role: "admin" });
+ fixture.remote.domains.push({ domain: "example.org", state: "pending" });
+ await openOrganizationSsoPortal(
+ ORGANIZATION_ID,
+ undefined,
+ "domain_verification",
+ );
+ expect(mocks.generateLink).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ organization: WORKOS_ORGANIZATION_ID,
+ intent: "domain_verification",
+ returnUrl: `https://cap.test${SETTINGS_PATH}?organizationId=${ORGANIZATION_ID}`,
+ }),
+ );
+ });
+});
+
+describe("organization security page SSO failure isolation", () => {
+ it.each([
+ ["WorkOS", "getOrganization", 404],
+ ["WorkOS", "getOrganization", 503],
+ ["Stripe", "syncSsoSubscription", 503],
+ ] as const)(
+ "preserves compliance settings when %s %s fails with %s",
+ async (provider, method, status) => {
+ makeFixture();
+ const error = Object.assign(new Error(`${provider} private detail`), {
+ status,
+ });
+ mocks[method].mockRejectedValueOnce(error);
+ const markup = renderToStaticMarkup(
+ await OrganizationSecurityPage({ searchParams: Promise.resolve({}) }),
+ );
+ expect(markup).toContain("Unable to load SAML SSO settings.");
+ expect(markup).toContain("Reload this page to try again.");
+ expect(markup).toContain('href="mailto:[email protected]"');
+ expect(markup).toContain('aria-label="Compliance settings"');
+ expect(markup).not.toContain('aria-label="SSO settings"');
+ expect(markup).not.toContain(error.message);
+ },
+ );
+
+ it("does not swallow an authentication redirect during settings loading", async () => {
+ const fixture = makeFixture();
+ mocks.getCurrentUser
+ .mockResolvedValueOnce(fixture.user)
+ .mockImplementationOnce(() => redirect("/auth/signin"));
+ await expect(
+ OrganizationSecurityPage({ searchParams: Promise.resolve({}) }),
+ ).rejects.toMatchObject({
+ digest: expect.stringContaining("/auth/signin"),
+ });
+ expect(mocks.getSsoBilling).not.toHaveBeenCalled();
+ });
+
+ it("passes successful settings and checkout confirmation to the normal SSO card", async () => {
+ makeFixture();
+ const markup = renderToStaticMarkup(
+ await OrganizationSecurityPage({
+ searchParams: Promise.resolve({
+ organizationId: ORGANIZATION_ID,
+ sso_checkout: "cs_verified",
+ }),
+ }),
+ );
+ expect(markup).toContain('aria-label="Compliance settings"');
+ expect(markup).toContain('aria-label="SSO settings"');
+ expect(markup).toContain(`data-organization-id="${ORGANIZATION_ID}"`);
+ expect(markup).toContain('data-checkout-session-id="cs_verified"');
+ });
+});
+
+describe("WorkOS organization setup binding", () => {
+ it("creates a pending domain with a stable external ID and idempotency key", async () => {
+ const fixture = makeFixture({ linked: false, verified: false });
+ mocks.getOrganizationByExternalId.mockRejectedValueOnce({ status: 404 });
+ await ensureWorkosOrganization(ORGANIZATION_ID, " EXAMPLE.COM ");
+ await ensureWorkosOrganization(ORGANIZATION_ID, "different.example");
+ expect(mocks.createOrganization).toHaveBeenCalledExactlyOnceWith(
+ {
+ name: "Company",
+ externalId: ORGANIZATION_ID,
+ domainData: [{ domain: "example.com", state: "pending" }],
+ },
+ { idempotencyKey: `cap-sso-organization:${ORGANIZATION_ID}` },
+ );
+ expect(fixture.organization.workosOrganizationId).toBe(
+ WORKOS_ORGANIZATION_ID,
+ );
+ expect(fixture.database.update).toHaveBeenCalledTimes(1);
+ });
+
+ it("recovers an existing external-ID mapping without creating another organization", async () => {
+ const fixture = makeFixture({ linked: false });
+ await ensureWorkosOrganization(ORGANIZATION_ID, "example.com");
+ expect(mocks.getOrganizationByExternalId).toHaveBeenCalledWith(
+ ORGANIZATION_ID,
+ );
+ expect(mocks.createOrganization).not.toHaveBeenCalled();
+ expect(fixture.organization.workosOrganizationId).toBe(
+ WORKOS_ORGANIZATION_ID,
+ );
+ });
+
+ it("does not bind a same-name WorkOS organization with a different external ID", async () => {
+ const fixture = makeFixture({ linked: false });
+ fixture.remote.externalId = OTHER_ORGANIZATION_ID;
+ await expect(
+ ensureWorkosOrganization(ORGANIZATION_ID, "example.com"),
+ ).rejects.toThrow("could not be verified");
+ expect(fixture.database.update).not.toHaveBeenCalled();
+ expect(mocks.listOrganizations).not.toHaveBeenCalled();
+ expect(fixture.organization.workosOrganizationId).toBeNull();
+ });
+
+ it("recovers a concurrent WorkOS create only by its expected external ID", async () => {
+ const fixture = makeFixture({ linked: false });
+ mocks.getOrganizationByExternalId.mockRejectedValueOnce({ status: 404 });
+ mocks.createOrganization.mockRejectedValue(
+ new Error("Duplicate external ID"),
+ );
+ await ensureWorkosOrganization(ORGANIZATION_ID, "example.com");
+ expect(mocks.getOrganizationByExternalId).toHaveBeenCalledTimes(2);
+ expect(fixture.organization.workosOrganizationId).toBe(
+ WORKOS_ORGANIZATION_ID,
+ );
+ });
+
+ it("does not create a duplicate after a WorkOS lookup outage", async () => {
+ makeFixture({ linked: false });
+ mocks.getOrganizationByExternalId.mockRejectedValue({ status: 503 });
+ await expect(
+ ensureWorkosOrganization(ORGANIZATION_ID, "example.com"),
+ ).rejects.toEqual({ status: 503 });
+ expect(mocks.createOrganization).not.toHaveBeenCalled();
+ });
+
+ it("does not overwrite an organization mapping that changed during setup", async () => {
+ const fixture = makeFixture({ linked: false });
+ fixture.hooks.beforeUpdate = () => {
+ fixture.organization.workosOrganizationId = "org_concurrent";
+ };
+ await expect(
+ ensureWorkosOrganization(ORGANIZATION_ID, "example.com"),
+ ).rejects.toThrow("organization changed");
+ expect(fixture.organization.workosOrganizationId).toBe("org_concurrent");
+ });
+
+ it("does not create resources for a deleted Cap organization", async () => {
+ const fixture = makeFixture({ linked: false });
+ fixture.organization.tombstoneAt = new Date();
+ await expect(
+ ensureWorkosOrganization(ORGANIZATION_ID, "example.com"),
+ ).rejects.toThrow("Organization not found");
+ expect(mocks.getOrganizationByExternalId).not.toHaveBeenCalled();
+ });
+
+ it("rejects a WorkOS response for a different organization ID", async () => {
+ const fixture = makeFixture();
+ fixture.remote.id = "org_other";
+ await expect(getSsoConfiguration(fixture.organization)).rejects.toThrow(
+ "could not be verified",
+ );
+ await expect(ensureWorkosOrganization(ORGANIZATION_ID)).rejects.toThrow(
+ "could not be verified",
+ );
+ });
+
+ it("rejects a connection belonging to a different WorkOS organization", async () => {
+ const fixture = makeFixture();
+ fixture.connection.organizationId = "org_other";
+ await expect(getSsoConfiguration(fixture.organization)).rejects.toThrow(
+ "could not be verified",
+ );
+ });
+
+ it("does not choose a sign-in connection from an incomplete page", async () => {
+ const fixture = makeFixture();
+ mocks.listConnections.mockResolvedValue({
+ data: fixture.connections,
+ listMetadata: { after: "conn_next" },
+ });
+ await expect(getSsoConfiguration(fixture.organization)).rejects.toThrow(
+ "too many SSO connections",
+ );
+ });
+
+ it("keeps settings manageable while an ambiguous default blocks discovery", async () => {
+ const fixture = makeFixture();
+ fixture.connections.push({ ...fixture.connection, id: "conn_second" });
+ await expect(
+ getSsoConfiguration(fixture.organization),
+ ).resolves.toMatchObject({
+ requiresConnectionSelection: true,
+ connection: null,
+ });
+ const settings = await getOrganizationSsoSettings(ORGANIZATION_ID);
+ expect(settings.connectionIssue).toContain("Multiple SSO connections");
+ expect(settings.signInUrl).toBeNull();
+ await expect(getOrganizationSSOData("example.com")).rejects.toThrow(
+ "SSO setup is not complete",
+ );
+ await expect(
+ getOrganizationSSOData("", CONNECTION_ID),
+ ).resolves.toMatchObject({
+ connectionId: CONNECTION_ID,
+ });
+ await expect(
+ openOrganizationSsoPortal(ORGANIZATION_ID),
+ ).resolves.toMatchObject({
+ url: expect.any(String),
+ });
+ fixture.organization.workosConnectionId = "conn_second";
+ const configuration = await getSsoConfiguration(fixture.organization);
+ expect(configuration?.connection?.id).toBe("conn_second");
+ });
+});
+
+describe("SSO sign-in discovery", () => {
+ it("resolves a verified work email and binds the signed intent to its organization", async () => {
+ makeFixture();
+ mocks.getCurrentUser.mockResolvedValue(null);
+ await expect(getOrganizationSSOData("[email protected]")).resolves.toEqual(
+ {
+ organizationId: WORKOS_ORGANIZATION_ID,
+ connectionId: CONNECTION_ID,
+ name: "Company",
+ },
+ );
+ expect(mocks.listOrganizations).toHaveBeenCalledWith({
+ domains: ["example.com"],
+ limit: 100,
+ });
+ const cookie = mocks.setCookie.mock.calls[0];
+ expect(cookie?.[0]).toBe("__Host-cap-sso-intent");
+ expect(cookie?.[2]).toMatchObject({
+ httpOnly: true,
+ secure: true,
+ sameSite: "lax",
+ path: "/",
+ maxAge: 600,
+ });
+ expect(
+ verifySsoLoginIntent(cookie?.[1], mocks.env.NEXTAUTH_SECRET),
+ ).toMatchObject({
+ organizationId: ORGANIZATION_ID,
+ workosOrganizationId: WORKOS_ORGANIZATION_ID,
+ connectionId: CONNECTION_ID,
+ actorId: null,
+ });
+ });
+
+ it("keeps shared organization links and binds an existing signed-in actor", async () => {
+ makeFixture();
+ await getOrganizationSSOData(ORGANIZATION_ID);
+ expect(mocks.listOrganizations).not.toHaveBeenCalled();
+ const signedIntent = mocks.setCookie.mock.calls[0]?.[1];
+ expect(
+ verifySsoLoginIntent(signedIntent, mocks.env.NEXTAUTH_SECRET),
+ ).toMatchObject({
+ organizationId: ORGANIZATION_ID,
+ actorId: OWNER_ID,
+ });
+ });
+
+ it("restarts an IdP-initiated connection through signed application state", async () => {
+ makeFixture();
+ await expect(
+ getOrganizationSSOData("", CONNECTION_ID),
+ ).resolves.toMatchObject({
+ organizationId: WORKOS_ORGANIZATION_ID,
+ connectionId: CONNECTION_ID,
+ });
+ expect(mocks.getConnection).toHaveBeenCalledWith(CONNECTION_ID);
+ expect(mocks.setCookie).toHaveBeenCalledOnce();
+ });
+
+ it("rejects an unverified domain even when its organization has the same name", async () => {
+ makeFixture({ verified: false });
+ await expect(getOrganizationSSOData("example.com")).rejects.toThrow(
+ "SSO is not configured",
+ );
+ expect(mocks.getSsoBilling).not.toHaveBeenCalled();
+ expect(mocks.setCookie).not.toHaveBeenCalled();
+ });
+
+ it("does not permit a share link to skip domain verification", async () => {
+ makeFixture({ verified: false });
+ await expect(getOrganizationSSOData(ORGANIZATION_ID)).rejects.toThrow(
+ "SSO setup is not complete",
+ );
+ expect(mocks.setCookie).not.toHaveBeenCalled();
+ });
+
+ it("does not start sign-in after the authoritative entitlement is canceled", async () => {
+ const fixture = makeFixture();
+ mocks.syncSsoSubscription.mockResolvedValue({
+ ...fixture.billing,
+ status: "canceled",
+ });
+ await expect(getOrganizationSSOData("example.com")).rejects.toThrow(
+ "SSO is not available",
+ );
+ expect(mocks.setCookie).not.toHaveBeenCalled();
+ });
+
+ it("rejects an inactive or unregistered IdP connection", async () => {
+ const fixture = makeFixture();
+ fixture.connection.state = "inactive";
+ await expect(getOrganizationSSOData("", CONNECTION_ID)).rejects.toThrow(
+ "SSO is not configured",
+ );
+ fixture.connection.state = "active";
+ fixture.connection.organizationId = "org_unknown";
+ await expect(getOrganizationSSOData("", CONNECTION_ID)).rejects.toThrow(
+ "SSO is not configured",
+ );
+ expect(mocks.setCookie).not.toHaveBeenCalled();
+ });
+
+ it("rejects a connection that changes organization during discovery", async () => {
+ const fixture = makeFixture();
+ mocks.getConnection
+ .mockResolvedValueOnce(fixture.connection)
+ .mockResolvedValueOnce({
+ ...fixture.connection,
+ organizationId: "org_other",
+ });
+ await expect(getOrganizationSSOData("", CONNECTION_ID)).rejects.toThrow(
+ "SSO setup is not complete",
+ );
+ expect(mocks.setCookie).not.toHaveBeenCalled();
+ });
+
+ it("requires an administrator's link for an ambiguous verified domain", async () => {
+ const fixture = makeFixture();
+ fixture.remoteOrganizations.push({ ...fixture.remote, id: "org_second" });
+ fixture.localOrganizations.push({
+ ...fixture.organization,
+ id: OTHER_ORGANIZATION_ID,
+ workosOrganizationId: "org_second",
+ });
+ await expect(getOrganizationSSOData("example.com")).rejects.toThrow(
+ "sign-in link provided by your administrator",
+ );
+ expect(mocks.setCookie).not.toHaveBeenCalled();
+ });
+
+ it("rejects incomplete paginated domain results", async () => {
+ const fixture = makeFixture();
+ mocks.listOrganizations.mockResolvedValue({
+ data: fixture.remoteOrganizations,
+ listMetadata: { after: "org_next" },
+ });
+ await expect(getOrganizationSSOData("example.com")).rejects.toThrow(
+ "SSO is not configured",
+ );
+ expect(mocks.setCookie).not.toHaveBeenCalled();
+ });
+
+ it("rate-limits discovery before accessing WorkOS", async () => {
+ makeFixture();
+ mocks.isRateLimited.mockResolvedValue(true);
+ await expect(getOrganizationSSOData("example.com")).rejects.toThrow(
+ "Too many SSO attempts",
+ );
+ expect(mocks.getWorkOS).not.toHaveBeenCalled();
+ expect(mocks.setCookie).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/actions/organization/sso.ts b/apps/web/actions/organization/sso.ts
new file mode 100644
index 000000000..798d92100
--- /dev/null
+++ b/apps/web/actions/organization/sso.ts
@@ -0,0 +1,209 @@
+"use server";
+
+import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { getSsoEmailDomain, getWorkOS } from "@cap/database/auth/sso";
+import { organizations } from "@cap/database/schema";
+import { serverEnv } from "@cap/env";
+import { hasSsoAccess } from "@cap/utils";
+import type { Organisation } from "@cap/web-domain";
+import { GeneratePortalLinkIntent } from "@workos-inc/node";
+import { and, eq, isNull } from "drizzle-orm";
+import { revalidatePath } from "next/cache";
+import {
+ attachSsoCheckout,
+ createSsoBillingPortal,
+ createSsoCheckout,
+ getSsoBilling,
+ getSsoPrices,
+ syncSsoSubscription,
+} from "@/lib/sso/billing";
+import {
+ ensureWorkosOrganization,
+ getSsoConfiguration,
+} from "@/lib/sso/workos";
+import { isSupportedCurrency } from "@/utils/currency";
+import {
+ requireOrganizationOwner,
+ requireOrganizationSettingsManager,
+} from "./authorization";
+
+const settingsPath = "/dashboard/settings/organization/security";
+
+export type OrganizationSsoSettings = {
+ organizationId: Organisation.OrganisationId;
+ organizationName: string;
+ canManageBilling: boolean;
+ ssoAvailable: boolean;
+ entitled: boolean;
+ hasSubscription: boolean;
+ subscriptionStatus: string | null;
+ cancelAtPeriodEnd: boolean;
+ currentPeriodEnd: string | null;
+ suggestedDomain: string;
+ prices: Array<{ currency: "usd" | "gbp" | "eur"; unitAmount: number }>;
+ domains: Array<{ domain: string; state: string }>;
+ connection: { name: string; state: string } | null;
+ connectionIssue?: string;
+ signInUrl: string | null;
+};
+
+async function requireSsoManager(organizationId: Organisation.OrganisationId) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+ const access = await requireOrganizationSettingsManager(
+ user.id,
+ organizationId,
+ );
+ const [organization] = await db()
+ .select()
+ .from(organizations)
+ .where(
+ and(
+ eq(organizations.id, organizationId),
+ isNull(organizations.tombstoneAt),
+ ),
+ )
+ .limit(1);
+ if (!organization) throw new Error("Organization not found.");
+ return { user, access, organization };
+}
+
+async function requireSsoOwner(organizationId: Organisation.OrganisationId) {
+ const user = await getCurrentUser();
+ if (!user) throw new Error("Unauthorized");
+ await requireOrganizationOwner(user.id, organizationId);
+ return user;
+}
+
+async function refreshSsoBilling(organizationId: Organisation.OrganisationId) {
+ const billing = await getSsoBilling(organizationId);
+ if (!billing?.stripeSubscriptionId) return billing;
+ return syncSsoSubscription(billing.stripeSubscriptionId);
+}
+
+export async function getOrganizationSsoSettings(
+ organizationId: Organisation.OrganisationId,
+): Promise<OrganizationSsoSettings> {
+ const { user, access, organization } =
+ await requireSsoManager(organizationId);
+ const env = serverEnv();
+ const ssoAvailable = Boolean(env.WORKOS_API_KEY && env.WORKOS_CLIENT_ID);
+ const [billing, prices, configuration] = await Promise.all([
+ refreshSsoBilling(organizationId),
+ getSsoPrices().catch(() => []),
+ ssoAvailable ? getSsoConfiguration(organization) : null,
+ ]);
+ const entitled = hasSsoAccess(billing);
+ const connection = configuration?.connection;
+ const signInUrl = new URL("/login", env.WEB_URL);
+ signInUrl.searchParams.set("organizationId", organizationId);
+ return {
+ organizationId,
+ organizationName: organization.name,
+ canManageBilling: access.role === "owner",
+ ssoAvailable,
+ entitled,
+ hasSubscription: Boolean(billing?.stripeSubscriptionId),
+ subscriptionStatus: billing?.status ?? null,
+ cancelAtPeriodEnd: billing?.cancelAtPeriodEnd ?? false,
+ currentPeriodEnd: billing?.currentPeriodEnd?.toISOString() ?? null,
+ suggestedDomain:
+ configuration?.organization.domains[0]?.domain ??
+ getSsoEmailDomain(user.email) ??
+ "",
+ prices,
+ domains:
+ configuration?.organization.domains.map(({ domain, state }) => ({
+ domain,
+ state,
+ })) ?? [],
+ connection: connection
+ ? { name: connection.name, state: connection.state }
+ : null,
+ connectionIssue: configuration?.requiresConnectionSelection
+ ? "Multiple SSO connections are active. Open Manage SSO to keep one active connection, or contact Cap support to select the default connection."
+ : undefined,
+ signInUrl:
+ entitled &&
+ connection?.state === "active" &&
+ configuration?.organization.domains.some(
+ (domain) => domain.state === "verified",
+ )
+ ? signInUrl.toString()
+ : null,
+ };
+}
+
+export async function startOrganizationSsoCheckout(
+ organizationId: Organisation.OrganisationId,
+ currency: string,
+) {
+ const user = await requireSsoOwner(organizationId);
+ if (!isSupportedCurrency(currency))
+ throw new Error("Unsupported billing currency.");
+ getWorkOS();
+ const url = await createSsoCheckout({
+ organizationId,
+ purchasedByUserId: user.id,
+ stripeCustomerId: user.stripeCustomerId,
+ currency,
+ });
+ return { url };
+}
+
+export async function openOrganizationSsoPortal(
+ organizationId: Organisation.OrganisationId,
+ domain?: string,
+ purpose: "sso" | "domain_verification" = "sso",
+) {
+ await requireSsoManager(organizationId);
+ if (purpose !== "sso" && purpose !== "domain_verification")
+ throw new Error("Invalid setup request.");
+ const billing = await refreshSsoBilling(organizationId);
+ if (!hasSsoAccess(billing))
+ throw new Error("An active SAML SSO add-on is required.");
+ const organization = await ensureWorkosOrganization(organizationId, domain);
+ const returnUrl = new URL(settingsPath, serverEnv().WEB_URL);
+ returnUrl.searchParams.set("organizationId", organizationId);
+ const successUrl = new URL(returnUrl);
+ successUrl.searchParams.set("sso_setup", "complete");
+ const result = await getWorkOS().portal.generateLink({
+ organization: organization.id,
+ intent:
+ purpose === "domain_verification" ||
+ !organization.domains.some((entry) => entry.state === "verified")
+ ? GeneratePortalLinkIntent.DomainVerification
+ : GeneratePortalLinkIntent.SSO,
+ returnUrl: returnUrl.toString(),
+ successUrl: successUrl.toString(),
+ });
+ revalidatePath(settingsPath);
+ return { url: result.link };
+}
+
+export async function confirmOrganizationSsoCheckout(
+ organizationId: Organisation.OrganisationId,
+ sessionId: string,
+) {
+ const user = await requireSsoOwner(organizationId);
+ if (!/^cs_[a-zA-Z0-9_]+$/.test(sessionId) || sessionId.length > 255)
+ throw new Error("Invalid checkout session.");
+ const billing = await attachSsoCheckout(sessionId, {
+ organizationId,
+ userId: user.id,
+ });
+ if (!hasSsoAccess(billing))
+ throw new Error(
+ "Your SSO payment is still processing. Please refresh in a moment.",
+ );
+ revalidatePath(settingsPath);
+ return getOrganizationSsoSettings(organizationId);
+}
+
+export async function manageOrganizationSsoBilling(
+ organizationId: Organisation.OrganisationId,
+) {
+ await requireSsoOwner(organizationId);
+ return { url: await createSsoBillingPortal(organizationId) };
+}
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/SsoCard.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/SsoCard.tsx
new file mode 100644
index 000000000..8a2415016
--- /dev/null
+++ b/apps/web/app/(org)/dashboard/settings/organization/components/SsoCard.tsx
@@ -0,0 +1,526 @@
+"use client";
+
+import {
+ Button,
+ Card,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Input,
+} from "@cap/ui";
+import { useCurrency } from "hooks/useCurrency";
+import { Copy, ExternalLink, RefreshCw, ShieldCheck } from "lucide-react";
+import { useRouter } from "next/navigation";
+import {
+ useCallback,
+ useEffect,
+ useId,
+ useRef,
+ useState,
+ useTransition,
+} from "react";
+import { toast } from "sonner";
+import {
+ confirmOrganizationSsoCheckout,
+ getOrganizationSsoSettings,
+ manageOrganizationSsoBilling,
+ type OrganizationSsoSettings,
+ openOrganizationSsoPortal,
+ startOrganizationSsoCheckout,
+} from "@/actions/organization/sso";
+import {
+ formatAmount,
+ isSupportedCurrency,
+ type SupportedCurrency,
+} from "@/utils/currency";
+
+type SsoAction = "checkout" | "portal" | "billing" | "refresh" | "confirm";
+
+const actionErrors: Record<SsoAction, string> = {
+ checkout: "We couldn't open checkout. Please try again or contact support.",
+ portal: "We couldn't open SSO setup. Please try again or contact support.",
+ billing: "We couldn't open billing. Please try again or contact support.",
+ refresh: "We couldn't refresh SSO status. Please try again.",
+ confirm:
+ "We couldn't confirm your SSO subscription yet. Refresh the status to try again, or contact support if you've been charged.",
+};
+
+export function SsoCard({
+ initialSettings,
+ checkoutSessionId,
+}: {
+ initialSettings: OrganizationSsoSettings;
+ checkoutSessionId?: string;
+}) {
+ const router = useRouter();
+ const { currency: detectedCurrency } = useCurrency();
+ const [settings, setSettings] = useState(initialSettings);
+ const [domain, setDomain] = useState(initialSettings.suggestedDomain);
+ const [selectedCurrency, setSelectedCurrency] =
+ useState<SupportedCurrency | null>(null);
+ const [pendingAction, setPendingAction] = useState<SsoAction | null>(
+ checkoutSessionId ? "confirm" : null,
+ );
+ const [error, setError] = useState<string | null>(null);
+ const [isPending, startTransition] = useTransition();
+ const actionInFlight = useRef(false);
+ const confirmationStarted = useRef<string | null>(null);
+ const confirmedCheckout = useRef<string | null>(null);
+ const domainInputId = useId();
+ const currencyInputId = useId();
+ const signInLinkInputId = useId();
+ const organizationId = initialSettings.organizationId;
+ const busy = isPending || pendingAction !== null;
+ const price =
+ settings.prices.find(
+ (candidate) =>
+ candidate.currency === (selectedCurrency ?? detectedCurrency),
+ ) ??
+ settings.prices.find((candidate) => candidate.currency === "usd") ??
+ settings.prices[0];
+ const monthlyAmount = price
+ ? formatAmount(price.unitAmount / 100, price.currency)
+ : null;
+ const hasVerifiedDomain = settings.domains.some(
+ (entry) => entry.state === "verified",
+ );
+ const isActive =
+ settings.entitled &&
+ settings.connection?.state === "active" &&
+ hasVerifiedDomain;
+ const hasExistingSubscription =
+ settings.hasSubscription &&
+ settings.subscriptionStatus !== "canceled" &&
+ settings.subscriptionStatus !== "incomplete_expired";
+ const periodEnd = settings.currentPeriodEnd
+ ? new Date(settings.currentPeriodEnd)
+ : null;
+ const periodEndLabel =
+ periodEnd && !Number.isNaN(periodEnd.getTime())
+ ? `on ${periodEnd.toLocaleDateString("en-GB", {
+ day: "numeric",
+ month: "long",
+ year: "numeric",
+ timeZone: "UTC",
+ })}`
+ : "at the end of your billing period";
+ let statusLabel = "Optional add-on";
+ if (settings.entitled) {
+ statusLabel = isActive ? "Active" : "Ready to configure";
+ } else if (hasExistingSubscription) {
+ statusLabel = "Billing needs attention";
+ }
+
+ const runAction = useCallback(
+ (action: SsoAction, operation: () => Promise<void>) => {
+ if (actionInFlight.current) return;
+ actionInFlight.current = true;
+ setPendingAction(action);
+ setError(null);
+ startTransition(async () => {
+ let succeeded = false;
+ try {
+ await operation();
+ succeeded = true;
+ } catch {
+ setError(actionErrors[action]);
+ } finally {
+ if (!succeeded || action === "refresh" || action === "confirm") {
+ actionInFlight.current = false;
+ setPendingAction(null);
+ }
+ }
+ });
+ },
+ [],
+ );
+
+ const confirmCheckout = useCallback(
+ (sessionId: string) => {
+ runAction("confirm", async () => {
+ const updated = await confirmOrganizationSsoCheckout(
+ organizationId,
+ sessionId,
+ );
+ setSettings(updated);
+ if (!updated.entitled) {
+ setError(
+ "Your payment is still being confirmed. Refresh the status shortly; you don't need to subscribe again.",
+ );
+ return;
+ }
+ confirmedCheckout.current = sessionId;
+ const url = new URL(window.location.href);
+ url.searchParams.delete("sso_checkout");
+ router.replace(`${url.pathname}${url.search}${url.hash}`, {
+ scroll: false,
+ });
+ router.refresh();
+ });
+ },
+ [organizationId, router, runAction],
+ );
+
+ const refreshSettings = useCallback(() => {
+ if (checkoutSessionId && confirmedCheckout.current !== checkoutSessionId) {
+ confirmCheckout(checkoutSessionId);
+ return;
+ }
+ runAction("refresh", async () => {
+ setSettings(await getOrganizationSsoSettings(organizationId));
+ router.refresh();
+ });
+ }, [checkoutSessionId, confirmCheckout, organizationId, router, runAction]);
+
+ useEffect(() => {
+ if (
+ !checkoutSessionId ||
+ confirmationStarted.current === checkoutSessionId
+ ) {
+ return;
+ }
+ confirmationStarted.current = checkoutSessionId;
+ confirmCheckout(checkoutSessionId);
+ }, [checkoutSessionId, confirmCheckout]);
+
+ useEffect(() => {
+ const refreshOnReturn = (event: PageTransitionEvent) => {
+ if (!event.persisted) return;
+ actionInFlight.current = false;
+ setPendingAction(null);
+ refreshSettings();
+ };
+ window.addEventListener("pageshow", refreshOnReturn);
+ return () => window.removeEventListener("pageshow", refreshOnReturn);
+ }, [refreshSettings]);
+
+ const openPortal = (purpose: "sso" | "domain_verification" = "sso") => {
+ const requestedDomain = settings.domains.length ? undefined : domain.trim();
+ if (requestedDomain && /[@/:\s]/.test(requestedDomain)) {
+ setError("Enter a domain such as company.com, without an email or URL.");
+ return;
+ }
+ runAction("portal", async () => {
+ const { url } = await openOrganizationSsoPortal(
+ organizationId,
+ requestedDomain || undefined,
+ purpose,
+ );
+ window.location.assign(url);
+ });
+ };
+
+ const openBilling = () => {
+ runAction("billing", async () => {
+ const { url } = await manageOrganizationSsoBilling(organizationId);
+ window.location.assign(url);
+ });
+ };
+
+ return (
+ <Card>
+ <div className="flex flex-wrap gap-4 justify-between items-start">
+ <div className="flex gap-3 items-start">
+ <div className="flex justify-center items-center rounded-xl bg-gray-3 size-10 shrink-0">
+ <ShieldCheck className="size-5 text-gray-11" aria-hidden="true" />
+ </div>
+ <CardHeader>
+ <CardTitle>SAML SSO</CardTitle>
+ <CardDescription className="max-w-xl">
+ Let your team sign in to Cap with your organization's identity
+ provider, including Okta, Microsoft Entra ID, and Google
+ Workspace.
+ </CardDescription>
+ </CardHeader>
+ </div>
+ <span
+ className={`rounded-full px-2.5 py-1 text-xs font-medium ${
+ isActive ? "bg-green-50 text-green-700" : "bg-gray-3 text-gray-11"
+ }`}
+ >
+ {statusLabel}
+ </span>
+ </div>
+
+ <div className="flex flex-col gap-4 mt-5">
+ <p className="text-sm leading-6 text-gray-11">
+ People who sign in with your SSO connection are automatically added to{" "}
+ <span className="font-medium text-gray-12">
+ {settings.organizationName}
+ </span>{" "}
+ as members. Cap Pro seats are billed separately from this add-on.
+ </p>
+
+ {!settings.ssoAvailable && (
+ <p className="rounded-xl border border-gray-4 bg-gray-2 p-3 text-sm text-gray-11">
+ SSO setup is currently unavailable. Contact{" "}
+ <a className="underline" href="mailto:[email protected]">
+ </a>{" "}
+ for help.
+ </p>
+ )}
+
+ {settings.entitled ? (
+ <>
+ {settings.domains.length ? (
+ <div className="flex flex-wrap gap-2">
+ {settings.domains.map((entry) => (
+ <span
+ key={entry.domain}
+ className="rounded-lg border border-gray-4 px-3 py-1.5 text-xs text-gray-11"
+ >
+ <span className="font-medium text-gray-12">
+ {entry.domain}
+ </span>
+ {" · "}
+ {entry.state === "verified"
+ ? "Verified"
+ : "Verification needed"}
+ </span>
+ ))}
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2 max-w-sm">
+ <label
+ htmlFor={domainInputId}
+ className="text-sm font-medium text-gray-12"
+ >
+ Organization domain
+ </label>
+ <Input
+ id={domainInputId}
+ value={domain}
+ onChange={(event) => setDomain(event.target.value)}
+ placeholder="company.com"
+ autoCapitalize="none"
+ autoCorrect="off"
+ disabled={busy || !settings.ssoAvailable}
+ />
+ </div>
+ )}
+ <p className="text-xs leading-5 text-gray-10">
+ {hasVerifiedDomain
+ ? "Your IT administrator completes SAML configuration in WorkOS. Return here to check the connection status."
+ : "First, verify your organization's domain in WorkOS. Then return here to set up the SAML connection."}
+ </p>
+ {settings.connection && (
+ <p className="text-sm text-gray-11">
+ {settings.connection.name}
+ {" · "}
+ {isActive ? "Ready for sign-in" : "Setup not complete"}
+ </p>
+ )}
+ {settings.connectionIssue && (
+ <output className="text-sm text-gray-11">
+ {settings.connectionIssue}
+ </output>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant="dark"
+ onClick={() => openPortal()}
+ disabled={busy || !settings.ssoAvailable}
+ spinner={pendingAction === "portal"}
+ >
+ {!hasVerifiedDomain
+ ? "Verify domain"
+ : settings.connection || settings.connectionIssue
+ ? "Manage SSO"
+ : "Set up SAML SSO"}
+ <ExternalLink className="ml-1 size-3.5" aria-hidden="true" />
+ </Button>
+ {hasVerifiedDomain &&
+ settings.domains.some(
+ (entry) => entry.state !== "verified",
+ ) && (
+ <Button
+ type="button"
+ size="sm"
+ variant="gray"
+ onClick={() => openPortal("domain_verification")}
+ disabled={busy || !settings.ssoAvailable}
+ >
+ Verify domains
+ </Button>
+ )}
+ {settings.canManageBilling && settings.hasSubscription && (
+ <Button
+ type="button"
+ size="sm"
+ variant="gray"
+ onClick={openBilling}
+ disabled={busy}
+ spinner={pendingAction === "billing"}
+ >
+ Manage subscription
+ </Button>
+ )}
+ </div>
+ {settings.cancelAtPeriodEnd && (
+ <p className="text-sm text-gray-11">
+ Your SSO add-on is scheduled to end {periodEndLabel}. Manage
+ your subscription to keep it active.
+ </p>
+ )}
+ </>
+ ) : settings.canManageBilling ? (
+ <div className="flex flex-col gap-3">
+ {hasExistingSubscription ? (
+ <>
+ <p className="text-sm text-gray-11">
+ Your SSO subscription needs attention before setup is
+ available. Manage the existing subscription to review its
+ payment status.
+ </p>
+ <Button
+ type="button"
+ size="sm"
+ variant="dark"
+ className="w-fit"
+ onClick={openBilling}
+ disabled={busy}
+ spinner={pendingAction === "billing"}
+ >
+ Manage SSO subscription
+ </Button>
+ </>
+ ) : (
+ <div className="flex flex-wrap gap-3 items-end">
+ {price && settings.prices.length > 1 && (
+ <div className="flex flex-col gap-1.5">
+ <label
+ htmlFor={currencyInputId}
+ className="text-xs font-medium text-gray-11"
+ >
+ Billing currency
+ </label>
+ <select
+ id={currencyInputId}
+ value={price.currency}
+ onChange={(event) => {
+ if (isSupportedCurrency(event.target.value)) {
+ setSelectedCurrency(event.target.value);
+ }
+ }}
+ disabled={busy || !settings.ssoAvailable}
+ className="h-10 rounded-lg border border-gray-4 bg-gray-1 px-3 text-sm text-gray-12"
+ >
+ {settings.prices.map((candidate) => (
+ <option
+ key={candidate.currency}
+ value={candidate.currency}
+ >
+ {candidate.currency.toUpperCase()}
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+ <Button
+ type="button"
+ size="sm"
+ variant="dark"
+ disabled={
+ busy ||
+ !settings.ssoAvailable ||
+ !price ||
+ Boolean(checkoutSessionId)
+ }
+ spinner={pendingAction === "checkout"}
+ onClick={() => {
+ if (!price) return;
+ setSelectedCurrency(price.currency);
+ runAction("checkout", async () => {
+ const { url } = await startOrganizationSsoCheckout(
+ organizationId,
+ price.currency,
+ );
+ window.location.assign(url);
+ });
+ }}
+ >
+ {monthlyAmount
+ ? `Add SAML SSO · ${monthlyAmount}/month`
+ : "Pricing unavailable"}
+ </Button>
+ </div>
+ )}
+ </div>
+ ) : (
+ <p className="text-sm text-gray-11">
+ Ask your organization owner to add SAML SSO. Once subscribed, owners
+ and admins can configure it here.
+ </p>
+ )}
+
+ {isActive && settings.signInUrl && (
+ <div className="flex flex-col gap-2 rounded-xl border border-gray-4 bg-gray-2 p-4">
+ <label
+ htmlFor={signInLinkInputId}
+ className="text-sm font-medium text-gray-12"
+ >
+ Share your SSO sign-in link
+ </label>
+ <div className="flex flex-col gap-2 sm:flex-row">
+ <Input
+ id={signInLinkInputId}
+ value={settings.signInUrl}
+ readOnly
+ className="min-w-0 flex-1"
+ />
+ <Button
+ type="button"
+ size="sm"
+ variant="gray"
+ onClick={async () => {
+ try {
+ await navigator.clipboard.writeText(
+ settings.signInUrl ?? "",
+ );
+ toast.success("SSO sign-in link copied");
+ } catch {
+ toast.error(
+ "Couldn't copy the link. Select it above and copy it manually.",
+ );
+ }
+ }}
+ >
+ <Copy className="mr-1 size-3.5" aria-hidden="true" />
+ Copy link
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {pendingAction === "confirm" && (
+ <output className="text-sm text-gray-11">
+ Confirming your SSO subscription…
+ </output>
+ )}
+ {error && (
+ <p
+ className="rounded-xl border border-red-200 bg-red-50 p-3 text-sm text-red-700"
+ role="alert"
+ >
+ {error}
+ </p>
+ )}
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="w-fit"
+ onClick={refreshSettings}
+ disabled={busy}
+ spinner={pendingAction === "refresh" || pendingAction === "confirm"}
+ >
+ {!busy && <RefreshCw className="mr-1 size-3.5" aria-hidden="true" />}
+ Refresh status
+ </Button>
+ </div>
+ </Card>
+ );
+}
diff --git a/apps/web/app/(org)/dashboard/settings/organization/security/page.tsx b/apps/web/app/(org)/dashboard/settings/organization/security/page.tsx
index 9e71a896b..af4ade3bb 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/security/page.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/security/page.tsx
@@ -1,13 +1,83 @@
+import { getCurrentUser } from "@cap/database/auth/session";
+import { Card, CardDescription, CardHeader, CardTitle } from "@cap/ui";
import type { Metadata } from "next";
+import { redirect, unstable_rethrow } from "next/navigation";
+import { getOrganizationSsoSettings } from "@/actions/organization/sso";
import { ComplianceCard } from "../components/ComplianceCard";
+import { SsoCard } from "../components/SsoCard";
export const metadata: Metadata = {
title: "Security & Compliance — Cap",
};
-export default function OrganizationSecurityPage() {
+export default async function OrganizationSecurityPage({
+ searchParams,
+}: {
+ searchParams: Promise<{
+ sso_checkout?: string | string[];
+ organizationId?: string | string[];
+ }>;
+}) {
+ const [user, query] = await Promise.all([getCurrentUser(), searchParams]);
+ if (!user) redirect("/auth/signin");
+ if (!user.activeOrganizationId) redirect("/dashboard/caps");
+ if (
+ (query.sso_checkout || query.organizationId) &&
+ query.organizationId !== user.activeOrganizationId
+ ) {
+ return (
+ <div className="flex flex-col gap-6">
+ <Card>
+ <CardHeader>
+ <CardTitle>Switch organizations to continue SSO setup</CardTitle>
+ <CardDescription>
+ Choose the organization you were setting up from the organization
+ switcher, then reload this page to refresh its payment and SSO
+ status. If you are already in the correct organization, contact
+ Cap support.
+ </CardDescription>
+ </CardHeader>
+ </Card>
+ <ComplianceCard />
+ </div>
+ );
+ }
+ let settings: Awaited<ReturnType<typeof getOrganizationSsoSettings>>;
+ try {
+ settings = await getOrganizationSsoSettings(user.activeOrganizationId);
+ } catch (error) {
+ unstable_rethrow(error);
+ return (
+ <div className="flex flex-col gap-6">
+ <Card>
+ <CardHeader>
+ <CardTitle>SAML SSO</CardTitle>
+ <CardDescription>
+ Unable to load SAML SSO settings. Reload this page to try again.
+ If the problem continues, contact{" "}
+ <a className="underline" href="mailto:[email protected]">
+ </a>{" "}
+ for help.
+ </CardDescription>
+ </CardHeader>
+ </Card>
+ <ComplianceCard />
+ </div>
+ );
+ }
+
return (
<div className="flex flex-col gap-6">
+ <SsoCard
+ key={settings.organizationId}
+ initialSettings={settings}
+ checkoutSessionId={
+ typeof query.sso_checkout === "string"
+ ? query.sso_checkout
+ : undefined
+ }
+ />
<ComplianceCard />
</div>
);
diff --git a/docs/saml-sso.md b/docs/saml-sso.md
new file mode 100644
index 000000000..fa31e2d93
--- /dev/null
+++ b/docs/saml-sso.md
@@ -0,0 +1,91 @@
+# SAML SSO
+
+Cap uses WorkOS Single Sign-On with its existing NextAuth sessions. Each Cap organization has its own paid SSO entitlement and an explicit WorkOS organization mapping. SSO billing is independent of Cap Pro seats and the Signed BAA add-on.
+
+## Customer flow
+
+1. An organization owner opens **Settings → Organization → Security & Compliance** and purchases the monthly SAML SSO add-on. Checkout displays the configured USD, GBP, or EUR amount from Stripe.
+2. Once payment is confirmed, owners and admins can use **Verify domain**. Cap creates or reuses that organization's WorkOS organization and opens the hosted domain-verification flow. Organizations whose domains are already verified skip this step.
+3. After domain verification, **Set up SAML SSO** opens WorkOS's SSO setup flow for the IT administrator to configure the identity provider. **Verify domains** remains available if additional domains need verification. Payment alone never verifies a domain.
+4. Team members choose SAML SSO on the sign-in page, enter their work email/domain, or follow the organization's sign-in link. An IdP-initiated visit to `/login?connection_id=...` starts the same protected authorization flow.
+5. Successful sign-in links the verified identity and adds the user to that specific Cap organization. New members receive the `member` role without a Pro seat. Existing roles, seats, and default organizations are preserved; the SSO organization becomes active.
+
+An existing Cap account can enter SSO explicitly using `/login?sso=1`. Organization and IdP sign-in links also work while already signed in, but an SSO identity cannot be attached to a different currently signed-in account. That user must sign out first.
+
+## Configuration
+
+Set these server-only variables in the deployment environment:
+
+| Variable | Requirement |
+| -------------------------------------------- | ------------------------------------------------------------------------------------ |
+| `WORKOS_API_KEY` | A working key for the intended WorkOS environment. |
+| `WORKOS_CLIENT_ID` | The client ID from that same environment. |
+| `WEB_URL`, `NEXTAUTH_URL` | The canonical HTTPS deployment origin. |
+| `NEXTAUTH_SECRET` | The existing strong session secret; also signs short-lived SSO intents. |
+| `STRIPE_SECRET_KEY`, `STRIPE_WEBHOOK_SECRET` | Matching Stripe environment and webhook endpoint credentials. |
+| `STRIPE_SAML_SSO_PRICE_ID` | Optional production override; required for a separate test/development Stripe price. |
+
+The default production price is `price_1UBJpTFJxA1XpeSsQmAOhibr`. Its supported currency amounts are read from Stripe, not converted in the browser. The legacy SAML price remains recognized without upgrading or repricing existing subscriptions. Use a monthly, quantity-one test price and a test Stripe key outside production; production price IDs do not exist in Stripe test mode.
+
+Configure WorkOS redirect settings for the same environment:
+
+| Purpose | Production URL |
+| ------------------------------------- | --------------------------------------------------------- |
+| OAuth callback / redirect URI | `https://cap.so/api/auth/callback/workos` |
+| SSO sign-in / initiate-login endpoint | `https://cap.so/login` |
+| Admin Portal return/success base | `https://cap.so/dashboard/settings/organization/security` |
+
+Cap supplies organization-scoped Admin Portal return and success URLs. API-generated links are short-lived bearer capabilities and should be opened immediately, never stored or logged. Use an HTTPS preview origin for a full Admin Portal test.
+
+Configure the Vercel Firewall SDK rule `rl_auth_sso_start`, for example 20 attempts per minute per IP. The shared rate-limit helper is best-effort and fails open when the rule is missing or the firewall is unavailable; merely deploying the rule ID does not enable rate limiting. Self-hosted deployments should provide equivalent perimeter protection.
+
+## Billing and recovery
+
+`organization_sso` stores the organization, purchaser, Stripe customer/subscription, payment-confirmed access period, and a durable checkout reservation. Only owners can purchase or manage billing. Owners and admins can configure WorkOS; members cannot obtain Admin Portal links.
+
+Entitlement requires a supported SAML subscription and a paid invoice line belonging to that subscription and item. Active access ends at the confirmed paid-through date. Previously paid `past_due` subscriptions receive a seven-day grace period; unpaid, incomplete, trialing, canceled, and expired subscriptions do not grant access. A scheduled end-of-period cancellation keeps access through the paid period.
+
+Stripe webhooks and settings/sign-in refreshes reconcile current Stripe state rather than trusting event order. SSO subscriptions are routed separately before Pro/BAA handling, including subscriptions already bound in the database whose Stripe metadata later changes. Renewal uses matching paid invoice periods. Retry failures return non-success responses so Stripe can redeliver them.
+
+Checkout retries reuse the persisted attempt and Stripe idempotency key. A currency change expires the exact prior open session before creating another attempt. An uncertain response never silently starts another payment. A reservation older than 23 hours without a known Stripe session requires support reconciliation because Stripe can prune idempotency keys. Do not clear such a reservation until the earlier payment/session has been found or proven absent.
+
+For a previously paid, unlinked customer:
+
+1. Independently identify the exact Cap owner and organization. A matching email domain alone is not enough, and must not bulk-join existing domain users.
+2. Verify the Stripe subscription/customer, supported SAML price, quantity, paid invoice, and paid-through period. Preserve the agreed price. A historical payment-link customer may differ from the owner's Pro customer.
+3. Verify the exact WorkOS organization and its domain proof. Do not adopt a similarly named organization or mark a pending domain verified from an untrusted request.
+4. After the schema and safe webhook code are deployed, create the explicit `organization_sso` binding and set `organizations.workosOrganizationId`, then reconcile the subscription. Use compare-and-set predicates and verify the resulting rows.
+5. If the old webhook overwrote the owner's Pro reference, independently verify the original Pro subscription, customer, and seat quantity before restoring those fields. Never place the SAML subscription in the user's Pro subscription fields.
+
+New WorkOS organizations use the Cap organization ID as `externalId`. An explicitly verified legacy mapping can retain its existing WorkOS external ID. Billing ownership/customer changes require support reconciliation; the application refuses to silently transfer an earlier payment to a different payer. Do not add SSO metadata to a legacy subscription while the old Pro-only webhook is still deployed.
+
+## Security boundaries
+
+The authorization start signs the Cap organization, WorkOS organization, connection, current user, and safe return path into a ten-minute HttpOnly cookie. NextAuth also validates OAuth state and PKCE. The callback checks the raw WorkOS profile IDs, live connection state, verified email domain, existing account binding, and paid organization before issuing a session.
+
+WorkOS authorization receives only the verified `connection` selector. Its `connection`, `organization`, and `provider` selectors are mutually exclusive; organization ownership remains bound and validated in Cap's signed intent rather than adding a second selector to the provider request.
+
+Membership provisioning is transactional and repeatable, using organization/user row locks and a deterministic WorkOS account key. Only invitations for the SSO organization are accepted. SSO-created users do not receive an unrelated personal organization or Stripe customer during signup. Membership is committed before the session token is issued.
+
+An ambiguous default connection blocks domain-based discovery but leaves settings accessible for repair; an explicit active IdP connection is still checked against the mapped organization. Settings and sign-in query WorkOS directly, so disabling/resetting a connection is recognized without a connection webhook cache.
+
+This feature does **not** enforce SSO-only login, implement SCIM/deprovisioning, revoke existing Cap sessions when a user leaves the IdP, or provide SAML single logout. Standard Cap sign-in remains available. Do not present these as delivered enterprise controls.
+
+## Rollout and verification
+
+Deploy the additive `0040_saml_sso` migration before the application changes. Preflight existing non-null WorkOS mappings for duplicates before adding the unique index. Reconcile existing mapped organizations rather than silently granting them unpaid access. Do not push schema directly to a shared local or production database as part of a test.
+
+Focused tests live under `apps/web/__tests__/unit/sso-*.test.ts`, alongside the existing auth, mobile, Pro, BAA, and webhook regression suites. `apps/web/__tests__/integration/sso-database.test.ts` uses actual MySQL and requires `CAP_SSO_TEST_DATABASE_URL` to point to a local, session-scoped database named `cap_sso_*` with the generated schema. It refuses production/non-local URLs and retains its synthetic fixtures for inspection.
+
+Before enabling a customer, verify a real WorkOS flow on the candidate deployment: owner purchase/confirmation, admin setup and domain verification, SP-initiated and IdP-initiated sign-in, a new member, an existing account, repeat/concurrent sign-ins, wrong-domain/organization rejection, and native app return. Check cancellation, failed renewal, webhook retries, and Pro/BAA isolation in Stripe test mode. Unit tests, mocks, and local database tests do not prove a live IdP roundtrip.
+
+## WorkOS references
+
+- [SSO quick start](https://workos.com/docs/sso)
+- [Authorization URL API and connection selectors](https://workos.com/docs/reference/sso/get-authorization-url)
+- [Login flows](https://workos.com/docs/sso/login-flows) and [redirect URIs](https://workos.com/docs/sso/redirect-uris)
+- [Organization domains and profile validation](https://workos.com/docs/sso/domains)
+- [Admin Portal](https://workos.com/docs/admin-portal) and [domain verification](https://workos.com/docs/domain-verification)
+- [JIT provisioning](https://workos.com/docs/sso/jit-provisioning)
+- [SSO testing](https://workos.com/docs/sso/test-sso) and [launch checklist](https://workos.com/docs/sso/launch-checklist)
+- [SAML security](https://workos.com/docs/sso/saml-security) and [single logout](https://workos.com/docs/sso/single-logout)