Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: expose owner-only SSO invoice downloads

Richie McIlroyadde123a1cfd
diff --git a/apps/web/__tests__/unit/billing-page.test.ts b/apps/web/__tests__/unit/billing-page.test.ts
new file mode 100644
index 000000000..bca08aa2c
--- /dev/null
+++ b/apps/web/__tests__/unit/billing-page.test.ts
@@ -0,0 +1,104 @@
+import { type ComponentProps, createElement, type ReactNode } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import BillingAndMembersPage from "@/app/(org)/dashboard/settings/organization/billing/page";
+
+const mocks = vi.hoisted(() => ({
+ userId: "owner",
+ memberRole: "owner",
+ organizationId: "org/invoice?history",
+ isCap: true,
+ invoices: vi.fn(),
+ portal: vi.fn(),
+ checkout: vi.fn(),
+}));
+
+vi.mock("@cap/env", () => ({
+ buildEnv: {
+ get NEXT_PUBLIC_IS_CAP() {
+ return mocks.isCap;
+ },
+ },
+}));
+vi.mock("@/app/(org)/dashboard/Contexts", () => ({
+ useDashboardContext: () => ({
+ user: { id: mocks.userId },
+ activeOrganization: {
+ organization: { id: mocks.organizationId, ownerId: "owner" },
+ members: [{ userId: mocks.userId, role: mocks.memberRole }],
+ },
+ setInviteDialogOpen: vi.fn(),
+ }),
+}));
+vi.mock("@/actions/organization/sso", () => ({
+ getOrganizationSsoInvoices: mocks.invoices,
+ manageOrganizationSsoBilling: mocks.portal,
+ startOrganizationSsoCheckout: mocks.checkout,
+}));
+vi.mock("next/link", () => ({
+ default: ({ children, href }: ComponentProps<"a"> & { prefetch?: boolean }) =>
+ createElement("a", { href }, children),
+}));
+vi.mock("@cap/ui", () => {
+ const container = ({ children }: { children?: ReactNode }) =>
+ createElement("div", null, children);
+ return {
+ Card: container,
+ CardHeader: container,
+ CardTitle: container,
+ CardDescription: container,
+ };
+});
+vi.mock(
+ "@/app/(org)/dashboard/settings/organization/components/BillingSummaryCard",
+ () => ({ BillingSummaryCard: () => null }),
+);
+vi.mock(
+ "@/app/(org)/dashboard/settings/organization/components/MembersCard",
+ () => ({ MembersCard: () => null }),
+);
+vi.mock(
+ "@/app/(org)/dashboard/settings/organization/components/SeatManagementCard",
+ () => ({ SeatManagementCard: () => null }),
+);
+vi.mock(
+ "@/app/(org)/dashboard/settings/organization/components/SignedBaaCard",
+ () => ({ SignedBaaCard: () => null }),
+);
+
+beforeEach(() => {
+ mocks.userId = "owner";
+ mocks.memberRole = "owner";
+ mocks.isCap = true;
+});
+
+describe("SSO invoice discovery on Billing", () => {
+ it("links the owner to the selected organization's Security page without loading invoices or starting billing", () => {
+ const markup = renderToStaticMarkup(createElement(BillingAndMembersPage));
+ expect(markup).toContain(
+ 'href="/dashboard/settings/organization/security?organizationId=org%2Finvoice%3Fhistory"',
+ );
+ expect(markup).toContain("Open SSO invoices in Security settings");
+ expect(mocks.invoices).not.toHaveBeenCalled();
+ expect(mocks.portal).not.toHaveBeenCalled();
+ expect(mocks.checkout).not.toHaveBeenCalled();
+ });
+
+ it.each(["admin", "member", "owner"])(
+ "hides invoice discovery from non-owning membership role %s",
+ (role) => {
+ mocks.userId = "someone_else";
+ mocks.memberRole = role;
+ const markup = renderToStaticMarkup(createElement(BillingAndMembersPage));
+ expect(markup).not.toContain("Open SSO invoices");
+ expect(markup).toContain("Billing is managed by the organization owner.");
+ },
+ );
+
+ it("does not show hosted billing discovery in a self-hosted deployment", () => {
+ mocks.isCap = false;
+ expect(
+ renderToStaticMarkup(createElement(BillingAndMembersPage)),
+ ).not.toContain("Open SSO invoices");
+ });
+});
diff --git a/apps/web/__tests__/unit/sso-billing.test.ts b/apps/web/__tests__/unit/sso-billing.test.ts
index 511b38cb0..3f018bc8d 100644
--- a/apps/web/__tests__/unit/sso-billing.test.ts
+++ b/apps/web/__tests__/unit/sso-billing.test.ts
@@ -68,6 +68,7 @@ import {
createSsoBillingPortal,
createSsoCheckout,
getSsoPrices,
+ listSsoInvoices,
syncSsoSubscription,
} from "@/lib/sso/billing";
@@ -1209,3 +1210,165 @@ describe("SSO prices and billing management", () => {
expect(mocks.stripe.billingPortal.sessions.create).not.toHaveBeenCalled();
});
});
+
+describe("read-only SSO invoices", () => {
+ beforeEach(() => {
+ state.billing.set(
+ organizationId,
+ billingRow({ stripeSubscriptionId: "sub_sso" }),
+ );
+ mocks.stripe.invoices.list.mockResolvedValue({
+ data: [
+ {
+ ...paidInvoice(),
+ number: "SSO-0001",
+ created: 1788307200,
+ total: 20000,
+ currency: "usd",
+ invoice_pdf: "https://pay.stripe.com/invoice/acct_test/inv_test/pdf",
+ hosted_invoice_url: "https://invoice.stripe.com/pay/inv_test",
+ customer_email: "[email protected]",
+ },
+ ],
+ has_more: false,
+ });
+ });
+
+ it("lists only the linked SSO customer and subscription, preserving separate Pro billing", async () => {
+ state.users.set(userId, {
+ id: userId,
+ stripeCustomerId: "cus_separate_pro",
+ });
+ const billingBefore = structuredClone(state.billing.get(organizationId));
+ expect(await listSsoInvoices(organizationId)).toEqual({
+ invoices: [
+ {
+ id: "in_sso",
+ number: "SSO-0001",
+ created: 1788307200,
+ total: 20000,
+ currency: "usd",
+ status: "paid",
+ pdfUrl: "https://pay.stripe.com/invoice/acct_test/inv_test/pdf",
+ },
+ ],
+ hasMore: false,
+ });
+ expect(mocks.stripe.invoices.list).toHaveBeenCalledWith({
+ customer: "cus_owner",
+ subscription: "sub_sso",
+ limit: 100,
+ });
+ expect(state.billing.get(organizationId)).toEqual(billingBefore);
+ expect(state.users.get(userId)?.stripeCustomerId).toBe("cus_separate_pro");
+ expect(mocks.stripe.billingPortal.sessions.create).not.toHaveBeenCalled();
+ expect(mocks.stripe.checkout.sessions.create).not.toHaveBeenCalled();
+ expect(mocks.stripe.customers.create).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { purchasedByUserId: User.UserId.make("user_old_owner") },
+ { stripeCustomerId: null },
+ { stripeSubscriptionId: null },
+ ])("rejects an untrusted billing mapping: %j", async (overrides) => {
+ state.billing.set(
+ organizationId,
+ billingRow({ stripeSubscriptionId: "sub_sso", ...overrides }),
+ );
+ await expect(listSsoInvoices(organizationId)).rejects.toThrow(
+ "current owner",
+ );
+ expect(mocks.stripe.invoices.list).not.toHaveBeenCalled();
+ });
+
+ it("rejects a missing billing mapping", async () => {
+ state.billing.clear();
+ await expect(listSsoInvoices(organizationId)).rejects.toThrow(
+ "current owner",
+ );
+ expect(mocks.stripe.invoices.list).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ssoSubscription({ customer: "cus_unrelated" }),
+ ssoSubscription({ id: "sub_unrelated" }),
+ proSubscription(),
+ ])("rejects an unrelated Stripe subscription", async (subscription) => {
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(subscription);
+ await expect(listSsoInvoices(organizationId)).rejects.toThrow(
+ "does not match",
+ );
+ expect(mocks.stripe.invoices.list).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { customer: "cus_unrelated" },
+ { subscription: "sub_pro" },
+ { subscription: null },
+ { customer: null },
+ ])("rejects mismatched returned invoice: %j", async (overrides) => {
+ mocks.stripe.invoices.list.mockResolvedValue({
+ data: [{ ...paidInvoice(), ...overrides }],
+ has_more: false,
+ });
+ await expect(listSsoInvoices(organizationId)).rejects.toThrow(
+ "invoices do not match",
+ );
+ });
+
+ it.each([
+ "javascript:alert(1)",
+ "http://pay.stripe.com/invoice/pdf",
+ "https://pay.stripe.com.evil.test/pdf",
+ "https://evil.test/pay.stripe.com/pdf",
+ "https://[email protected]/pdf",
+ "https://user:[email protected]/pdf",
+ "https://pay.stripe.com:8443/pdf",
+ "not a URL",
+ null,
+ undefined,
+ ])("does not expose an unsafe or missing PDF: %s", async (invoicePdf) => {
+ mocks.stripe.invoices.list.mockResolvedValue({
+ data: [
+ {
+ ...paidInvoice(),
+ invoice_pdf: invoicePdf,
+ hosted_invoice_url: "https://invoice.stripe.com/pay/inv_test",
+ },
+ ],
+ has_more: false,
+ });
+ const result = await listSsoInvoices(organizationId);
+ expect(result.invoices[0]?.pdfUrl).toBeNull();
+ });
+
+ it("accepts expanded bindings and Stripe invoice PDF hosts", async () => {
+ mocks.stripe.subscriptions.retrieve.mockResolvedValue(
+ ssoSubscription({ customer: { id: "cus_owner" } as Stripe.Customer }),
+ );
+ mocks.stripe.invoices.list.mockResolvedValue({
+ data: [
+ {
+ ...paidInvoice(),
+ customer: { id: "cus_owner" },
+ subscription: { id: "sub_sso" },
+ invoice_pdf: "https://invoice.stripe.com/i/acct_test/inv_test/pdf",
+ },
+ ],
+ has_more: true,
+ });
+ const result = await listSsoInvoices(organizationId);
+ expect(result.invoices[0]?.pdfUrl).toBe(
+ "https://invoice.stripe.com/i/acct_test/inv_test/pdf",
+ );
+ expect(result.hasMore).toBe(true);
+ });
+
+ it("returns an empty page without changing billing", async () => {
+ mocks.stripe.invoices.list.mockResolvedValue({ data: [], has_more: false });
+ expect(await listSsoInvoices(organizationId)).toEqual({
+ invoices: [],
+ hasMore: false,
+ });
+ });
+});
diff --git a/apps/web/__tests__/unit/sso-card.test.ts b/apps/web/__tests__/unit/sso-card.test.ts
new file mode 100644
index 000000000..b71e5d0ce
--- /dev/null
+++ b/apps/web/__tests__/unit/sso-card.test.ts
@@ -0,0 +1,325 @@
+// @vitest-environment jsdom
+
+import { Organisation } from "@cap/web-domain";
+import { act, type ComponentProps, createElement, type ReactNode } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from "vitest";
+import {
+ getOrganizationSsoInvoices,
+ getOrganizationSsoSettings,
+ manageOrganizationSsoBilling,
+ type OrganizationSsoSettings,
+ openOrganizationSsoPortal,
+ startOrganizationSsoCheckout,
+} from "@/actions/organization/sso";
+import { SsoCard } from "@/app/(org)/dashboard/settings/organization/components/SsoCard";
+
+const mocks = vi.hoisted(() => ({ refresh: vi.fn(), replace: vi.fn() }));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => mocks,
+}));
+vi.mock("hooks/useCurrency", () => ({
+ useCurrency: () => ({ currency: "usd", symbol: "$" }),
+}));
+vi.mock("@/actions/organization/sso", () => ({
+ confirmOrganizationSsoCheckout: vi.fn(),
+ getOrganizationSsoInvoices: vi.fn(),
+ getOrganizationSsoSettings: vi.fn(),
+ manageOrganizationSsoBilling: vi.fn(),
+ openOrganizationSsoPortal: vi.fn(),
+ startOrganizationSsoCheckout: vi.fn(),
+}));
+vi.mock("@cap/ui", async () => {
+ const { createElement } = await import("react");
+ const container = ({ children }: { children?: ReactNode }) =>
+ createElement("div", null, children);
+ return {
+ Card: container,
+ CardDescription: container,
+ CardHeader: container,
+ CardTitle: container,
+ Button: ({
+ children,
+ disabled,
+ onClick,
+ type,
+ spinner,
+ }: ComponentProps<"button"> & { spinner?: boolean }) =>
+ createElement(
+ "button",
+ { disabled, onClick, type, "data-spinner": Boolean(spinner) },
+ children,
+ ),
+ Input: (props: ComponentProps<"input">) => createElement("input", props),
+ };
+});
+
+const organizationId = Organisation.OrganisationId.make("org_sso");
+const settings = (
+ overrides: Partial<OrganizationSsoSettings> = {},
+): OrganizationSsoSettings => ({
+ organizationId,
+ organizationName: "Example Organization",
+ canManageBilling: true,
+ ssoAvailable: true,
+ entitled: true,
+ hasSubscription: true,
+ subscriptionStatus: "active",
+ cancelAtPeriodEnd: false,
+ currentPeriodEnd: null,
+ suggestedDomain: "example.com",
+ prices: [{ currency: "usd", unitAmount: 20000 }],
+ domains: [{ domain: "example.com", state: "verified" }],
+ connection: { name: "Example SSO", state: "active" },
+ signInUrl: "https://cap.test/login?organizationId=org_sso",
+ ...overrides,
+});
+
+const actEnvironment = globalThis as typeof globalThis & {
+ IS_REACT_ACT_ENVIRONMENT?: boolean;
+};
+let root: Root;
+let container: HTMLDivElement;
+const button = (text: string) =>
+ Array.from(container.querySelectorAll("button")).find(
+ (element) => element.textContent === text,
+ );
+const render = async (overrides: Partial<OrganizationSsoSettings> = {}) => {
+ const initialSettings = settings(overrides);
+ await act(async () =>
+ root.render(
+ createElement(SsoCard, {
+ key: initialSettings.organizationId,
+ initialSettings,
+ }),
+ ),
+ );
+};
+
+type InvoiceResult = Awaited<ReturnType<typeof getOrganizationSsoInvoices>>;
+const invoiceResult = (): InvoiceResult => ({
+ invoices: [
+ {
+ id: "in_sso",
+ number: "SSO-0001",
+ created: 1790812800,
+ total: 20000,
+ currency: "usd",
+ status: "paid",
+ pdfUrl: "https://pay.stripe.test/invoice/sso.pdf",
+ },
+ ],
+ hasMore: false,
+});
+
+describe("SSO invoices", () => {
+ beforeAll(() => {
+ actEnvironment.IS_REACT_ACT_ENVIRONMENT = true;
+ });
+ beforeEach(() => {
+ window.history.replaceState(
+ null,
+ "",
+ "/dashboard/settings/organization/security",
+ );
+ vi.mocked(getOrganizationSsoInvoices)
+ .mockReset()
+ .mockResolvedValue(invoiceResult());
+ vi.mocked(getOrganizationSsoSettings)
+ .mockReset()
+ .mockResolvedValue(settings());
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ });
+ afterEach(async () => {
+ await act(async () => root.unmount());
+ document.body.replaceChildren();
+ });
+ afterAll(() => {
+ delete actEnvironment.IS_REACT_ACT_ENVIRONMENT;
+ });
+
+ it.each([
+ { subscriptionStatus: "active", entitled: true, cancelAtPeriodEnd: false },
+ { subscriptionStatus: "active", entitled: true, cancelAtPeriodEnd: true },
+ { subscriptionStatus: "unpaid", entitled: false, cancelAtPeriodEnd: false },
+ {
+ subscriptionStatus: "canceled",
+ entitled: false,
+ cancelAtPeriodEnd: false,
+ },
+ ])(
+ "offers owners billing history for $subscriptionStatus subscriptions, canceling=$cancelAtPeriodEnd",
+ async (overrides) => {
+ await render(overrides);
+ expect(button("View invoices")?.disabled).toBe(false);
+ },
+ );
+
+ it("hides billing from admins while preserving SSO setup", async () => {
+ await render({ canManageBilling: false });
+ expect(button("View invoices")).toBeUndefined();
+ expect(button("Manage SSO")).toBeDefined();
+ });
+
+ it("keeps invoice history available when SSO setup is unavailable", async () => {
+ await render({ ssoAvailable: false });
+ expect(button("View invoices")?.disabled).toBe(false);
+ expect(button("Manage SSO")?.disabled).toBe(true);
+ await act(async () => button("View invoices")?.click());
+ expect(getOrganizationSsoInvoices).toHaveBeenCalledExactlyOnceWith(
+ organizationId,
+ );
+ });
+
+ it("hides billing before an owner has a subscription", async () => {
+ await render({
+ hasSubscription: false,
+ entitled: false,
+ subscriptionStatus: null,
+ });
+ expect(button("View invoices")).toBeUndefined();
+ expect(button("Add SAML SSO · $200.00/month")).toBeDefined();
+ });
+
+ it("loads only invoice PDFs without opening billing, checkout or SSO setup", async () => {
+ await render();
+ expect(getOrganizationSsoInvoices).not.toHaveBeenCalled();
+ const initialUrl = window.location.href;
+ await act(async () => button("View invoices")?.click());
+ expect(getOrganizationSsoInvoices).toHaveBeenCalledExactlyOnceWith(
+ organizationId,
+ );
+ expect(manageOrganizationSsoBilling).not.toHaveBeenCalled();
+ expect(openOrganizationSsoPortal).not.toHaveBeenCalled();
+ expect(startOrganizationSsoCheckout).not.toHaveBeenCalled();
+ expect(window.location.href).toBe(initialUrl);
+ expect(button("View invoices")?.disabled).toBe(false);
+ expect(container.textContent).toContain("SSO-0001");
+ const link = container.querySelector(
+ 'a[href="https://pay.stripe.test/invoice/sso.pdf"]',
+ );
+ expect(link).not.toBeNull();
+ expect(container.textContent).not.toMatch(/Manage (SSO )?subscription/);
+ });
+
+ it("blocks repeated clicks and other actions while invoices load", async () => {
+ let complete: (value: InvoiceResult) => void = () => {};
+ vi.mocked(getOrganizationSsoInvoices).mockReturnValue(
+ new Promise((resolve) => {
+ complete = resolve;
+ }),
+ );
+ await render();
+ const target = button("View invoices");
+ expect(target).toBeDefined();
+ await act(async () => {
+ target?.click();
+ target?.click();
+ });
+ expect(getOrganizationSsoInvoices).toHaveBeenCalledTimes(1);
+ expect(target?.disabled).toBe(true);
+ expect(target?.dataset.spinner).toBe("true");
+ expect(button("Manage SSO")?.disabled).toBe(true);
+ expect(button("Refresh status")?.disabled).toBe(true);
+ await act(async () => complete(invoiceResult()));
+ expect(button("View invoices")?.disabled).toBe(false);
+ expect(button("View invoices")?.dataset.spinner).toBe("false");
+ });
+
+ it("shows an invoice error and allows retry after failure", async () => {
+ vi.mocked(getOrganizationSsoInvoices).mockRejectedValueOnce(
+ new Error("Unavailable"),
+ );
+ await render();
+ await act(async () => button("View invoices")?.click());
+ expect(container.querySelector('[role="alert"]')?.textContent).toBe(
+ "We couldn't load SSO invoices. Please try again or contact support.",
+ );
+ expect(button("View invoices")?.disabled).toBe(false);
+ expect(button("View invoices")?.dataset.spinner).toBe("false");
+ await act(async () => button("View invoices")?.click());
+ expect(getOrganizationSsoInvoices).toHaveBeenCalledTimes(2);
+ expect(container.querySelector('[role="alert"]')).toBeNull();
+ expect(container.textContent).toContain("SSO-0001");
+ });
+
+ it("does not leak a late invoice response after switching organizations", async () => {
+ let complete: (value: InvoiceResult) => void = () => {};
+ vi.mocked(getOrganizationSsoInvoices).mockReturnValueOnce(
+ new Promise((resolve) => {
+ complete = resolve;
+ }),
+ );
+ await render();
+ await act(async () => button("View invoices")?.click());
+ const nextOrganizationId = Organisation.OrganisationId.make("org_another");
+ await render({
+ organizationId: nextOrganizationId,
+ organizationName: "Another Organization",
+ });
+ expect(button("View invoices")?.disabled).toBe(false);
+ expect(container.textContent).not.toContain("SSO-0001");
+ vi.mocked(getOrganizationSsoInvoices).mockResolvedValueOnce({
+ invoices: [],
+ hasMore: false,
+ });
+ await act(async () => button("View invoices")?.click());
+ expect(getOrganizationSsoInvoices).toHaveBeenLastCalledWith(
+ nextOrganizationId,
+ );
+ await act(async () => complete(invoiceResult()));
+ expect(container.textContent).toContain("Another Organization");
+ expect(container.textContent).toContain("No SSO invoices found.");
+ expect(container.textContent).not.toContain("SSO-0001");
+ expect(container.querySelector('a[href*="stripe"]')).toBeNull();
+ });
+
+ it("shows an explicit empty state without billing portal links", async () => {
+ vi.mocked(getOrganizationSsoInvoices).mockResolvedValue({
+ invoices: [],
+ hasMore: false,
+ });
+ await render();
+ await act(async () => button("View invoices")?.click());
+ expect(container.textContent).toMatch(/no .*invoices/i);
+ expect(container.querySelector('a[href*="stripe"]')).toBeNull();
+ });
+
+ it("keeps an invoice without a PDF visible without inventing a download link", async () => {
+ const result = invoiceResult();
+ const invoice = result.invoices[0];
+ if (!invoice) throw new Error("Missing invoice fixture");
+ invoice.pdfUrl = null;
+ vi.mocked(getOrganizationSsoInvoices).mockResolvedValue(result);
+ await render();
+ await act(async () => button("View invoices")?.click());
+ expect(container.textContent).toContain("SSO-0001");
+ expect(container.textContent).toMatch(
+ /PDF.*(unavailable|available|ready)/i,
+ );
+ expect(container.querySelector('a[href*="stripe"]')).toBeNull();
+ });
+
+ it("warns when invoice history exceeds the first 100 results", async () => {
+ vi.mocked(getOrganizationSsoInvoices).mockResolvedValue({
+ ...invoiceResult(),
+ hasMore: true,
+ });
+ await render();
+ await act(async () => button("View invoices")?.click());
+ expect(container.textContent).toContain("100");
+ expect(container.textContent).toMatch(/older|more/i);
+ });
+});
diff --git a/apps/web/__tests__/unit/sso-settings.test.ts b/apps/web/__tests__/unit/sso-settings.test.ts
index b0567b12e..bf58bca41 100644
--- a/apps/web/__tests__/unit/sso-settings.test.ts
+++ b/apps/web/__tests__/unit/sso-settings.test.ts
@@ -10,6 +10,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { getOrganizationSSOData } from "@/actions/organization/get-organization-sso-data";
import {
confirmOrganizationSsoCheckout,
+ getOrganizationSsoInvoices,
getOrganizationSsoSettings,
manageOrganizationSsoBilling,
openOrganizationSsoPortal,
@@ -39,6 +40,7 @@ const mocks = vi.hoisted(() => ({
createSsoCheckout: vi.fn(),
attachSsoCheckout: vi.fn(),
createSsoBillingPortal: vi.fn(),
+ listSsoInvoices: vi.fn(),
setCookie: vi.fn(),
revalidatePath: vi.fn(),
isRateLimited: vi.fn(),
@@ -115,6 +117,7 @@ vi.mock("@/lib/sso/billing", () => ({
createSsoCheckout: mocks.createSsoCheckout,
attachSsoCheckout: mocks.attachSsoCheckout,
createSsoBillingPortal: mocks.createSsoBillingPortal,
+ listSsoInvoices: mocks.listSsoInvoices,
}));
const ORGANIZATION_ID = Organisation.OrganisationId.make("a".repeat(15));
@@ -326,6 +329,7 @@ function makeFixture({
mocks.createSsoBillingPortal.mockResolvedValue(
"https://billing.stripe.test/sso",
);
+ mocks.listSsoInvoices.mockResolvedValue({ invoices: [], hasMore: false });
mocks.isRateLimited.mockResolvedValue(false);
return {
user,
@@ -434,6 +438,7 @@ describe("organization SSO settings authorization", () => {
expect(markup).toContain("Manage SSO");
expect(markup).toContain("Share your SSO sign-in link");
expect(markup).not.toMatch(/Manage (SSO )?subscription/);
+ expect(markup).toContain("View invoices");
if (cancelAtPeriodEnd) {
expect(markup).toContain("scheduled to end on 3 October 2026");
}
@@ -457,6 +462,7 @@ describe("organization SSO settings authorization", () => {
expect(markup).toContain('href="mailto:[email protected]"');
expect(markup).toContain("purchase it again");
expect(markup).not.toMatch(/Manage (SSO )?subscription/);
+ expect(markup).toContain("View invoices");
expect(markup).not.toContain("Add SAML SSO");
});
@@ -526,6 +532,56 @@ describe("organization SSO settings authorization", () => {
expect(mocks.createSsoBillingPortal).not.toHaveBeenCalled();
});
+ it("lets the owner list only their organization SSO invoices", async () => {
+ makeFixture();
+ const result = {
+ invoices: [
+ {
+ id: "in_sso",
+ number: "SSO-0001",
+ created: 1790812800,
+ total: 20000,
+ currency: "usd",
+ status: "paid",
+ pdfUrl: "https://pay.stripe.test/invoice/sso.pdf",
+ },
+ ],
+ hasMore: false,
+ };
+ mocks.listSsoInvoices.mockResolvedValue(result);
+ await expect(getOrganizationSsoInvoices(ORGANIZATION_ID)).resolves.toEqual(
+ result,
+ );
+ expect(mocks.listSsoInvoices).toHaveBeenCalledExactlyOnceWith(
+ ORGANIZATION_ID,
+ );
+ expect(mocks.createSsoBillingPortal).not.toHaveBeenCalled();
+ expect(mocks.createSsoCheckout).not.toHaveBeenCalled();
+ });
+
+ it.each(["admin", "member", "stranger", "forged-owner"] as const)(
+ "denies %s access to invoice history",
+ async (role) => {
+ makeFixture({ role });
+ await expect(
+ getOrganizationSsoInvoices(ORGANIZATION_ID),
+ ).rejects.toThrow();
+ expect(mocks.listSsoInvoices).not.toHaveBeenCalled();
+ },
+ );
+
+ it("rejects invoice requests for another organization or a signed-out user", async () => {
+ makeFixture();
+ await expect(
+ getOrganizationSsoInvoices(OTHER_ORGANIZATION_ID),
+ ).rejects.toThrow("Forbidden");
+ mocks.getCurrentUser.mockResolvedValue(null);
+ await expect(getOrganizationSsoInvoices(ORGANIZATION_ID)).rejects.toThrow(
+ "Unauthorized",
+ );
+ expect(mocks.listSsoInvoices).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);
diff --git a/apps/web/actions/organization/sso.ts b/apps/web/actions/organization/sso.ts
index 1d24af410..65a8e80d0 100644
--- a/apps/web/actions/organization/sso.ts
+++ b/apps/web/actions/organization/sso.ts
@@ -16,6 +16,7 @@ import {
createSsoCheckout,
getSsoBilling,
getSsoPrices,
+ listSsoInvoices,
syncSsoSubscription,
} from "@/lib/sso/billing";
import {
@@ -207,3 +208,10 @@ export async function manageOrganizationSsoBilling(
await requireSsoOwner(organizationId);
return { url: await createSsoBillingPortal(organizationId) };
}
+
+export async function getOrganizationSsoInvoices(
+ organizationId: Organisation.OrganisationId,
+) {
+ await requireSsoOwner(organizationId);
+ return listSsoInvoices(organizationId);
+}
diff --git a/apps/web/app/(org)/dashboard/settings/organization/billing/page.tsx b/apps/web/app/(org)/dashboard/settings/organization/billing/page.tsx
index b8064d86e..473213104 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/billing/page.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/billing/page.tsx
@@ -2,6 +2,7 @@
import { buildEnv } from "@cap/env";
import { Card, CardDescription, CardHeader, CardTitle } from "@cap/ui";
+import Link from "next/link";
import { useDashboardContext } from "@/app/(org)/dashboard/Contexts";
import {
canManageOrganizationBilling,
@@ -31,6 +32,24 @@ export default function BillingAndMembersPage() {
(canManageBilling ? (
<>
<BillingSummaryCard />
+ {activeOrganization && (
+ <Card>
+ <CardHeader>
+ <CardTitle>SAML SSO invoices</CardTitle>
+ <CardDescription>
+ If your organization has an SSO subscription, open its
+ invoices from Security settings.
+ </CardDescription>
+ </CardHeader>
+ <Link
+ href={`/dashboard/settings/organization/security?organizationId=${encodeURIComponent(activeOrganization.organization.id)}`}
+ className="mt-3 inline-block text-sm font-medium underline"
+ prefetch={false}
+ >
+ Open SSO invoices in Security settings
+ </Link>
+ </Card>
+ )}
{activeOrganization?.hasActiveProSeatProvider ? (
<div className="grid gap-6 items-stretch md:grid-cols-2">
<SeatManagementCard />
diff --git a/apps/web/app/(org)/dashboard/settings/organization/components/SsoCard.tsx b/apps/web/app/(org)/dashboard/settings/organization/components/SsoCard.tsx
index 43b2c802b..72d45f1df 100644
--- a/apps/web/app/(org)/dashboard/settings/organization/components/SsoCard.tsx
+++ b/apps/web/app/(org)/dashboard/settings/organization/components/SsoCard.tsx
@@ -22,6 +22,7 @@ import {
import { toast } from "sonner";
import {
confirmOrganizationSsoCheckout,
+ getOrganizationSsoInvoices,
getOrganizationSsoSettings,
type OrganizationSsoSettings,
openOrganizationSsoPortal,
@@ -33,11 +34,13 @@ import {
type SupportedCurrency,
} from "@/utils/currency";
-type SsoAction = "checkout" | "portal" | "refresh" | "confirm";
+type SsoAction = "checkout" | "portal" | "invoices" | "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.",
+ invoices:
+ "We couldn't load SSO invoices. 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.",
@@ -60,6 +63,9 @@ export function SsoCard({
checkoutSessionId ? "confirm" : null,
);
const [error, setError] = useState<string | null>(null);
+ const [invoiceHistory, setInvoiceHistory] = useState<Awaited<
+ ReturnType<typeof getOrganizationSsoInvoices>
+ > | null>(null);
const [isPending, startTransition] = useTransition();
const actionInFlight = useRef(false);
const confirmationStarted = useRef<string | null>(null);
@@ -123,7 +129,12 @@ export function SsoCard({
} catch {
setError(actionErrors[action]);
} finally {
- if (!succeeded || action === "refresh" || action === "confirm") {
+ if (
+ !succeeded ||
+ action === "refresh" ||
+ action === "confirm" ||
+ action === "invoices"
+ ) {
actionInFlight.current = false;
setPendingAction(null);
}
@@ -425,6 +436,86 @@ export function SsoCard({
</p>
)}
+ {settings.canManageBilling && settings.hasSubscription && (
+ <div className="flex flex-col gap-3">
+ <Button
+ type="button"
+ size="sm"
+ variant="gray"
+ className="w-fit"
+ disabled={busy}
+ spinner={pendingAction === "invoices"}
+ onClick={() => {
+ setInvoiceHistory(null);
+ runAction("invoices", async () => {
+ setInvoiceHistory(
+ await getOrganizationSsoInvoices(organizationId),
+ );
+ });
+ }}
+ >
+ View invoices
+ </Button>
+ {invoiceHistory && (
+ <div className="rounded-xl border border-gray-4 p-4">
+ <h3 className="text-sm font-medium text-gray-12">
+ SSO invoices
+ </h3>
+ {invoiceHistory.invoices.length ? (
+ <ul className="mt-3 flex flex-col gap-3">
+ {invoiceHistory.invoices.map((invoice) => (
+ <li
+ key={invoice.id}
+ className="flex flex-wrap items-center justify-between gap-2 text-sm"
+ >
+ <span className="text-gray-11">
+ {invoice.number ?? invoice.id}
+ {" · "}
+ {new Date(invoice.created * 1000).toLocaleDateString(
+ "en-GB",
+ { timeZone: "UTC" },
+ )}
+ </span>
+ {invoice.pdfUrl ? (
+ <a
+ href={invoice.pdfUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="font-medium underline"
+ >
+ Download PDF
+ <span className="sr-only">
+ {" "}
+ for invoice {invoice.number ?? invoice.id}
+ </span>
+ </a>
+ ) : (
+ <span className="text-gray-10">
+ PDF not available yet
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="mt-2 text-sm text-gray-11">
+ No SSO invoices found.
+ </p>
+ )}
+ {invoiceHistory.hasMore && (
+ <p className="mt-3 text-sm text-gray-11">
+ Showing the latest 100 invoices. Contact{" "}
+ <a href="mailto:[email protected]" className="underline">
+ </a>{" "}
+ for older invoices.
+ </p>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+
{isActive && settings.signInUrl && (
<div className="flex flex-col gap-2 rounded-xl border border-gray-4 bg-gray-2 p-4">
<label
diff --git a/apps/web/lib/sso/billing.ts b/apps/web/lib/sso/billing.ts
index 8616a940a..24d1327da 100644
--- a/apps/web/lib/sso/billing.ts
+++ b/apps/web/lib/sso/billing.ts
@@ -820,9 +820,9 @@ export async function createSsoCheckout(
throw new Error("The SAML SSO checkout expired. Refresh before retrying.");
}
-export async function createSsoBillingPortal(
+async function requireSsoBillingAccount(
organizationId: Organisation.OrganisationId,
-): Promise<string> {
+) {
const owner = await getOwner(organizationId);
const record = await getSsoBilling(organizationId);
if (
@@ -838,6 +838,7 @@ export async function createSsoBillingPortal(
record.stripeSubscriptionId,
);
if (
+ subscription.id !== record.stripeSubscriptionId ||
!isSsoSubscription(subscription) ||
stripeId(subscription.customer) !== record.stripeCustomerId
) {
@@ -845,9 +846,83 @@ export async function createSsoBillingPortal(
"The SAML SSO subscription does not match its billing account.",
);
}
+ return {
+ customerId: record.stripeCustomerId,
+ subscriptionId: record.stripeSubscriptionId,
+ };
+}
+
+export async function createSsoBillingPortal(
+ organizationId: Organisation.OrganisationId,
+): Promise<string> {
+ const { customerId } = await requireSsoBillingAccount(organizationId);
const session = await stripe().billingPortal.sessions.create({
- customer: record.stripeCustomerId,
+ customer: customerId,
return_url: billingUrl(organizationId),
});
return session.url;
}
+
+export type SsoInvoices = {
+ invoices: Array<{
+ id: string;
+ number: string | null;
+ created: number;
+ total: number;
+ currency: string;
+ status: Stripe.Invoice.Status | null;
+ pdfUrl: string | null;
+ }>;
+ hasMore: boolean;
+};
+
+function invoicePdfUrl(value: string | null | undefined): string | null {
+ if (!value) return null;
+ try {
+ const url = new URL(value);
+ if (
+ url.protocol !== "https:" ||
+ !["pay.stripe.com", "invoice.stripe.com"].includes(url.hostname) ||
+ url.username ||
+ url.password ||
+ url.port
+ )
+ return null;
+ return url.toString();
+ } catch {
+ return null;
+ }
+}
+
+export async function listSsoInvoices(
+ organizationId: Organisation.OrganisationId,
+): Promise<SsoInvoices> {
+ const { customerId, subscriptionId } =
+ await requireSsoBillingAccount(organizationId);
+ const result = await stripe().invoices.list({
+ customer: customerId,
+ subscription: subscriptionId,
+ limit: 100,
+ });
+ if (
+ result.data.some(
+ (invoice) =>
+ stripeId(invoice.customer) !== customerId ||
+ stripeId(invoice.subscription) !== subscriptionId,
+ )
+ ) {
+ throw new Error("The SAML SSO invoices do not match its billing account.");
+ }
+ return {
+ invoices: result.data.map((invoice) => ({
+ id: invoice.id,
+ number: invoice.number,
+ created: invoice.created,
+ total: invoice.total,
+ currency: invoice.currency,
+ status: invoice.status,
+ pdfUrl: invoicePdfUrl(invoice.invoice_pdf),
+ })),
+ hasMore: result.has_more,
+ };
+}