Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
fix: disallow public emails
Marc Seitz0eed7f15e9af
diff --git a/app/(ee)/api/teams/[teamId]/saml/route.ts b/app/(ee)/api/teams/[teamId]/saml/route.tsindex c17e2ce3..25d0848f 100644--- a/app/(ee)/api/teams/[teamId]/saml/route.ts+++ b/app/(ee)/api/teams/[teamId]/saml/route.ts@@ -1,6 +1,7 @@import { jackson, jacksonProduct, samlAudience } from "@/lib/jackson";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";+import { isGenericDomain } from "@/lib/utils/email-domain";import { getServerSession } from "next-auth/next";import { NextResponse } from "next/server";@@ -97,7 +98,7 @@ export async function POST(try {const { apiController } = await jackson();const body = await req.json();- const { rawMetadata, encodedRawMetadata, metadataUrl } = body;+ const { rawMetadata, encodedRawMetadata, metadataUrl, domain } = body;if (!rawMetadata && !metadataUrl && !encodedRawMetadata) {return NextResponse.json(@@ -109,8 +110,30 @@ export async function POST();}- // Extract email domain from the admin's email for SSO domain binding- const ssoEmailDomain = auth.email.split("@")[1]?.toLowerCase();+ // Normalize the explicit domain provided by the admin (if any)+ const explicitDomain = typeof domain === "string"+ ? domain.trim().toLowerCase().replace(/^@/, "")+ : undefined;++ // Validate explicit domain format if provided+ if (explicitDomain && !/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(explicitDomain)) {+ return NextResponse.json(+ { error: "Invalid domain format. Please provide a valid domain (e.g., example.com)." },+ { status: 400 },+ );+ }++ // Reject public / free email provider domains – SSO should only be+ // configured for organisation-owned domains.+ if (explicitDomain && isGenericDomain(explicitDomain)) {+ return NextResponse.json(+ {+ error:+ "Public email domains (e.g., gmail.com, outlook.com) cannot be used for SSO. Please provide your organization's domain.",+ },+ { status: 400 },+ );+ }const connection = await apiController.createSAMLConnection({defaultRedirectUrl: `${process.env.NEXTAUTH_URL}/auth/saml`,@@ -122,13 +145,71 @@ export async function POST(metadataUrl: metadataUrl || undefined,});- // Store the email domain for SSO enforcement- await prisma.team.update({- where: { id: teamId },- data: {- ssoEmailDomain: ssoEmailDomain || undefined,- },- });+ // Attempt to extract a domain hint from the IdP metadata returned by the+ // SAML connection. Standard IdP entity IDs / SSO URLs sometimes contain+ // the organisation's own domain (e.g. for self-hosted IdPs). We use this+ // as an additional validation signal – if the admin supplied a domain we+ // check it is consistent; if not, we fall back to the metadata hint only+ // when it looks like a real organisation domain (not a generic IdP host).+ let metadataDomain: string | undefined;+ try {+ const idpMeta = (connection as any)?.idpMetadata;+ const candidateUrls: string[] = [+ idpMeta?.entityID,+ idpMeta?.sso?.postUrl,+ idpMeta?.sso?.redirectUrl,+ ].filter(Boolean);++ const genericIdpHosts = new Set([+ "accounts.google.com",+ "login.microsoftonline.com",+ "sts.windows.net",+ "idp.ssocircle.com",+ "www.okta.com",+ "dev.okta.com",+ "auth0.com",+ "onelogin.com",+ "pingone.com",+ ]);++ for (const raw of candidateUrls) {+ try {+ const host = new URL(raw).hostname.toLowerCase();+ // Skip well-known generic IdP hosts and public email domains+ if (+ [...genericIdpHosts].some((g) => host === g || host.endsWith(`.${g}`)) ||+ isGenericDomain(host)+ ) {+ continue;+ }+ // Must have at least two labels (e.g. "company.com")+ if (host.split(".").length >= 2) {+ metadataDomain = host;+ break;+ }+ } catch {+ // not a valid URL – skip+ }+ }+ } catch {+ // metadata extraction is best-effort+ }++ // Determine the validated domain to persist:+ // 1. Prefer the explicitly admin-provided domain.+ // 2. Fall back to a domain extracted from metadata (if non-generic).+ // 3. If neither is available, do NOT store a domain.+ const validatedDomain = explicitDomain || metadataDomain || undefined;++ // Only persist ssoEmailDomain when we have a validated value+ if (validatedDomain) {+ await prisma.team.update({+ where: { id: teamId },+ data: {+ ssoEmailDomain: validatedDomain,+ },+ });+ }return NextResponse.json(connection, { status: 201 });} catch (error: any) {diff --git a/ee/features/security/sso/components/saml-config-modal.tsx b/ee/features/security/sso/components/saml-config-modal.tsxindex aafa0dcc..2718d291 100644--- a/ee/features/security/sso/components/saml-config-modal.tsx+++ b/ee/features/security/sso/components/saml-config-modal.tsx@@ -42,6 +42,7 @@ export function SAMLConfigModal({ teamId }: SAMLConfigModalProps) {SAMLProviderKey | undefined>();const [metadataUrl, setMetadataUrl] = useState("");+ const [domain, setDomain] = useState("");const [file, setFile] = useState<File | null>(null);const [fileContent, setFileContent] = useState("");@@ -72,6 +73,11 @@ export function SAMLConfigModal({ teamId }: SAMLConfigModalProps) {body.metadataUrl = metadataUrl;}+ // Include the explicit SSO email domain if provided by the admin+ if (domain.trim()) {+ body.domain = domain.trim();+ }+const res = await fetch(`/api/teams/${teamId}/saml`, {method: "POST",headers: { "Content-Type": "application/json" },@@ -86,6 +92,7 @@ export function SAMLConfigModal({ teamId }: SAMLConfigModalProps) {toast.success("SAML SSO configured successfully!");setOpen(false);setMetadataUrl("");+ setDomain("");setFile(null);setFileContent("");setSelectedProvider(undefined);@@ -372,6 +379,27 @@ export function SAMLConfigModal({ teamId }: SAMLConfigModalProps) {</div>)}+ {/* Step 4: SSO Email Domain */}+ {currentProvider && (+ <div className="space-y-2">+ <Label htmlFor="ssoDomain">+ Step 4: SSO Email Domain+ </Label>+ <Input+ id="ssoDomain"+ placeholder="example.com"+ value={domain}+ onChange={(e) => setDomain(e.target.value)}+ disabled={submitting}+ />+ <p className="text-xs text-muted-foreground">+ The email domain used by your organization (e.g.,+ example.com). Only users with this domain will be able to+ sign in via SSO.+ </p>+ </div>+ )}+<DialogFooter><Buttontype="button"diff --git a/lib/api/teams/is-saml-enforced-for-email-domain.ts b/lib/api/teams/is-saml-enforced-for-email-domain.tsindex 44e9a9b9..eb1802b6 100644--- a/lib/api/teams/is-saml-enforced-for-email-domain.ts+++ b/lib/api/teams/is-saml-enforced-for-email-domain.ts@@ -1,4 +1,5 @@import prisma from "@/lib/prisma";+import { isGenericEmail } from "@/lib/utils/email-domain";/*** Checks if SAML SSO is enforced for a given email address's domain.@@ -15,24 +16,7 @@ export async function isSamlEnforcedForEmailDomain(}// Skip generic email providers — SSO enforcement doesn't apply- const genericDomains = [- "gmail.com",- "googlemail.com",- "yahoo.com",- "hotmail.com",- "outlook.com",- "live.com",- "aol.com",- "icloud.com",- "me.com",- "mail.com",- "protonmail.com",- "proton.me",- "fastmail.com",- "zoho.com",- ];-- if (genericDomains.includes(emailDomain)) {+ if (isGenericEmail(email)) {return false;}diff --git a/lib/utils/email-domain.ts b/lib/utils/email-domain.tsindex 01a39f7e..e6e81cd3 100644--- a/lib/utils/email-domain.ts+++ b/lib/utils/email-domain.ts@@ -1,3 +1,51 @@+export const GENERIC_EMAIL_DOMAINS = [+ "gmail.com",+ "googlemail.com",+ "yahoo.com",+ "yahoo.co.uk",+ "ymail.com",+ "hotmail.com",+ "outlook.com",+ "live.com",+ "msn.com",+ "aol.com",+ "icloud.com",+ "me.com",+ "mac.com",+ "comcast.net",+ "verizon.net",+ "att.net",+ "protonmail.com",+ "proton.me",+ "zoho.com",+ "mail.com",+ "gmx.com",+ "gmx.net",+ "yandex.com",+ "tutanota.com",+ "tuta.com",+ "fastmail.com",+ "hey.com",+];++/**+ * Returns true if the email belongs to a well-known free / consumer email+ * provider (e.g. gmail.com, outlook.com). Useful for distinguishing+ * organisation-owned domains from personal addresses.+ */+export const isGenericEmail = (email: string): boolean => {+ const domain = email.trim().toLowerCase().split("@").pop();+ return !!domain && GENERIC_EMAIL_DOMAINS.includes(domain);+};++/**+ * Returns true if the bare domain (no "@" prefix) is a well-known free /+ * consumer email provider.+ */+export const isGenericDomain = (domain: string): boolean => {+ return GENERIC_EMAIL_DOMAINS.includes(domain.trim().toLowerCase());+};+export function extractEmailDomain(email: string): string | null {if (!email || typeof email !== "string") {return null;