Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: authenticate and provision organization members with WorkOS

Richie McIlroy95399b579107
diff --git a/apps/web/__tests__/integration/sso-database.test.ts b/apps/web/__tests__/integration/sso-database.test.ts
new file mode 100644
index 000000000..5d4c6ce48
--- /dev/null
+++ b/apps/web/__tests__/integration/sso-database.test.ts
@@ -0,0 +1,348 @@
+import { randomUUID } from "node:crypto";
+import {
+ accounts,
+ organizationInvites,
+ organizationMembers,
+ organizationSso,
+ organizations,
+ users,
+} from "@cap/database/schema";
+import { Organisation, User } from "@cap/web-domain";
+import { and, eq } from "drizzle-orm";
+import { drizzle, type MySql2Database } from "drizzle-orm/mysql2";
+import { createPool, type Pool } from "mysql2/promise";
+import type { Adapter, AdapterUser } from "next-auth/adapters";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { DrizzleAdapter } from "../../../../packages/database/auth/drizzle-adapter";
+import {
+ provisionSsoMembership,
+ type ValidatedSsoIdentity,
+} from "../../../../packages/database/auth/sso";
+
+const fixture = vi.hoisted(() => ({
+ database: undefined as MySql2Database | undefined,
+ stripe: vi.fn(() => {
+ throw new Error("Database integration tests must not call Stripe.");
+ }),
+}));
+
+vi.mock("@cap/database", () => ({
+ db: () => {
+ if (!fixture.database) throw new Error("Test database is not connected.");
+ return fixture.database;
+ },
+}));
+vi.mock("@cap/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@cap/utils")>()),
+ STRIPE_AVAILABLE: () => false,
+ stripe: fixture.stripe,
+}));
+
+const databaseUrl = process.env.CAP_SSO_TEST_DATABASE_URL;
+
+function database() {
+ if (!fixture.database) throw new Error("Test database is not connected.");
+ return fixture.database;
+}
+
+function id() {
+ return randomUUID().replaceAll("-", "").slice(0, 15);
+}
+
+async function makeOrganization() {
+ const ownerId = User.UserId.make(id());
+ const organizationId = Organisation.OrganisationId.make(id());
+ const workosOrganizationId = `org_fixture_${id()}`;
+ await database()
+ .insert(users)
+ .values({
+ id: ownerId,
+ email: `${ownerId}@example.com`,
+ activeOrganizationId: organizationId,
+ });
+ await database().insert(organizations).values({
+ id: organizationId,
+ ownerId,
+ name: "SSO database fixture",
+ workosOrganizationId,
+ });
+ await database()
+ .insert(organizationSso)
+ .values({
+ organizationId,
+ purchasedByUserId: ownerId,
+ stripeCustomerId: `cus_fixture_${id()}`,
+ stripeSubscriptionId: `sub_fixture_${id()}`,
+ status: "active",
+ paidThrough: new Date(Date.now() + 86_400_000),
+ });
+ return { ownerId, organizationId, workosOrganizationId };
+}
+
+async function createIdentity() {
+ const organization = await makeOrganization();
+ const identity: ValidatedSsoIdentity = {
+ organizationId: organization.organizationId,
+ workosOrganizationId: organization.workosOrganizationId,
+ connectionId: `conn_fixture_${id()}`,
+ profileId: `prof_fixture_${id()}`,
+ email: `${id()}@example.com`,
+ };
+ const adapter = DrizzleAdapter(database(), {
+ getSsoIdentity: () => identity,
+ });
+ return { identity, adapter, ...organization };
+}
+
+async function createUser(
+ adapter: Adapter,
+ email: string,
+): Promise<AdapterUser> {
+ if (!adapter.createUser) throw new Error("Missing createUser adapter.");
+ return adapter.createUser({
+ id: "ignored",
+ email,
+ name: "SSO teammate",
+ emailVerified: null,
+ });
+}
+
+async function linkAccount(
+ adapter: Adapter,
+ userId: string,
+ profileId: string,
+) {
+ if (!adapter.linkAccount) throw new Error("Missing linkAccount adapter.");
+ await adapter.linkAccount({
+ userId,
+ type: "oauth",
+ provider: "workos",
+ providerAccountId: profileId,
+ access_token: "fixture-token-must-not-be-persisted",
+ });
+}
+
+describe.runIf(Boolean(databaseUrl))(
+ "SSO with an isolated MySQL database",
+ () => {
+ let pool: Pool | undefined;
+
+ beforeAll(async () => {
+ if (!databaseUrl) throw new Error("Missing isolated test database URL.");
+ const url = new URL(databaseUrl);
+ if (
+ url.protocol !== "mysql:" ||
+ !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) ||
+ !/^\/cap_sso_[a-z0-9_]+$/.test(url.pathname)
+ ) {
+ throw new Error("SSO tests require a session-scoped local database.");
+ }
+ pool = createPool(databaseUrl);
+ fixture.database = drizzle(pool);
+ await database().select().from(organizationSso).limit(1);
+ });
+
+ afterAll(async () => {
+ await pool?.end();
+ fixture.database = undefined;
+ });
+
+ it("serializes concurrent signups and account links without a personal organization", async () => {
+ const { identity, adapter } = await createIdentity();
+ const created = await Promise.all(
+ Array.from({ length: 6 }, () => createUser(adapter, identity.email)),
+ );
+ expect(new Set(created.map((user) => user.id)).size).toBe(1);
+ const first = created[0];
+ if (!first) throw new Error("User was not created.");
+ await Promise.all(
+ created.map((user) =>
+ linkAccount(adapter, user.id, identity.profileId),
+ ),
+ );
+ const linked = await database()
+ .select()
+ .from(accounts)
+ .where(eq(accounts.providerAccountId, identity.profileId));
+ expect(linked).toHaveLength(1);
+ expect(linked[0]?.access_token).toBeNull();
+ expect(
+ await database()
+ .select()
+ .from(organizations)
+ .where(eq(organizations.ownerId, User.UserId.make(first.id))),
+ ).toHaveLength(0);
+ expect(fixture.stripe).not.toHaveBeenCalled();
+ });
+
+ it("accepts duplicate legacy rows but rejects a hidden conflicting account binding", async () => {
+ const { identity, adapter, ownerId } = await createIdentity();
+ const user = await createUser(adapter, identity.email);
+ const userId = User.UserId.make(user.id);
+ await database()
+ .insert(accounts)
+ .values(
+ Array.from({ length: 2 }, () => ({
+ id: id(),
+ userId,
+ type: "oauth",
+ provider: "workos",
+ providerAccountId: identity.profileId,
+ })),
+ );
+ await linkAccount(adapter, userId, identity.profileId);
+ await provisionSsoMembership(userId, identity);
+ await database().insert(accounts).values({
+ id: id(),
+ userId: ownerId,
+ type: "oauth",
+ provider: "workos",
+ providerAccountId: identity.profileId,
+ });
+ await expect(
+ linkAccount(adapter, userId, identity.profileId),
+ ).rejects.toThrow("already linked");
+ await expect(provisionSsoMembership(userId, identity)).rejects.toThrow(
+ "not linked",
+ );
+ expect(
+ await database()
+ .select()
+ .from(accounts)
+ .where(eq(accounts.providerAccountId, identity.profileId)),
+ ).toHaveLength(3);
+ expect(
+ await database()
+ .select()
+ .from(organizationMembers)
+ .where(
+ and(
+ eq(organizationMembers.userId, userId),
+ eq(organizationMembers.organizationId, identity.organizationId),
+ ),
+ ),
+ ).toHaveLength(1);
+ });
+
+ it("makes concurrent repeat logins idempotent and accepts only this organization's invitation", async () => {
+ const { identity, adapter, ownerId } = await createIdentity();
+ const other = await makeOrganization();
+ const user = await createUser(adapter, identity.email);
+ const userId = User.UserId.make(user.id);
+ await linkAccount(adapter, userId, identity.profileId);
+ await database()
+ .insert(organizationInvites)
+ .values([
+ {
+ id: id(),
+ organizationId: identity.organizationId,
+ invitedByUserId: ownerId,
+ invitedEmail: identity.email,
+ role: "member",
+ },
+ {
+ id: id(),
+ organizationId: other.organizationId,
+ invitedByUserId: other.ownerId,
+ invitedEmail: identity.email,
+ role: "member",
+ },
+ ]);
+ await Promise.all(
+ Array.from({ length: 6 }, () =>
+ provisionSsoMembership(userId, identity),
+ ),
+ );
+ const members = await database()
+ .select()
+ .from(organizationMembers)
+ .where(eq(organizationMembers.userId, userId));
+ expect(members).toHaveLength(1);
+ expect(members[0]).toMatchObject({
+ organizationId: identity.organizationId,
+ role: "member",
+ hasProSeat: false,
+ });
+ const invitations = await database()
+ .select()
+ .from(organizationInvites)
+ .where(eq(organizationInvites.invitedEmail, identity.email));
+ expect(
+ invitations.find(
+ (invite) => invite.organizationId === identity.organizationId,
+ )?.status,
+ ).toBe("accepted");
+ expect(
+ invitations.find(
+ (invite) => invite.organizationId === other.organizationId,
+ )?.status,
+ ).toBe("pending");
+ const [updatedUser] = await database()
+ .select()
+ .from(users)
+ .where(eq(users.id, userId));
+ expect(updatedUser).toMatchObject({
+ activeOrganizationId: identity.organizationId,
+ defaultOrgId: identity.organizationId,
+ stripeCustomerId: null,
+ stripeSubscriptionId: null,
+ });
+ expect(updatedUser?.onboarding_completed_at).toBeInstanceOf(Date);
+ });
+
+ it("preserves an existing admin's role, seat and default organization", async () => {
+ const { identity, adapter } = await createIdentity();
+ const other = await makeOrganization();
+ const user = await createUser(adapter, identity.email);
+ const userId = User.UserId.make(user.id);
+ await linkAccount(adapter, userId, identity.profileId);
+ await database().insert(organizationMembers).values({
+ id: id(),
+ organizationId: identity.organizationId,
+ userId,
+ role: "admin",
+ hasProSeat: true,
+ });
+ await database()
+ .update(users)
+ .set({ defaultOrgId: other.organizationId })
+ .where(eq(users.id, userId));
+ await provisionSsoMembership(userId, identity);
+ const [member] = await database()
+ .select()
+ .from(organizationMembers)
+ .where(
+ and(
+ eq(organizationMembers.userId, userId),
+ eq(organizationMembers.organizationId, identity.organizationId),
+ ),
+ );
+ const [updatedUser] = await database()
+ .select()
+ .from(users)
+ .where(eq(users.id, userId));
+ expect(member).toMatchObject({ role: "admin", hasProSeat: true });
+ expect(updatedUser?.defaultOrgId).toBe(other.organizationId);
+ });
+
+ it("rejects a revoked entitlement without partially granting membership", async () => {
+ const { identity, adapter } = await createIdentity();
+ const user = await createUser(adapter, identity.email);
+ const userId = User.UserId.make(user.id);
+ await linkAccount(adapter, userId, identity.profileId);
+ await database()
+ .update(organizationSso)
+ .set({ status: "canceled" })
+ .where(eq(organizationSso.organizationId, identity.organizationId));
+ await expect(provisionSsoMembership(userId, identity)).rejects.toThrow(
+ "no longer available",
+ );
+ expect(
+ await database()
+ .select()
+ .from(organizationMembers)
+ .where(eq(organizationMembers.userId, userId)),
+ ).toHaveLength(0);
+ });
+ },
+);
diff --git a/apps/web/__tests__/unit/auth-options.test.ts b/apps/web/__tests__/unit/auth-options.test.ts
index a6ae03d5a..176befebf 100644
--- a/apps/web/__tests__/unit/auth-options.test.ts
+++ b/apps/web/__tests__/unit/auth-options.test.ts
@@ -1,10 +1,42 @@
import { authOptions } from "@cap/database/auth/auth-options";
+import type {
+ SsoAuthContext,
+ ValidatedSsoIdentity,
+} from "@cap/database/auth/sso";
+import { Organisation } from "@cap/web-domain";
+import type { SQL } from "drizzle-orm";
+import { MySqlDialect } from "drizzle-orm/mysql-core";
+import type { Account, NextAuthOptions } from "next-auth";
+import type { Adapter } from "next-auth/adapters";
import { beforeEach, describe, expect, it, vi } from "vitest";
+type AuthUser = {
+ id: string;
+ name: string;
+ lastName: string | null;
+ email: string;
+ image: string | null;
+ authSessionVersion: number;
+};
+
+const mocks = vi.hoisted(() => ({
+ users: [] as AuthUser[],
+ where: vi.fn(),
+ select: vi.fn(),
+ validate: vi.fn<(...args: unknown[]) => Promise<ValidatedSsoIdentity>>(),
+ provision: vi.fn<(...args: unknown[]) => Promise<void>>(),
+ adapter: vi.fn<
+ (
+ client: unknown,
+ options: { getSsoIdentity: () => ValidatedSsoIdentity | null },
+ ) => Adapter
+ >(() => ({})),
+}));
+
const env = vi.hoisted(() => ({
APPLE_CLIENT_ID: "so.cap.auth",
APPLE_CLIENT_SECRET: "apple-secret",
- CAP_ALLOWED_SIGNUP_DOMAINS: undefined,
+ CAP_ALLOWED_SIGNUP_DOMAINS: undefined as string | undefined,
GOOGLE_CLIENT_ID: "google-client",
GOOGLE_CLIENT_SECRET: "google-secret",
NEXTAUTH_SECRET: "next-auth-secret",
@@ -17,10 +49,89 @@ vi.mock("@cap/env", () => ({
serverEnv: () => env,
}));
+vi.mock("@cap/database", () => ({
+ db: () => ({ select: mocks.select }),
+}));
+
+vi.mock("@cap/database/auth/sso", () => ({
+ validateSsoSignIn: mocks.validate,
+ provisionSsoMembership: mocks.provision,
+}));
+
+vi.mock("../../../../packages/database/auth/drizzle-adapter", () => ({
+ DrizzleAdapter: mocks.adapter,
+}));
+
+const WORKOS_ACCOUNT: Account = {
+ provider: "workos",
+ providerAccountId: "prof_01A",
+ type: "oauth",
+};
+const PROFILE = {
+ id: "prof_01A",
+ organization_id: "org_01A",
+ connection_id: "conn_01A",
+ email: "[email protected]",
+};
+const IDENTITY: ValidatedSsoIdentity = {
+ organizationId: Organisation.OrganisationId.make("cap-org"),
+ workosOrganizationId: PROFILE.organization_id,
+ connectionId: PROFILE.connection_id,
+ profileId: PROFILE.id,
+ email: PROFILE.email,
+};
+const CONTEXT: SsoAuthContext = {
+ actorId: null,
+ intent: {
+ version: 1,
+ organizationId: IDENTITY.organizationId,
+ workosOrganizationId: IDENTITY.workosOrganizationId,
+ connectionId: IDENTITY.connectionId,
+ actorId: null,
+ issuedAt: 1,
+ nonce: "a".repeat(32),
+ },
+};
+const AUTHENTICATED_USER = { id: "authenticated-user", email: PROFILE.email };
+
+function callbacksFor(options: NextAuthOptions) {
+ const signIn = options.callbacks?.signIn;
+ const jwt = options.callbacks?.jwt;
+ if (!signIn || !jwt) throw new Error("Auth callbacks are missing");
+ return { signIn, jwt };
+}
+
describe("authOptions", () => {
beforeEach(() => {
env.APPLE_CLIENT_ID = "so.cap.auth";
env.APPLE_CLIENT_SECRET = "apple-secret";
+ env.WORKOS_CLIENT_ID = "workos-client";
+ env.WORKOS_API_KEY = "workos-secret";
+ env.CAP_ALLOWED_SIGNUP_DOMAINS = undefined;
+ mocks.validate.mockReset().mockResolvedValue(IDENTITY);
+ mocks.provision.mockReset().mockResolvedValue(undefined);
+ mocks.adapter.mockClear();
+ mocks.users = [
+ {
+ ...AUTHENTICATED_USER,
+ name: "Alex",
+ lastName: null,
+ image: null,
+ authSessionVersion: 4,
+ },
+ ];
+ mocks.select.mockReset().mockImplementation(() => ({
+ from: () => ({ where: mocks.where }),
+ }));
+ mocks.where.mockReset().mockImplementation((condition: SQL) => ({
+ limit: async () => {
+ const query = new MySqlDialect().sqlToQuery(condition);
+ const match = /^`users`\.`(id|email)` = \?$/.exec(query.sql);
+ if (!match?.[1]) throw new Error("Unexpected auth-user predicate");
+ const column = match[1] as "id" | "email";
+ return mocks.users.filter((user) => user[column] === query.params[0]);
+ },
+ }));
});
it("enables Apple when both OAuth credentials are configured", () => {
@@ -40,6 +151,17 @@ describe("authOptions", () => {
expect(providers).not.toContain("apple");
});
+ it.each(["WORKOS_CLIENT_ID", "WORKOS_API_KEY"] as const)(
+ "does not offer SSO when %s is missing",
+ (key) => {
+ env[key] = "";
+
+ expect(
+ authOptions().providers.map((provider) => provider.id),
+ ).not.toContain("workos");
+ },
+ );
+
// Without an explicit maxAge next-auth falls back to 24 hours, which is far
// too long for a 6-digit code and contradicts what the OTP email tells users.
it("expires email verification codes after the advertised 10 minutes", () => {
@@ -52,4 +174,205 @@ describe("authOptions", () => {
10 * 60,
);
});
+
+ it("validates the raw WorkOS profile before exposing it to the adapter", async () => {
+ const options = authOptions(CONTEXT);
+ const adapter = options.adapter;
+ const adapterOptions = mocks.adapter.mock.lastCall?.[1];
+ const callbacks = callbacksFor(options);
+ expect(adapter).toBeDefined();
+ expect(adapterOptions?.getSsoIdentity()).toBeNull();
+
+ await expect(
+ callbacks.signIn({
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ profile: PROFILE,
+ }),
+ ).resolves.toBe(true);
+
+ expect(mocks.validate).toHaveBeenCalledWith(
+ PROFILE,
+ WORKOS_ACCOUNT.providerAccountId,
+ CONTEXT,
+ );
+ expect(adapterOptions?.getSsoIdentity()).toEqual(IDENTITY);
+ expect(mocks.provision).not.toHaveBeenCalled();
+ });
+
+ it("rejects failed validation without retaining an adapter identity", async () => {
+ const options = authOptions(CONTEXT);
+ const callbacks = callbacksFor(options);
+ const adapter = options.adapter;
+ const adapterOptions = mocks.adapter.mock.lastCall?.[1];
+ expect(adapter).toBeDefined();
+ await callbacks.signIn({
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ profile: PROFILE,
+ });
+ mocks.validate.mockRejectedValueOnce(new Error("Connection unavailable"));
+
+ await expect(
+ callbacks.signIn({
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ profile: PROFILE,
+ }),
+ ).resolves.toBe("/login?error=SsoSignInFailed");
+
+ expect(adapterOptions?.getSsoIdentity()).toBeNull();
+ expect(mocks.provision).not.toHaveBeenCalled();
+ });
+
+ it("does not provision membership without a successful signIn callback", async () => {
+ const callbacks = callbacksFor(authOptions(CONTEXT));
+
+ await expect(
+ callbacks.jwt({
+ token: { id: "old-user", email: PROFILE.email },
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ }),
+ ).rejects.toThrow("not verified");
+
+ expect(mocks.provision).not.toHaveBeenCalled();
+ expect(mocks.select).not.toHaveBeenCalled();
+ });
+
+ it("preserves the signed mobile continuation when SSO validation fails", async () => {
+ if (!CONTEXT.intent) throw new Error("Missing fixture intent");
+ const returnTo = "/api/mobile/session/request?redirectUri=cap%3A%2F%2Fauth";
+ const callbacks = callbacksFor(
+ authOptions({
+ ...CONTEXT,
+ intent: { ...CONTEXT.intent, returnTo },
+ }),
+ );
+ mocks.validate.mockRejectedValueOnce(new Error("SSO was canceled"));
+
+ const result = await callbacks.signIn({
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ profile: PROFILE,
+ });
+
+ if (typeof result !== "string") throw new Error("Missing error redirect");
+ const redirect = new URL(result, "https://cap.example");
+ expect(redirect.pathname).toBe("/login");
+ expect(redirect.searchParams.get("error")).toBe("SsoSignInFailed");
+ expect(redirect.searchParams.get("next")).toBe(returnTo);
+ expect(mocks.provision).not.toHaveBeenCalled();
+ });
+
+ it("does not share validation between separate authOptions instances", async () => {
+ const first = callbacksFor(authOptions(CONTEXT));
+ const second = callbacksFor(authOptions(CONTEXT));
+ await first.signIn({
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ profile: PROFILE,
+ });
+
+ await expect(
+ second.jwt({
+ token: { id: "old-user", email: PROFILE.email },
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ }),
+ ).rejects.toThrow("not verified");
+ expect(mocks.provision).not.toHaveBeenCalled();
+ });
+
+ it("awaits membership provisioning before resolving a session token", async () => {
+ const callbacks = callbacksFor(authOptions(CONTEXT));
+ await callbacks.signIn({
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ profile: PROFILE,
+ });
+ let release: (() => void) | undefined;
+ mocks.provision.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ release = resolve;
+ }),
+ );
+
+ const pending = callbacks.jwt({
+ token: { id: "old-user", email: PROFILE.email },
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ });
+ expect(mocks.provision).toHaveBeenCalledWith(
+ AUTHENTICATED_USER.id,
+ IDENTITY,
+ );
+ expect(mocks.select).not.toHaveBeenCalled();
+ if (!release) throw new Error("Provisioning was not started");
+ release();
+ await expect(pending).resolves.toMatchObject({ id: AUTHENTICATED_USER.id });
+ });
+
+ it("does not resolve a token when membership provisioning fails", async () => {
+ const callbacks = callbacksFor(authOptions(CONTEXT));
+ await callbacks.signIn({
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ profile: PROFILE,
+ });
+ mocks.provision.mockRejectedValueOnce(new Error("SSO billing revoked"));
+
+ await expect(
+ callbacks.jwt({
+ token: { id: "old-user", email: PROFILE.email },
+ user: AUTHENTICATED_USER,
+ account: WORKOS_ACCOUNT,
+ }),
+ ).rejects.toThrow("SSO billing revoked");
+ expect(mocks.select).not.toHaveBeenCalled();
+ });
+
+ it.each(["workos", "google", "apple"])(
+ "anchors %s tokens to the authenticated user ID instead of token email",
+ async (provider) => {
+ const callbacks = callbacksFor(authOptions(CONTEXT));
+ const account = { ...WORKOS_ACCOUNT, provider };
+ mocks.users.push({
+ id: "wrong-email-user",
+ email: "[email protected]",
+ name: "Wrong identity",
+ lastName: null,
+ image: null,
+ authSessionVersion: 9,
+ });
+ await callbacks.signIn({
+ user: AUTHENTICATED_USER,
+ account,
+ profile: PROFILE,
+ });
+
+ const token = await callbacks.jwt({
+ token: {
+ id: "old-user",
+ email: "[email protected]",
+ sub: "provider-sub",
+ },
+ user: AUTHENTICATED_USER,
+ account,
+ });
+
+ expect(token).toMatchObject({
+ id: AUTHENTICATED_USER.id,
+ email: AUTHENTICATED_USER.email,
+ name: "Alex",
+ sessionVersion: 4,
+ });
+ expect(token.sub).toBeUndefined();
+ if (provider !== "workos") {
+ expect(mocks.validate).not.toHaveBeenCalled();
+ expect(mocks.provision).not.toHaveBeenCalled();
+ }
+ },
+ );
});
diff --git a/apps/web/__tests__/unit/mobile-api-contract.test.ts b/apps/web/__tests__/unit/mobile-api-contract.test.ts
index 131d2399a..39bb49dc7 100644
--- a/apps/web/__tests__/unit/mobile-api-contract.test.ts
+++ b/apps/web/__tests__/unit/mobile-api-contract.test.ts
@@ -212,6 +212,66 @@ describe("mobile API contract schemas", () => {
expect(continuationUrl.searchParams.get("redirectUri")).toBe(redirectUri);
});
+ it.each(["[email protected]", "example.com", "aaaaaaaaaaaaaaa"])(
+ "consumes the SSO choice for %s while preserving the mobile callback",
+ (organizationId) => {
+ const requestUrl = new URL(
+ "https://incoming.test/api/mobile/session/request",
+ );
+ requestUrl.searchParams.set("provider", "workos");
+ requestUrl.searchParams.set("organizationId", organizationId);
+ requestUrl.searchParams.set("redirectUri", "cap://auth");
+ requestUrl.searchParams.set("type", "api_key");
+ const loginRedirectUrl = Mobile.createMobileSessionLoginRedirectUrl({
+ deploymentOrigin: "https://cap.so",
+ requestUrl: requestUrl.toString(),
+ provider: "workos",
+ organizationId,
+ });
+ const continuationUrl = new URL(
+ loginRedirectUrl.searchParams.get("next") ?? "",
+ );
+
+ expect(loginRedirectUrl.origin).toBe("https://cap.so");
+ expect(loginRedirectUrl.searchParams.get("mobileProvider")).toBe(
+ "workos",
+ );
+ expect(loginRedirectUrl.searchParams.get("organizationId")).toBe(
+ organizationId,
+ );
+ expect(continuationUrl.origin).toBe("https://cap.so");
+ expect(continuationUrl.pathname).toBe("/api/mobile/session/request");
+ expect(Array.from(continuationUrl.searchParams)).toEqual([
+ ["redirectUri", "cap://auth"],
+ ["type", "api_key"],
+ ]);
+ expect(
+ Schema.decodeUnknownSync(Mobile.MobileSessionRequestParams)(
+ Object.fromEntries(continuationUrl.searchParams),
+ ),
+ ).toEqual({ redirectUri: "cap://auth" });
+ },
+ );
+
+ it("preserves the Expo callback when SSO starts without an organization identifier", () => {
+ const redirectUri =
+ "exp+cap://expo-development-client/?url=http%3A%2F%2F127.0.0.1%3A8081%2F--%2Fauth";
+ const loginRedirectUrl = Mobile.createMobileSessionLoginRedirectUrl({
+ deploymentOrigin: "http://localhost:3000",
+ requestUrl: `/api/mobile/session/request?provider=workos&redirectUri=${encodeURIComponent(redirectUri)}`,
+ provider: "workos",
+ });
+ const continuationUrl = new URL(
+ loginRedirectUrl.searchParams.get("next") ?? "",
+ );
+
+ expect(loginRedirectUrl.searchParams.get("mobileProvider")).toBe("workos");
+ expect(loginRedirectUrl.searchParams.has("organizationId")).toBe(false);
+ expect(continuationUrl.toString()).toBe(
+ `http://localhost:3000/api/mobile/session/request?redirectUri=${encodeURIComponent(redirectUri)}`,
+ );
+ });
+
it("allows only mobile auth callback redirects for session requests", () => {
const decodeRedirect = (redirectUri: string) =>
Schema.decodeUnknownSync(Mobile.MobileSessionRequestParams)({
diff --git a/apps/web/__tests__/unit/onboarding-organization-authorization.test.ts b/apps/web/__tests__/unit/onboarding-organization-authorization.test.ts
new file mode 100644
index 000000000..d1029fc48
--- /dev/null
+++ b/apps/web/__tests__/unit/onboarding-organization-authorization.test.ts
@@ -0,0 +1,428 @@
+import * as Db from "@cap/database/schema";
+import {
+ CurrentUser,
+ DatabaseError,
+ ImageUpload,
+ Organisation,
+ User,
+} from "@cap/web-domain";
+import type { SQL } from "drizzle-orm";
+import {
+ type AnyMySqlColumn,
+ MySqlDialect,
+ type MySqlTable,
+} from "drizzle-orm/mysql-core";
+import { Effect, Option } from "effect";
+import { describe, expect, it } from "vitest";
+import {
+ Database,
+ type DbClient,
+} from "../../../../packages/web-backend/src/Database";
+import { ImageUploads } from "../../../../packages/web-backend/src/ImageUploads";
+import { UsersOnboarding } from "../../../../packages/web-backend/src/Users/UsersOnboarding";
+
+const USER_ID = User.UserId.make("onboarding-user");
+const OTHER_USER_ID = User.UserId.make("different-owner");
+const ORGANIZATION_ID = Organisation.OrganisationId.make("sso-org");
+const DEFAULT_ORGANIZATION_ID =
+ Organisation.OrganisationId.make("personal-org");
+const ICON_KEY = ImageUpload.ImageKey.make("organizations/onboarding-icon.png");
+const ICON = {
+ data: new Uint8Array([1, 2, 3]),
+ contentType: "image/png",
+ fileName: "icon.png",
+};
+
+type Row = Record<string, unknown>;
+
+function matchesRow(condition: SQL | undefined, row: Row) {
+ if (!condition) return true;
+ const query = new MySqlDialect().sqlToQuery(condition);
+ let parameterIndex = 0;
+ return query.sql
+ .replaceAll("(", "")
+ .replaceAll(")", "")
+ .split(" and ")
+ .every((clause) => {
+ const match = /^`[^`]+`\.`([^`]+)`( = \?| is null)$/.exec(clause);
+ if (!match?.[1]) throw new Error(`Unsupported predicate: ${clause}`);
+ return match[2] === " is null"
+ ? row[match[1]] == null
+ : row[match[1]] === query.params[parameterIndex++];
+ });
+}
+
+function makeFixture(
+ options: {
+ user?: Partial<
+ Pick<
+ typeof Db.users.$inferSelect,
+ "activeOrganizationId" | "defaultOrgId" | "name" | "onboardingSteps"
+ >
+ >;
+ organization?: Partial<
+ Pick<
+ typeof Db.organizations.$inferSelect,
+ "name" | "ownerId" | "tombstoneAt"
+ >
+ >;
+ organizationExists?: boolean;
+ sessionOrganizationId?: Organisation.OrganisationId;
+ } = {},
+) {
+ const user: Row = {
+ id: USER_ID,
+ email: "[email protected]",
+ name: "Member",
+ activeOrganizationId: ORGANIZATION_ID,
+ defaultOrgId: DEFAULT_ORGANIZATION_ID,
+ onboardingSteps: { welcome: true, inviteTeam: true },
+ ...options.user,
+ };
+ const organization: Row = {
+ id: ORGANIZATION_ID,
+ name: "Company",
+ ownerId: OTHER_USER_ID,
+ tombstoneAt: null,
+ iconUrl: null,
+ ...options.organization,
+ };
+ const organizations =
+ options.organizationExists === false ? [] : [organization];
+ const memberships: Row[] = [];
+ const tables = new Map<MySqlTable, Row[]>([
+ [Db.users, [user]],
+ [Db.organizations, organizations],
+ [Db.organizationMembers, memberships],
+ ]);
+ const hooks: {
+ beforeOrganizationUpdate?: (patch: Row) => void;
+ beforeIconUpdate?: () => void;
+ } = {};
+ const uploadedPrefixes: string[] = [];
+ const rowsFor = (table: MySqlTable) => {
+ const rows = tables.get(table);
+ if (!rows) throw new Error("Unexpected table");
+ return rows;
+ };
+ const database = {
+ select: (columns?: Record<string, AnyMySqlColumn>) => ({
+ from: (table: MySqlTable) => ({
+ where: async (condition: SQL | undefined) =>
+ rowsFor(table)
+ .filter((row) => matchesRow(condition, row))
+ .map((row) =>
+ columns
+ ? Object.fromEntries(
+ Object.entries(columns).map(([key, column]) => [
+ key,
+ row[column.name],
+ ]),
+ )
+ : { ...row },
+ ),
+ }),
+ }),
+ update: (table: MySqlTable) => ({
+ set: (patch: Row) => ({
+ where: async (condition: SQL | undefined) => {
+ if (table === Db.organizations)
+ hooks.beforeOrganizationUpdate?.(patch);
+ for (const row of rowsFor(table)) {
+ if (matchesRow(condition, row)) Object.assign(row, patch);
+ }
+ },
+ }),
+ }),
+ insert: (table: MySqlTable) => ({
+ values: async (row: Row) => {
+ rowsFor(table).push({ tombstoneAt: null, ...row });
+ },
+ }),
+ transaction: <T>(callback: (client: DbClient) => Promise<T>) =>
+ callback(database as unknown as DbClient),
+ };
+ const databaseService = Database.make({
+ use: (callback) =>
+ Effect.tryPromise({
+ try: () => callback(database as unknown as DbClient),
+ catch: (cause) => new DatabaseError({ cause }),
+ }),
+ });
+ const imageUploads = ImageUploads.make({
+ applyUpdate: (args) =>
+ Effect.gen(function* () {
+ uploadedPrefixes.push(args.keyPrefix);
+ hooks.beforeIconUpdate?.();
+ yield* databaseService.use((client) => args.update(client, ICON_KEY));
+ }),
+ resolveImageUrl: () =>
+ Effect.succeed(ImageUpload.ImageUrl.make("https://example.com/icon.png")),
+ });
+
+ return {
+ user,
+ organization,
+ organizations,
+ memberships,
+ hooks,
+ uploadedPrefixes,
+ run: <A, E>(
+ operation: (service: UsersOnboarding) => Effect.Effect<A, E, CurrentUser>,
+ ) =>
+ Effect.runPromise(
+ Effect.flatMap(UsersOnboarding, operation).pipe(
+ Effect.provide(UsersOnboarding.DefaultWithoutDependencies),
+ Effect.provideService(Database, databaseService),
+ Effect.provideService(ImageUploads, imageUploads),
+ Effect.provideService(CurrentUser, {
+ id: USER_ID,
+ email: "[email protected]",
+ activeOrganizationId:
+ options.sessionOrganizationId ?? ORGANIZATION_ID,
+ iconUrlOrKey: Option.none(),
+ }),
+ ),
+ ),
+ };
+}
+
+describe("onboarding organization authorization", () => {
+ it("lets members complete setup without changing organization metadata or their default", async () => {
+ const fixture = makeFixture();
+
+ const result = await fixture.run((service) =>
+ service.organizationSetup({
+ organizationName: "Replacement",
+ organizationIcon: ICON,
+ }),
+ );
+
+ expect(result).toEqual({ organizationId: ORGANIZATION_ID });
+ expect(fixture.organization).toMatchObject({
+ name: "Company",
+ iconUrl: null,
+ });
+ expect(fixture.user).toMatchObject({
+ activeOrganizationId: ORGANIZATION_ID,
+ defaultOrgId: DEFAULT_ORGANIZATION_ID,
+ onboardingSteps: {
+ welcome: true,
+ inviteTeam: true,
+ organizationSetup: true,
+ },
+ });
+ expect(fixture.uploadedPrefixes).toEqual([]);
+ expect(fixture.organizations).toHaveLength(1);
+ expect(fixture.memberships).toEqual([]);
+ });
+
+ it("preserves owner name and icon setup", async () => {
+ const fixture = makeFixture({ organization: { ownerId: USER_ID } });
+
+ await fixture.run((service) =>
+ service.organizationSetup({
+ organizationName: " New Company ",
+ organizationIcon: ICON,
+ }),
+ );
+
+ expect(fixture.organization).toMatchObject({
+ name: "New Company",
+ iconUrl: ICON_KEY,
+ });
+ expect(fixture.user.defaultOrgId).toBe(ORGANIZATION_ID);
+ expect(fixture.uploadedPrefixes).toEqual([
+ `organizations/${ORGANIZATION_ID}`,
+ ]);
+ });
+
+ it.each([
+ {
+ ownerId: USER_ID,
+ tombstoneAt: null,
+ expectedName: "Jane's Organization",
+ },
+ {
+ ownerId: OTHER_USER_ID,
+ tombstoneAt: null,
+ expectedName: "My Organization",
+ },
+ {
+ ownerId: USER_ID,
+ tombstoneAt: new Date("2026-09-01T00:00:00.000Z"),
+ expectedName: "My Organization",
+ },
+ ])(
+ "personalizes only a live owner's organization ($ownerId, $tombstoneAt)",
+ async (scenario) => {
+ const fixture = makeFixture({
+ organization: {
+ name: "My Organization",
+ ownerId: scenario.ownerId,
+ tombstoneAt: scenario.tombstoneAt,
+ },
+ });
+
+ await fixture.run((service) =>
+ service.welcome({ firstName: " Jane ", lastName: " Doe " }),
+ );
+
+ expect(fixture.organization.name).toBe(scenario.expectedName);
+ expect(fixture.user).toMatchObject({
+ name: "Jane",
+ lastName: "Doe",
+ onboardingSteps: { welcome: true, inviteTeam: true },
+ });
+ },
+ );
+
+ it("preserves an owner's already configured name during welcome", async () => {
+ const fixture = makeFixture({ organization: { ownerId: USER_ID } });
+
+ await fixture.run((service) => service.welcome({ firstName: "Jane" }));
+
+ expect(fixture.organization.name).toBe("Company");
+ });
+
+ it("does not mutate or replace a tombstoned organization during setup", async () => {
+ const fixture = makeFixture({
+ organization: { ownerId: USER_ID, tombstoneAt: new Date() },
+ });
+
+ await fixture.run((service) =>
+ service.organizationSetup({
+ organizationName: "Replacement",
+ organizationIcon: ICON,
+ }),
+ );
+
+ expect(fixture.organization).toMatchObject({
+ name: "Company",
+ iconUrl: null,
+ });
+ expect(fixture.user.defaultOrgId).toBe(DEFAULT_ORGANIZATION_ID);
+ expect(fixture.user.onboardingSteps).toMatchObject({
+ organizationSetup: true,
+ });
+ expect(fixture.uploadedPrefixes).toEqual([]);
+ expect(fixture.organizations).toHaveLength(1);
+ });
+
+ it.each(["ownership", "deletion"] as const)(
+ "rechecks %s when applying the organization name",
+ async (change) => {
+ const fixture = makeFixture({ organization: { ownerId: USER_ID } });
+ fixture.hooks.beforeOrganizationUpdate = () => {
+ if (change === "ownership")
+ fixture.organization.ownerId = OTHER_USER_ID;
+ else fixture.organization.tombstoneAt = new Date();
+ };
+
+ await fixture.run((service) =>
+ service.organizationSetup({
+ organizationName: "Replacement",
+ organizationIcon: ICON,
+ }),
+ );
+
+ expect(fixture.organization).toMatchObject({
+ name: "Company",
+ iconUrl: null,
+ });
+ expect(fixture.uploadedPrefixes).toEqual([]);
+ },
+ );
+
+ it.each(["ownership", "deletion"] as const)(
+ "rechecks %s after the icon upload",
+ async (change) => {
+ const fixture = makeFixture({ organization: { ownerId: USER_ID } });
+ fixture.hooks.beforeIconUpdate = () => {
+ if (change === "ownership")
+ fixture.organization.ownerId = OTHER_USER_ID;
+ else fixture.organization.tombstoneAt = new Date();
+ };
+
+ await fixture.run((service) =>
+ service.organizationSetup({
+ organizationName: "Owner's Update",
+ organizationIcon: ICON,
+ }),
+ );
+
+ expect(fixture.organization).toMatchObject({
+ name: "Owner's Update",
+ iconUrl: null,
+ });
+ expect(fixture.uploadedPrefixes).toHaveLength(1);
+ },
+ );
+
+ it("creates an owned organization for a user without one", async () => {
+ const fixture = makeFixture({
+ organizationExists: false,
+ user: {
+ activeOrganizationId: Organisation.OrganisationId.make(""),
+ defaultOrgId: null,
+ },
+ });
+
+ const result = await fixture.run((service) =>
+ service.organizationSetup({
+ organizationName: "New Company",
+ organizationIcon: ICON,
+ }),
+ );
+
+ expect(fixture.organizations).toEqual([
+ expect.objectContaining({
+ id: result.organizationId,
+ name: "New Company",
+ ownerId: USER_ID,
+ iconUrl: ICON_KEY,
+ }),
+ ]);
+ expect(fixture.memberships).toEqual([
+ expect.objectContaining({
+ organizationId: result.organizationId,
+ userId: USER_ID,
+ role: "owner",
+ }),
+ ]);
+ expect(fixture.user).toMatchObject({
+ activeOrganizationId: result.organizationId,
+ defaultOrgId: result.organizationId,
+ });
+ });
+
+ it.each(["active", "default"] as const)(
+ "uses a member's stored %s organization when skipping onboarding",
+ async (source) => {
+ const fixture = makeFixture({
+ sessionOrganizationId:
+ Organisation.OrganisationId.make("stale-session-org"),
+ user:
+ source === "default"
+ ? {
+ activeOrganizationId: Organisation.OrganisationId.make(""),
+ defaultOrgId: ORGANIZATION_ID,
+ }
+ : {},
+ });
+
+ await fixture.run((service) => service.skipToDashboard());
+
+ expect(fixture.organizations).toHaveLength(1);
+ expect(fixture.organization.name).toBe("Company");
+ expect(fixture.memberships).toEqual([]);
+ expect(fixture.user.defaultOrgId).toBe(
+ source === "default" ? ORGANIZATION_ID : DEFAULT_ORGANIZATION_ID,
+ );
+ expect(fixture.user.onboardingSteps).toMatchObject({
+ organizationSetup: true,
+ download: true,
+ });
+ },
+ );
+});
diff --git a/apps/web/__tests__/unit/sso-auth-route.test.ts b/apps/web/__tests__/unit/sso-auth-route.test.ts
new file mode 100644
index 000000000..82a19cf5e
--- /dev/null
+++ b/apps/web/__tests__/unit/sso-auth-route.test.ts
@@ -0,0 +1,432 @@
+import type { SsoAuthContext } from "@cap/database/auth/sso";
+import {
+ createSsoLoginIntent,
+ SSO_INTENT_MAX_AGE,
+ ssoIntentCookie,
+ verifySsoLoginIntent,
+} from "@cap/database/auth/sso-state";
+import { NextRequest } from "next/server";
+import type { NextAuthOptions } from "next-auth";
+import type { JWT } from "next-auth/jwt";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { GET, POST } from "@/app/api/auth/[...nextauth]/route";
+
+type RouteContext = { params: Promise<{ nextauth: string[] }> };
+
+const mocks = vi.hoisted(() => ({
+ authOptions: vi.fn<(context?: SsoAuthContext) => NextAuthOptions>(() => ({
+ providers: [],
+ })),
+ decode: vi.fn(),
+ getToken: vi.fn<() => Promise<JWT | null>>(),
+ nextAuth:
+ vi.fn<
+ (
+ request: NextRequest,
+ context: RouteContext,
+ options: NextAuthOptions,
+ ) => Promise<Response>
+ >(),
+}));
+
+const env = vi.hoisted(() => ({
+ WEB_URL: "https://cap.example",
+ NEXTAUTH_SECRET: "test-sso-route-secret-with-sufficient-entropy",
+}));
+
+vi.mock("@cap/env", () => ({ serverEnv: () => env }));
+vi.mock("@cap/database/auth/auth-options", () => ({
+ authOptions: mocks.authOptions,
+ decodeSessionToken: mocks.decode,
+}));
+vi.mock("next-auth", () => ({ default: mocks.nextAuth }));
+vi.mock("next-auth/jwt", () => ({ getToken: mocks.getToken }));
+
+const RETURN_TO = "/api/mobile/session/request?redirectUri=cap%3A%2F%2Fauth";
+const INTENT = {
+ organizationId: "caporganization",
+ workosOrganizationId: "org_verified",
+ connectionId: "conn_verified",
+ actorId: null,
+ returnTo: RETURN_TO,
+};
+
+function makeRequest(
+ options: {
+ action?: "signin" | "callback";
+ provider?: string;
+ method?: "GET" | "POST";
+ intent?: string | null;
+ body?: string | URLSearchParams;
+ contentType?: string;
+ callbackCookie?: string;
+ query?: Record<string, string> | URLSearchParams;
+ } = {},
+) {
+ const action = options.action ?? "signin";
+ const provider = options.provider ?? "workos";
+ const method = options.method ?? (action === "callback" ? "GET" : "POST");
+ const url = new URL(`/api/auth/${action}/${provider}`, env.WEB_URL);
+ if (options.query) {
+ url.search = new URLSearchParams(options.query).toString();
+ } else if (action === "signin") {
+ url.searchParams.set("connection", INTENT.connectionId);
+ }
+ const intent =
+ options.intent === undefined
+ ? createSsoLoginIntent(INTENT, env.NEXTAUTH_SECRET)
+ : options.intent;
+ const cookieName = ssoIntentCookie(true).name;
+ const cookies = [
+ ...(intent ? [`${cookieName}=${intent}`] : []),
+ ...(options.callbackCookie
+ ? [`next-auth.callback-url=${encodeURIComponent(options.callbackCookie)}`]
+ : []),
+ ];
+ const headers = new Headers({ cookie: cookies.join("; ") });
+ if (method === "POST") {
+ headers.set(
+ "content-type",
+ options.contentType ?? "application/x-www-form-urlencoded",
+ );
+ }
+ const request = new NextRequest(url, {
+ method,
+ headers,
+ body:
+ method === "POST"
+ ? (options.body ??
+ new URLSearchParams({
+ json: "true",
+ callbackUrl: RETURN_TO,
+ csrfToken: "fixture-csrf-token",
+ }))
+ : undefined,
+ });
+ const context: RouteContext = {
+ params: Promise.resolve({ nextauth: [action, provider] }),
+ };
+ return { request, context, intent };
+}
+
+async function errorUrl(response: Response) {
+ if (response.headers.get("content-type")?.includes("application/json")) {
+ const body = (await response.json()) as { url: string };
+ return new URL(body.url);
+ }
+ return new URL(response.headers.get("location") ?? "");
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getToken.mockReset().mockResolvedValue(null);
+ mocks.nextAuth.mockReset().mockImplementation(async () => {
+ return new Response(null, {
+ status: 302,
+ headers: {
+ location: "/dashboard",
+ "set-cookie": "next-auth.session-token=verified-session; Path=/",
+ },
+ });
+ });
+});
+
+describe("SSO auth request boundary", () => {
+ it.each(["missing", "tampered", "expired"])(
+ "returns a JSON sign-in error for a %s intent without calling NextAuth",
+ async (reason) => {
+ const intent =
+ reason === "missing"
+ ? null
+ : reason === "tampered"
+ ? "tampered.invalid-signature"
+ : createSsoLoginIntent(
+ INTENT,
+ env.NEXTAUTH_SECRET,
+ Date.now() - (SSO_INTENT_MAX_AGE + 1) * 1000,
+ );
+ const { request, context } = makeRequest({ intent });
+
+ const response = await POST(request, context);
+ const redirect = await errorUrl(response);
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("location")).toBeNull();
+ expect(redirect.origin).toBe(env.WEB_URL);
+ expect(redirect.pathname).toBe("/login");
+ expect(redirect.searchParams.get("error")).toBe("SsoSessionExpired");
+ expect(redirect.searchParams.get("next")).toBe(RETURN_TO);
+ expect(response.headers.get("set-cookie")).toContain("Max-Age=0");
+ expect(mocks.nextAuth).not.toHaveBeenCalled();
+ expect(mocks.authOptions).not.toHaveBeenCalled();
+ expect(request.bodyUsed).toBe(false);
+ },
+ );
+
+ it("supports the JSON body contract without consuming the request", async () => {
+ const { request, context } = makeRequest({
+ intent: null,
+ contentType: "application/json",
+ body: JSON.stringify({ json: "true", callbackUrl: RETURN_TO }),
+ });
+
+ const response = await POST(request, context);
+
+ expect(response.headers.get("content-type")).toContain("application/json");
+ expect((await errorUrl(response)).searchParams.get("next")).toBe(RETURN_TO);
+ expect(request.bodyUsed).toBe(false);
+ });
+
+ it.each([
+ "https://attacker.example/steal",
+ "//attacker.example/steal",
+ "/\\attacker.example/steal",
+ "https://cap.example//attacker.example/steal",
+ ])("does not preserve an unsafe callback URL %s", async (callbackUrl) => {
+ const { request, context } = makeRequest({
+ intent: null,
+ body: new URLSearchParams({ json: "true", callbackUrl }),
+ });
+
+ const redirect = await errorUrl(await POST(request, context));
+
+ expect(redirect.origin).toBe(env.WEB_URL);
+ expect(redirect.searchParams.get("next")).toBeNull();
+ });
+
+ it("uses a 303 redirect for a document form instead of replaying its POST", async () => {
+ const { request, context } = makeRequest({
+ intent: null,
+ body: new URLSearchParams({ callbackUrl: RETURN_TO }),
+ });
+
+ const response = await POST(request, context);
+
+ expect(response.status).toBe(303);
+ expect((await errorUrl(response)).searchParams.get("next")).toBe(RETURN_TO);
+ });
+
+ it("handles malformed JSON as a failed document request", async () => {
+ const { request, context } = makeRequest({
+ intent: null,
+ contentType: "application/json",
+ body: "{malformed",
+ });
+
+ const response = await POST(request, context);
+
+ expect(response.status).toBe(303);
+ expect((await errorUrl(response)).searchParams.get("next")).toBeNull();
+ expect(mocks.nextAuth).not.toHaveBeenCalled();
+ });
+
+ it.each<Record<string, string>>([
+ {},
+ { connection: "" },
+ { organization: INTENT.workosOrganizationId },
+ { organization: "org_other" },
+ { connection: "conn_other" },
+ ])("rejects a missing or changed connection selector %j", async (query) => {
+ const { request, context } = makeRequest({ query });
+
+ const response = await POST(request, context);
+
+ expect((await errorUrl(response)).searchParams.get("error")).toBe(
+ "SsoSessionExpired",
+ );
+ expect(mocks.nextAuth).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["organization", INTENT.workosOrganizationId],
+ ["organization", "org_other"],
+ ["provider", "GoogleOAuth"],
+ ["domain", "company.example"],
+ ["redirect_uri", "https://attacker.example/callback"],
+ ["client_id", "client_other"],
+ ["response_type", "token"],
+ ["state", "injected-state"],
+ ["code_challenge", "injected-challenge"],
+ ["unknown", ""],
+ ])(
+ "rejects an extra authorization query parameter %s",
+ async (key, value) => {
+ const { request, context } = makeRequest({
+ query: new URLSearchParams([
+ ["connection", INTENT.connectionId],
+ [key, value],
+ ]),
+ });
+
+ const response = await POST(request, context);
+
+ expect((await errorUrl(response)).searchParams.get("error")).toBe(
+ "SsoSessionExpired",
+ );
+ expect(mocks.nextAuth).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([INTENT.connectionId, "conn_other", ""])(
+ "rejects duplicate connection parameters even when the second is %s",
+ async (second) => {
+ const { request, context } = makeRequest({
+ query: new URLSearchParams([
+ ["connection", INTENT.connectionId],
+ ["connection", second],
+ ]),
+ });
+
+ const response = await POST(request, context);
+
+ expect((await errorUrl(response)).searchParams.get("error")).toBe(
+ "SsoSessionExpired",
+ );
+ expect(mocks.nextAuth).not.toHaveBeenCalled();
+ },
+ );
+
+ it("rejects a changed browser account and preserves the signed return path", async () => {
+ mocks.getToken.mockResolvedValueOnce({ id: "different-user" });
+ const { request, context } = makeRequest({
+ body: new URLSearchParams({
+ json: "true",
+ callbackUrl: "/different-return",
+ }),
+ });
+
+ const redirect = await errorUrl(await POST(request, context));
+
+ expect(redirect.searchParams.get("error")).toBe("SsoSessionExpired");
+ expect(redirect.searchParams.get("next")).toBe(RETURN_TO);
+ expect(mocks.nextAuth).not.toHaveBeenCalled();
+ });
+
+ it("accepts connection-only authorization with the intact POST and signed tenant identity", async () => {
+ const intent = createSsoLoginIntent(
+ { ...INTENT, actorId: "signed-in-user" },
+ env.NEXTAUTH_SECRET,
+ );
+ mocks.getToken.mockResolvedValueOnce({ id: "signed-in-user" });
+ const { request, context } = makeRequest({ intent });
+ let receivedBody = "";
+ mocks.nextAuth.mockImplementationOnce(async (receivedRequest) => {
+ receivedBody = await receivedRequest.text();
+ return Response.json({ url: "https://api.workos.com/sso/authorize" });
+ });
+
+ const response = await POST(request, context);
+
+ expect(new URLSearchParams(receivedBody).get("csrfToken")).toBe(
+ "fixture-csrf-token",
+ );
+ expect(mocks.authOptions).toHaveBeenCalledWith({
+ intent: verifySsoLoginIntent(intent, env.NEXTAUTH_SECRET),
+ actorId: "signed-in-user",
+ });
+ expect(mocks.nextAuth).toHaveBeenCalledWith(request, context, {
+ providers: [],
+ });
+ expect(response.headers.get("set-cookie")).toBeNull();
+ });
+
+ it("expires only the intent after callback and preserves the session cookie", async () => {
+ const { request, context } = makeRequest({
+ action: "callback",
+ query: { code: "fixture-code", state: "fixture-state" },
+ });
+
+ const response = await GET(request, context);
+
+ expect(response.headers.get("location")).toBe("/dashboard");
+ expect(response.headers.get("set-cookie")).toContain(
+ "next-auth.session-token=verified-session",
+ );
+ expect(response.headers.get("set-cookie")).toContain(
+ `${ssoIntentCookie(true).name}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0; Secure`,
+ );
+ });
+
+ it.each([
+ "/api/auth/error?error=OAuthCallback",
+ "https://cap.example/api/auth/error?error=Callback",
+ "/api/auth/signin",
+ "/login?error=SsoSignInFailed",
+ ])(
+ "preserves mobile continuation after NextAuth redirects to %s",
+ async (location) => {
+ mocks.nextAuth.mockResolvedValueOnce(
+ new Response(null, { status: 302, headers: { location } }),
+ );
+ const { request, context } = makeRequest({ action: "callback" });
+
+ const redirect = await errorUrl(await GET(request, context));
+
+ expect(redirect.origin).toBe(env.WEB_URL);
+ expect(redirect.pathname).toBe("/login");
+ expect(redirect.searchParams.get("error")).toBe("SsoSignInFailed");
+ expect(redirect.searchParams.get("next")).toBe(RETURN_TO);
+ },
+ );
+
+ it("does not append the signed continuation to an external redirect", async () => {
+ const location = "https://attacker.example/login?error=Callback";
+ mocks.nextAuth.mockResolvedValueOnce(
+ new Response(null, { status: 302, headers: { location } }),
+ );
+ const { request, context } = makeRequest({ action: "callback" });
+
+ const response = await GET(request, context);
+
+ expect(response.headers.get("location")).toBe(location);
+ });
+
+ it("recovers a safe mobile continuation cookie after callback intent expiry", async () => {
+ const { request, context } = makeRequest({
+ action: "callback",
+ intent: createSsoLoginIntent(
+ INTENT,
+ env.NEXTAUTH_SECRET,
+ Date.now() - (SSO_INTENT_MAX_AGE + 1) * 1000,
+ ),
+ callbackCookie: `${env.WEB_URL}${RETURN_TO}`,
+ });
+
+ const response = await GET(request, context);
+ const redirect = await errorUrl(response);
+
+ expect(response.status).toBe(303);
+ expect(redirect.searchParams.get("error")).toBe("SsoSessionExpired");
+ expect(redirect.searchParams.get("next")).toBe(RETURN_TO);
+ expect(mocks.nextAuth).not.toHaveBeenCalled();
+ });
+
+ it("does not use an external continuation cookie after missing intent", async () => {
+ const { request, context } = makeRequest({
+ action: "callback",
+ intent: null,
+ callbackCookie: "https://attacker.example/steal",
+ });
+
+ const redirect = await errorUrl(await GET(request, context));
+
+ expect(redirect.origin).toBe(env.WEB_URL);
+ expect(redirect.searchParams.get("next")).toBeNull();
+ });
+
+ it("does not apply SSO intent checks to another provider", async () => {
+ const { request, context } = makeRequest({
+ provider: "google",
+ intent: null,
+ });
+
+ const response = await POST(request, context);
+
+ expect(mocks.getToken).not.toHaveBeenCalled();
+ expect(mocks.authOptions).toHaveBeenCalledWith();
+ expect(mocks.nextAuth).toHaveBeenCalledWith(request, context, {
+ providers: [],
+ });
+ expect(response.headers.get("set-cookie")).not.toContain("cap-sso-intent");
+ });
+});
diff --git a/apps/web/__tests__/unit/sso-auth.test.ts b/apps/web/__tests__/unit/sso-auth.test.ts
new file mode 100644
index 000000000..b65ea702e
--- /dev/null
+++ b/apps/web/__tests__/unit/sso-auth.test.ts
@@ -0,0 +1,1074 @@
+import {
+ getSsoEmailDomain,
+ normalizeSsoDomain,
+ provisionSsoMembership,
+ type SsoAuthContext,
+ type ValidatedSsoIdentity,
+ validateSsoSignIn,
+} from "@cap/database/auth/sso";
+import {
+ createSsoLoginIntent,
+ SSO_INTENT_MAX_AGE,
+ type SsoLoginIntent,
+ verifySsoLoginIntent,
+} from "@cap/database/auth/sso-state";
+import * as Db from "@cap/database/schema";
+import { Organisation, User } from "@cap/web-domain";
+import { getTableName, is, type SQL } from "drizzle-orm";
+import {
+ type AnyMySqlColumn,
+ MySqlDialect,
+ MySqlTable,
+} from "drizzle-orm/mysql-core";
+import type { MySql2Database } from "drizzle-orm/mysql2";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { DrizzleAdapter } from "../../../../packages/database/auth/drizzle-adapter";
+
+const mocks = vi.hoisted(() => ({
+ db: vi.fn(),
+ getOrganization: vi.fn(),
+ getConnection: vi.fn(),
+ stripe: vi.fn(),
+}));
+
+vi.mock("@cap/database", () => ({ db: mocks.db }));
+vi.mock("@cap/env", () => ({
+ serverEnv: () => ({
+ WORKOS_CLIENT_ID: "client_test",
+ WORKOS_API_KEY: "workos_test_secret",
+ }),
+}));
+vi.mock("@workos-inc/node", () => ({
+ WorkOS: class {
+ organizations = { getOrganization: mocks.getOrganization };
+ sso = { getConnection: mocks.getConnection };
+ },
+}));
+vi.mock("@cap/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@cap/utils")>()),
+ STRIPE_AVAILABLE: () => true,
+ stripe: mocks.stripe,
+}));
+
+type Row = Record<string, unknown>;
+type RowScope = Record<string, Row>;
+type Selection = Record<string, MySqlTable | AnyMySqlColumn>;
+
+function matchesRow(condition: SQL | undefined, scope: RowScope) {
+ if (!condition) return true;
+ const query = new MySqlDialect().sqlToQuery(condition);
+ let parameterIndex = 0;
+ return query.sql
+ .replaceAll("(", "")
+ .replaceAll(")", "")
+ .split(" and ")
+ .every((clause) => {
+ const match =
+ /^`([^`]+)`\.`([^`]+)` (is null|= \?|= `([^`]+)`\.`([^`]+)`)$/.exec(
+ clause,
+ );
+ if (!match?.[1] || !match[2]) {
+ throw new Error(`Unsupported query predicate: ${clause}`);
+ }
+ const value = scope[match[1]]?.[match[2]];
+ if (match[3] === "is null") return value == null;
+ if (match[3] === "= ?") return value === query.params[parameterIndex++];
+ if (!match[4] || !match[5]) throw new Error("Invalid joined predicate");
+ return value === scope[match[4]]?.[match[5]];
+ });
+}
+
+function createDatabase(seed: Map<MySqlTable, Row[]>) {
+ const tables = new Map(seed);
+ const hooks: { beforeUpdate?: (table: MySqlTable) => void } = {};
+ const rows = (table: MySqlTable) => {
+ const result = tables.get(table);
+ if (!result) throw new Error("Unexpected table");
+ return result;
+ };
+ class SelectQuery {
+ private table: MySqlTable | undefined;
+ private condition: SQL | undefined;
+ private rowLimit = Number.POSITIVE_INFINITY;
+ private joins: { table: MySqlTable; condition: SQL | undefined }[] = [];
+
+ constructor(
+ private selection?: Selection,
+ private distinct = false,
+ ) {}
+
+ from(table: MySqlTable) {
+ this.table = table;
+ return this;
+ }
+
+ innerJoin(table: MySqlTable, condition: SQL | undefined) {
+ this.joins.push({ table, condition });
+ return this;
+ }
+
+ where(condition: SQL | undefined) {
+ this.condition = condition;
+ return this;
+ }
+
+ limit(count: number) {
+ this.rowLimit = count;
+ return Promise.resolve().then(() => this.execute());
+ }
+
+ for() {
+ return Promise.resolve().then(() => this.execute());
+ }
+
+ private execute() {
+ const table = this.table;
+ if (!table) throw new Error("Missing query table");
+ const tableName = getTableName(table);
+ let scopes: RowScope[] = rows(table).map((row) => ({ [tableName]: row }));
+ for (const join of this.joins) {
+ scopes = scopes.flatMap((scope) =>
+ rows(join.table)
+ .map((row) => ({ ...scope, [getTableName(join.table)]: row }))
+ .filter((joined) => matchesRow(join.condition, joined)),
+ );
+ }
+ const selected = scopes
+ .filter((scope) => matchesRow(this.condition, scope))
+ .map((scope) =>
+ this.selection
+ ? Object.fromEntries(
+ Object.entries(this.selection).map(([key, field]) => [
+ key,
+ is(field, MySqlTable)
+ ? { ...scope[getTableName(field)] }
+ : scope[getTableName(field.table)]?.[field.name],
+ ]),
+ )
+ : { ...scope[tableName] },
+ );
+ const result = this.distinct
+ ? [
+ ...new Map(
+ selected.map((row) => [JSON.stringify(row), row]),
+ ).values(),
+ ]
+ : selected;
+ return result.slice(0, this.rowLimit);
+ }
+ }
+
+ const client = {
+ select: vi.fn((selection?: Selection) => new SelectQuery(selection)),
+ selectDistinct: vi.fn(
+ (selection?: Selection) => new SelectQuery(selection, true),
+ ),
+ insert: vi.fn((table: MySqlTable) => ({
+ values: (value: Row) => {
+ const insert = (update?: Row) => {
+ const existing = rows(table).find(
+ (row) =>
+ row.id === value.id ||
+ (table === Db.users && row.email === value.email),
+ );
+ if (existing) {
+ if (!update) throw new Error("Duplicate row");
+ Object.assign(existing, update);
+ } else {
+ rows(table).push({
+ emailVerified: null,
+ defaultOrgId: null,
+ onboardingSteps: null,
+ onboarding_completed_at: null,
+ ...value,
+ });
+ }
+ };
+ let update: Row | undefined;
+ const pending = Promise.resolve().then(() => insert(update));
+ return Object.assign(pending, {
+ onDuplicateKeyUpdate: ({ set }: { set: Row }) => {
+ update = set;
+ return pending;
+ },
+ });
+ },
+ })),
+ update: vi.fn((table: MySqlTable) => ({
+ set: (patch: Row) => ({
+ where: async (condition: SQL | undefined) => {
+ hooks.beforeUpdate?.(table);
+ for (const row of rows(table)) {
+ if (matchesRow(condition, { [getTableName(table)]: row })) {
+ Object.assign(row, patch);
+ }
+ }
+ },
+ }),
+ })),
+ transaction: vi.fn(
+ async (callback: (database: MySql2Database) => Promise<unknown>) => {
+ const snapshot = new Map(
+ [...tables].map(([table, records]) => [
+ table,
+ structuredClone(records),
+ ]),
+ );
+ try {
+ return await callback(client as unknown as MySql2Database);
+ } catch (error) {
+ for (const [table, records] of snapshot) tables.set(table, records);
+ throw error;
+ }
+ },
+ ),
+ };
+ return { client, rows, hooks };
+}
+
+const USER_ID = User.UserId.make("sso-user");
+const OTHER_USER_ID = User.UserId.make("other-user");
+const ORGANIZATION_ID = Organisation.OrganisationId.make("cap-org");
+const OTHER_ORGANIZATION_ID = Organisation.OrganisationId.make("other-org");
+const PROFILE = {
+ id: "prof_01A",
+ organization_id: "org_01A",
+ connection_id: "conn_01A",
+ email: "[email protected]",
+};
+const IDENTITY: ValidatedSsoIdentity = {
+ organizationId: ORGANIZATION_ID,
+ workosOrganizationId: PROFILE.organization_id,
+ connectionId: PROFILE.connection_id,
+ profileId: PROFILE.id,
+ email: PROFILE.email,
+};
+const INTENT: SsoLoginIntent = {
+ version: 1,
+ organizationId: ORGANIZATION_ID,
+ workosOrganizationId: PROFILE.organization_id,
+ connectionId: PROFILE.connection_id,
+ actorId: null,
+ issuedAt: 1,
+ nonce: "a".repeat(32),
+};
+const CONTEXT: SsoAuthContext = { intent: INTENT, actorId: null };
+
+function actorContext(actorId: string): SsoAuthContext {
+ return { intent: { ...INTENT, actorId }, actorId };
+}
+
+function makeFixture() {
+ const database = createDatabase(
+ new Map<MySqlTable, Row[]>([
+ [
+ Db.users,
+ [
+ {
+ id: USER_ID,
+ email: PROFILE.email,
+ name: "Alex",
+ activeOrganizationId: OTHER_ORGANIZATION_ID,
+ defaultOrgId: OTHER_ORGANIZATION_ID,
+ emailVerified: null,
+ onboarding_completed_at: null,
+ onboardingSteps: { welcome: false },
+ },
+ {
+ id: OTHER_USER_ID,
+ email: "[email protected]",
+ activeOrganizationId: OTHER_ORGANIZATION_ID,
+ },
+ ],
+ ],
+ [
+ Db.organizations,
+ [
+ {
+ id: ORGANIZATION_ID,
+ ownerId: OTHER_USER_ID,
+ workosOrganizationId: PROFILE.organization_id,
+ workosConnectionId: PROFILE.connection_id,
+ tombstoneAt: null,
+ },
+ {
+ id: OTHER_ORGANIZATION_ID,
+ ownerId: OTHER_USER_ID,
+ workosOrganizationId: "org_01B",
+ workosConnectionId: "conn_01B",
+ tombstoneAt: null,
+ },
+ ],
+ ],
+ [
+ Db.organizationSso,
+ [
+ {
+ organizationId: ORGANIZATION_ID,
+ status: "active",
+ paidThrough: new Date("2099-01-01T00:00:00.000Z"),
+ },
+ {
+ organizationId: OTHER_ORGANIZATION_ID,
+ status: "active",
+ paidThrough: new Date("2099-01-01T00:00:00.000Z"),
+ },
+ ],
+ ],
+ [
+ Db.organizationInvites,
+ [
+ {
+ id: "same-org-invite",
+ organizationId: ORGANIZATION_ID,
+ invitedEmail: PROFILE.email,
+ status: "pending",
+ },
+ {
+ id: "other-org-invite",
+ organizationId: OTHER_ORGANIZATION_ID,
+ invitedEmail: PROFILE.email,
+ status: "pending",
+ },
+ {
+ id: "other-email-invite",
+ organizationId: ORGANIZATION_ID,
+ invitedEmail: "[email protected]",
+ status: "pending",
+ },
+ ],
+ ],
+ [Db.accounts, []],
+ [Db.organizationMembers, []],
+ ]),
+ );
+ const workosOrganization = {
+ id: PROFILE.organization_id,
+ domains: [{ domain: "company.example", state: "verified" }],
+ };
+ const connection = {
+ id: PROFILE.connection_id,
+ organizationId: PROFILE.organization_id,
+ state: "active",
+ };
+ mocks.db.mockReturnValue(database.client);
+ mocks.getOrganization.mockResolvedValue(workosOrganization);
+ mocks.getConnection.mockResolvedValue(connection);
+ const row = (table: MySqlTable, id: string, column = "id") => {
+ const record = database.rows(table).find((record) => record[column] === id);
+ if (!record) throw new Error("Fixture row was not found");
+ return record;
+ };
+ return {
+ ...database,
+ workosOrganization,
+ connection,
+ get user() {
+ return row(Db.users, USER_ID);
+ },
+ get organization() {
+ return row(Db.organizations, ORGANIZATION_ID);
+ },
+ get billing() {
+ return row(Db.organizationSso, ORGANIZATION_ID, "organizationId");
+ },
+ link(userId = USER_ID) {
+ database.rows(Db.accounts).push({
+ id: `account-${database.rows(Db.accounts).length}`,
+ userId,
+ provider: "workos",
+ providerAccountId: PROFILE.id,
+ });
+ },
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getOrganization.mockReset();
+ mocks.getConnection.mockReset();
+ mocks.stripe.mockReset().mockImplementation(() => {
+ throw new Error("SSO must not bootstrap Stripe billing");
+ });
+});
+
+describe("SSO identity validation", () => {
+ it("validates the exact tenant and verified profile without granting membership", async () => {
+ const fixture = makeFixture();
+
+ await expect(
+ validateSsoSignIn(
+ { ...PROFILE, email: " [email protected] " },
+ PROFILE.id,
+ CONTEXT,
+ ),
+ ).resolves.toEqual(IDENTITY);
+
+ expect(mocks.getOrganization).toHaveBeenCalledWith(PROFILE.organization_id);
+ expect(mocks.getConnection).toHaveBeenCalledWith(PROFILE.connection_id);
+ expect(fixture.client.transaction).not.toHaveBeenCalled();
+ expect(fixture.client.insert).not.toHaveBeenCalled();
+ expect(fixture.client.update).not.toHaveBeenCalled();
+ });
+
+ it.each([undefined, { intent: null, actorId: null }])(
+ "rejects a missing server intent",
+ async (context) => {
+ makeFixture();
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, context),
+ ).rejects.toThrow("expired");
+ expect(mocks.db).not.toHaveBeenCalled();
+ expect(mocks.getOrganization).not.toHaveBeenCalled();
+ },
+ );
+
+ it("rejects an intent when the browser actor changed", async () => {
+ makeFixture();
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, {
+ intent: { ...INTENT, actorId: USER_ID },
+ actorId: OTHER_USER_ID,
+ }),
+ ).rejects.toThrow("expired");
+ expect(mocks.db).not.toHaveBeenCalled();
+ });
+
+ it("rejects expired intent after the request boundary verifies its signature", async () => {
+ makeFixture();
+ const now = Date.UTC(2026, 8, 2);
+ const value = createSsoLoginIntent(INTENT, "secret", now);
+ const intent = verifySsoLoginIntent(
+ value,
+ "secret",
+ now + SSO_INTENT_MAX_AGE * 1000,
+ );
+
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, { intent, actorId: null }),
+ ).rejects.toThrow("expired");
+ expect(mocks.getOrganization).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { organization_id: "org_01B" },
+ { connection_id: "conn_01B" },
+ { id: "prof_01B" },
+ { email: null },
+ ])(
+ "rejects profile fields that do not match the tenant intent: %j",
+ async (override) => {
+ makeFixture();
+ await expect(
+ validateSsoSignIn({ ...PROFILE, ...override }, PROFILE.id, CONTEXT),
+ ).rejects.toThrow();
+ expect(mocks.db).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([null, undefined, "profile", 42])(
+ "rejects malformed profile %j",
+ async (profile) => {
+ makeFixture();
+ await expect(
+ validateSsoSignIn(profile, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("profile");
+ },
+ );
+
+ it.each([
+ "no-at",
+ "a@@company.example",
+ ])("rejects malformed email %s", async (email) => {
+ makeFixture();
+ await expect(
+ validateSsoSignIn({ ...PROFILE, email }, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("email");
+ expect(mocks.getOrganization).not.toHaveBeenCalled();
+ });
+
+ it.each(["unpaid", "canceled", "incomplete", "past_due", "active"])(
+ "denies %s billing with no remaining paid access",
+ async (status) => {
+ const fixture = makeFixture();
+ Object.assign(fixture.billing, { status, paidThrough: new Date(0) });
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("not available");
+ expect(mocks.getOrganization).not.toHaveBeenCalled();
+ },
+ );
+
+ it("rejects a tombstoned Cap organization", async () => {
+ const fixture = makeFixture();
+ fixture.organization.tombstoneAt = new Date();
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("not available");
+ });
+
+ it("rejects an unregistered organization even when the other tenant is paid", async () => {
+ const fixture = makeFixture();
+ fixture.rows(Db.organizationSso).splice(0, 1);
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("not available");
+ });
+
+ it("rejects an organization whose WorkOS association changed", async () => {
+ const fixture = makeFixture();
+ fixture.organization.workosOrganizationId = "org_01B";
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("no longer connected");
+ });
+
+ it.each(["pending", "inactive", "deleted"])(
+ "rejects an %s connection",
+ async (state) => {
+ const fixture = makeFixture();
+ fixture.connection.state = state;
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("not verified");
+ },
+ );
+
+ it.each(["getOrganization", "getConnection"] as const)(
+ "fails closed when WorkOS %s fails",
+ async (method) => {
+ const fixture = makeFixture();
+ mocks[method].mockRejectedValueOnce(
+ new Error("WorkOS resource not found"),
+ );
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("not found");
+ expect(fixture.client.insert).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(["organization", "connection"] as const)(
+ "rejects a mismatched WorkOS %s response",
+ async (resource) => {
+ const fixture = makeFixture();
+ if (resource === "organization")
+ fixture.workosOrganization.id = "org_01B";
+ else fixture.connection.organizationId = "org_01B";
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("not verified");
+ },
+ );
+
+ it.each(["pending", "unverified"])(
+ "does not trust a domain in %s state",
+ async (state) => {
+ const fixture = makeFixture();
+ fixture.workosOrganization.domains = [
+ { domain: "company.example", state },
+ ];
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("not verified");
+ },
+ );
+
+ it("blocks an IdP from asserting an email outside its verified domains", async () => {
+ const fixture = makeFixture();
+ fixture.workosOrganization.domains = [
+ { domain: "attacker.example", state: "verified" },
+ ];
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("not verified");
+ expect(fixture.client.insert).not.toHaveBeenCalled();
+ });
+
+ it("does not grant verified parent-domain trust to subdomains", async () => {
+ makeFixture();
+ await expect(
+ validateSsoSignIn(
+ { ...PROFILE, email: "[email protected]" },
+ PROFILE.id,
+ CONTEXT,
+ ),
+ ).rejects.toThrow("not verified");
+ });
+
+ it("rejects an already-linked profile whose email changed", async () => {
+ const fixture = makeFixture();
+ fixture.link();
+ fixture.user.email = "[email protected]";
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("different account");
+ });
+
+ it("rejects conflicting profile links hidden behind duplicate account rows", async () => {
+ const fixture = makeFixture();
+ fixture.link();
+ fixture.link();
+ fixture.link(OTHER_USER_ID);
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT),
+ ).rejects.toThrow("different account");
+ });
+
+ it.each([OTHER_USER_ID, "missing-user"])(
+ "rejects a mismatched browser account %s",
+ async (actorId) => {
+ makeFixture();
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, actorContext(actorId)),
+ ).rejects.toThrow("Sign out");
+ },
+ );
+
+ it("allows the same browser account after validating its stored email", async () => {
+ const fixture = makeFixture();
+ fixture.link();
+ await expect(
+ validateSsoSignIn(PROFILE, PROFILE.id, actorContext(USER_ID)),
+ ).resolves.toEqual(IDENTITY);
+ });
+});
+
+describe("SSO membership provisioning", () => {
+ it("adds only the authenticated organization and accepts only its matching invitation", async () => {
+ const fixture = makeFixture();
+ fixture.link();
+
+ await provisionSsoMembership(USER_ID, IDENTITY);
+
+ expect(fixture.rows(Db.organizationMembers)).toEqual([
+ expect.objectContaining({
+ userId: USER_ID,
+ organizationId: ORGANIZATION_ID,
+ role: "member",
+ hasProSeat: false,
+ }),
+ ]);
+ expect(
+ fixture
+ .rows(Db.organizationInvites)
+ .map(({ id, status }) => ({ id, status })),
+ ).toEqual([
+ { id: "same-org-invite", status: "accepted" },
+ { id: "other-org-invite", status: "pending" },
+ { id: "other-email-invite", status: "pending" },
+ ]);
+ expect(fixture.user).toMatchObject({
+ activeOrganizationId: ORGANIZATION_ID,
+ defaultOrgId: OTHER_ORGANIZATION_ID,
+ emailVerified: expect.any(Date),
+ onboarding_completed_at: expect.any(Date),
+ onboardingSteps: {
+ welcome: true,
+ organizationSetup: true,
+ customDomain: true,
+ inviteTeam: true,
+ download: true,
+ },
+ });
+ expect(
+ fixture.rows(Db.users).find((user) => user.id === OTHER_USER_ID)
+ ?.activeOrganizationId,
+ ).toBe(OTHER_ORGANIZATION_ID);
+ expect(mocks.stripe).not.toHaveBeenCalled();
+ });
+
+ it.each(["owner", "admin", "member"])(
+ "preserves the existing %s role and Pro seat",
+ async (role) => {
+ const fixture = makeFixture();
+ fixture.link();
+ const member = {
+ id: "member-existing",
+ userId: USER_ID,
+ organizationId: ORGANIZATION_ID,
+ role,
+ hasProSeat: true,
+ };
+ fixture.rows(Db.organizationMembers).push({ ...member });
+
+ await provisionSsoMembership(USER_ID, IDENTITY);
+ await provisionSsoMembership(USER_ID, IDENTITY);
+
+ expect(fixture.rows(Db.organizationMembers)).toEqual([member]);
+ expect(fixture.client.insert).not.toHaveBeenCalled();
+ },
+ );
+
+ it("restores a missing membership with the authoritative owner's role", async () => {
+ const fixture = makeFixture();
+ fixture.organization.ownerId = USER_ID;
+ fixture.link();
+
+ await provisionSsoMembership(USER_ID, IDENTITY);
+ await provisionSsoMembership(USER_ID, IDENTITY);
+
+ expect(fixture.rows(Db.organizationMembers)).toEqual([
+ expect.objectContaining({
+ userId: USER_ID,
+ organizationId: ORGANIZATION_ID,
+ role: "owner",
+ hasProSeat: false,
+ }),
+ ]);
+ expect(fixture.client.insert).toHaveBeenCalledTimes(1);
+ });
+
+ it("does not mistake membership in another organization for this one", async () => {
+ const fixture = makeFixture();
+ fixture.link();
+ const previous = {
+ id: "other-member",
+ userId: USER_ID,
+ organizationId: OTHER_ORGANIZATION_ID,
+ role: "admin",
+ hasProSeat: true,
+ };
+ fixture.rows(Db.organizationMembers).push({ ...previous });
+
+ await provisionSsoMembership(USER_ID, IDENTITY);
+
+ expect(fixture.rows(Db.organizationMembers)).toContainEqual(previous);
+ expect(fixture.rows(Db.organizationMembers)).toContainEqual(
+ expect.objectContaining({
+ userId: USER_ID,
+ organizationId: ORGANIZATION_ID,
+ role: "member",
+ hasProSeat: false,
+ }),
+ );
+ });
+
+ it("sets the SSO organization as default only when no default exists", async () => {
+ const fixture = makeFixture();
+ fixture.link();
+ fixture.user.defaultOrgId = null;
+ await provisionSsoMembership(USER_ID, IDENTITY);
+ expect(fixture.user.defaultOrgId).toBe(ORGANIZATION_ID);
+ });
+
+ it("does not reset existing verification and onboarding dates", async () => {
+ const fixture = makeFixture();
+ fixture.link();
+ const before = new Date("2020-01-01T00:00:00.000Z");
+ Object.assign(fixture.user, {
+ emailVerified: before,
+ onboarding_completed_at: before,
+ });
+ await provisionSsoMembership(USER_ID, IDENTITY);
+ expect(fixture.user.emailVerified).toEqual(before);
+ expect(fixture.user.onboarding_completed_at).toEqual(before);
+ });
+
+ it("rejects payment revocation between validation and provisioning", async () => {
+ const fixture = makeFixture();
+ fixture.link();
+ const identity = await validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT);
+ fixture.billing.status = "canceled";
+
+ await expect(provisionSsoMembership(USER_ID, identity)).rejects.toThrow(
+ "no longer available",
+ );
+ expect(fixture.client.insert).not.toHaveBeenCalled();
+ expect(fixture.client.update).not.toHaveBeenCalled();
+ });
+
+ it.each(["deleted", "disconnected", "changed-email"])(
+ "fails closed after %s during sign-in",
+ async (change) => {
+ const fixture = makeFixture();
+ fixture.link();
+ if (change === "deleted") fixture.organization.tombstoneAt = new Date();
+ else if (change === "disconnected")
+ fixture.organization.workosOrganizationId = "org_01B";
+ else fixture.user.email = "[email protected]";
+ await expect(provisionSsoMembership(USER_ID, IDENTITY)).rejects.toThrow(
+ "no longer available",
+ );
+ expect(fixture.client.insert).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ "missing",
+ "other-user",
+ "other-profile",
+ "ambiguous",
+ "orphaned-conflict",
+ ])("rejects a %s linked account", async (link) => {
+ const fixture = makeFixture();
+ if (link === "other-user") fixture.link(OTHER_USER_ID);
+ if (link === "ambiguous" || link === "orphaned-conflict") {
+ fixture.link();
+ fixture.link();
+ fixture.link(
+ link === "ambiguous" ? OTHER_USER_ID : User.UserId.make("deleted-user"),
+ );
+ }
+ if (link === "other-profile") {
+ fixture.rows(Db.accounts).push({
+ id: "another-profile",
+ userId: USER_ID,
+ provider: "workos",
+ providerAccountId: "prof_01B",
+ });
+ }
+ await expect(provisionSsoMembership(USER_ID, IDENTITY)).rejects.toThrow(
+ "not linked",
+ );
+ expect(fixture.client.insert).not.toHaveBeenCalled();
+ expect(fixture.client.update).not.toHaveBeenCalled();
+ });
+
+ it("rolls back membership and invitation updates when the user update fails", async () => {
+ const fixture = makeFixture();
+ fixture.link();
+ fixture.hooks.beforeUpdate = (table) => {
+ if (table === Db.users) throw new Error("User update failed");
+ };
+ await expect(provisionSsoMembership(USER_ID, IDENTITY)).rejects.toThrow(
+ "User update failed",
+ );
+ expect(fixture.rows(Db.organizationMembers)).toEqual([]);
+ expect(
+ fixture
+ .rows(Db.organizationInvites)
+ .every((invite) => invite.status === "pending"),
+ ).toBe(true);
+ expect(fixture.user.activeOrganizationId).toBe(OTHER_ORGANIZATION_ID);
+ });
+});
+
+describe("SSO adapter provisioning", () => {
+ it("creates, links, then joins a new user without a personal organization or Stripe bootstrap", async () => {
+ const fixture = makeFixture();
+ fixture.rows(Db.users).splice(0, 1);
+ fixture.rows(Db.organizationInvites).splice(0);
+ const identity = await validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT);
+ const adapter = DrizzleAdapter(
+ fixture.client as unknown as MySql2Database,
+ {
+ getSsoIdentity: () => identity,
+ },
+ );
+ if (!adapter.createUser || !adapter.linkAccount)
+ throw new Error("Missing adapter methods");
+ const user = await adapter.createUser({
+ email: PROFILE.email,
+ name: "Alex",
+ emailVerified: null,
+ });
+
+ expect(fixture.rows(Db.organizations)).toHaveLength(2);
+ expect(fixture.rows(Db.organizationMembers)).toEqual([]);
+ expect(mocks.stripe).not.toHaveBeenCalled();
+ await expect(
+ provisionSsoMembership(User.UserId.make(user.id), identity),
+ ).rejects.toThrow("not linked");
+
+ await adapter.linkAccount({
+ userId: user.id,
+ provider: "workos",
+ providerAccountId: PROFILE.id,
+ type: "oauth",
+ });
+ await adapter.linkAccount({
+ userId: user.id,
+ provider: "workos",
+ providerAccountId: PROFILE.id,
+ type: "oauth",
+ });
+ await provisionSsoMembership(User.UserId.make(user.id), identity);
+
+ expect(fixture.rows(Db.accounts)).toHaveLength(1);
+ expect(fixture.rows(Db.organizationMembers)).toEqual([
+ expect.objectContaining({
+ userId: user.id,
+ organizationId: ORGANIZATION_ID,
+ role: "member",
+ hasProSeat: false,
+ }),
+ ]);
+ expect(mocks.stripe).not.toHaveBeenCalled();
+ });
+
+ it("refuses to create a different email from the validated SSO identity", async () => {
+ const fixture = makeFixture();
+ const adapter = DrizzleAdapter(
+ fixture.client as unknown as MySql2Database,
+ { getSsoIdentity: () => IDENTITY },
+ );
+ if (!adapter.createUser) throw new Error("Missing createUser");
+ await expect(
+ adapter.createUser({
+ email: "[email protected]",
+ emailVerified: null,
+ }),
+ ).rejects.toThrow("does not match");
+ expect(fixture.client.insert).not.toHaveBeenCalled();
+ });
+
+ it("requires validated context to link a WorkOS account", async () => {
+ const fixture = makeFixture();
+ const adapter = DrizzleAdapter(fixture.client as unknown as MySql2Database);
+ if (!adapter.linkAccount) throw new Error("Missing linkAccount");
+ await expect(
+ adapter.linkAccount({
+ userId: USER_ID,
+ provider: "workos",
+ providerAccountId: PROFILE.id,
+ type: "oauth",
+ }),
+ ).rejects.toThrow("not been verified");
+ expect(fixture.client.insert).not.toHaveBeenCalled();
+ });
+
+ it("does not link the validated identity to a user with a different stored email", async () => {
+ const fixture = makeFixture();
+ const adapter = DrizzleAdapter(
+ fixture.client as unknown as MySql2Database,
+ { getSsoIdentity: () => IDENTITY },
+ );
+ if (!adapter.linkAccount) throw new Error("Missing linkAccount");
+
+ await expect(
+ adapter.linkAccount({
+ userId: OTHER_USER_ID,
+ provider: "workos",
+ providerAccountId: PROFILE.id,
+ type: "oauth",
+ }),
+ ).rejects.toThrow("different user");
+
+ expect(fixture.rows(Db.accounts)).toEqual([]);
+ });
+
+ it("does not link a different WorkOS profile after validation", async () => {
+ const fixture = makeFixture();
+ const adapter = DrizzleAdapter(
+ fixture.client as unknown as MySql2Database,
+ { getSsoIdentity: () => IDENTITY },
+ );
+ if (!adapter.linkAccount) throw new Error("Missing linkAccount");
+
+ await expect(
+ adapter.linkAccount({
+ userId: USER_ID,
+ provider: "workos",
+ providerAccountId: "prof_01B",
+ type: "oauth",
+ }),
+ ).rejects.toThrow("not been verified");
+
+ expect(fixture.client.transaction).not.toHaveBeenCalled();
+ expect(fixture.rows(Db.accounts)).toEqual([]);
+ });
+
+ it("refuses a conflicting identity link hidden behind duplicate rows after validation", async () => {
+ const fixture = makeFixture();
+ const identity = await validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT);
+ fixture.link();
+ fixture.link();
+ fixture.link(OTHER_USER_ID);
+ const adapter = DrizzleAdapter(
+ fixture.client as unknown as MySql2Database,
+ { getSsoIdentity: () => identity },
+ );
+ if (!adapter.linkAccount) throw new Error("Missing linkAccount");
+
+ await expect(
+ adapter.linkAccount({
+ userId: USER_ID,
+ provider: "workos",
+ providerAccountId: PROFILE.id,
+ type: "oauth",
+ }),
+ ).rejects.toThrow("another account");
+
+ expect(fixture.rows(Db.accounts)).toEqual([
+ expect.objectContaining({ userId: USER_ID }),
+ expect.objectContaining({ userId: USER_ID }),
+ expect.objectContaining({ userId: OTHER_USER_ID }),
+ ]);
+ expect(fixture.rows(Db.organizationMembers)).toEqual([]);
+ });
+
+ it("allows duplicate rows for the same identity through validation, linking, and repeat login", async () => {
+ const fixture = makeFixture();
+ fixture.link();
+ fixture.link();
+ const identity = await validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT);
+ const adapter = DrizzleAdapter(
+ fixture.client as unknown as MySql2Database,
+ { getSsoIdentity: () => identity },
+ );
+ if (!adapter.linkAccount) throw new Error("Missing linkAccount");
+
+ await adapter.linkAccount({
+ userId: USER_ID,
+ provider: "workos",
+ providerAccountId: PROFILE.id,
+ type: "oauth",
+ });
+ await provisionSsoMembership(USER_ID, identity);
+ await provisionSsoMembership(USER_ID, identity);
+
+ expect(fixture.rows(Db.accounts)).toEqual([
+ expect.objectContaining({ userId: USER_ID }),
+ expect.objectContaining({ userId: USER_ID }),
+ ]);
+ expect(fixture.rows(Db.organizationMembers)).toEqual([
+ expect.objectContaining({
+ userId: USER_ID,
+ organizationId: ORGANIZATION_ID,
+ role: "member",
+ hasProSeat: false,
+ }),
+ ]);
+ });
+
+ it("reuses an existing corporate user without changing its organizations or billing", async () => {
+ const fixture = makeFixture();
+ const identity = await validateSsoSignIn(PROFILE, PROFILE.id, CONTEXT);
+ const adapter = DrizzleAdapter(
+ fixture.client as unknown as MySql2Database,
+ { getSsoIdentity: () => identity },
+ );
+ if (!adapter.createUser) throw new Error("Missing createUser");
+
+ const user = await adapter.createUser({
+ email: PROFILE.email,
+ name: "Alex",
+ emailVerified: null,
+ });
+
+ expect(user.id).toBe(USER_ID);
+ expect(fixture.rows(Db.users)).toHaveLength(2);
+ expect(fixture.rows(Db.organizations)).toHaveLength(2);
+ expect(fixture.rows(Db.organizationMembers)).toEqual([]);
+ expect(fixture.user).toMatchObject({
+ defaultOrgId: OTHER_ORGANIZATION_ID,
+ activeOrganizationId: OTHER_ORGANIZATION_ID,
+ });
+ expect(mocks.stripe).not.toHaveBeenCalled();
+ });
+});
+
+describe("SSO domain normalization", () => {
+ it("normalizes case and IDNs without accepting URLs or email addresses", () => {
+ expect(normalizeSsoDomain(" Company.Example ")).toBe("company.example");
+ expect(normalizeSsoDomain("münchen.example")).toBe(
+ "xn--mnchen-3ya.example",
+ );
+ expect(normalizeSsoDomain("https://company.example")).toBeNull();
+ expect(normalizeSsoDomain("[email protected]")).toBeNull();
+ expect(getSsoEmailDomain("[email protected]")).toBe("company.example");
+ });
+});
diff --git a/apps/web/__tests__/unit/sso-login-pages.test.ts b/apps/web/__tests__/unit/sso-login-pages.test.ts
new file mode 100644
index 000000000..531a623f3
--- /dev/null
+++ b/apps/web/__tests__/unit/sso-login-pages.test.ts
@@ -0,0 +1,139 @@
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import LoginPage from "@/app/(org)/login/page";
+import SignupPage from "@/app/(org)/signup/page";
+
+const mocks = vi.hoisted(() => ({
+ getCurrentUser: vi.fn(),
+ redirect: vi.fn((url: string): never => {
+ throw new Error(`redirect:${url}`);
+ }),
+}));
+
+vi.mock("@cap/database/auth/session", () => ({
+ getCurrentUser: mocks.getCurrentUser,
+}));
+vi.mock("@cap/env", () => ({
+ serverEnv: () => ({ WEB_URL: "https://cap.test" }),
+}));
+vi.mock("next/navigation", () => ({ redirect: mocks.redirect }));
+vi.mock("@/app/(org)/login/form", () => ({
+ LoginForm: () => createElement("form", { "aria-label": "Login form" }),
+}));
+vi.mock("@/app/(org)/signup/form", () => ({
+ SignupForm: () => createElement("form", { "aria-label": "Signup form" }),
+}));
+
+type Query = Record<string, string | string[]>;
+
+const ssoEntries: [string, Query][] = [
+ ["organization link", { organizationId: "aaaaaaaaaaaaaaa" }],
+ ["IdP connection link", { connection_id: "conn_company" }],
+ ["mobile SSO request", { mobileProvider: "workos" }],
+ ["work-domain entry", { sso: "1" }],
+ ["expired intent retry", { error: "SsoSessionExpired" }],
+ ["failed SSO retry", { error: "SsoSignInFailed" }],
+ [
+ "unapproved domain retry",
+ { error: "profile_not_allowed_outside_organization" },
+ ],
+ ["canceled consent retry", { error: "signin_consent_denied" }],
+];
+
+beforeEach(() => {
+ mocks.getCurrentUser.mockResolvedValue({ id: "existing-user" });
+});
+
+describe.each([
+ ["login", LoginPage, "Login form"],
+ ["signup", SignupPage, "Signup form"],
+] as const)("%s SSO entry", (_name, Page, label) => {
+ it.each(ssoEntries)(
+ "shows the form to an authenticated user following an %s",
+ async (_scenario, query) => {
+ const markup = renderToStaticMarkup(
+ await Page({ searchParams: Promise.resolve(query) }),
+ );
+ expect(markup).toContain(`aria-label="${label}"`);
+ expect(mocks.redirect).not.toHaveBeenCalled();
+ },
+ );
+
+ it("uses the first query value consistently with the client form", async () => {
+ const markup = renderToStaticMarkup(
+ await Page({
+ searchParams: Promise.resolve({
+ organizationId: ["aaaaaaaaaaaaaaa", ""],
+ }),
+ }),
+ );
+ expect(markup).toContain(`aria-label="${label}"`);
+ expect(mocks.redirect).not.toHaveBeenCalled();
+ });
+
+ it("renders the ordinary authentication form when signed out", async () => {
+ mocks.getCurrentUser.mockResolvedValue(null);
+ const markup = renderToStaticMarkup(
+ await Page({ searchParams: Promise.resolve({}) }),
+ );
+ expect(markup).toContain(`aria-label="${label}"`);
+ expect(mocks.redirect).not.toHaveBeenCalled();
+ });
+
+ it.each<Query>([
+ {},
+ { error: "OAuthCallback" },
+ { mobileProvider: "google" },
+ { sso: "0" },
+ { organizationId: "", connection_id: "" },
+ { sso: ["0", "1"] },
+ ])("preserves the normal authenticated redirect for %j", async (query) => {
+ await expect(
+ Page({ searchParams: Promise.resolve(query) }),
+ ).rejects.toThrow("redirect:/dashboard");
+ });
+});
+
+describe("authenticated login continuation", () => {
+ it("preserves a safe mobile callback for an ordinary login visit", async () => {
+ const continuation =
+ "/api/mobile/session/request?redirectUri=cap%3A%2F%2Fauth";
+ await expect(
+ LoginPage({
+ searchParams: Promise.resolve({
+ next: `https://cap.test${continuation}`,
+ }),
+ }),
+ ).rejects.toThrow(`redirect:${continuation}`);
+ });
+
+ it("does not follow an external next URL", async () => {
+ await expect(
+ LoginPage({
+ searchParams: Promise.resolve({ next: "https://other.test/account" }),
+ }),
+ ).rejects.toThrow("redirect:/dashboard");
+ });
+
+ it("keeps an SSO retry on the form despite an existing mobile continuation", async () => {
+ const markup = renderToStaticMarkup(
+ await LoginPage({
+ searchParams: Promise.resolve({
+ error: "SsoSignInFailed",
+ next: "/api/mobile/session/request?redirectUri=cap%3A%2F%2Fauth",
+ }),
+ }),
+ );
+ expect(markup).toContain("Login form");
+ expect(mocks.redirect).not.toHaveBeenCalled();
+ });
+
+ it("keeps the existing ordinary signup redirect unchanged", async () => {
+ await expect(
+ SignupPage({
+ searchParams: Promise.resolve({ next: "/dashboard/caps" }),
+ }),
+ ).rejects.toThrow("redirect:/dashboard");
+ });
+});
diff --git a/apps/web/actions/organization/get-organization-sso-data.ts b/apps/web/actions/organization/get-organization-sso-data.ts
index 00b42981b..dc1bd67c3 100644
--- a/apps/web/actions/organization/get-organization-sso-data.ts
+++ b/apps/web/actions/organization/get-organization-sso-data.ts
@@ -1,37 +1,151 @@
"use server";
import { db } from "@cap/database";
+import { getCurrentUser } from "@cap/database/auth/session";
+import {
+ getRegisteredSsoOrganization,
+ getSsoEmailDomain,
+ getWorkOS,
+ normalizeSsoDomain,
+} from "@cap/database/auth/sso";
+import {
+ createSsoLoginIntent,
+ ssoIntentCookie,
+} from "@cap/database/auth/sso-state";
import { organizations } from "@cap/database/schema";
-import type { Organisation } from "@cap/web-domain";
-import { eq } from "drizzle-orm";
+import { serverEnv } from "@cap/env";
+import { hasSsoAccess } from "@cap/utils";
+import { Organisation } from "@cap/web-domain";
+import { and, eq, inArray, isNull } from "drizzle-orm";
+import { cookies } from "next/headers";
+import { getSafeNextPath } from "@/app/(org)/safe-next";
+import { isRateLimited } from "@/lib/rate-limit";
+import { getSsoBilling, syncSsoSubscription } from "@/lib/sso/billing";
+import { getSsoConfiguration } from "@/lib/sso/workos";
export async function getOrganizationSSOData(
- organizationId: Organisation.OrganisationId,
+ identifier: string,
+ connectionId?: string,
+ returnTo?: string,
) {
- if (!organizationId) {
- throw new Error("Organization ID is required");
+ if (
+ typeof identifier !== "string" ||
+ identifier.length > 255 ||
+ (connectionId !== undefined &&
+ (typeof connectionId !== "string" ||
+ !/^conn_[a-zA-Z0-9]{1,100}$/.test(connectionId)))
+ ) {
+ throw new Error("Enter a valid work email or organization domain.");
}
-
- const [organization] = await db()
- .select({
- workosOrganizationId: organizations.workosOrganizationId,
- workosConnectionId: organizations.workosConnectionId,
- name: organizations.name,
- })
- .from(organizations)
- .where(eq(organizations.id, organizationId));
-
+ if (await isRateLimited("rl_auth_sso_start"))
+ throw new Error("Too many SSO attempts. Please try again shortly.");
+ const workos = getWorkOS();
+ const value = identifier.trim().toLowerCase();
+ let organizationId: Organisation.OrganisationId;
+ if (connectionId) {
+ const connection = await workos.sso.getConnection(connectionId);
+ if (connection.state !== "active" || !connection.organizationId)
+ throw new Error("SSO is not configured for this organization.");
+ const [organization] = await db()
+ .select({ id: organizations.id })
+ .from(organizations)
+ .where(
+ and(
+ eq(organizations.workosOrganizationId, connection.organizationId),
+ isNull(organizations.tombstoneAt),
+ ),
+ )
+ .limit(1);
+ if (!organization)
+ throw new Error("SSO is not configured for this organization.");
+ organizationId = organization.id;
+ } else if (/^[a-z0-9]{15}$/.test(value)) {
+ organizationId = Organisation.OrganisationId.make(value);
+ } else {
+ const domain = value.includes("@")
+ ? getSsoEmailDomain(value)
+ : normalizeSsoDomain(value);
+ if (!domain)
+ throw new Error("Enter a valid work email or organization domain.");
+ const remote = await workos.organizations.listOrganizations({
+ domains: [domain],
+ limit: 100,
+ });
+ const verified = remote.data.filter((organization) =>
+ organization.domains.some(
+ (entry) =>
+ entry.state === "verified" &&
+ normalizeSsoDomain(entry.domain) === domain,
+ ),
+ );
+ if (verified.length === 0 || remote.listMetadata.after)
+ throw new Error("SSO is not configured for this organization.");
+ const matches = await db()
+ .select({ id: organizations.id })
+ .from(organizations)
+ .where(
+ and(
+ inArray(
+ organizations.workosOrganizationId,
+ verified.map((organization) => organization.id),
+ ),
+ isNull(organizations.tombstoneAt),
+ ),
+ )
+ .limit(2);
+ if (matches.length !== 1 || !matches[0])
+ throw new Error(
+ "Use the SSO sign-in link provided by your administrator.",
+ );
+ organizationId = matches[0].id;
+ }
+ const existingBilling = await getSsoBilling(organizationId);
+ const billing = existingBilling?.stripeSubscriptionId
+ ? await syncSsoSubscription(existingBilling.stripeSubscriptionId)
+ : null;
+ if (!hasSsoAccess(billing))
+ throw new Error(
+ "SSO is not available for this organization. Contact your administrator.",
+ );
+ const organization = await getRegisteredSsoOrganization(organizationId);
+ const configuration = await getSsoConfiguration(organization);
+ const connection = connectionId
+ ? await workos.sso.getConnection(connectionId)
+ : configuration?.connection;
if (
- !organization ||
- !organization.workosOrganizationId ||
- !organization.workosConnectionId
+ !configuration ||
+ !connection ||
+ connection.state !== "active" ||
+ connection.organizationId !== organization.workosOrganizationId ||
+ !configuration.organization.domains.some(
+ (domain) => domain.state === "verified",
+ )
) {
- throw new Error("Organization not found or SSO not configured");
+ throw new Error("SSO setup is not complete. Contact your administrator.");
}
-
+ const user = await getCurrentUser();
+ const env = serverEnv();
+ const cookie = ssoIntentCookie(new URL(env.WEB_URL).protocol === "https:");
+ (await cookies()).set(
+ cookie.name,
+ createSsoLoginIntent(
+ {
+ organizationId,
+ workosOrganizationId: configuration.organization.id,
+ connectionId: connection.id,
+ actorId: user?.id ?? null,
+ returnTo: getSafeNextPath(
+ typeof returnTo === "string" ? returnTo : undefined,
+ env.WEB_URL,
+ ),
+ },
+ env.NEXTAUTH_SECRET,
+ ),
+ cookie.options,
+ );
return {
- organizationId: organization.workosOrganizationId,
- connectionId: organization.workosConnectionId,
+ organizationId: configuration.organization.id,
+ connectionId: connection.id,
name: organization.name,
};
}
diff --git a/apps/web/app/(org)/login/form.tsx b/apps/web/app/(org)/login/form.tsx
index 0b2646323..68eba9c6b 100644
--- a/apps/web/app/(org)/login/form.tsx
+++ b/apps/web/app/(org)/login/form.tsx
@@ -1,7 +1,6 @@
"use client";
import { Button, Input, LogoBadge } from "@cap/ui";
-import { Organisation } from "@cap/web-domain";
import {
faArrowLeft,
faEnvelope,
@@ -22,6 +21,7 @@ import {
useId,
useRef,
useState,
+ useTransition,
} from "react";
import { toast } from "sonner";
import { getOrganizationSSOData } from "@/actions/organization/get-organization-sso-data";
@@ -43,15 +43,24 @@ export function LoginForm() {
const [loading, setLoading] = useState(false);
const [emailSent, setEmailSent] = useState(false);
const [oauthError, setOauthError] = useState(false);
- const [showOrgInput, setShowOrgInput] = useState(false);
- const [organizationId, setOrganizationId] = useState("");
+ const [showOrgInput, setShowOrgInput] = useState(
+ Boolean(
+ searchParams?.get("organizationId") ||
+ searchParams?.get("connection_id") ||
+ searchParams?.get("sso") === "1" ||
+ searchParams?.get("mobileProvider") === "workos",
+ ),
+ );
+ const [ssoIdentifier, setSsoIdentifier] = useState("");
+ const [ssoLoading, startSsoTransition] = useTransition();
const [organizationName, setOrganizationName] = useState<string | null>(null);
const [lastEmailSentTime, setLastEmailSentTime] = useState<number | null>(
null,
);
const mobileAppleSignInStarted = useRef(false);
const mobileGoogleSignInStarted = useRef(false);
- const mobileWorkosSignInStarted = useRef(false);
+ const workosSignInStarted = useRef(false);
+ const workosSignInPending = useRef(false);
const loginFormMounted = useRef(false);
const theme = Cookies.get("theme") || "light";
const getNextPath = useCallback(
@@ -75,23 +84,35 @@ export function LoginForm() {
useEffect(() => {
const error = searchParams?.get("error");
- const errorDesc = searchParams?.get("error_description");
const handleErrors = () => {
- if (error === "OAuthAccountNotLinked" && !errorDesc) {
+ if (error === "OAuthAccountNotLinked") {
setOauthError(true);
return toast.error(
- "This email is already associated with a different sign-in method",
+ "This email already has a Cap account. Sign in using your original sign-in method.",
+ );
+ } else if (error === "SsoSessionExpired") {
+ setShowOrgInput(true);
+ return toast.error(
+ "Your SSO sign-in session expired. Enter your work email or domain to start again.",
);
- } else if (
- error === "profile_not_allowed_outside_organization" &&
- !errorDesc
- ) {
+ } else if (error === "SsoSignInFailed") {
+ setShowOrgInput(true);
+ return toast.error(
+ "SSO sign-in could not be completed. Start again with your work email or domain, or contact your organization's administrator.",
+ );
+ } else if (error === "profile_not_allowed_outside_organization") {
return toast.error(
"Your email domain is not authorized for SSO access. Please use your work email or contact your administrator.",
);
- } else if (error && errorDesc) {
- return toast.error(errorDesc);
+ } else if (error === "signin_consent_denied") {
+ return toast.error(
+ "SSO sign-in was canceled. Only continue if you recognize your organization's identity provider.",
+ );
+ } else if (error) {
+ return toast.error(
+ "Sign-in could not be completed. Please try again, or contact your organization's administrator if you use SSO.",
+ );
}
};
handleErrors();
@@ -150,16 +171,43 @@ export function LoginForm() {
}, [getNextPath]);
const handleWorkosSignIn = useCallback(
- async (orgId: string) => {
- const nextPath = getNextPath();
- const data = await getOrganizationSSOData(
- Organisation.OrganisationId.make(orgId),
- );
- setOrganizationName(data.name);
+ (identifier: string, connectionId?: string) => {
+ if (workosSignInPending.current) return;
+ workosSignInPending.current = true;
+ setOrganizationName(null);
- signIn("workos", nextPath ? { callbackUrl: nextPath } : undefined, {
- organization: data.organizationId,
- connection: data.connectionId,
+ startSsoTransition(async () => {
+ try {
+ const data = await getOrganizationSSOData(
+ identifier,
+ connectionId,
+ getNextPath() ?? "/dashboard",
+ );
+ if (!loginFormMounted.current) return;
+ setOrganizationName(data.name);
+ trackEvent("auth_started", {
+ method: "workos",
+ is_signup: false,
+ auth_surface: "login",
+ });
+ await signIn(
+ "workos",
+ { callbackUrl: getNextPath() ?? "/dashboard" },
+ {
+ connection: data.connectionId,
+ },
+ );
+ } catch {
+ if (!loginFormMounted.current) return;
+ setOrganizationName(null);
+ setSsoIdentifier(identifier);
+ setShowOrgInput(true);
+ toast.error(
+ "SSO is not available for this organization yet. Check your work email or domain, or contact your administrator.",
+ );
+ } finally {
+ workosSignInPending.current = false;
+ }
});
},
[getNextPath],
@@ -180,36 +228,33 @@ export function LoginForm() {
return;
}
- if (searchParams?.get("mobileProvider") !== "workos") return;
- const mobileOrganizationId = searchParams.get("organizationId");
- if (!mobileOrganizationId) {
- setShowOrgInput(true);
+ if (searchParams?.get("error")) return;
+ const organizationId = searchParams?.get("organizationId");
+ const connectionId = searchParams?.get("connection_id");
+ if (
+ searchParams?.get("mobileProvider") !== "workos" &&
+ !organizationId &&
+ !connectionId
+ ) {
return;
}
- if (mobileWorkosSignInStarted.current) return;
- mobileWorkosSignInStarted.current = true;
-
- handleWorkosSignIn(mobileOrganizationId).catch(() => {
- if (!loginFormMounted.current) return;
- setOrganizationId(mobileOrganizationId);
- setShowOrgInput(true);
- toast.error("Organization not found or SSO not configured");
- });
+ setShowOrgInput(true);
+ if (!organizationId && !connectionId) return;
+ if (workosSignInStarted.current) return;
+ workosSignInStarted.current = true;
+ setSsoIdentifier(organizationId ?? "");
+ handleWorkosSignIn(organizationId ?? "", connectionId ?? undefined);
}, [handleAppleSignIn, handleGoogleSignIn, handleWorkosSignIn, searchParams]);
- const handleOrganizationLookup = async (e: React.FormEvent) => {
+ const handleOrganizationLookup = (e: React.FormEvent) => {
e.preventDefault();
- if (!organizationId) {
- toast.error("Please enter an organization ID");
+ const identifier = ssoIdentifier.trim();
+ if (!identifier) {
+ toast.error("Enter your work email or domain.");
return;
}
- try {
- await handleWorkosSignIn(organizationId);
- } catch (error) {
- console.error("Lookup Error:", error);
- toast.error("Organization not found or SSO not configured");
- }
+ handleWorkosSignIn(identifier);
};
return (
@@ -221,7 +266,8 @@ export function LoginForm() {
}}
className="overflow-hidden relative w-[calc(100%-5%)] p-[28px] max-w-[432px] bg-gray-3 border border-gray-5 rounded-2xl"
>
- <motion.div
+ <motion.button
+ type="button"
layout="position"
key="back-button"
initial={{ opacity: 0, display: "none" }}
@@ -231,13 +277,14 @@ export function LoginForm() {
transition: { duration: 0.1, delay: 0.2 },
}}
onClick={() => setShowOrgInput(false)}
+ disabled={ssoLoading}
className="absolute overflow-hidden top-5 rounded-full left-5 z-20 hover:bg-gray-1 gap-2 items-center py-1.5 px-3 text-gray-12 bg-transparent border border-gray-4 transition-colors duration-300 cursor-pointer"
>
<FontAwesomeIcon className="w-2" icon={faArrowLeft} />
<motion.p layout="position" className="text-xs text-inherit">
Back
</motion.p>
- </motion.div>
+ </motion.button>
<MotionLink layout="position" className="flex mx-auto size-fit" href="/">
<MotionLogoBadge layout="position" className="size-12" />
</MotionLink>
@@ -297,9 +344,10 @@ export function LoginForm() {
>
<LoginWithSSO
handleOrganizationLookup={handleOrganizationLookup}
- organizationId={organizationId}
- setOrganizationId={setOrganizationId}
+ identifier={ssoIdentifier}
+ setIdentifier={setSsoIdentifier}
organizationName={organizationName}
+ loading={ssoLoading}
/>
</motion.div>
) : (
@@ -411,16 +459,18 @@ export function LoginForm() {
const LoginWithSSO = ({
handleOrganizationLookup,
- organizationId,
- setOrganizationId,
+ identifier,
+ setIdentifier,
organizationName,
+ loading,
}: {
handleOrganizationLookup: (e: React.FormEvent) => void;
- organizationId: string;
- setOrganizationId: (organizationId: string) => void;
+ identifier: string;
+ setIdentifier: (identifier: string) => void;
organizationName: string | null;
+ loading: boolean;
}) => {
- const organizationIdInputId = useId();
+ const identifierInputId = useId();
return (
<motion.form
@@ -428,19 +478,36 @@ const LoginWithSSO = ({
onSubmit={handleOrganizationLookup}
className="relative space-y-2"
>
+ <label htmlFor={identifierInputId} className="text-sm text-gray-12">
+ Work email or domain
+ </label>
<MotionInput
- id={organizationIdInputId}
- placeholder="Enter your Organization ID..."
- value={organizationId}
- onChange={(e) => setOrganizationId(e.target.value)}
+ id={identifierInputId}
+ name="organization"
+ placeholder="[email protected] or company.com"
+ autoComplete="username"
+ autoCapitalize="none"
+ autoCorrect="off"
+ required
+ value={identifier}
+ disabled={loading}
+ onChange={(e) => setIdentifier(e.target.value)}
className="w-full max-w-full"
/>
- {organizationName && (
- <p className="text-sm text-gray-1">Signing in to: {organizationName}</p>
- )}
+ <p className="text-xs leading-5 text-gray-10" aria-live="polite">
+ {organizationName
+ ? `Signing in to ${organizationName}…`
+ : "Your organization must have SSO set up before you can continue."}
+ </p>
<div>
- <Button type="submit" variant="dark" className="w-full max-w-full">
- Continue with SSO
+ <Button
+ type="submit"
+ variant="dark"
+ className="w-full max-w-full"
+ disabled={loading}
+ spinner={loading}
+ >
+ {loading ? "Connecting to SSO…" : "Continue with SSO"}
</Button>
</div>
</motion.form>
diff --git a/apps/web/app/(org)/login/page.tsx b/apps/web/app/(org)/login/page.tsx
index 195cd182a..f98e51377 100644
--- a/apps/web/app/(org)/login/page.tsx
+++ b/apps/web/app/(org)/login/page.tsx
@@ -10,14 +10,38 @@ import { LoginForm } from "./form";
export const dynamic = "force-dynamic";
export default async function LoginPage(props: {
- searchParams: Promise<{ next?: string | string[] }>;
+ searchParams: Promise<{
+ next?: string | string[];
+ organizationId?: string | string[];
+ connection_id?: string | string[];
+ mobileProvider?: string | string[];
+ sso?: string | string[];
+ error?: string | string[];
+ }>;
}) {
const [searchParams, session] = await Promise.all([
props.searchParams,
getCurrentUser(),
]);
+ const [organizationId, connectionId, mobileProvider, sso, error] = [
+ searchParams.organizationId,
+ searchParams.connection_id,
+ searchParams.mobileProvider,
+ searchParams.sso,
+ searchParams.error,
+ ].map((value) => (Array.isArray(value) ? value[0] : value));
+ const isSsoEntry = Boolean(
+ organizationId ||
+ connectionId ||
+ mobileProvider === "workos" ||
+ sso === "1" ||
+ error === "SsoSessionExpired" ||
+ error === "SsoSignInFailed" ||
+ error === "profile_not_allowed_outside_organization" ||
+ error === "signin_consent_denied",
+ );
- if (session) {
+ if (session && !isSsoEntry) {
redirect(getSafeNextPath(searchParams.next, serverEnv().WEB_URL));
}
diff --git a/apps/web/app/(org)/signup/form.tsx b/apps/web/app/(org)/signup/form.tsx
index c64f24309..61f444760 100644
--- a/apps/web/app/(org)/signup/form.tsx
+++ b/apps/web/app/(org)/signup/form.tsx
@@ -1,7 +1,6 @@
"use client";
import { Button, Input, LogoBadge } from "@cap/ui";
-import { Organisation } from "@cap/web-domain";
import {
faArrowLeft,
faEnvelope,
@@ -15,7 +14,15 @@ import Image from "next/image";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { signIn } from "next-auth/react";
-import { Suspense, useEffect, useId, useState } from "react";
+import {
+ Suspense,
+ useCallback,
+ useEffect,
+ useId,
+ useRef,
+ useState,
+ useTransition,
+} from "react";
import { toast } from "sonner";
import { getOrganizationSSOData } from "@/actions/organization/get-organization-sso-data";
import { trackEvent } from "@/app/utils/analytics";
@@ -36,15 +43,34 @@ export function SignupForm() {
const [loading, setLoading] = useState(false);
const [emailSent, setEmailSent] = useState(false);
const [oauthError, setOauthError] = useState(false);
- const [showOrgInput, setShowOrgInput] = useState(false);
- const [organizationId, setOrganizationId] = useState("");
+ const [showOrgInput, setShowOrgInput] = useState(
+ Boolean(
+ searchParams?.get("organizationId") ||
+ searchParams?.get("connection_id") ||
+ searchParams?.get("sso") === "1",
+ ),
+ );
+ const [ssoIdentifier, setSsoIdentifier] = useState("");
+ const [ssoLoading, startSsoTransition] = useTransition();
const [organizationName, setOrganizationName] = useState<string | null>(null);
const [lastEmailSentTime, setLastEmailSentTime] = useState<number | null>(
null,
);
+ const workosSignInStarted = useRef(false);
+ const workosSignInPending = useRef(false);
+ const signupFormMounted = useRef(false);
const theme = Cookies.get("theme") || "light";
- const getNextPath = () =>
- next ? getSafeNextPath(next, window.location.origin) : null;
+ const getNextPath = useCallback(
+ () => (next ? getSafeNextPath(next, window.location.origin) : null),
+ [next],
+ );
+
+ useEffect(() => {
+ signupFormMounted.current = true;
+ return () => {
+ signupFormMounted.current = false;
+ };
+ }, []);
useEffect(() => {
document.body.className = theme === "dark" ? "dark" : "light";
@@ -55,23 +81,35 @@ export function SignupForm() {
useEffect(() => {
const error = searchParams?.get("error");
- const errorDesc = searchParams?.get("error_description");
const handleErrors = () => {
- if (error === "OAuthAccountNotLinked" && !errorDesc) {
+ if (error === "OAuthAccountNotLinked") {
setOauthError(true);
return toast.error(
- "This email is already associated with a different sign-in method",
+ "This email already has a Cap account. Sign in using your original sign-in method.",
+ );
+ } else if (error === "SsoSessionExpired") {
+ setShowOrgInput(true);
+ return toast.error(
+ "Your SSO sign-in session expired. Enter your work email or domain to start again.",
);
- } else if (
- error === "profile_not_allowed_outside_organization" &&
- !errorDesc
- ) {
+ } else if (error === "SsoSignInFailed") {
+ setShowOrgInput(true);
+ return toast.error(
+ "SSO sign-in could not be completed. Start again with your work email or domain, or contact your organization's administrator.",
+ );
+ } else if (error === "profile_not_allowed_outside_organization") {
return toast.error(
"Your email domain is not authorized for SSO access. Please use your work email or contact your administrator.",
);
- } else if (error && errorDesc) {
- return toast.error(errorDesc);
+ } else if (error === "signin_consent_denied") {
+ return toast.error(
+ "SSO sign-in was canceled. Only continue if you recognize your organization's identity provider.",
+ );
+ } else if (error) {
+ return toast.error(
+ "Sign-in could not be completed. Please try again, or contact your organization's administrator if you use SSO.",
+ );
}
};
handleErrors();
@@ -117,27 +155,69 @@ export function SignupForm() {
});
};
- const handleOrganizationLookup = async (e: React.FormEvent) => {
- e.preventDefault();
- if (!organizationId) {
- toast.error("Please enter an organization ID");
- return;
- }
+ const handleWorkosSignIn = useCallback(
+ (identifier: string, connectionId?: string) => {
+ if (workosSignInPending.current) return;
+ workosSignInPending.current = true;
+ setOrganizationName(null);
- try {
- const data = await getOrganizationSSOData(
- Organisation.OrganisationId.make(organizationId),
- );
- setOrganizationName(data.name);
-
- signIn("workos", undefined, {
- organization: data.organizationId,
- connection: data.connectionId,
+ startSsoTransition(async () => {
+ try {
+ const data = await getOrganizationSSOData(
+ identifier,
+ connectionId,
+ getNextPath() ?? "/dashboard",
+ );
+ if (!signupFormMounted.current) return;
+ setOrganizationName(data.name);
+ trackEvent("auth_started", {
+ method: "workos",
+ is_signup: true,
+ auth_surface: "signup",
+ });
+ await signIn(
+ "workos",
+ { callbackUrl: getNextPath() ?? "/dashboard" },
+ {
+ connection: data.connectionId,
+ },
+ );
+ } catch {
+ if (!signupFormMounted.current) return;
+ setOrganizationName(null);
+ setSsoIdentifier(identifier);
+ setShowOrgInput(true);
+ toast.error(
+ "SSO is not available for this organization yet. Check your work email or domain, or contact your administrator.",
+ );
+ } finally {
+ workosSignInPending.current = false;
+ }
});
- } catch (error) {
- console.error("Lookup Error:", error);
- toast.error("Organization not found or SSO not configured");
+ },
+ [getNextPath],
+ );
+
+ useEffect(() => {
+ if (searchParams?.get("error")) return;
+ const organizationId = searchParams?.get("organizationId");
+ const connectionId = searchParams?.get("connection_id");
+ if (!organizationId && !connectionId) return;
+ if (workosSignInStarted.current) return;
+ workosSignInStarted.current = true;
+ setShowOrgInput(true);
+ setSsoIdentifier(organizationId ?? "");
+ handleWorkosSignIn(organizationId ?? "", connectionId ?? undefined);
+ }, [handleWorkosSignIn, searchParams]);
+
+ const handleOrganizationLookup = (e: React.FormEvent) => {
+ e.preventDefault();
+ const identifier = ssoIdentifier.trim();
+ if (!identifier) {
+ toast.error("Enter your work email or domain.");
+ return;
}
+ handleWorkosSignIn(identifier);
};
return (
@@ -149,7 +229,8 @@ export function SignupForm() {
}}
className="overflow-hidden relative w-[calc(100%-5%)] p-[28px] max-w-[432px] bg-gray-3 border border-gray-5 rounded-2xl"
>
- <motion.div
+ <motion.button
+ type="button"
layout="position"
key="back-button"
initial={{ opacity: 0, display: "none" }}
@@ -159,13 +240,14 @@ export function SignupForm() {
transition: { duration: 0.1, delay: 0.2 },
}}
onClick={() => setShowOrgInput(false)}
+ disabled={ssoLoading}
className="absolute overflow-hidden top-5 rounded-full left-5 z-20 hover:bg-gray-1 gap-2 items-center py-1.5 px-3 text-gray-12 bg-transparent border border-gray-4 transition-colors duration-300 cursor-pointer"
>
<FontAwesomeIcon className="w-2" icon={faArrowLeft} />
<motion.p layout="position" className="text-xs text-inherit">
Back
</motion.p>
- </motion.div>
+ </motion.button>
<MotionLink layout="position" className="flex mx-auto size-fit" href="/">
<MotionLogoBadge layout="position" className="w-[72px] h-[72px]" />
</MotionLink>
@@ -225,9 +307,10 @@ export function SignupForm() {
>
<SignupWithSSO
handleOrganizationLookup={handleOrganizationLookup}
- organizationId={organizationId}
- setOrganizationId={setOrganizationId}
+ identifier={ssoIdentifier}
+ setIdentifier={setSsoIdentifier}
organizationName={organizationName}
+ loading={ssoLoading}
/>
</motion.div>
) : (
@@ -351,16 +434,18 @@ export function SignupForm() {
const SignupWithSSO = ({
handleOrganizationLookup,
- organizationId,
- setOrganizationId,
+ identifier,
+ setIdentifier,
organizationName,
+ loading,
}: {
handleOrganizationLookup: (e: React.FormEvent) => void;
- organizationId: string;
- setOrganizationId: (organizationId: string) => void;
+ identifier: string;
+ setIdentifier: (identifier: string) => void;
organizationName: string | null;
+ loading: boolean;
}) => {
- const organizationIdInputId = useId();
+ const identifierInputId = useId();
return (
<motion.form
@@ -368,21 +453,36 @@ const SignupWithSSO = ({
onSubmit={handleOrganizationLookup}
className="relative space-y-2"
>
+ <label htmlFor={identifierInputId} className="text-sm text-gray-12">
+ Work email or domain
+ </label>
<MotionInput
- id={organizationIdInputId}
- placeholder="Enter your Organization ID..."
- value={organizationId}
- onChange={(e) => setOrganizationId(e.target.value)}
+ id={identifierInputId}
+ name="organization"
+ placeholder="[email protected] or company.com"
+ autoComplete="username"
+ autoCapitalize="none"
+ autoCorrect="off"
+ required
+ value={identifier}
+ disabled={loading}
+ onChange={(e) => setIdentifier(e.target.value)}
className="w-full max-w-full"
/>
- {organizationName && (
- <p className="text-sm text-gray-1">
- Signing up with: {organizationName}
- </p>
- )}
+ <p className="text-xs leading-5 text-gray-10" aria-live="polite">
+ {organizationName
+ ? `Signing in to ${organizationName}…`
+ : "Your organization must have SSO set up before you can continue."}
+ </p>
<div>
- <Button type="submit" variant="dark" className="w-full max-w-full">
- Continue with SSO
+ <Button
+ type="submit"
+ variant="dark"
+ className="w-full max-w-full"
+ disabled={loading}
+ spinner={loading}
+ >
+ {loading ? "Connecting to SSO…" : "Continue with SSO"}
</Button>
</div>
</motion.form>
diff --git a/apps/web/app/(org)/signup/page.tsx b/apps/web/app/(org)/signup/page.tsx
index de68b63d0..dd570c327 100644
--- a/apps/web/app/(org)/signup/page.tsx
+++ b/apps/web/app/(org)/signup/page.tsx
@@ -7,9 +7,38 @@ import { SignupForm } from "./form";
export const dynamic = "force-dynamic";
-export default async function SignupPage() {
- const session = await getCurrentUser();
- if (session) {
+export default async function SignupPage(props: {
+ searchParams: Promise<{
+ next?: string | string[];
+ organizationId?: string | string[];
+ connection_id?: string | string[];
+ mobileProvider?: string | string[];
+ sso?: string | string[];
+ error?: string | string[];
+ }>;
+}) {
+ const [searchParams, session] = await Promise.all([
+ props.searchParams,
+ getCurrentUser(),
+ ]);
+ const [organizationId, connectionId, mobileProvider, sso, error] = [
+ searchParams.organizationId,
+ searchParams.connection_id,
+ searchParams.mobileProvider,
+ searchParams.sso,
+ searchParams.error,
+ ].map((value) => (Array.isArray(value) ? value[0] : value));
+ const isSsoEntry = Boolean(
+ organizationId ||
+ connectionId ||
+ mobileProvider === "workos" ||
+ sso === "1" ||
+ error === "SsoSessionExpired" ||
+ error === "SsoSignInFailed" ||
+ error === "profile_not_allowed_outside_organization" ||
+ error === "signin_consent_denied",
+ );
+ if (session && !isSsoEntry) {
redirect("/dashboard");
}
return (
diff --git a/apps/web/app/api/auth/[...nextauth]/route.ts b/apps/web/app/api/auth/[...nextauth]/route.ts
index e89058ce4..dc47d3e2a 100644
--- a/apps/web/app/api/auth/[...nextauth]/route.ts
+++ b/apps/web/app/api/auth/[...nextauth]/route.ts
@@ -1,8 +1,124 @@
-import { authOptions } from "@cap/database/auth/auth-options";
+import {
+ authOptions,
+ decodeSessionToken,
+} from "@cap/database/auth/auth-options";
+import {
+ ssoIntentCookie,
+ ssoLoginErrorPath,
+ verifySsoLoginIntent,
+} from "@cap/database/auth/sso-state";
+import { serverEnv } from "@cap/env";
+import { type NextRequest, NextResponse } from "next/server";
import NextAuth from "next-auth";
+import { getToken } from "next-auth/jwt";
+import { getSafeNextPath } from "@/app/(org)/safe-next";
export const dynamic = "force-dynamic";
-const handler = NextAuth(authOptions());
+async function readSignInBody(request: NextRequest) {
+ if (request.method !== "POST") return null;
+ try {
+ const contentType = request.headers.get("content-type");
+ if (contentType?.includes("application/json")) {
+ const body: unknown = await request.clone().json();
+ if (!body || typeof body !== "object") return null;
+ const payload = body as Record<string, unknown>;
+ return {
+ json: payload.json === "true",
+ callbackUrl:
+ typeof payload.callbackUrl === "string" ? payload.callbackUrl : null,
+ };
+ }
+ if (contentType?.includes("application/x-www-form-urlencoded")) {
+ const body = new URLSearchParams(await request.clone().text());
+ return {
+ json: body.get("json") === "true",
+ callbackUrl: body.get("callbackUrl"),
+ };
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
+
+async function handler(
+ request: NextRequest,
+ context: { params: Promise<{ nextauth: string[] }> },
+) {
+ const { nextauth } = await context.params;
+ if (nextauth[1] !== "workos") {
+ return NextAuth(request, context, authOptions());
+ }
+ const env = serverEnv();
+ const cookie = ssoIntentCookie(new URL(env.WEB_URL).protocol === "https:");
+ const intent = verifySsoLoginIntent(
+ request.cookies.get(cookie.name)?.value,
+ env.NEXTAUTH_SECRET,
+ );
+ const token = await getToken({
+ req: request,
+ secret: env.NEXTAUTH_SECRET,
+ cookieName: "next-auth.session-token",
+ decode: decodeSessionToken,
+ });
+ const actorId = typeof token?.id === "string" ? token.id : null;
+ if (
+ !intent ||
+ intent.actorId !== actorId ||
+ (nextauth[0] === "signin" &&
+ (request.nextUrl.searchParams.size !== 1 ||
+ request.nextUrl.searchParams.get("connection") !== intent.connectionId))
+ ) {
+ const body =
+ nextauth[0] === "signin" ? await readSignInBody(request) : null;
+ const returnTo = getSafeNextPath(
+ intent?.returnTo ??
+ body?.callbackUrl ??
+ request.cookies.get("next-auth.callback-url")?.value,
+ env.WEB_URL,
+ );
+ const errorUrl = new URL(
+ ssoLoginErrorPath("SsoSessionExpired", returnTo),
+ env.WEB_URL,
+ );
+ const response = body?.json
+ ? NextResponse.json({ url: errorUrl.toString() })
+ : NextResponse.redirect(errorUrl, 303);
+ response.cookies.set(cookie.name, "", { ...cookie.options, maxAge: 0 });
+ return response;
+ }
+ const response: Response = await NextAuth(
+ request,
+ context,
+ authOptions({ intent, actorId }),
+ );
+ if (nextauth[0] === "callback") {
+ response.headers.append(
+ "set-cookie",
+ `${cookie.name}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${cookie.options.secure ? "; Secure" : ""}`,
+ );
+ const location = response.headers.get("location");
+ if (location) {
+ const redirectUrl = new URL(location, env.WEB_URL);
+ if (
+ redirectUrl.origin === new URL(env.WEB_URL).origin &&
+ (redirectUrl.pathname === "/api/auth/error" ||
+ redirectUrl.pathname === "/api/auth/signin" ||
+ (redirectUrl.pathname === "/login" &&
+ redirectUrl.searchParams.has("error")))
+ ) {
+ response.headers.set(
+ "location",
+ new URL(
+ ssoLoginErrorPath("SsoSignInFailed", intent.returnTo),
+ env.WEB_URL,
+ ).toString(),
+ );
+ }
+ }
+ }
+ return response;
+}
export { handler as GET, handler as POST };
diff --git a/apps/web/app/api/mobile/[...route]/route.ts b/apps/web/app/api/mobile/[...route]/route.ts
index 084b7f1a0..b9598d4d4 100644
--- a/apps/web/app/api/mobile/[...route]/route.ts
+++ b/apps/web/app/api/mobile/[...route]/route.ts
@@ -2766,14 +2766,16 @@ const ApiLive = HttpApiBuilder.api(Mobile.MobileApiContract).pipe(
serverEnv().APPLE_CLIENT_ID && serverEnv().APPLE_CLIENT_SECRET,
),
googleAuthAvailable: Boolean(serverEnv().GOOGLE_CLIENT_ID),
- workosAuthAvailable: Boolean(serverEnv().WORKOS_CLIENT_ID),
+ workosAuthAvailable: Boolean(
+ serverEnv().WORKOS_CLIENT_ID && serverEnv().WORKOS_API_KEY,
+ ),
}),
)
.handle("requestSession", ({ request, urlParams }) =>
withMappedErrors(
Effect.gen(function* () {
const user = yield* getCurrentUser;
- if (Option.isNone(user)) {
+ if (Option.isNone(user) || urlParams.provider === "workos") {
const loginRedirectUrl =
Mobile.createMobileSessionLoginRedirectUrl({
deploymentOrigin: getDeploymentOrigin(),
diff --git a/apps/web/lib/sso/workos.ts b/apps/web/lib/sso/workos.ts
new file mode 100644
index 000000000..3034256f7
--- /dev/null
+++ b/apps/web/lib/sso/workos.ts
@@ -0,0 +1,134 @@
+import { db } from "@cap/database";
+import { getWorkOS, normalizeSsoDomain } from "@cap/database/auth/sso";
+import { organizations } from "@cap/database/schema";
+import type { Organisation } from "@cap/web-domain";
+import { DomainDataState } from "@workos-inc/node";
+import { and, eq, isNull } from "drizzle-orm";
+
+type CapOrganization = typeof organizations.$inferSelect;
+
+export async function getSsoConfiguration(organization: CapOrganization) {
+ if (!organization.workosOrganizationId) return null;
+ const workos = getWorkOS();
+ const [remote, connections] = await Promise.all([
+ workos.organizations.getOrganization(organization.workosOrganizationId),
+ workos.sso.listConnections({
+ organizationId: organization.workosOrganizationId,
+ limit: 100,
+ }),
+ ]);
+ if (
+ remote.id !== organization.workosOrganizationId ||
+ connections.data.some(
+ (connection) => connection.organizationId !== remote.id,
+ )
+ ) {
+ throw new Error("The SSO organization could not be verified.");
+ }
+ if (connections.listMetadata.after) {
+ throw new Error(
+ "This organization has too many SSO connections. Please contact Cap support.",
+ );
+ }
+ const active = connections.data.filter(
+ (connection) => connection.state === "active",
+ );
+ const configured = active.find(
+ (connection) => connection.id === organization.workosConnectionId,
+ );
+ return {
+ organization: remote,
+ requiresConnectionSelection: active.length > 1 && !configured,
+ connection:
+ configured ??
+ (active.length === 1
+ ? active[0]
+ : connections.data.length === 1
+ ? connections.data[0]
+ : null) ??
+ null,
+ };
+}
+
+export async function ensureWorkosOrganization(
+ organizationId: Organisation.OrganisationId,
+ domainInput?: string,
+) {
+ 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.");
+ const workos = getWorkOS();
+ if (organization.workosOrganizationId) {
+ const remote = await workos.organizations.getOrganization(
+ organization.workosOrganizationId,
+ );
+ if (remote.id !== organization.workosOrganizationId)
+ throw new Error("The SSO organization could not be verified.");
+ return remote;
+ }
+ const domain = normalizeSsoDomain(domainInput ?? "");
+ if (!domain) throw new Error("Enter your organization's work email domain.");
+ let remote: Awaited<ReturnType<typeof workos.organizations.getOrganization>>;
+ try {
+ remote =
+ await workos.organizations.getOrganizationByExternalId(organizationId);
+ } catch (error) {
+ if (
+ !(
+ error &&
+ typeof error === "object" &&
+ "status" in error &&
+ error.status === 404
+ )
+ )
+ throw error;
+ try {
+ remote = await workos.organizations.createOrganization(
+ {
+ name: organization.name,
+ externalId: organization.id,
+ domainData: [{ domain, state: DomainDataState.Pending }],
+ },
+ { idempotencyKey: `cap-sso-organization:${organization.id}` },
+ );
+ } catch {
+ remote =
+ await workos.organizations.getOrganizationByExternalId(organizationId);
+ }
+ }
+ if (remote.externalId !== organizationId)
+ throw new Error("The SSO organization could not be verified.");
+ await db()
+ .update(organizations)
+ .set({ workosOrganizationId: remote.id })
+ .where(
+ and(
+ eq(organizations.id, organizationId),
+ isNull(organizations.tombstoneAt),
+ isNull(organizations.workosOrganizationId),
+ ),
+ );
+ const [linked] = await db()
+ .select({ workosOrganizationId: organizations.workosOrganizationId })
+ .from(organizations)
+ .where(
+ and(
+ eq(organizations.id, organizationId),
+ isNull(organizations.tombstoneAt),
+ ),
+ )
+ .limit(1);
+ if (linked?.workosOrganizationId !== remote.id)
+ throw new Error(
+ "The SSO organization changed. Please refresh and try again.",
+ );
+ return remote;
+}
diff --git a/packages/database/auth/auth-options.ts b/packages/database/auth/auth-options.ts
index b10723a6e..b44feecc4 100644
--- a/packages/database/auth/auth-options.ts
+++ b/packages/database/auth/auth-options.ts
@@ -16,6 +16,13 @@ import { db } from "../index.ts";
import { users } from "../schema.ts";
import { isEmailAllowedForSignup } from "./domain-utils.ts";
import { DrizzleAdapter } from "./drizzle-adapter.ts";
+import {
+ provisionSsoMembership,
+ type SsoAuthContext,
+ type ValidatedSsoIdentity,
+ validateSsoSignIn,
+} from "./sso.ts";
+import { ssoLoginErrorPath } from "./sso-state.ts";
export const maxDuration = 120;
@@ -46,14 +53,17 @@ export async function decodeSessionToken(
return token;
}
-export const authOptions = (): NextAuthOptions => {
+export const authOptions = (ssoContext?: SsoAuthContext): NextAuthOptions => {
let _adapter: Adapter | undefined;
let _providers: Provider[] | undefined;
+ let validatedSsoIdentity: ValidatedSsoIdentity | null = null;
return {
get adapter() {
if (_adapter) return _adapter;
- _adapter = DrizzleAdapter(db());
+ _adapter = DrizzleAdapter(db(), {
+ getSsoIdentity: () => validatedSsoIdentity,
+ });
return _adapter;
},
debug: process.env.NODE_ENV !== "production",
@@ -95,20 +105,29 @@ export const authOptions = (): NextAuthOptions => {
},
},
}),
- WorkOSProvider({
- clientId: serverEnv().WORKOS_CLIENT_ID as string,
- clientSecret: serverEnv().WORKOS_API_KEY as string,
- profile(profile) {
- return {
- id: profile.id,
- name: profile.first_name
- ? `${profile.first_name} ${profile.last_name || ""}`
- : profile.email?.split("@")[0] || profile.id,
- email: profile.email,
- image: profile.profile_picture_url,
- };
- },
- }),
+ ...(serverEnv().WORKOS_CLIENT_ID && serverEnv().WORKOS_API_KEY
+ ? [
+ WorkOSProvider({
+ clientId: serverEnv().WORKOS_CLIENT_ID as string,
+ clientSecret: serverEnv().WORKOS_API_KEY as string,
+ checks: ["state", "pkce"],
+ allowDangerousEmailAccountLinking: true,
+ profile(profile) {
+ return {
+ id: profile.id,
+ name:
+ [profile.first_name, profile.last_name]
+ .filter(Boolean)
+ .join(" ") ||
+ profile.email?.split("@")[0] ||
+ profile.id,
+ email: profile.email?.trim().toLowerCase(),
+ image: null,
+ };
+ },
+ }),
+ ]
+ : []),
EmailProvider({
// next-auth defaults to 24h, but the code is 6 digits and the
// verify path has no attempt limiting, so a day-long window is a
@@ -183,7 +202,22 @@ export const authOptions = (): NextAuthOptions => {
},
},
callbacks: {
- async signIn({ user, email, credentials }) {
+ async signIn({ user, email, credentials, account, profile }) {
+ if (account?.provider === "workos") {
+ validatedSsoIdentity = null;
+ try {
+ validatedSsoIdentity = await validateSsoSignIn(
+ profile,
+ account.providerAccountId,
+ ssoContext,
+ );
+ } catch {
+ return ssoLoginErrorPath(
+ "SsoSignInFailed",
+ ssoContext?.intent?.returnTo,
+ );
+ }
+ }
const allowedDomains = serverEnv().CAP_ALLOWED_SIGNUP_DOMAINS;
if (!allowedDomains) return true;
@@ -226,7 +260,16 @@ export const authOptions = (): NextAuthOptions => {
return session;
},
- async jwt({ token, user }) {
+ async jwt({ token, user, account }) {
+ if (account?.provider === "workos") {
+ if (!user || !validatedSsoIdentity) {
+ throw new Error("The SSO sign-in was not verified.");
+ }
+ await provisionSsoMembership(
+ User.UserId.make(user.id),
+ validatedSsoIdentity,
+ );
+ }
if (user || !token.id) {
const [dbUser] = await db()
.select({
@@ -238,7 +281,11 @@ export const authOptions = (): NextAuthOptions => {
authSessionVersion: users.authSessionVersion,
})
.from(users)
- .where(eq(users.email, (token.email || "").toLowerCase()))
+ .where(
+ user
+ ? eq(users.id, User.UserId.make(user.id))
+ : eq(users.email, (token.email || "").toLowerCase()),
+ )
.limit(1);
if (!dbUser) {
diff --git a/packages/database/auth/drizzle-adapter.ts b/packages/database/auth/drizzle-adapter.ts
index 5431d734e..16f7e1045 100644
--- a/packages/database/auth/drizzle-adapter.ts
+++ b/packages/database/auth/drizzle-adapter.ts
@@ -1,4 +1,5 @@
-import { STRIPE_AVAILABLE, stripe } from "@cap/utils";
+import { createHash } from "node:crypto";
+import { isProSubscription, STRIPE_AVAILABLE, stripe } from "@cap/utils";
import { type ImageUpload, Organisation, User } from "@cap/web-domain";
import { and, eq } from "drizzle-orm";
import type { MySql2Database } from "drizzle-orm/mysql2";
@@ -14,6 +15,7 @@ import {
users,
verificationTokens,
} from "../schema.ts";
+import type { ValidatedSsoIdentity } from "./sso.ts";
type CreateUserData = Parameters<NonNullable<Adapter["createUser"]>>[0];
type LinkAccountData = Parameters<NonNullable<Adapter["linkAccount"]>>[0];
@@ -68,12 +70,27 @@ async function hasLinkedAccount(db: MySql2Database, userId: User.UserId) {
return !!linkedAccount;
}
-export function DrizzleAdapter(db: MySql2Database): Adapter {
+export function DrizzleAdapter(
+ db: MySql2Database,
+ options?: { getSsoIdentity: () => ValidatedSsoIdentity | null },
+): Adapter {
return {
async createUser(userData: CreateUserData) {
const normalizedEmail = userData.email.toLowerCase();
+ const ssoIdentity = options?.getSsoIdentity();
+ if (ssoIdentity && ssoIdentity.email !== normalizedEmail) {
+ throw new Error("The user does not match the verified SSO identity.");
+ }
let userId = User.UserId.make(nanoId());
await db.transaction(async (tx) => {
+ if (ssoIdentity) {
+ const [organization] = await tx
+ .select({ id: organizations.id })
+ .from(organizations)
+ .where(eq(organizations.id, ssoIdentity.organizationId))
+ .for("update");
+ if (!organization) throw new Error("SSO organization not found.");
+ }
const [existingUser] = await tx
.select()
.from(users)
@@ -115,7 +132,7 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
)
.limit(1);
- await tx.insert(users).values({
+ const insertUser = tx.insert(users).values({
id: userId,
email: normalizedEmail,
emailVerified: userData.emailVerified,
@@ -123,8 +140,22 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
image: userData.image as ImageUpload.ImageUrlOrKey | null,
activeOrganizationId: Organisation.OrganisationId.make(""),
});
+ if (ssoIdentity) {
+ await insertUser.onDuplicateKeyUpdate({
+ set: { email: normalizedEmail },
+ });
+ const [createdUser] = await tx
+ .select({ id: users.id })
+ .from(users)
+ .where(eq(users.email, normalizedEmail))
+ .limit(1);
+ if (!createdUser) throw new Error("User was not created.");
+ userId = createdUser.id;
+ } else {
+ await insertUser;
+ }
- if (pendingInvite) {
+ if (pendingInvite || ssoIdentity) {
return;
}
@@ -160,7 +191,7 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
let row = rows[0];
if (!row) throw new Error("User not found");
- if (STRIPE_AVAILABLE()) {
+ if (STRIPE_AVAILABLE() && !ssoIdentity) {
const existingCustomers = await stripe().customers.list({
email: normalizedEmail,
limit: 1,
@@ -191,7 +222,8 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
limit: 100,
});
- const inviteQuota = subscriptions.data.reduce((total, sub) => {
+ const proSubscriptions = subscriptions.data.filter(isProSubscription);
+ const inviteQuota = proSubscriptions.reduce((total, sub) => {
return (
total +
sub.items.data.reduce(
@@ -201,7 +233,7 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
);
}, 0);
- const mostRecentSubscription = subscriptions.data[0];
+ const mostRecentSubscription = proSubscriptions[0];
await db
.update(users)
@@ -295,6 +327,54 @@ export function DrizzleAdapter(db: MySql2Database): Adapter {
await db.delete(users).where(eq(users.id, User.UserId.make(userId)));
},
async linkAccount(account: LinkAccountData) {
+ if (account.provider === "workos") {
+ const identity = options?.getSsoIdentity();
+ if (!identity || identity.profileId !== account.providerAccountId) {
+ throw new Error("The SSO identity has not been verified.");
+ }
+ await db.transaction(async (tx) => {
+ await tx
+ .select({ id: organizations.id })
+ .from(organizations)
+ .where(eq(organizations.id, identity.organizationId))
+ .for("update");
+ const [user] = await tx
+ .select({ email: users.email })
+ .from(users)
+ .where(eq(users.id, User.UserId.make(account.userId)))
+ .for("update");
+ if (user?.email.toLowerCase() !== identity.email) {
+ throw new Error("The SSO account belongs to a different user.");
+ }
+ const linked = await tx
+ .selectDistinct({ userId: accounts.userId })
+ .from(accounts)
+ .where(
+ and(
+ eq(accounts.provider, "workos"),
+ eq(accounts.providerAccountId, identity.profileId),
+ ),
+ )
+ .limit(2);
+ if (linked.some((row) => row.userId !== account.userId)) {
+ throw new Error(
+ "The SSO identity is already linked to another account.",
+ );
+ }
+ if (linked.length > 0) return;
+ await tx.insert(accounts).values({
+ id: createHash("sha256")
+ .update(`workos:${identity.profileId}`)
+ .digest("base64url")
+ .slice(0, 15),
+ userId: account.userId,
+ type: account.type,
+ provider: "workos",
+ providerAccountId: identity.profileId,
+ });
+ });
+ return;
+ }
await db.insert(accounts).values({
id: User.UserId.make(nanoId()),
userId: account.userId,
diff --git a/packages/web-backend/src/Users/UsersOnboarding.ts b/packages/web-backend/src/Users/UsersOnboarding.ts
index 90abc007a..9e0402ab3 100644
--- a/packages/web-backend/src/Users/UsersOnboarding.ts
+++ b/packages/web-backend/src/Users/UsersOnboarding.ts
@@ -45,24 +45,21 @@ export class UsersOnboarding extends Effect.Service<UsersOnboarding>()(
.where(Dz.eq(Db.users.id, currentUser.id)),
);
- const activeOrgId = user.activeOrganizationId ?? user.defaultOrgId;
+ const activeOrgId = user.activeOrganizationId || user.defaultOrgId;
if (activeOrgId && firstName.length > 0) {
- const [organization] = yield* db.use((db) =>
+ yield* db.use((db) =>
db
- .select({ name: Db.organizations.name })
- .from(Db.organizations)
- .where(Dz.eq(Db.organizations.id, activeOrgId)),
+ .update(Db.organizations)
+ .set({ name: `${firstName}'s Organization` })
+ .where(
+ Dz.and(
+ Dz.eq(Db.organizations.id, activeOrgId),
+ Dz.eq(Db.organizations.ownerId, currentUser.id),
+ Dz.isNull(Db.organizations.tombstoneAt),
+ Dz.eq(Db.organizations.name, "My Organization"),
+ ),
+ ),
);
-
- if (organization?.name === "My Organization") {
- const personalizedName = `${firstName}'s Organization`;
- yield* db.use((db) =>
- db
- .update(Db.organizations)
- .set({ name: personalizedName })
- .where(Dz.eq(Db.organizations.id, activeOrgId)),
- );
- }
}
}),
@@ -86,27 +83,33 @@ export class UsersOnboarding extends Effect.Service<UsersOnboarding>()(
const organizationName =
data.organizationName.trim() || data.organizationName;
- let organizationId =
- user.activeOrganizationId ?? user.defaultOrgId ?? null;
-
- yield* db.use((db) =>
- db.transaction(async (tx) => {
- let resolvedOrgId = organizationId;
-
- if (resolvedOrgId) {
- const [existingOrg] = await tx
- .select({ id: Db.organizations.id })
- .from(Db.organizations)
- .where(Dz.eq(Db.organizations.id, resolvedOrgId));
-
- if (existingOrg) {
- await tx
- .update(Db.organizations)
- .set({ name: organizationName })
- .where(Dz.eq(Db.organizations.id, resolvedOrgId));
- } else {
- resolvedOrgId = Organisation.OrganisationId.make(nanoId());
-
+ const preferredOrganizationId =
+ user.activeOrganizationId || user.defaultOrgId;
+
+ const { organizationId, canEditOrganization } = yield* db.use(
+ (db) =>
+ db.transaction(async (tx) => {
+ const [existingOrg] = preferredOrganizationId
+ ? await tx
+ .select({
+ id: Db.organizations.id,
+ ownerId: Db.organizations.ownerId,
+ tombstoneAt: Db.organizations.tombstoneAt,
+ })
+ .from(Db.organizations)
+ .where(
+ Dz.eq(Db.organizations.id, preferredOrganizationId),
+ )
+ : [];
+ const resolvedOrgId =
+ existingOrg?.id ??
+ Organisation.OrganisationId.make(nanoId());
+ const canEditOrganization =
+ !existingOrg ||
+ (existingOrg.ownerId === currentUser.id &&
+ existingOrg.tombstoneAt === null);
+
+ if (!existingOrg) {
await tx.insert(Db.organizations).values({
id: resolvedOrgId,
ownerId: currentUser.id,
@@ -119,49 +122,57 @@ export class UsersOnboarding extends Effect.Service<UsersOnboarding>()(
userId: currentUser.id,
role: "owner",
});
+ } else if (canEditOrganization) {
+ await tx
+ .update(Db.organizations)
+ .set({ name: organizationName })
+ .where(
+ Dz.and(
+ Dz.eq(Db.organizations.id, resolvedOrgId),
+ Dz.eq(Db.organizations.ownerId, currentUser.id),
+ Dz.isNull(Db.organizations.tombstoneAt),
+ ),
+ );
}
- } else {
- resolvedOrgId = Organisation.OrganisationId.make(nanoId());
-
- await tx.insert(Db.organizations).values({
- id: resolvedOrgId,
- ownerId: currentUser.id,
- name: organizationName,
- });
-
- await tx.insert(Db.organizationMembers).values({
- id: nanoId(),
- organizationId: resolvedOrgId,
- userId: currentUser.id,
- role: "owner",
- });
- }
- await tx
- .update(Db.users)
- .set({
- activeOrganizationId: resolvedOrgId,
- defaultOrgId: resolvedOrgId,
- onboardingSteps: {
- ...user.onboardingSteps,
- organizationSetup: true,
- },
- })
- .where(Dz.eq(Db.users.id, currentUser.id));
-
- organizationId = resolvedOrgId;
- }),
+ await tx
+ .update(Db.users)
+ .set({
+ ...(!existingOrg?.tombstoneAt && {
+ activeOrganizationId: resolvedOrgId,
+ }),
+ ...(canEditOrganization && {
+ defaultOrgId: resolvedOrgId,
+ }),
+ onboardingSteps: {
+ ...user.onboardingSteps,
+ organizationSetup: true,
+ },
+ })
+ .where(Dz.eq(Db.users.id, currentUser.id));
+
+ return { organizationId: resolvedOrgId, canEditOrganization };
+ }),
);
- if (!organizationId) {
- throw new Error(
- "Failed to resolve organization during onboarding",
- );
- }
-
const finalOrganizationId = organizationId;
- if (data.organizationIcon) {
+ if (canEditOrganization && data.organizationIcon) {
+ const [ownedOrganization] = yield* db.use((db) =>
+ db
+ .select({ id: Db.organizations.id })
+ .from(Db.organizations)
+ .where(
+ Dz.and(
+ Dz.eq(Db.organizations.id, finalOrganizationId),
+ Dz.eq(Db.organizations.ownerId, currentUser.id),
+ Dz.isNull(Db.organizations.tombstoneAt),
+ ),
+ ),
+ );
+ if (!ownedOrganization)
+ return { organizationId: finalOrganizationId };
+
const organizationIcon = data.organizationIcon;
const uploadEffect = Effect.gen(function* () {
const {
@@ -191,7 +202,13 @@ export class UsersOnboarding extends Effect.Service<UsersOnboarding>()(
db
.update(Db.organizations)
.set({ iconUrl })
- .where(Dz.eq(Db.organizations.id, finalOrganizationId)),
+ .where(
+ Dz.and(
+ Dz.eq(Db.organizations.id, finalOrganizationId),
+ Dz.eq(Db.organizations.ownerId, currentUser.id),
+ Dz.isNull(Db.organizations.tombstoneAt),
+ ),
+ ),
});
}).pipe(
Effect.catchAll((error) =>
@@ -284,12 +301,14 @@ export class UsersOnboarding extends Effect.Service<UsersOnboarding>()(
})
.where(Dz.eq(Db.users.id, currentUser.id));
- const [existingOrg] = await tx
- .select()
- .from(Db.organizations)
- .where(
- Dz.eq(Db.organizations.id, currentUser.activeOrganizationId),
- );
+ const organizationId =
+ user.activeOrganizationId || user.defaultOrgId;
+ const [existingOrg] = organizationId
+ ? await tx
+ .select()
+ .from(Db.organizations)
+ .where(Dz.eq(Db.organizations.id, organizationId))
+ : [];
if (!existingOrg) {
const newOrgId = Organisation.OrganisationId.make(nanoId());
diff --git a/packages/web-domain/src/Mobile.ts b/packages/web-domain/src/Mobile.ts
index 6369bad3b..5c4dc4cde 100644
--- a/packages/web-domain/src/Mobile.ts
+++ b/packages/web-domain/src/Mobile.ts
@@ -94,6 +94,10 @@ export const createMobileSessionLoginRedirectUrl = ({
`${incomingUrl.pathname}${incomingUrl.search}`,
canonicalOrigin,
);
+ if (provider === "workos") {
+ continuationUrl.searchParams.delete("provider");
+ continuationUrl.searchParams.delete("organizationId");
+ }
const loginRedirectUrl = new URL("/login", canonicalOrigin);
loginRedirectUrl.searchParams.set("next", continuationUrl.toString());