Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(auth): add CAP_BLOCKED_SIGNUP_DOMAINS blocklist with a friendly notice (#2294)
Richie McIlroyedb0747ac9bf
diff --git a/apps/web/__tests__/unit/auth-options.test.ts b/apps/web/__tests__/unit/auth-options.test.tsindex 176befebf..8f919507e 100644--- a/apps/web/__tests__/unit/auth-options.test.ts+++ b/apps/web/__tests__/unit/auth-options.test.ts@@ -1,4 +1,7 @@-import { authOptions } from "@cap/database/auth/auth-options";+import {+ authOptions,+ decodeSessionToken,+} from "@cap/database/auth/auth-options";import type {SsoAuthContext,ValidatedSsoIdentity,@@ -37,6 +40,7 @@ const env = vi.hoisted(() => ({APPLE_CLIENT_ID: "so.cap.auth",APPLE_CLIENT_SECRET: "apple-secret",CAP_ALLOWED_SIGNUP_DOMAINS: undefined as string | undefined,+ CAP_BLOCKED_SIGNUP_DOMAINS: undefined as string | undefined,GOOGLE_CLIENT_ID: "google-client",GOOGLE_CLIENT_SECRET: "google-secret",NEXTAUTH_SECRET: "next-auth-secret",@@ -108,6 +112,7 @@ describe("authOptions", () => {env.WORKOS_CLIENT_ID = "workos-client";env.WORKOS_API_KEY = "workos-secret";env.CAP_ALLOWED_SIGNUP_DOMAINS = undefined;+ env.CAP_BLOCKED_SIGNUP_DOMAINS = undefined;mocks.validate.mockReset().mockResolvedValue(IDENTITY);mocks.provision.mockReset().mockResolvedValue(undefined);mocks.adapter.mockClear();@@ -175,6 +180,70 @@ describe("authOptions", () => {);});+ it("sends blocked domains and addresses to the login page with SignupBlocked", async () => {+ env.CAP_BLOCKED_SIGNUP_DOMAINS = "blocked.example, [email protected]";+ const callbacks = callbacksFor(authOptions(CONTEXT));++ await expect(+ callbacks.signIn({+ user: { id: "u1", email: "[email protected]" },+ account: { provider: "google", providerAccountId: "g1", type: "oauth" },+ }),+ ).resolves.toBe("/login?error=SignupBlocked");+ await expect(+ callbacks.signIn({+ user: { id: "u2", email: "[email protected]" },+ account: {+ provider: "email",+ providerAccountId: "[email protected]",+ type: "email",+ },+ email: { verificationRequest: true },+ }),+ ).resolves.toBe("/login?error=SignupBlocked");+ await expect(+ callbacks.signIn({+ user: { id: "u3", email: "[email protected]" },+ account: { provider: "google", providerAccountId: "g3", type: "oauth" },+ }),+ ).resolves.toBe(true);+ });++ it("expires existing sessions whose email is blocked", async () => {+ const { encode } = await import("next-auth/jwt");+ const secret = "next-auth-secret";+ const token = await encode({+ token: {+ id: "user-1",+ email: "[email protected]",+ sessionVersion: 0,+ },+ secret,+ });+ env.CAP_BLOCKED_SIGNUP_DOMAINS = "blocked.example";+ await expect(decodeSessionToken({ token, secret })).resolves.toBeNull();+ env.CAP_BLOCKED_SIGNUP_DOMAINS = undefined;+ mocks.select.mockReturnValueOnce({+ from: () => ({+ where: () => ({ limit: async () => [{ authSessionVersion: 0 }] }),+ }),+ } as never);+ await expect(decodeSessionToken({ token, secret })).resolves.toMatchObject({+ id: "user-1",+ email: "[email protected]",+ });+ });++ it("does not block anyone when CAP_BLOCKED_SIGNUP_DOMAINS is unset", async () => {+ const callbacks = callbacksFor(authOptions(CONTEXT));+ await expect(+ callbacks.signIn({+ user: { id: "u1", email: "[email protected]" },+ account: { provider: "google", providerAccountId: "g1", type: "oauth" },+ }),+ ).resolves.toBe(true);+ });+it("validates the raw WorkOS profile before exposing it to the adapter", async () => {const options = authOptions(CONTEXT);const adapter = options.adapter;diff --git a/apps/web/__tests__/unit/sso-login-pages.test.ts b/apps/web/__tests__/unit/sso-login-pages.test.tsindex 339124803..25d34a45c 100644--- a/apps/web/__tests__/unit/sso-login-pages.test.ts+++ b/apps/web/__tests__/unit/sso-login-pages.test.ts@@ -202,6 +202,18 @@ describe.each(["login", "signup"] as const)(expect(markup).toContain("Continue with SSO");});+ it("tells blocked sign-ups that Cap is open source", async () => {+ mocks.searchParams.set("error", "SignupBlocked");++ const markup = await renderForm();++ expect(markup).toContain('role="alert"');+ expect(markup).toContain("open source");+ expect(markup).toContain("https://github.com/CapSoftware/Cap");+ expect(markup).toContain("mailto:[email protected]");+ expect(markup).not.toContain("SSO profile details are missing");+ });+it.each(["", "SsoSignInFailed", "<script>untrusted error</script>"])("does not show a missing-profile notice for %j",async (error) => {diff --git a/apps/web/app/(org)/auth-email.ts b/apps/web/app/(org)/auth-email.tsindex 315ad0464..b6c0bd35b 100644--- a/apps/web/app/(org)/auth-email.ts+++ b/apps/web/app/(org)/auth-email.ts@@ -63,6 +63,13 @@ export async function requestEmailCode({return normalizedEmail;}+ if (response?.error === "SignupBlocked") {+ const params = new URLSearchParams(window.location.search);+ params.set("error", "SignupBlocked");+ window.location.assign(`${window.location.pathname}?${params.toString()}`);+ return null;+ }+toast.error(response?.error === "EmailSignin"? "Please wait 30 seconds before requesting a new code."diff --git a/apps/web/app/(org)/login/form.tsx b/apps/web/app/(org)/login/form.tsxindex f68643c74..5172e8ae5 100644--- a/apps/web/app/(org)/login/form.tsx+++ b/apps/web/app/(org)/login/form.tsx@@ -96,6 +96,8 @@ export function LoginForm() {} else if (error === "SsoMissingProfileAttributes") {setShowOrgInput(true);return;+ } else if (error === "SignupBlocked") {+ return;} else if (error === "SsoSessionExpired") {setShowOrgInput(true);return toast.error(diff --git a/apps/web/app/(org)/signup/form.tsx b/apps/web/app/(org)/signup/form.tsxindex b83835edd..ab81a3579 100644--- a/apps/web/app/(org)/signup/form.tsx+++ b/apps/web/app/(org)/signup/form.tsx@@ -103,6 +103,8 @@ export function SignupForm() {} else if (error === "SsoMissingProfileAttributes") {setShowOrgInput(true);return;+ } else if (error === "SignupBlocked") {+ return;} else if (error === "SsoSessionExpired") {setShowOrgInput(true);return toast.error(diff --git a/apps/web/app/(org)/sso-error-notice.tsx b/apps/web/app/(org)/sso-error-notice.tsxindex 2e0522910..bcb5b5101 100644--- a/apps/web/app/(org)/sso-error-notice.tsx+++ b/apps/web/app/(org)/sso-error-notice.tsx@@ -3,6 +3,37 @@ export function SsoErrorNotice({}: {error: string | null | undefined;}) {+ if (error === "SignupBlocked") {+ return (+ <div+ role="alert"+ className="rounded-xl border border-blue-200 bg-blue-50 p-4 text-sm text-blue-900"+ >+ <h2 className="mb-2 font-semibold">+ Interested in Cap? We're open source.+ </h2>+ <p>+ If you're a competitor and interested in signing up to Cap, we're open+ source. I'm very flattered that you want to snoop around. Feel free to+ check out our codebase on{" "}+ <a+ className="font-semibold underline"+ href="https://github.com/CapSoftware/Cap"+ rel="noreferrer"+ target="_blank"+ >+ GitHub+ </a>+ , or{" "}+ <a className="font-semibold underline" href="mailto:[email protected]">+ message Richie+ </a>+ , the founder, directly.+ </p>+ </div>+ );+ }+if (error !== "SsoMissingProfileAttributes") return null;return (diff --git a/apps/web/app/api/desktop/[...route]/root.ts b/apps/web/app/api/desktop/[...route]/root.tsindex 7ae82cb19..3727d4467 100644--- a/apps/web/app/api/desktop/[...route]/root.ts+++ b/apps/web/app/api/desktop/[...route]/root.ts@@ -1,4 +1,5 @@import { db } from "@cap/database";+import { isBlockedAccountEmail } from "@cap/database/auth/domain-utils";import { getCurrentUser } from "@cap/database/auth/session";import { sendEmail } from "@cap/database/emails/config";import { Feedback } from "@cap/database/emails/feedback";@@ -108,7 +109,8 @@ async function getDesktopProfileUser(c: Context) {.where(eq(authApiKeys.id, authHeader)).limit(1);- return user ?? null;+ if (!user || isBlockedAccountEmail(user.email)) return null;+ return user;}const user = await getCurrentUser();diff --git a/apps/web/app/api/utils.ts b/apps/web/app/api/utils.tsindex 3d25b5167..aaea02b42 100644--- a/apps/web/app/api/utils.ts+++ b/apps/web/app/api/utils.ts@@ -1,4 +1,5 @@import { db } from "@cap/database";+import { isBlockedAccountEmail } from "@cap/database/auth/domain-utils";import { getCurrentUser } from "@cap/database/auth/session";import {authApiKeys,@@ -79,6 +80,7 @@ async function getAuth(c: Context) {.leftJoin(authApiKeys, eq(users.id, authApiKeys.userId)).where(eq(authApiKeys.id, authHeader));user = res[0]?.users;+ if (user && isBlockedAccountEmail(user.email)) user = undefined;} else {user = await getCurrentUser();}diff --git a/packages/database/auth/auth-options.ts b/packages/database/auth/auth-options.tsindex b44feecc4..b8641c378 100644--- a/packages/database/auth/auth-options.ts+++ b/packages/database/auth/auth-options.ts@@ -14,7 +14,11 @@ import WorkOSProvider from "next-auth/providers/workos";import { sendEmail } from "../emails/config.ts";import { db } from "../index.ts";import { users } from "../schema.ts";-import { isEmailAllowedForSignup } from "./domain-utils.ts";+import {+ isBlockedAccountEmail,+ isEmailAllowedForSignup,+ isEmailBlockedFromSignup,+} from "./domain-utils.ts";import { DrizzleAdapter } from "./drizzle-adapter.ts";import {provisionSsoMembership,@@ -33,6 +37,9 @@ export async function decodeSessionToken(): Promise<JWT | null> {const token = await decode(params);if (!token) return null;+ // A blocked email loses its existing sessions, not just new sign-ins.+ if (typeof token.email === "string" && isBlockedAccountEmail(token.email))+ return null;const userId = typeof token.id === "string" ? token.id : null;if (!userId) return token;@@ -218,9 +225,6 @@ export const authOptions = (ssoContext?: SsoAuthContext): NextAuthOptions => {);}}- const allowedDomains = serverEnv().CAP_ALLOWED_SIGNUP_DOMAINS;- if (!allowedDomains) return true;-const rawEmail =user?.email ||(typeof email === "string"@@ -231,6 +235,19 @@ export const authOptions = (ssoContext?: SsoAuthContext): NextAuthOptions => {if (!rawEmail || typeof rawEmail !== "string") return true;const userEmail = rawEmail.toLowerCase();+ if (+ isEmailBlockedFromSignup(+ userEmail,+ serverEnv().CAP_BLOCKED_SIGNUP_DOMAINS,+ )+ ) {+ console.warn(`Sign-in blocked for email: ${userEmail}`);+ return "/login?error=SignupBlocked";+ }++ const allowedDomains = serverEnv().CAP_ALLOWED_SIGNUP_DOMAINS;+ if (!allowedDomains) return true;+const [existingUser] = await db().select().from(users)diff --git a/packages/database/auth/domain-utils.ts b/packages/database/auth/domain-utils.tsindex 9f6438301..c25e96545 100644--- a/packages/database/auth/domain-utils.ts+++ b/packages/database/auth/domain-utils.ts@@ -1,3 +1,4 @@+import { serverEnv } from "@cap/env";import { z } from "zod";export function isEmailAllowedForSignup(@@ -18,6 +19,46 @@ export function isEmailAllowedForSignup(return allowedDomains.includes(emailDomain.toLowerCase());}+/**+ * Whether an account email is refused everywhere: sign-in, existing sessions,+ * and API keys. Reads CAP_BLOCKED_SIGNUP_DOMAINS.+ */+export function isBlockedAccountEmail(+ email: string | null | undefined,+): boolean {+ if (!email) return false;+ return isEmailBlockedFromSignup(+ email,+ serverEnv().CAP_BLOCKED_SIGNUP_DOMAINS,+ );+}++/**+ * Whether an email is refused at sign-in. Entries are domains ("example.com")+ * or full addresses ("[email protected]"), comma-separated. Unlike the+ * allowlist this applies to existing users too, so a blocked account cannot+ * sign back in after it has been removed.+ */+export function isEmailBlockedFromSignup(+ email: string,+ blockedConfig?: string,+): boolean {+ if (!blockedConfig || blockedConfig.trim() === "") return false;+ const normalized = email.trim().toLowerCase();+ const emailDomain = extractDomainFromEmail(normalized);+ if (!emailDomain) return false;+ for (const raw of blockedConfig.split(",")) {+ const entry = raw.trim().toLowerCase();+ if (!entry) continue;+ if (entry.includes("@")) {+ if (entry === normalized) return true;+ } else if (isValidDomain(entry) && entry === emailDomain.toLowerCase()) {+ return true;+ }+ }+ return false;+}+function extractDomainFromEmail(email: string): string | null {// TODO: replace with zod v4's z.email()const emailValidation = z.string().email().safeParse(email);diff --git a/packages/env/server.ts b/packages/env/server.tsindex f2fcc43f5..78d649a44 100644--- a/packages/env/server.ts+++ b/packages/env/server.ts@@ -87,6 +87,12 @@ function createServerEnv() {.string().optional().describe("Comma-separated list of permitted signup domains"),+ CAP_BLOCKED_SIGNUP_DOMAINS: z+ .string()+ .optional()+ .describe(+ "Comma-separated domains or full email addresses refused at sign-in",+ ),/// AI providersASSEMBLY_API_KEY: z.string().optional().describe("Audio transcription"),diff --git a/packages/web-backend/src/AgentAuth.ts b/packages/web-backend/src/AgentAuth.tsindex e5d490c12..6290b63f7 100644--- a/packages/web-backend/src/AgentAuth.ts+++ b/packages/web-backend/src/AgentAuth.ts@@ -1,4 +1,5 @@import { createHash } from "node:crypto";+import { isBlockedAccountEmail } from "@cap/database/auth/domain-utils";import * as Db from "@cap/database/schema";import { Agent } from "@cap/web-domain";import { HttpServerRequest } from "@effect/platform";@@ -125,7 +126,8 @@ export const AgentHttpAuthMiddlewareLive = Layer.effect(.where(eq(Db.agentApiKeys.tokenHash, hashToken(token))).limit(1),);- if (!row) return yield* authRequired();+ if (!row || isBlockedAccountEmail(row.email))+ return yield* authRequired();if (row.revokedAt || row.expiresAt.getTime() <= Date.now()) {return yield* tokenExpired();}@@ -179,7 +181,8 @@ export const AgentHttpAuthMiddlewareLive = Layer.effect(.where(eq(Db.authApiKeys.id, token)).limit(1),);- if (!row) return yield* authRequired();+ if (!row || isBlockedAccountEmail(row.email))+ return yield* authRequired();if (!isLegacyAgentKeySource(row.source)) return yield* authRequired();return Agent.AgentPrincipal.of({diff --git a/packages/web-backend/src/Auth.ts b/packages/web-backend/src/Auth.tsindex 356fffdd3..aa6ebda01 100644--- a/packages/web-backend/src/Auth.ts+++ b/packages/web-backend/src/Auth.ts@@ -1,4 +1,5 @@import { getServerSession } from "@cap/database/auth/auth-options";+import { isBlockedAccountEmail } from "@cap/database/auth/domain-utils";import * as Db from "@cap/database/schema";import {CurrentUser,@@ -80,7 +81,13 @@ export const HttpAuthMiddlewareLive = Layer.effect().where(Dz.eq(Db.authApiKeys.id, authHeader)),)- .pipe(Effect.map(([entry]) => Option.fromNullable(entry?.users)));+ .pipe(+ Effect.map(([entry]) =>+ Option.fromNullable(entry?.users).pipe(+ Option.filter((user) => !isBlockedAccountEmail(user.email)),+ ),+ ),+ );} else {user = yield* getCurrentUser;}