Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: add enterprise saml sso / scim

Marc Seitz9089b6cc4591
diff --git a/.env.example b/.env.example
index 7b5951a0..248692f1 100644
--- a/.env.example
+++ b/.env.example
@@ -79,11 +79,3 @@ NEXT_PRIVATE_VERIFICATION_SECRET=
# [[INCOMING WEBHOOKS]]
NEXT_PUBLIC_WEBHOOK_BASE_URL=
NEXT_PUBLIC_WEBHOOK_BASE_HOST=
-
-# [[JACKSON SAML/SCIM]]
-# The SAML audience URI that you'll give to IdP admins (e.g. https://saml.your-app.com)
-SAML_AUDIENCE=https://saml.your-app.com
-# Product identifier for Jackson (your app name)
-JACKSON_PRODUCT=papermark
-# Public product identifier for client-side use
-NEXT_PUBLIC_JACKSON_PRODUCT=papermark
diff --git a/app/(auth)/auth/saml/page-client.tsx b/app/(auth)/auth/saml/page-client.tsx
index b5cb8c6b..aeb54e6d 100644
--- a/app/(auth)/auth/saml/page-client.tsx
+++ b/app/(auth)/auth/saml/page-client.tsx
@@ -6,6 +6,17 @@ import { useEffect, useState } from "react";
import { signIn } from "next-auth/react";
+/**
+ * SAML Callback Page
+ *
+ * This page handles IdP-initiated SSO flow:
+ * 1. User clicks the app tile in their IdP dashboard
+ * 2. Jackson processes the SAML response and redirects here with a `code`
+ * 3. We exchange the code via the `saml-idp` CredentialsProvider
+ *
+ * SP-initiated SSO (user clicks "Continue with SSO" on login page) is handled
+ * entirely by NextAuth's OAuth flow via the `saml` provider — it never hits this page.
+ */
export default function SAMLCallbackClient() {
const searchParams = useSearchParams();
const router = useRouter();
@@ -15,7 +26,6 @@ export default function SAMLCallbackClient() {
useEffect(() => {
const code = searchParams?.get("code");
if (code) {
- // Use NextAuth's signIn with the saml-idp credentials provider
signIn("saml-idp", {
code,
redirect: false,
@@ -31,7 +41,9 @@ export default function SAMLCallbackClient() {
});
} else {
setStatus("error");
- setErrorMessage("No authorization code received from your identity provider.");
+ setErrorMessage(
+ "No authorization code received from your identity provider.",
+ );
}
}, [searchParams, router]);
diff --git a/app/(auth)/login/page-client.tsx b/app/(auth)/login/page-client.tsx
index 6b8b8e93..2fc0e7f8 100644
--- a/app/(auth)/login/page-client.tsx
+++ b/app/(auth)/login/page-client.tsx
@@ -5,6 +5,7 @@ import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
+import { SSOLogin } from "@/ee/features/security/sso";
import { signInWithPasskey } from "@teamhanko/passkeys-next-auth-provider/client";
import { signIn } from "next-auth/react";
import { toast } from "sonner";
@@ -12,7 +13,6 @@ import { z } from "zod";
import { cn } from "@/lib/utils";
-import { SSOLogin } from "@/components/auth/sso-login";
import { LastUsed, useLastUsed } from "@/components/hooks/useLastUsed";
import Google from "@/components/shared/icons/google";
import LinkedIn from "@/components/shared/icons/linkedin";
@@ -212,19 +212,7 @@ export default function Login() {
{lastUsed === "passkey" && <LastUsed />}
</Button>
</div>
- </div>
- <div className="px-4 pt-4 sm:px-12">
<div className="relative">
- <div className="absolute inset-0 flex items-center">
- <span className="w-full border-t border-gray-200" />
- </div>
- <div className="relative flex justify-center text-xs uppercase">
- <span className="bg-gray-50 px-2 text-muted-foreground">
- Enterprise SSO
- </span>
- </div>
- </div>
- <div className="mt-4">
<SSOLogin />
</div>
</div>
diff --git a/app/(ee)/api/auth/saml/authorize/route.ts b/app/(ee)/api/auth/saml/authorize/route.ts
new file mode 100644
index 00000000..5e0773b7
--- /dev/null
+++ b/app/(ee)/api/auth/saml/authorize/route.ts
@@ -0,0 +1,63 @@
+import { jackson } from "@/lib/jackson";
+import { NextResponse } from "next/server";
+
+export async function GET(req: Request) {
+ try {
+ const { oauthController } = await jackson();
+
+ const url = new URL(req.url);
+ const requestParams = Object.fromEntries(url.searchParams.entries());
+
+ const { redirect_url, authorize_form } =
+ await oauthController.authorize(requestParams);
+
+ if (redirect_url) {
+ return NextResponse.redirect(redirect_url, { status: 302 });
+ } else if (authorize_form) {
+ return new Response(authorize_form, {
+ headers: { "Content-Type": "text/html; charset=utf-8" },
+ });
+ }
+
+ return NextResponse.json(
+ { error: "No redirect URL returned" },
+ { status: 400 },
+ );
+ } catch (error: any) {
+ console.error("[SAML] Authorize error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
+
+export async function POST(req: Request) {
+ try {
+ const { oauthController } = await jackson();
+
+ const body = await req.json();
+
+ const { redirect_url, authorize_form } =
+ await oauthController.authorize(body);
+
+ if (redirect_url) {
+ return NextResponse.redirect(redirect_url, { status: 302 });
+ } else if (authorize_form) {
+ return new Response(authorize_form, {
+ headers: { "Content-Type": "text/html; charset=utf-8" },
+ });
+ }
+
+ return NextResponse.json(
+ { error: "No redirect URL returned" },
+ { status: 400 },
+ );
+ } catch (error: any) {
+ console.error("[SAML] Authorize error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/app/(ee)/api/auth/saml/callback/route.ts b/app/(ee)/api/auth/saml/callback/route.ts
new file mode 100644
index 00000000..4f5fc0f6
--- /dev/null
+++ b/app/(ee)/api/auth/saml/callback/route.ts
@@ -0,0 +1,32 @@
+import { jackson } from "@/lib/jackson";
+import { NextResponse } from "next/server";
+
+export async function POST(req: Request) {
+ try {
+ const { oauthController } = await jackson();
+
+ const formData = await req.formData();
+ const RelayState = (formData.get("RelayState") as string) || "";
+ const SAMLResponse = (formData.get("SAMLResponse") as string) || "";
+
+ const { redirect_url } = await oauthController.samlResponse({
+ RelayState,
+ SAMLResponse,
+ });
+
+ if (!redirect_url) {
+ return NextResponse.json(
+ { error: "No redirect URL returned" },
+ { status: 400 },
+ );
+ }
+
+ return NextResponse.redirect(redirect_url, { status: 302 });
+ } catch (error: any) {
+ console.error("[SAML] Callback error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/app/(ee)/api/auth/saml/token/route.ts b/app/(ee)/api/auth/saml/token/route.ts
new file mode 100644
index 00000000..f757b0de
--- /dev/null
+++ b/app/(ee)/api/auth/saml/token/route.ts
@@ -0,0 +1,31 @@
+import { jackson } from "@/lib/jackson";
+// These imports fix crypto module bundling issues with Jackson in Next.js.
+// Without them, the serverless function bundle tree-shakes away jose's crypto
+// primitives, causing ERR_CRYPTO_INVALID_KEYLEN at runtime.
+// See: https://github.com/ory/polis/blob/main/pages/api/import-hack.ts
+import * as jose from "jose";
+import { NextResponse } from "next/server";
+import * as openidClient from "openid-client";
+
+// Reference the imports so they aren't removed by tree-shaking
+const _dependencies = [jose, openidClient];
+void _dependencies;
+
+export async function POST(req: Request) {
+ try {
+ const { oauthController } = await jackson();
+
+ const formData = await req.formData();
+ const body = Object.fromEntries(formData.entries());
+
+ const token = await oauthController.token(body as any);
+
+ return NextResponse.json(token);
+ } catch (error: any) {
+ console.error("[SAML] Token error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/app/(ee)/api/auth/saml/userinfo/route.ts b/app/(ee)/api/auth/saml/userinfo/route.ts
new file mode 100644
index 00000000..4792df4e
--- /dev/null
+++ b/app/(ee)/api/auth/saml/userinfo/route.ts
@@ -0,0 +1,31 @@
+import { jackson } from "@/lib/jackson";
+// Force-include crypto dependencies (same workaround as token route)
+import * as jose from "jose";
+import { NextResponse } from "next/server";
+import * as openidClient from "openid-client";
+
+const _dependencies = [jose, openidClient];
+void _dependencies;
+
+export async function GET(req: Request) {
+ try {
+ const { oauthController } = await jackson();
+
+ const authHeader = req.headers.get("Authorization");
+ if (!authHeader) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ // RFC 6750: token type is case-insensitive
+ const token = authHeader.replace(/^bearer\s+/i, "");
+ const userInfo = await oauthController.userInfo(token);
+
+ return NextResponse.json(userInfo);
+ } catch (error: any) {
+ console.error("[SAML] UserInfo error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/app/(ee)/api/auth/saml/verify/route.ts b/app/(ee)/api/auth/saml/verify/route.ts
new file mode 100644
index 00000000..1cd3d1cd
--- /dev/null
+++ b/app/(ee)/api/auth/saml/verify/route.ts
@@ -0,0 +1,73 @@
+import { jackson, jacksonProduct } from "@/lib/jackson";
+import prisma from "@/lib/prisma";
+import { NextResponse } from "next/server";
+
+/**
+ * POST /api/auth/saml/verify
+ * Verifies that a team has SSO configured.
+ * Accepts either `slug` (preferred, user-friendly) or `teamId` (fallback).
+ * Returns only the teamId — no team names, provider info, or other metadata.
+ */
+export async function POST(req: Request) {
+ try {
+ const body = await req.json();
+ const { slug, teamId } = body;
+
+ if (!slug && !teamId) {
+ return NextResponse.json(
+ { error: "Team slug or ID is required" },
+ { status: 400 },
+ );
+ }
+
+ // Look up team by slug first, then by ID
+ const team = slug
+ ? await prisma.team.findUnique({
+ where: { slug },
+ select: { id: true, ssoEnabled: true },
+ })
+ : await prisma.team.findUnique({
+ where: { id: teamId },
+ select: { id: true, ssoEnabled: true },
+ });
+
+ if (!team) {
+ // Generic error — don't reveal whether team exists
+ return NextResponse.json(
+ { error: "SSO is not configured for this team." },
+ { status: 404 },
+ );
+ }
+
+ if (!team.ssoEnabled) {
+ return NextResponse.json(
+ { error: "SSO is not enabled for this team." },
+ { status: 404 },
+ );
+ }
+
+ // Check Jackson for actual SAML connections
+ const { apiController } = await jackson();
+
+ const connections = await apiController.getConnections({
+ tenant: team.id,
+ product: jacksonProduct,
+ });
+
+ if (!connections || connections.length === 0) {
+ return NextResponse.json(
+ { error: "No SSO connections found for this team." },
+ { status: 404 },
+ );
+ }
+
+ // Only return the team ID — no names, providers, or other metadata
+ return NextResponse.json({ data: { teamId: team.id } });
+ } catch (error: any) {
+ console.error("[SAML] Verify error:", error);
+ return NextResponse.json(
+ { error: "Something went wrong" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/app/(ee)/api/scim/v2.0/[...directory]/route.ts b/app/(ee)/api/scim/v2.0/[...directory]/route.ts
new file mode 100644
index 00000000..a2636e41
--- /dev/null
+++ b/app/(ee)/api/scim/v2.0/[...directory]/route.ts
@@ -0,0 +1,264 @@
+import { jackson } from "@/lib/jackson";
+import prisma from "@/lib/prisma";
+import type { DirectorySyncEvent } from "@boxyhq/saml-jackson";
+import { headers } from "next/headers";
+import { NextResponse } from "next/server";
+
+const handler = async (
+ req: Request,
+ { params }: { params: Promise<{ directory: string[] }> },
+) => {
+ try {
+ const resolvedParams = await params;
+ const headersList = await headers();
+ const authHeader = headersList.get("Authorization");
+ const apiSecret = authHeader ? authHeader.split(" ")[1] : null;
+
+ const url = new URL(req.url);
+ const query = Object.fromEntries(url.searchParams.entries());
+
+ const [directoryId, path, resourceId] = resolvedParams.directory;
+
+ let body: any = {};
+ try {
+ body = await req.json();
+ } catch {
+ body = {};
+ }
+
+ const { directorySyncController } = await jackson();
+
+ const request = {
+ method: req.method as "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
+ body,
+ directoryId,
+ resourceId,
+ resourceType: (path === "Users" ? "users" : "groups") as
+ | "users"
+ | "groups",
+ apiSecret,
+ query: {
+ count: query.count ? parseInt(query.count) : undefined,
+ startIndex: query.startIndex ? parseInt(query.startIndex) : undefined,
+ filter: query.filter as string,
+ },
+ };
+
+ const { status, data } = await directorySyncController.requests.handle(
+ request,
+ handleSCIMEvents,
+ );
+
+ return NextResponse.json(data, { status });
+ } catch (error: any) {
+ console.error("[SCIM] Request error:", error);
+ return NextResponse.json(
+ {
+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
+ detail: error.message || "Internal server error",
+ status: 500,
+ },
+ { status: 500 },
+ );
+ }
+};
+
+export {
+ handler as DELETE,
+ handler as GET,
+ handler as PATCH,
+ handler as POST,
+ handler as PUT,
+};
+
+// ──────────────────────────────────────────────────────────
+// SCIM Event Handler — sync changes to the main app DB
+// ──────────────────────────────────────────────────────────
+async function handleSCIMEvents(event: DirectorySyncEvent) {
+ const { event: eventType, data, tenant } = event;
+
+ // Verify the team exists and has SSO enabled
+ const team = await prisma.team.findUnique({
+ where: { id: tenant },
+ select: { id: true, plan: true, ssoEnabled: true },
+ });
+
+ if (!team || !team.ssoEnabled) {
+ console.warn(
+ `[SCIM] Ignoring event for tenant ${tenant} — SSO not enabled`,
+ );
+ return;
+ }
+
+ // Plan gate: only datarooms-premium or higher
+ const allowedPlans = ["datarooms-premium", "datarooms-premium+old"];
+ if (!allowedPlans.includes(team.plan)) {
+ console.warn(
+ `[SCIM] Ignoring event for tenant ${tenant} — plan ${team.plan} not eligible`,
+ );
+ return;
+ }
+
+ if (!("email" in data) || !data.email) {
+ return;
+ }
+
+ try {
+ switch (eventType) {
+ case "user.created": {
+ console.log(
+ `[SCIM] User created: ${data.email} for tenant ${tenant}`,
+ );
+
+ const user = await prisma.user.upsert({
+ where: { email: data.email },
+ create: {
+ email: data.email,
+ name: [data.first_name, data.last_name].filter(Boolean).join(" "),
+ },
+ update: {},
+ });
+
+ await prisma.userTeam.upsert({
+ where: {
+ userId_teamId: {
+ userId: user.id,
+ teamId: tenant,
+ },
+ },
+ update: {},
+ create: {
+ userId: user.id,
+ teamId: tenant,
+ role: "MEMBER",
+ },
+ });
+ break;
+ }
+
+ case "user.updated": {
+ console.log(
+ `[SCIM] User updated: ${data.email} for tenant ${tenant}`,
+ );
+
+ // Handle Azure AD's active/inactive (can be boolean or string)
+ const isActive =
+ (data as any).active === true || (data as any).active === "True";
+ const isInactive =
+ (data as any).active === false || (data as any).active === "False";
+
+ if (isInactive) {
+ // Deactivated — remove from team (same as user.deleted)
+ const user = await prisma.user.findUnique({
+ where: { email: data.email },
+ });
+
+ if (user) {
+ await prisma.userTeam
+ .delete({
+ where: {
+ userId_teamId: {
+ userId: user.id,
+ teamId: tenant,
+ },
+ },
+ })
+ .catch(() => {
+ console.warn(
+ `[SCIM] Could not remove team membership for ${data.email}`,
+ );
+ });
+ }
+ } else if (isActive) {
+ // Reactivated — re-add to team
+ const user = await prisma.user.upsert({
+ where: { email: data.email },
+ create: {
+ email: data.email,
+ name: [data.first_name, data.last_name]
+ .filter(Boolean)
+ .join(" "),
+ },
+ update: {
+ name:
+ [data.first_name, data.last_name].filter(Boolean).join(" ") ||
+ undefined,
+ },
+ });
+
+ await prisma.userTeam.upsert({
+ where: {
+ userId_teamId: {
+ userId: user.id,
+ teamId: tenant,
+ },
+ },
+ update: {},
+ create: {
+ userId: user.id,
+ teamId: tenant,
+ role: "MEMBER",
+ },
+ });
+ } else {
+ // Just a name/attribute update
+ await prisma.user
+ .update({
+ where: { email: data.email },
+ data: {
+ name:
+ [data.first_name, data.last_name]
+ .filter(Boolean)
+ .join(" ") || undefined,
+ },
+ })
+ .catch(() => {
+ console.warn(
+ `[SCIM] Could not update user ${data.email} — user not found`,
+ );
+ });
+ }
+ break;
+ }
+
+ case "user.deleted": {
+ console.log(
+ `[SCIM] User deleted: ${data.email} for tenant ${tenant}`,
+ );
+
+ const user = await prisma.user.findUnique({
+ where: { email: data.email },
+ });
+
+ if (user) {
+ await prisma.userTeam
+ .delete({
+ where: {
+ userId_teamId: {
+ userId: user.id,
+ teamId: tenant,
+ },
+ },
+ })
+ .catch(() => {
+ console.warn(
+ `[SCIM] Could not remove team membership for ${data.email}`,
+ );
+ });
+ }
+ break;
+ }
+
+ case "group.created":
+ case "group.updated":
+ case "group.deleted":
+ case "group.user_added":
+ case "group.user_removed": {
+ console.log(`[SCIM] Group event ${eventType} for tenant ${tenant}`);
+ break;
+ }
+ }
+ } catch (error) {
+ console.error(`[SCIM] Error handling event ${eventType}:`, error);
+ }
+}
diff --git a/app/(ee)/api/teams/[teamId]/directory-sync/route.ts b/app/(ee)/api/teams/[teamId]/directory-sync/route.ts
new file mode 100644
index 00000000..12e9fd64
--- /dev/null
+++ b/app/(ee)/api/teams/[teamId]/directory-sync/route.ts
@@ -0,0 +1,167 @@
+import { jackson, jacksonProduct } from "@/lib/jackson";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { getServerSession } from "next-auth/next";
+import { NextResponse } from "next/server";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+
+const SSO_ELIGIBLE_PLANS = ["datarooms-premium", "datarooms-premium+old"];
+
+async function getAuthenticatedAdmin(teamId: string) {
+ const session = await getServerSession(authOptions);
+ if (!session) return null;
+
+ const userId = (session.user as CustomUser).id;
+
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: { userId_teamId: { userId, teamId } },
+ select: { role: true },
+ });
+
+ if (!teamAccess || teamAccess.role !== "ADMIN") return null;
+
+ const team = await prisma.team.findUnique({
+ where: { id: teamId },
+ select: { id: true, plan: true, ssoEnabled: true },
+ });
+
+ if (!team) return null;
+
+ return { userId, team };
+}
+
+// GET /api/teams/:teamId/directory-sync — list SCIM directories
+export async function GET(
+ req: Request,
+ { params }: { params: Promise<{ teamId: string }> },
+) {
+ const { teamId } = await params;
+ const auth = await getAuthenticatedAdmin(teamId);
+ if (!auth) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ try {
+ const { directorySyncController } = await jackson();
+
+ const { data, error } =
+ await directorySyncController.directories.getByTenantAndProduct(
+ teamId,
+ jacksonProduct,
+ );
+
+ if (error) {
+ return NextResponse.json({ error: error.message }, { status: 400 });
+ }
+
+ return NextResponse.json({ directories: data });
+ } catch (error: any) {
+ console.error("[SCIM] Get directories error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
+
+// POST /api/teams/:teamId/directory-sync — create a SCIM directory connection
+export async function POST(
+ req: Request,
+ { params }: { params: Promise<{ teamId: string }> },
+) {
+ const { teamId } = await params;
+ const auth = await getAuthenticatedAdmin(teamId);
+ if (!auth) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ // Plan gate
+ if (!SSO_ELIGIBLE_PLANS.includes(auth.team.plan)) {
+ return NextResponse.json(
+ { error: "SCIM Directory Sync requires a Datarooms Premium plan" },
+ { status: 403 },
+ );
+ }
+
+ // Feature flag gate
+ if (!auth.team.ssoEnabled) {
+ return NextResponse.json(
+ { error: "SSO is not enabled for this team" },
+ { status: 403 },
+ );
+ }
+
+ try {
+ const { directorySyncController } = await jackson();
+ const body = await req.json();
+ const { name, type, currentDirectoryId } = body;
+
+ const [result] = await Promise.all([
+ directorySyncController.directories.create({
+ tenant: teamId,
+ product: jacksonProduct,
+ name: name || "Papermark SCIM Directory",
+ type: type || "azure-scim-v2",
+ }),
+ // If replacing an existing directory, delete the old one
+ currentDirectoryId &&
+ directorySyncController.directories.delete(currentDirectoryId),
+ ]);
+
+ if (result.error) {
+ return NextResponse.json(
+ { error: result.error.message },
+ { status: 400 },
+ );
+ }
+
+ return NextResponse.json(result, { status: 201 });
+ } catch (error: any) {
+ console.error("[SCIM] Create directory error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
+
+// DELETE /api/teams/:teamId/directory-sync — delete a SCIM directory
+export async function DELETE(
+ req: Request,
+ { params }: { params: Promise<{ teamId: string }> },
+) {
+ const { teamId } = await params;
+ const auth = await getAuthenticatedAdmin(teamId);
+ if (!auth) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ try {
+ const { directorySyncController } = await jackson();
+ const body = await req.json();
+ const { directoryId } = body;
+
+ if (!directoryId) {
+ return NextResponse.json(
+ { error: "directoryId is required" },
+ { status: 400 },
+ );
+ }
+
+ const { error } =
+ await directorySyncController.directories.delete(directoryId);
+
+ if (error) {
+ return NextResponse.json({ error: error.message }, { status: 400 });
+ }
+
+ return NextResponse.json({ ok: true });
+ } catch (error: any) {
+ console.error("[SCIM] Delete directory error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/app/(ee)/api/teams/[teamId]/saml/route.ts b/app/(ee)/api/teams/[teamId]/saml/route.ts
new file mode 100644
index 00000000..c17e2ce3
--- /dev/null
+++ b/app/(ee)/api/teams/[teamId]/saml/route.ts
@@ -0,0 +1,265 @@
+import { jackson, jacksonProduct, samlAudience } from "@/lib/jackson";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+import { getServerSession } from "next-auth/next";
+import { NextResponse } from "next/server";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+
+const SSO_ELIGIBLE_PLANS = ["datarooms-premium", "datarooms-premium+old"];
+
+async function getAuthenticatedAdmin(teamId: string) {
+ const session = await getServerSession(authOptions);
+ if (!session) return null;
+
+ const userId = (session.user as CustomUser).id;
+
+ const teamAccess = await prisma.userTeam.findUnique({
+ where: { userId_teamId: { userId, teamId } },
+ select: { role: true },
+ });
+
+ if (!teamAccess || teamAccess.role !== "ADMIN") return null;
+
+ const team = await prisma.team.findUnique({
+ where: { id: teamId },
+ select: { id: true, plan: true, ssoEnabled: true, ssoEmailDomain: true, ssoEnforcedAt: true, slug: true },
+ });
+
+ if (!team) return null;
+
+ return { userId, team, email: (session.user as CustomUser).email! };
+}
+
+// GET /api/teams/:teamId/saml — list SAML connections + issuer/acs info
+export async function GET(
+ req: Request,
+ { params }: { params: Promise<{ teamId: string }> },
+) {
+ const { teamId } = await params;
+ const auth = await getAuthenticatedAdmin(teamId);
+ if (!auth) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ try {
+ const { apiController } = await jackson();
+
+ const connections = await apiController.getConnections({
+ tenant: teamId,
+ product: jacksonProduct,
+ });
+
+ return NextResponse.json({
+ connections,
+ issuer: samlAudience,
+ acs: `${process.env.NEXTAUTH_URL}/api/auth/saml/callback`,
+ ssoEmailDomain: auth.team.ssoEmailDomain,
+ ssoEnforcedAt: auth.team.ssoEnforcedAt,
+ slug: auth.team.slug,
+ });
+ } catch (error: any) {
+ console.error("[SAML] Get connections error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
+
+// POST /api/teams/:teamId/saml — create a new SAML connection
+export async function POST(
+ req: Request,
+ { params }: { params: Promise<{ teamId: string }> },
+) {
+ const { teamId } = await params;
+ const auth = await getAuthenticatedAdmin(teamId);
+ if (!auth) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ // Plan gate
+ if (!SSO_ELIGIBLE_PLANS.includes(auth.team.plan)) {
+ return NextResponse.json(
+ { error: "SSO requires a Datarooms Premium plan" },
+ { status: 403 },
+ );
+ }
+
+ // Feature flag gate
+ if (!auth.team.ssoEnabled) {
+ return NextResponse.json(
+ { error: "SSO is not enabled for this team" },
+ { status: 403 },
+ );
+ }
+
+ try {
+ const { apiController } = await jackson();
+ const body = await req.json();
+ const { rawMetadata, encodedRawMetadata, metadataUrl } = body;
+
+ if (!rawMetadata && !metadataUrl && !encodedRawMetadata) {
+ return NextResponse.json(
+ {
+ error:
+ "Either rawMetadata, encodedRawMetadata, or metadataUrl is required",
+ },
+ { status: 400 },
+ );
+ }
+
+ // Extract email domain from the admin's email for SSO domain binding
+ const ssoEmailDomain = auth.email.split("@")[1]?.toLowerCase();
+
+ const connection = await apiController.createSAMLConnection({
+ defaultRedirectUrl: `${process.env.NEXTAUTH_URL}/auth/saml`,
+ redirectUrl: process.env.NEXTAUTH_URL as string,
+ tenant: teamId,
+ product: jacksonProduct,
+ rawMetadata: rawMetadata || undefined,
+ encodedRawMetadata: encodedRawMetadata || undefined,
+ metadataUrl: metadataUrl || undefined,
+ });
+
+ // Store the email domain for SSO enforcement
+ await prisma.team.update({
+ where: { id: teamId },
+ data: {
+ ssoEmailDomain: ssoEmailDomain || undefined,
+ },
+ });
+
+ return NextResponse.json(connection, { status: 201 });
+ } catch (error: any) {
+ console.error("[SAML] Create connection error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
+
+// PATCH /api/teams/:teamId/saml — update SSO enforcement settings
+export async function PATCH(
+ req: Request,
+ { params }: { params: Promise<{ teamId: string }> },
+) {
+ const { teamId } = await params;
+ const auth = await getAuthenticatedAdmin(teamId);
+ if (!auth) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ try {
+ const body = await req.json();
+ const { enforced } = body;
+
+ if (typeof enforced !== "boolean") {
+ return NextResponse.json(
+ { error: "'enforced' must be a boolean" },
+ { status: 400 },
+ );
+ }
+
+ // Can only enforce if there's an ssoEmailDomain set (which is set when SAML is configured)
+ if (enforced && !auth.team.ssoEmailDomain) {
+ return NextResponse.json(
+ {
+ error:
+ "Cannot enforce SSO without a configured email domain. Please configure SAML first.",
+ },
+ { status: 400 },
+ );
+ }
+
+ // Verify there are active SAML connections before enforcing
+ if (enforced) {
+ const { apiController } = await jackson();
+ const connections = await apiController.getConnections({
+ tenant: teamId,
+ product: jacksonProduct,
+ });
+
+ if (!connections || connections.length === 0) {
+ return NextResponse.json(
+ {
+ error:
+ "Cannot enforce SSO without an active SAML connection. Please configure SAML first.",
+ },
+ { status: 400 },
+ );
+ }
+ }
+
+ await prisma.team.update({
+ where: { id: teamId },
+ data: {
+ ssoEnforcedAt: enforced ? new Date() : null,
+ },
+ });
+
+ return NextResponse.json({
+ enforced,
+ ssoEnforcedAt: enforced ? new Date().toISOString() : null,
+ });
+ } catch (error: any) {
+ console.error("[SAML] Update enforcement error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
+
+// DELETE /api/teams/:teamId/saml — remove a SAML connection
+export async function DELETE(
+ req: Request,
+ { params }: { params: Promise<{ teamId: string }> },
+) {
+ const { teamId } = await params;
+ const auth = await getAuthenticatedAdmin(teamId);
+ if (!auth) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ try {
+ const { apiController } = await jackson();
+ const body = await req.json();
+ const { clientID, clientSecret } = body;
+
+ if (!clientID || !clientSecret) {
+ return NextResponse.json(
+ { error: "clientID and clientSecret are required" },
+ { status: 400 },
+ );
+ }
+
+ await apiController.deleteConnections({ clientID, clientSecret });
+
+ // Check if there are remaining connections
+ const remaining = await apiController.getConnections({
+ tenant: teamId,
+ product: jacksonProduct,
+ });
+
+ if (!remaining || (Array.isArray(remaining) && remaining.length === 0)) {
+ // No more connections — clear SSO domain and enforcement
+ await prisma.team.update({
+ where: { id: teamId },
+ data: {
+ ssoEmailDomain: null,
+ ssoEnforcedAt: null,
+ },
+ });
+ }
+
+ return NextResponse.json({ ok: true });
+ } catch (error: any) {
+ console.error("[SAML] Delete connection error:", error);
+ return NextResponse.json(
+ { error: error.message || "Internal server error" },
+ { status: 500 },
+ );
+ }
+}
diff --git a/components/auth/sso-login.tsx b/components/auth/sso-login.tsx
deleted file mode 100644
index 32b51323..00000000
--- a/components/auth/sso-login.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-"use client";
-
-import { useState } from "react";
-
-import { Shield } from "lucide-react";
-import { toast } from "sonner";
-
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-
-export function SSOLogin() {
- const [email, setEmail] = useState("");
- const [loading, setLoading] = useState(false);
- const [step, setStep] = useState<"email" | "redirecting">("email");
-
- async function handleSSOLogin(e: React.FormEvent) {
- e.preventDefault();
-
- if (!email) {
- toast.error("Please enter your work email");
- return;
- }
-
- setLoading(true);
-
- try {
- // Step 1: Check if SAML is configured for this email domain
- const checkRes = await fetch(
- `/api/auth/saml/check?email=${encodeURIComponent(email)}`,
- );
- const checkData = await checkRes.json();
-
- if (!checkData.hasSaml) {
- toast.error(
- "SSO is not configured for your organization. Please contact your admin.",
- );
- setLoading(false);
- return;
- }
-
- setStep("redirecting");
-
- // Step 2: Redirect to Jackson's authorize endpoint
- const params = new URLSearchParams({
- tenant: checkData.teamId,
- product: process.env.NEXT_PUBLIC_JACKSON_PRODUCT || "papermark",
- redirect_uri: `${window.location.origin}/auth/saml`,
- state: crypto.randomUUID(),
- });
-
- window.location.href = `/api/auth/saml/authorize?${params.toString()}`;
- } catch (error) {
- console.error("[SSO] Login error:", error);
- toast.error("Something went wrong. Please try again.");
- setLoading(false);
- setStep("email");
- }
- }
-
- if (step === "redirecting") {
- return (
- <div className="flex flex-col items-center space-y-2 py-4">
- <div className="h-6 w-6 animate-spin rounded-full border-2 border-gray-300 border-t-gray-900" />
- <p className="text-sm text-gray-600">
- Redirecting to your identity provider...
- </p>
- </div>
- );
- }
-
- return (
- <form onSubmit={handleSSOLogin} className="flex flex-col space-y-3">
- <Label className="sr-only" htmlFor="sso-email">
- Work Email
- </Label>
- <Input
- id="sso-email"
- placeholder="[email protected]"
- type="email"
- autoCapitalize="none"
- autoComplete="email"
- autoCorrect="off"
- disabled={loading}
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- className="flex h-10 w-full rounded-md border-0 bg-background bg-white px-3 py-2 text-sm text-gray-900 ring-1 ring-gray-200 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white"
- />
- <Button
- type="submit"
- loading={loading}
- disabled={!email || loading}
- className="flex w-full items-center justify-center space-x-2 border border-gray-300 bg-gray-100 font-normal text-gray-900 hover:bg-gray-200"
- >
- <Shield className="h-4 w-4" />
- <span>Continue with SSO</span>
- </Button>
- </form>
- );
-}
diff --git a/components/settings/security/directory-sync-config-modal.tsx b/components/settings/security/directory-sync-config-modal.tsx
deleted file mode 100644
index d18f5e08..00000000
--- a/components/settings/security/directory-sync-config-modal.tsx
+++ /dev/null
@@ -1,381 +0,0 @@
-"use client";
-
-import { useState } from "react";
-
-import { Copy, FolderSync, Trash2 } from "lucide-react";
-import { toast } from "sonner";
-
-import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@/components/ui/dialog";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@/components/ui/select";
-
-interface DirectoryConnection {
- id: string;
- name?: string;
- type?: string;
- scim?: {
- endpoint?: string;
- secret?: string;
- };
-}
-
-interface DirectorySyncConfigModalProps {
- teamId: string;
- directories: DirectoryConnection[];
- onUpdate: () => void;
-}
-
-export function DirectorySyncConfigModal({
- teamId,
- directories,
- onUpdate,
-}: DirectorySyncConfigModalProps) {
- const [open, setOpen] = useState(false);
- const [loading, setLoading] = useState(false);
- const [provider, setProvider] = useState("azure-scim-v2");
- const [name, setName] = useState("");
- const [newDirectory, setNewDirectory] = useState<DirectoryConnection | null>(
- null,
- );
-
- const providerOptions = [
- { value: "azure-scim-v2", label: "Microsoft Entra ID" },
- { value: "okta-scim-v2", label: "Okta" },
- { value: "google", label: "Google Workspace" },
- { value: "generic-scim-v2", label: "Generic SCIM v2.0" },
- ];
-
- async function handleSubmit(e: React.FormEvent) {
- e.preventDefault();
- setLoading(true);
-
- try {
- const providerLabel =
- providerOptions.find((p) => p.value === provider)?.label || provider;
-
- const res = await fetch(`/api/teams/${teamId}/directory-sync`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- name: name || `${providerLabel} SCIM`,
- type: provider,
- }),
- });
-
- if (!res.ok) {
- const data = await res.json();
- throw new Error(data.error || "Failed to create directory sync");
- }
-
- const data = await res.json();
- setNewDirectory(data);
-
- toast.success("Directory sync configured successfully!");
- onUpdate();
- } catch (error: any) {
- toast.error(error.message || "Failed to configure directory sync");
- } finally {
- setLoading(false);
- }
- }
-
- async function handleDelete(directoryId: string) {
- if (
- !confirm(
- "Are you sure you want to remove this directory sync? User provisioning will stop.",
- )
- ) {
- return;
- }
-
- try {
- const res = await fetch(`/api/teams/${teamId}/directory-sync`, {
- method: "DELETE",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ directoryId }),
- });
-
- if (!res.ok) {
- const data = await res.json();
- throw new Error(data.error || "Failed to delete directory sync");
- }
-
- toast.success("Directory sync removed");
- onUpdate();
- } catch (error: any) {
- toast.error(error.message || "Failed to remove directory sync");
- }
- }
-
- function copyToClipboard(text: string, label: string) {
- navigator.clipboard.writeText(text);
- toast.success(`${label} copied to clipboard`);
- }
-
- return (
- <div className="space-y-4">
- {/* Existing directories */}
- {directories.length > 0 && (
- <div className="space-y-3">
- {directories.map((dir) => (
- <div
- key={dir.id}
- className="rounded-lg border p-4"
- >
- <div className="flex items-center justify-between">
- <div className="flex items-center space-x-2">
- <FolderSync className="h-4 w-4 text-green-600" />
- <span className="text-sm font-medium">
- {dir.name || "Directory Sync"}
- </span>
- </div>
- <Button
- variant="ghost"
- size="sm"
- className="text-destructive hover:text-destructive"
- onClick={() => handleDelete(dir.id)}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
-
- {dir.scim?.endpoint && (
- <div className="mt-3 space-y-2 rounded-md border bg-muted/50 p-3">
- <div>
- <Label className="text-xs font-medium">
- SCIM 2.0 Base URL
- </Label>
- <div className="flex items-center space-x-2">
- <Input
- readOnly
- value={dir.scim.endpoint}
- className="h-8 text-xs"
- />
- <Button
- variant="ghost"
- size="sm"
- onClick={() =>
- copyToClipboard(
- dir.scim!.endpoint!,
- "SCIM Base URL",
- )
- }
- >
- <Copy className="h-3 w-3" />
- </Button>
- </div>
- </div>
- {dir.scim.secret && (
- <div>
- <Label className="text-xs font-medium">
- Bearer Token
- </Label>
- <div className="flex items-center space-x-2">
- <Input
- readOnly
- type="password"
- value={dir.scim.secret}
- className="h-8 text-xs"
- />
- <Button
- variant="ghost"
- size="sm"
- onClick={() =>
- copyToClipboard(
- dir.scim!.secret!,
- "Bearer Token",
- )
- }
- >
- <Copy className="h-3 w-3" />
- </Button>
- </div>
- <p className="mt-1 text-[10px] text-muted-foreground">
- Copy this token now. It will not be shown again.
- </p>
- </div>
- )}
- </div>
- )}
- </div>
- ))}
- </div>
- )}
-
- {/* Add new directory dialog */}
- <Dialog
- open={open}
- onOpenChange={(isOpen) => {
- setOpen(isOpen);
- if (!isOpen) {
- setNewDirectory(null);
- setName("");
- }
- }}
- >
- <DialogTrigger asChild>
- <Button
- className="w-full"
- variant={directories.length > 0 ? "outline" : "default"}
- >
- <FolderSync className="mr-2 h-4 w-4" />
- {directories.length > 0
- ? "Add Another Directory"
- : "Configure Directory Sync"}
- </Button>
- </DialogTrigger>
- <DialogContent className="sm:max-w-lg">
- <DialogHeader>
- <DialogTitle>Configure Directory Sync</DialogTitle>
- <DialogDescription>
- Enable automatic user provisioning and deprovisioning from your
- Identity Provider.
- </DialogDescription>
- </DialogHeader>
-
- {newDirectory ? (
- // Show the SCIM credentials after creation
- <div className="space-y-4">
- <div className="rounded-lg border border-green-200 bg-green-50 p-4 dark:border-green-900 dark:bg-green-950">
- <p className="text-sm font-medium text-green-900 dark:text-green-100">
- Directory sync created successfully!
- </p>
- <p className="mt-1 text-xs text-green-700 dark:text-green-300">
- Copy the values below and add them to your Identity
- Provider&apos;s provisioning settings.
- </p>
- </div>
-
- <div className="space-y-3">
- <div>
- <Label className="text-sm font-medium">
- SCIM 2.0 Base URL (Tenant URL)
- </Label>
- <div className="mt-1 flex items-center space-x-2">
- <Input
- readOnly
- value={newDirectory.scim?.endpoint || ""}
- className="font-mono text-xs"
- />
- <Button
- variant="outline"
- size="sm"
- onClick={() =>
- copyToClipboard(
- newDirectory.scim?.endpoint || "",
- "SCIM Base URL",
- )
- }
- >
- <Copy className="h-3 w-3" />
- </Button>
- </div>
- </div>
-
- <div>
- <Label className="text-sm font-medium">
- Secret Token (Bearer Token)
- </Label>
- <div className="mt-1 flex items-center space-x-2">
- <Input
- readOnly
- value={newDirectory.scim?.secret || ""}
- className="font-mono text-xs"
- />
- <Button
- variant="outline"
- size="sm"
- onClick={() =>
- copyToClipboard(
- newDirectory.scim?.secret || "",
- "Bearer Token",
- )
- }
- >
- <Copy className="h-3 w-3" />
- </Button>
- </div>
- <p className="mt-1 text-xs text-amber-600 dark:text-amber-400">
- Save this token now — it will not be shown again.
- </p>
- </div>
- </div>
-
- <DialogFooter>
- <Button onClick={() => setOpen(false)}>Done</Button>
- </DialogFooter>
- </div>
- ) : (
- <form onSubmit={handleSubmit} className="space-y-4">
- <div className="space-y-2">
- <Label>Directory Provider</Label>
- <Select value={provider} onValueChange={setProvider}>
- <SelectTrigger>
- <SelectValue placeholder="Select a provider" />
- </SelectTrigger>
- <SelectContent>
- {providerOptions.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
-
- <div className="space-y-2">
- <Label>
- Connection Name{" "}
- <span className="text-muted-foreground">(optional)</span>
- </Label>
- <Input
- placeholder={`e.g., ${providerOptions.find((p) => p.value === provider)?.label || "Directory"} SCIM`}
- value={name}
- onChange={(e) => setName(e.target.value)}
- disabled={loading}
- />
- </div>
-
- <div className="rounded-lg border bg-muted/50 p-3">
- <p className="text-xs text-muted-foreground">
- After creating the directory sync connection, you&apos;ll
- receive a SCIM 2.0 Base URL and Bearer Token. Add these to
- your Identity Provider&apos;s provisioning settings.
- </p>
- </div>
-
- <DialogFooter>
- <Button
- type="button"
- variant="outline"
- onClick={() => setOpen(false)}
- >
- Cancel
- </Button>
- <Button type="submit" loading={loading} disabled={loading}>
- Create Connection
- </Button>
- </DialogFooter>
- </form>
- )}
- </DialogContent>
- </Dialog>
- </div>
- );
-}
diff --git a/components/settings/settings-header.tsx b/components/settings/settings-header.tsx
index 11d0a4be..2756fd81 100644
--- a/components/settings/settings-header.tsx
+++ b/components/settings/settings-header.tsx
@@ -1,9 +1,11 @@
import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";
+import { useIsAdmin } from "@/lib/hooks/use-is-admin";
import { NavMenu } from "../navigation-menu";
export function SettingsHeader() {
const { features } = useFeatureFlags();
+ const { isAdmin } = useIsAdmin();
return (
<header>
@@ -82,11 +84,13 @@ export function SettingsHeader() {
label: "Security",
href: `/settings/security`,
segment: "security",
+ disabled: !isAdmin,
},
{
label: "Billing",
href: `/settings/billing`,
segment: "billing",
+ disabled: !isAdmin,
},
]}
/>
diff --git a/components/sidebar/app-sidebar.tsx b/components/sidebar/app-sidebar.tsx
index 5dfbc323..6886dc8e 100644
--- a/components/sidebar/app-sidebar.tsx
+++ b/components/sidebar/app-sidebar.tsx
@@ -23,6 +23,7 @@ import {
} from "lucide-react";
import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";
+import { useIsAdmin } from "@/lib/hooks/use-is-admin";
import { usePlan } from "@/lib/swr/use-billing";
import useDataroomsSimple from "@/lib/swr/use-datarooms-simple";
import useLimits from "@/lib/swr/use-limits";
@@ -77,6 +78,9 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
// Check feature flags
const { features } = useFeatureFlags();
+ // Check if current user is admin (for gating Security & Billing)
+ const { isAdmin } = useIsAdmin();
+
// Fetch datarooms for the current team (simple mode - no filters or extra data)
const { datarooms } = useDataroomsSimple();
@@ -201,16 +205,20 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
url: "/settings/slack",
current: router.pathname.includes("settings/slack"),
},
- {
- title: "Security",
- url: "/settings/security",
- current: router.pathname.includes("settings/security"),
- },
- {
- title: "Billing",
- url: "/settings/billing",
- current: router.pathname.includes("settings/billing"),
- },
+ ...(isAdmin
+ ? [
+ {
+ title: "Security",
+ url: "/settings/security",
+ current: router.pathname.includes("settings/security"),
+ },
+ {
+ title: "Billing",
+ url: "/settings/billing",
+ current: router.pathname.includes("settings/billing"),
+ },
+ ]
+ : []),
],
},
// {
diff --git a/ee/features/security/sso/components/directory-sync-config-modal.tsx b/ee/features/security/sso/components/directory-sync-config-modal.tsx
new file mode 100644
index 00000000..e666eea4
--- /dev/null
+++ b/ee/features/security/sso/components/directory-sync-config-modal.tsx
@@ -0,0 +1,286 @@
+"use client";
+
+import { useState } from "react";
+
+import { Copy, Eye, EyeOff, FolderSync, Trash2 } from "lucide-react";
+import { toast } from "sonner";
+
+import useSCIM from "@/lib/swr/use-scim";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+
+import { SAML_PROVIDERS, type SCIMProviderKey } from "../constants";
+
+interface DirectorySyncConfigModalProps {
+ teamId: string;
+}
+
+export function DirectorySyncConfigModal({
+ teamId,
+}: DirectorySyncConfigModalProps) {
+ const { directories, configured, mutate, loading } = useSCIM();
+
+ const [open, setOpen] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
+ const [selectedProvider, setSelectedProvider] = useState<
+ SCIMProviderKey | undefined
+ >();
+ const [showBearerToken, setShowBearerToken] = useState(false);
+
+ const currentProvider = SAML_PROVIDERS.find(
+ (p) => p.scim === selectedProvider,
+ );
+
+ async function handleSubmit(e: React.FormEvent) {
+ e.preventDefault();
+ setSubmitting(true);
+
+ try {
+ const res = await fetch(`/api/teams/${teamId}/directory-sync`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ type: selectedProvider,
+ ...(configured && { currentDirectoryId: directories[0]?.id }),
+ }),
+ });
+
+ if (!res.ok) {
+ const data = await res.json();
+ throw new Error(data.error || "Failed to create directory sync");
+ }
+
+ toast.success("Directory sync configured successfully!");
+ await mutate();
+ } catch (error: any) {
+ toast.error(error.message || "Failed to configure directory sync");
+ } finally {
+ setSubmitting(false);
+ }
+ }
+
+ async function handleDelete(directoryId: string) {
+ if (
+ !confirm(
+ "Are you sure you want to remove this directory sync connection? User provisioning will stop.",
+ )
+ ) {
+ return;
+ }
+
+ try {
+ const res = await fetch(`/api/teams/${teamId}/directory-sync`, {
+ method: "DELETE",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ directoryId }),
+ });
+
+ if (!res.ok) {
+ const data = await res.json();
+ throw new Error(data.error || "Failed to delete directory sync");
+ }
+
+ toast.success("Directory sync connection removed");
+ await mutate();
+ } catch (error: any) {
+ toast.error(
+ error.message || "Failed to remove directory sync connection",
+ );
+ }
+ }
+
+ function copyToClipboard(text: string, label: string) {
+ navigator.clipboard.writeText(text);
+ toast.success(`${label} copied to clipboard`);
+ }
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center py-8">
+ <div className="text-sm text-muted-foreground">
+ Loading directory sync configuration...
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-4">
+ {/* Existing directories */}
+ {directories.map((dir: any) => (
+ <div
+ key={dir.id}
+ className="space-y-3 rounded-lg border p-4"
+ >
+ <div className="flex items-center justify-between">
+ <div className="space-y-1">
+ <div className="flex items-center space-x-2">
+ <FolderSync className="h-4 w-4 text-green-600" />
+ <span className="text-sm font-medium">
+ {dir.name || "Directory Sync"}
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ Type: {dir.type}
+ </p>
+ </div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-destructive hover:text-destructive"
+ onClick={() => handleDelete(dir.id)}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </div>
+
+ {/* SCIM endpoint + token */}
+ {dir.scim && (
+ <div className="space-y-2 rounded-md border bg-muted/50 p-3">
+ <div>
+ <Label className="text-xs font-medium">SCIM Base URL</Label>
+ <div className="mt-1 flex items-center justify-between rounded-md border bg-white px-3 py-1.5">
+ <p className="overflow-hidden text-ellipsis whitespace-nowrap text-xs text-muted-foreground">
+ {dir.scim.endpoint}
+ </p>
+ <button
+ type="button"
+ onClick={() =>
+ copyToClipboard(dir.scim.endpoint, "SCIM Base URL")
+ }
+ className="ml-2 shrink-0"
+ >
+ <Copy className="h-3 w-3 text-muted-foreground" />
+ </button>
+ </div>
+ </div>
+
+ <div>
+ <Label className="text-xs font-medium">Bearer Token</Label>
+ <div className="mt-1 flex items-center justify-between rounded-md border bg-white px-3 py-1.5">
+ <input
+ type={showBearerToken ? "text" : "password"}
+ readOnly
+ className="w-full border-none bg-transparent p-0 text-xs focus:outline-none focus:ring-0"
+ value={dir.scim.secret}
+ />
+ <div className="flex shrink-0 space-x-1.5 pl-2">
+ <button
+ type="button"
+ onClick={() =>
+ copyToClipboard(dir.scim.secret, "Bearer Token")
+ }
+ >
+ <Copy className="h-3 w-3 text-muted-foreground" />
+ </button>
+ <button
+ type="button"
+ onClick={() => setShowBearerToken(!showBearerToken)}
+ >
+ {showBearerToken ? (
+ <Eye className="h-3 w-3 text-muted-foreground" />
+ ) : (
+ <EyeOff className="h-3 w-3 text-muted-foreground" />
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ ))}
+
+ {/* Add new directory dialog */}
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <Button
+ className="w-full"
+ variant={configured ? "outline" : "default"}
+ >
+ <FolderSync className="mr-2 h-4 w-4" />
+ {configured
+ ? "Replace Directory Provider"
+ : "Configure Directory Sync"}
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-lg">
+ <DialogHeader>
+ <DialogTitle>Configure SCIM Directory Sync</DialogTitle>
+ <DialogDescription>
+ Select your directory provider to enable automatic user
+ provisioning and deprovisioning.
+ </DialogDescription>
+ </DialogHeader>
+
+ <form onSubmit={handleSubmit} className="space-y-4">
+ <div className="space-y-2">
+ <Label>Directory Provider</Label>
+ <Select
+ value={selectedProvider}
+ onValueChange={(v) =>
+ setSelectedProvider(v as SCIMProviderKey)
+ }
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Select a provider" />
+ </SelectTrigger>
+ <SelectContent>
+ {SAML_PROVIDERS.map((p) => (
+ <SelectItem key={p.scim} value={p.scim}>
+ {p.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+
+ {currentProvider && (
+ <div className="rounded-lg border bg-muted/30 p-3 text-xs text-muted-foreground">
+ <p>
+ After creating the directory, you&apos;ll receive a SCIM Base
+ URL and Bearer Token. Configure these in your{" "}
+ {currentProvider.name} admin console.
+ </p>
+ </div>
+ )}
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => setOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ loading={submitting}
+ disabled={submitting || !selectedProvider}
+ >
+ {configured ? "Replace & Configure" : "Create Directory"}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
diff --git a/components/settings/security/saml-config-modal.tsx b/ee/features/security/sso/components/saml-config-modal.tsx
similarity index 59%
rename from components/settings/security/saml-config-modal.tsx
rename to ee/features/security/sso/components/saml-config-modal.tsx
index 7d76e28d..aafa0dcc 100644
--- a/components/settings/security/saml-config-modal.tsx
+++ b/ee/features/security/sso/components/saml-config-modal.tsx
@@ -2,9 +2,11 @@
import { useState } from "react";
-import { Copy, Shield, Trash2 } from "lucide-react";
+import { Copy, Shield, Trash2, UploadCloud } from "lucide-react";
import { toast } from "sonner";
+import useSAML from "@/lib/swr/use-saml";
+
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -25,74 +27,49 @@ import {
SelectValue,
} from "@/components/ui/select";
-interface SAMLConnection {
- clientID: string;
- clientSecret: string;
- name?: string;
- description?: string;
- idpMetadata?: {
- provider?: string;
- };
-}
+import { type SAMLProviderKey, SAML_PROVIDERS } from "../constants";
interface SAMLConfigModalProps {
teamId: string;
- connections: SAMLConnection[];
- onUpdate: () => void;
}
-export function SAMLConfigModal({
- teamId,
- connections,
- onUpdate,
-}: SAMLConfigModalProps) {
+export function SAMLConfigModal({ teamId }: SAMLConfigModalProps) {
+ const { connections, issuer, acs, mutate, loading } = useSAML();
+
const [open, setOpen] = useState(false);
- const [loading, setLoading] = useState(false);
- const [provider, setProvider] = useState("azure");
+ const [submitting, setSubmitting] = useState(false);
+ const [selectedProvider, setSelectedProvider] = useState<
+ SAMLProviderKey | undefined
+ >();
const [metadataUrl, setMetadataUrl] = useState("");
- const [rawMetadata, setRawMetadata] = useState("");
- const [inputMode, setInputMode] = useState<"url" | "xml">("url");
-
- const acsUrl = `${process.env.NEXT_PUBLIC_BASE_URL || window.location.origin}/api/auth/saml/callback`;
- const entityId =
- process.env.NEXT_PUBLIC_SAML_AUDIENCE ||
- process.env.NEXT_PUBLIC_BASE_URL ||
- window.location.origin;
+ const [file, setFile] = useState<File | null>(null);
+ const [fileContent, setFileContent] = useState("");
- const providerOptions = [
- { value: "azure", label: "Microsoft Entra ID (Azure AD)" },
- { value: "okta", label: "Okta" },
- { value: "google", label: "Google Workspace" },
- { value: "custom", label: "Custom SAML IdP" },
- ];
-
- const providerName =
- providerOptions.find((p) => p.value === provider)?.label || provider;
+ const currentProvider = SAML_PROVIDERS.find(
+ (p) => p.saml === selectedProvider,
+ );
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
- setLoading(true);
+ setSubmitting(true);
try {
- const body: Record<string, string> = {
- name: providerName,
- description: `SAML SSO via ${providerName}`,
- };
+ const body: Record<string, string> = {};
- if (inputMode === "url") {
- if (!metadataUrl) {
- toast.error("Please enter a metadata URL");
- setLoading(false);
+ if (selectedProvider === "google") {
+ if (!fileContent) {
+ toast.error("Please upload the XML metadata file");
+ setSubmitting(false);
return;
}
- body.metadataUrl = metadataUrl;
+ body.encodedRawMetadata = btoa(fileContent);
} else {
- if (!rawMetadata) {
- toast.error("Please enter the XML metadata");
- setLoading(false);
+ if (!metadataUrl) {
+ toast.error("Please enter a metadata URL");
+ setSubmitting(false);
return;
}
- body.rawMetadata = rawMetadata;
+ body.metadataUrl = metadataUrl;
}
const res = await fetch(`/api/teams/${teamId}/saml`, {
@@ -109,16 +86,18 @@ export function SAMLConfigModal({
toast.success("SAML SSO configured successfully!");
setOpen(false);
setMetadataUrl("");
- setRawMetadata("");
- onUpdate();
+ setFile(null);
+ setFileContent("");
+ setSelectedProvider(undefined);
+ await mutate();
} catch (error: any) {
toast.error(error.message || "Failed to configure SAML SSO");
} finally {
- setLoading(false);
+ setSubmitting(false);
}
}
- async function handleDelete(connection: SAMLConnection) {
+ async function handleDelete(conn: any) {
if (
!confirm(
"Are you sure you want to remove this SAML connection? Users will no longer be able to sign in via SSO.",
@@ -132,8 +111,8 @@ export function SAMLConfigModal({
method: "DELETE",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
- clientID: connection.clientID,
- clientSecret: connection.clientSecret,
+ clientID: conn.clientID,
+ clientSecret: conn.clientSecret,
}),
});
@@ -143,7 +122,7 @@ export function SAMLConfigModal({
}
toast.success("SAML connection removed");
- onUpdate();
+ await mutate();
} catch (error: any) {
toast.error(error.message || "Failed to remove SAML connection");
}
@@ -154,12 +133,22 @@ export function SAMLConfigModal({
toast.success(`${label} copied to clipboard`);
}
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center py-8">
+ <div className="text-sm text-muted-foreground">
+ Loading SAML configuration...
+ </div>
+ </div>
+ );
+ }
+
return (
<div className="space-y-4">
{/* Existing connections */}
{connections.length > 0 && (
<div className="space-y-3">
- {connections.map((conn) => (
+ {connections.map((conn: any) => (
<div
key={conn.clientID}
className="flex items-center justify-between rounded-lg border p-4"
@@ -168,7 +157,7 @@ export function SAMLConfigModal({
<div className="flex items-center space-x-2">
<Shield className="h-4 w-4 text-green-600" />
<span className="text-sm font-medium">
- {conn.name || "SAML Connection"}
+ {conn.idpMetadata?.provider || "SAML Connection"}
</span>
</div>
<p className="text-xs text-muted-foreground">
@@ -203,12 +192,12 @@ export function SAMLConfigModal({
<Label className="text-xs font-medium">
Entity ID (Identifier)
</Label>
- <p className="text-xs text-muted-foreground">{entityId}</p>
+ <p className="text-xs text-muted-foreground">{issuer}</p>
</div>
<Button
variant="ghost"
size="sm"
- onClick={() => copyToClipboard(entityId, "Entity ID")}
+ onClick={() => copyToClipboard(issuer, "Entity ID")}
>
<Copy className="h-3 w-3" />
</Button>
@@ -218,12 +207,12 @@ export function SAMLConfigModal({
<Label className="text-xs font-medium">
Reply URL (ACS URL)
</Label>
- <p className="text-xs text-muted-foreground">{acsUrl}</p>
+ <p className="text-xs text-muted-foreground">{acs}</p>
</div>
<Button
variant="ghost"
size="sm"
- onClick={() => copyToClipboard(acsUrl, "ACS URL")}
+ onClick={() => copyToClipboard(acs, "ACS URL")}
>
<Copy className="h-3 w-3" />
</Button>
@@ -235,7 +224,10 @@ export function SAMLConfigModal({
{/* Add new connection dialog */}
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
- <Button className="w-full" variant={connections.length > 0 ? "outline" : "default"}>
+ <Button
+ className="w-full"
+ variant={connections.length > 0 ? "outline" : "default"}
+ >
<Shield className="mr-2 h-4 w-4" />
{connections.length > 0
? "Add Another Connection"
@@ -261,11 +253,16 @@ export function SAMLConfigModal({
<span className="font-medium">Entity ID:</span>
<div className="flex items-center space-x-1">
<code className="rounded bg-muted px-1.5 py-0.5 text-[10px]">
- {entityId}
+ {issuer || "https://saml.papermark.com"}
</code>
<button
type="button"
- onClick={() => copyToClipboard(entityId, "Entity ID")}
+ onClick={() =>
+ copyToClipboard(
+ issuer || "https://saml.papermark.com",
+ "Entity ID",
+ )
+ }
className="text-muted-foreground hover:text-foreground"
>
<Copy className="h-3 w-3" />
@@ -276,11 +273,18 @@ export function SAMLConfigModal({
<span className="font-medium">ACS URL:</span>
<div className="flex items-center space-x-1">
<code className="rounded bg-muted px-1.5 py-0.5 text-[10px]">
- {acsUrl}
+ {acs ||
+ `${window.location.origin}/api/auth/saml/callback`}
</code>
<button
type="button"
- onClick={() => copyToClipboard(acsUrl, "ACS URL")}
+ onClick={() =>
+ copyToClipboard(
+ acs ||
+ `${window.location.origin}/api/auth/saml/callback`,
+ "ACS URL",
+ )
+ }
className="text-muted-foreground hover:text-foreground"
>
<Copy className="h-3 w-3" />
@@ -292,15 +296,18 @@ export function SAMLConfigModal({
{/* Step 2: Provider selection */}
<div className="space-y-2">
- <Label>SAML Provider</Label>
- <Select value={provider} onValueChange={setProvider}>
+ <Label>Step 2: Select SAML Provider</Label>
+ <Select
+ value={selectedProvider}
+ onValueChange={(v) => setSelectedProvider(v as SAMLProviderKey)}
+ >
<SelectTrigger>
<SelectValue placeholder="Select a provider" />
</SelectTrigger>
<SelectContent>
- {providerOptions.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
+ {SAML_PROVIDERS.map((p) => (
+ <SelectItem key={p.saml} value={p.saml}>
+ {p.name}
</SelectItem>
))}
</SelectContent>
@@ -308,58 +315,62 @@ export function SAMLConfigModal({
</div>
{/* Step 3: Metadata input */}
- <div className="space-y-2">
- <div className="flex items-center space-x-2">
- <Label>
- Step 2: Paste your IdP metadata
- </Label>
- <div className="flex rounded-md border text-xs">
- <button
- type="button"
- className={`px-2 py-1 ${inputMode === "url" ? "bg-muted font-medium" : ""}`}
- onClick={() => setInputMode("url")}
- >
- URL
- </button>
- <button
- type="button"
- className={`px-2 py-1 ${inputMode === "xml" ? "bg-muted font-medium" : ""}`}
- onClick={() => setInputMode("xml")}
+ {currentProvider && (
+ <div className="space-y-2">
+ <Label>Step 3: {currentProvider.samlModalCopy}</Label>
+
+ {selectedProvider === "google" ? (
+ <label
+ htmlFor="metadataRaw"
+ className="group relative flex h-24 w-full cursor-pointer flex-col items-center justify-center rounded-md border border-dashed bg-muted/30 transition-all hover:bg-muted/50"
>
- XML
- </button>
- </div>
+ {file ? (
+ <>
+ <UploadCloud className="h-5 w-5 text-green-600" />
+ <p className="mt-2 text-sm text-muted-foreground">
+ {file.name}
+ </p>
+ </>
+ ) : (
+ <>
+ <UploadCloud className="h-5 w-5 text-muted-foreground" />
+ <p className="mt-2 text-sm text-muted-foreground">
+ Upload .xml metadata file
+ </p>
+ </>
+ )}
+ <input
+ id="metadataRaw"
+ type="file"
+ accept="text/xml,.xml"
+ className="sr-only"
+ onChange={(e) => {
+ const f = e.target?.files?.[0];
+ setFile(f || null);
+ if (f) {
+ const reader = new FileReader();
+ reader.onload = (ev) => {
+ setFileContent(ev.target?.result as string);
+ };
+ reader.readAsText(f);
+ }
+ }}
+ />
+ </label>
+ ) : (
+ <Input
+ placeholder={
+ selectedProvider === "azure"
+ ? "https://login.microsoftonline.com/.../federationmetadata/..."
+ : "https://your-idp.example.com/metadata"
+ }
+ value={metadataUrl}
+ onChange={(e) => setMetadataUrl(e.target.value)}
+ disabled={submitting}
+ />
+ )}
</div>
-
- {inputMode === "url" ? (
- <Input
- placeholder={
- provider === "azure"
- ? "https://login.microsoftonline.com/.../federationmetadata/2007-06/federationmetadata.xml"
- : "Paste your App Federation Metadata URL"
- }
- value={metadataUrl}
- onChange={(e) => setMetadataUrl(e.target.value)}
- disabled={loading}
- />
- ) : (
- <textarea
- placeholder="Paste your SAML metadata XML here..."
- className="flex min-h-[120px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
- value={rawMetadata}
- onChange={(e) => setRawMetadata(e.target.value)}
- disabled={loading}
- />
- )}
-
- {provider === "azure" && (
- <p className="text-xs text-muted-foreground">
- Find this in Azure Portal → Enterprise Applications → Your
- App → Single sign-on → SAML Certificates → App Federation
- Metadata URL
- </p>
- )}
- </div>
+ )}
<DialogFooter>
<Button
@@ -369,7 +380,11 @@ export function SAMLConfigModal({
>
Cancel
</Button>
- <Button type="submit" loading={loading} disabled={loading}>
+ <Button
+ type="submit"
+ loading={submitting}
+ disabled={submitting || !selectedProvider}
+ >
Save Configuration
</Button>
</DialogFooter>
diff --git a/ee/features/security/sso/components/sso-enforcement-toggle.tsx b/ee/features/security/sso/components/sso-enforcement-toggle.tsx
new file mode 100644
index 00000000..7f74d528
--- /dev/null
+++ b/ee/features/security/sso/components/sso-enforcement-toggle.tsx
@@ -0,0 +1,168 @@
+"use client";
+
+import { useState } from "react";
+
+import { AlertTriangle, Lock, LockOpen } from "lucide-react";
+import { toast } from "sonner";
+
+import useSAML from "@/lib/swr/use-saml";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+
+interface SSOEnforcementToggleProps {
+ teamId: string;
+}
+
+export function SSOEnforcementToggle({ teamId }: SSOEnforcementToggleProps) {
+ const { configured, ssoEmailDomain, ssoEnforcedAt, slug, mutate, loading } =
+ useSAML();
+ const [submitting, setSubmitting] = useState(false);
+ const [confirmOpen, setConfirmOpen] = useState(false);
+
+ const isEnforced = !!ssoEnforcedAt;
+
+ async function toggleEnforcement(enforced: boolean) {
+ setSubmitting(true);
+
+ try {
+ const res = await fetch(`/api/teams/${teamId}/saml`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enforced }),
+ });
+
+ if (!res.ok) {
+ const data = await res.json();
+ throw new Error(data.error || "Failed to update enforcement");
+ }
+
+ toast.success(
+ enforced
+ ? `SSO is now enforced for @${ssoEmailDomain} users`
+ : "SSO enforcement has been disabled",
+ );
+ setConfirmOpen(false);
+ await mutate();
+ } catch (error: any) {
+ toast.error(error.message || "Failed to update SSO enforcement");
+ } finally {
+ setSubmitting(false);
+ }
+ }
+
+ if (loading || !configured) {
+ return null;
+ }
+
+ return (
+ <div className="rounded-lg border p-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-start space-x-3">
+ {isEnforced ? (
+ <Lock className="mt-0.5 h-4 w-4 text-orange-600" />
+ ) : (
+ <LockOpen className="mt-0.5 h-4 w-4 text-muted-foreground" />
+ )}
+ <div className="space-y-1">
+ <h3 className="text-sm font-medium">SSO Enforcement</h3>
+ {isEnforced ? (
+ <p className="text-xs text-muted-foreground">
+ All users with <strong>@{ssoEmailDomain}</strong> must sign in
+ via SSO. Email, Google, and other login methods are blocked for
+ this domain.
+ </p>
+ ) : (
+ <p className="text-xs text-muted-foreground">
+ SSO is available but not required.{" "}
+ {ssoEmailDomain
+ ? `Users with @${ssoEmailDomain} can still sign in with other methods.`
+ : "Configure SAML first to set up enforcement."}
+ </p>
+ )}
+ {slug && (
+ <p className="mt-1 text-xs text-muted-foreground">
+ Team slug for SSO login:{" "}
+ <code className="rounded bg-muted px-1 py-0.5 font-mono text-[10px]">
+ {slug}
+ </code>
+ </p>
+ )}
+ </div>
+ </div>
+
+ {isEnforced ? (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => toggleEnforcement(false)}
+ loading={submitting}
+ disabled={submitting}
+ >
+ Disable
+ </Button>
+ ) : (
+ <Dialog open={confirmOpen} onOpenChange={setConfirmOpen}>
+ <DialogTrigger asChild>
+ <Button
+ variant="default"
+ size="sm"
+ disabled={!ssoEmailDomain || !configured}
+ >
+ Enforce SSO
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle className="flex items-center space-x-2">
+ <AlertTriangle className="h-5 w-5 text-orange-500" />
+ <span>Enforce SSO for @{ssoEmailDomain}?</span>
+ </DialogTitle>
+ <DialogDescription className="space-y-2 pt-2">
+ <p>
+ Once enforced, <strong>all users</strong> with an{" "}
+ <strong>@{ssoEmailDomain}</strong> email address will be{" "}
+ <strong>required</strong> to sign in through your Identity
+ Provider.
+ </p>
+ <p>
+ Email magic links, Google, LinkedIn, and passkey login will
+ be <strong>blocked</strong> for these users.
+ </p>
+ <p className="font-medium">
+ Make sure your SAML configuration is working correctly before
+ enabling enforcement.
+ </p>
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter className="gap-2 sm:gap-0">
+ <Button
+ variant="outline"
+ onClick={() => setConfirmOpen(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => toggleEnforcement(true)}
+ loading={submitting}
+ disabled={submitting}
+ >
+ Enforce SSO
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/ee/features/security/sso/components/sso-login.tsx b/ee/features/security/sso/components/sso-login.tsx
new file mode 100644
index 00000000..baf1e3cb
--- /dev/null
+++ b/ee/features/security/sso/components/sso-login.tsx
@@ -0,0 +1,125 @@
+"use client";
+
+import { useRef, useState } from "react";
+
+import { Shield } from "lucide-react";
+import { signIn } from "next-auth/react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+
+import { JACKSON_PRODUCT } from "../product";
+
+export function SSOLogin() {
+ const [teamSlug, setTeamSlug] = useState("");
+ const [loading, setLoading] = useState(false);
+ const [expanded, setExpanded] = useState(false);
+ const [step, setStep] = useState<"idle" | "redirecting">("idle");
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ async function handleSSOLogin(e: React.FormEvent) {
+ e.preventDefault();
+
+ const value = teamSlug.trim().toLowerCase();
+ if (!value) {
+ toast.error("Please enter your team identifier");
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ // Step 1: Verify SSO is configured for this team
+ const verifyRes = await fetch("/api/auth/saml/verify", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ slug: value }),
+ });
+
+ const verifyData = await verifyRes.json();
+
+ if (!verifyRes.ok || verifyData.error) {
+ toast.error(
+ verifyData.error ||
+ "SSO is not configured for this team. Please contact your admin.",
+ );
+ setLoading(false);
+ return;
+ }
+
+ setStep("redirecting");
+
+ // Step 2: Initiate SAML SSO via NextAuth's OAuth provider (with PKCE + state)
+ await signIn("saml", undefined, {
+ tenant: verifyData.data.teamId,
+ product: JACKSON_PRODUCT,
+ });
+ } catch (error) {
+ console.error("[SSO] Login error:", error);
+ toast.error("Something went wrong. Please try again.");
+ setLoading(false);
+ setStep("idle");
+ }
+ }
+
+ if (step === "redirecting") {
+ return (
+ <div className="flex flex-col items-center space-y-2 py-4">
+ <div className="h-6 w-6 animate-spin rounded-full border-2 border-gray-300 border-t-gray-900" />
+ <p className="text-sm text-gray-600">
+ Redirecting to your identity provider...
+ </p>
+ </div>
+ );
+ }
+
+ if (!expanded) {
+ return (
+ <Button
+ type="button"
+ onClick={() => {
+ setExpanded(true);
+ // Focus the input after it renders
+ requestAnimationFrame(() => inputRef.current?.focus());
+ }}
+ className="flex w-full items-center justify-center space-x-2 border border-gray-300 bg-gray-100 font-normal text-gray-900 hover:bg-gray-200"
+ >
+ <Shield className="h-4 w-4" />
+ <span>Continue with SAML SSO</span>
+ </Button>
+ );
+ }
+
+ return (
+ <form onSubmit={handleSSOLogin} className="flex flex-col space-y-3">
+ <Label className="sr-only" htmlFor="sso-team-slug">
+ Team Identifier
+ </Label>
+ <Input
+ ref={inputRef}
+ id="sso-team-slug"
+ placeholder="your-team-slug"
+ type="text"
+ autoCapitalize="none"
+ autoComplete="off"
+ autoCorrect="off"
+ autoFocus
+ disabled={loading}
+ value={teamSlug}
+ onChange={(e) => setTeamSlug(e.target.value)}
+ className="flex h-10 w-full rounded-md border-0 bg-background bg-white px-3 py-2 text-sm text-gray-900 ring-1 ring-gray-200 transition-colors placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 dark:bg-white"
+ />
+ <Button
+ type="submit"
+ loading={loading}
+ disabled={!teamSlug.trim() || loading}
+ className="flex w-full items-center justify-center space-x-2 border border-gray-300 bg-gray-100 font-normal text-gray-900 hover:bg-gray-200"
+ >
+ <Shield className="h-4 w-4" />
+ <span>Continue with SAML SSO</span>
+ </Button>
+ </form>
+ );
+}
diff --git a/ee/features/security/sso/constants.ts b/ee/features/security/sso/constants.ts
new file mode 100644
index 00000000..b29dea29
--- /dev/null
+++ b/ee/features/security/sso/constants.ts
@@ -0,0 +1,35 @@
+export const SAML_PROVIDERS = [
+ {
+ name: "Okta",
+ saml: "okta",
+ samlModalCopy: "Metadata URL",
+ scim: "okta-scim-v2",
+ scimModalCopy: {
+ url: "SCIM 2.0 Base URL",
+ token: "OAuth Bearer Token",
+ },
+ },
+ {
+ name: "Entra ID (formerly Azure AD)",
+ saml: "azure",
+ samlModalCopy: "App Federation Metadata URL",
+ scim: "azure-scim-v2",
+ scimModalCopy: {
+ url: "Tenant URL",
+ token: "Secret Token",
+ },
+ },
+ {
+ name: "Google Workspace",
+ saml: "google",
+ samlModalCopy: "XML Metadata File",
+ scim: "google",
+ scimModalCopy: {
+ url: "SCIM 2.0 Base URL",
+ token: "OAuth Bearer Token",
+ },
+ },
+] as const;
+
+export type SAMLProviderKey = (typeof SAML_PROVIDERS)[number]["saml"];
+export type SCIMProviderKey = (typeof SAML_PROVIDERS)[number]["scim"];
diff --git a/ee/features/security/sso/index.ts b/ee/features/security/sso/index.ts
new file mode 100644
index 00000000..f0bb09ea
--- /dev/null
+++ b/ee/features/security/sso/index.ts
@@ -0,0 +1,5 @@
+export { SSOLogin } from "./components/sso-login";
+export { SAMLConfigModal } from "./components/saml-config-modal";
+export { DirectorySyncConfigModal } from "./components/directory-sync-config-modal";
+export { SSOEnforcementToggle } from "./components/sso-enforcement-toggle";
+export { SAML_PROVIDERS } from "./constants";
diff --git a/ee/features/security/sso/product.ts b/ee/features/security/sso/product.ts
new file mode 100644
index 00000000..eecb1fca
--- /dev/null
+++ b/ee/features/security/sso/product.ts
@@ -0,0 +1,6 @@
+/**
+ * Jackson product identifier — must match on server and client.
+ * Used as the `product` parameter when creating SAML connections
+ * and when initiating SSO login.
+ */
+export const JACKSON_PRODUCT = "papermark";
diff --git a/lib/api/teams/is-saml-enforced-for-email-domain.ts b/lib/api/teams/is-saml-enforced-for-email-domain.ts
new file mode 100644
index 00000000..44e9a9b9
--- /dev/null
+++ b/lib/api/teams/is-saml-enforced-for-email-domain.ts
@@ -0,0 +1,49 @@
+import prisma from "@/lib/prisma";
+
+/**
+ * Checks if SAML SSO is enforced for a given email address's domain.
+ * When enforced, users with this email domain MUST use SSO to log in —
+ * email magic links, Google OAuth, etc. are blocked.
+ */
+export async function isSamlEnforcedForEmailDomain(
+ email: string,
+): Promise<boolean> {
+ const emailDomain = email.split("@")[1]?.toLowerCase();
+
+ if (!emailDomain) {
+ return false;
+ }
+
+ // 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)) {
+ return false;
+ }
+
+ const team = await prisma.team.findUnique({
+ where: {
+ ssoEmailDomain: emailDomain,
+ },
+ select: {
+ ssoEnforcedAt: true,
+ },
+ });
+
+ return !!team?.ssoEnforcedAt;
+}
diff --git a/lib/featureFlags/index.ts b/lib/featureFlags/index.ts
index 64f02a69..d64f5395 100644
--- a/lib/featureFlags/index.ts
+++ b/lib/featureFlags/index.ts
@@ -14,7 +14,8 @@ export type BetaFeatures =
| "annotations"
| "dataroomInvitations"
| "workflows"
- | "ai";
+ | "ai"
+ | "sso";
type BetaFeaturesRecord = Record<BetaFeatures, string[]>;
@@ -34,6 +35,7 @@ export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {
dataroomInvitations: false,
workflows: false,
ai: false,
+ sso: false,
};
// Return all features as false if edge config is not available
diff --git a/lib/hooks/use-is-admin.ts b/lib/hooks/use-is-admin.ts
new file mode 100644
index 00000000..e27a8869
--- /dev/null
+++ b/lib/hooks/use-is-admin.ts
@@ -0,0 +1,23 @@
+import { useSession } from "next-auth/react";
+
+import { useGetTeam } from "@/lib/swr/use-team";
+import { CustomUser } from "@/lib/types";
+
+/**
+ * Returns whether the current user is an Admin of the active team.
+ * Relies on `useGetTeam()` (SWR-cached) so it won't cause extra fetches
+ * when the team data is already loaded on a settings page.
+ */
+export function useIsAdmin() {
+ const { data: session } = useSession();
+ const { team, loading } = useGetTeam();
+
+ const userId = (session?.user as CustomUser)?.id;
+
+ const isAdmin =
+ !!team?.users?.some(
+ (u) => u.userId === userId && u.role === "ADMIN",
+ );
+
+ return { isAdmin, loading };
+}
diff --git a/lib/jackson.ts b/lib/jackson.ts
index d12236fe..3c81cb86 100644
--- a/lib/jackson.ts
+++ b/lib/jackson.ts
@@ -5,9 +5,19 @@ import type {
JacksonOption,
} from "@boxyhq/saml-jackson";
import samlJackson from "@boxyhq/saml-jackson";
+import crypto from "crypto";
-export const samlAudience =
- process.env.SAML_AUDIENCE || "https://saml.papermark.com";
+export const samlAudience = "https://saml.papermark.com";
+
+export { JACKSON_PRODUCT as jacksonProduct } from "@/ee/features/security/sso/product";
+
+// Jackson's AES-256-GCM encrypter requires exactly 32 bytes.
+// Derive a stable 32-byte key from NEXTAUTH_SECRET using SHA-256.
+const encryptionKey = crypto
+ .createHash("sha256")
+ .update(process.env.NEXTAUTH_SECRET || "")
+ .digest("base64url")
+ .substring(0, 32);
const opts: JacksonOption = {
externalUrl: process.env.NEXTAUTH_URL || "https://app.papermark.com",
@@ -17,10 +27,12 @@ const opts: JacksonOption = {
engine: "sql",
type: "postgres",
url:
- process.env.POSTGRES_PRISMA_URL_NON_POOLING ||
- (process.env.POSTGRES_PRISMA_URL as string),
+ (process.env.POSTGRES_PRISMA_URL as string) ||
+ process.env.POSTGRES_PRISMA_URL_NON_POOLING,
+
+ encryptionKey,
},
- idpEnabled: true, // to allow folks to SSO directly from their IDP
+ idpEnabled: true, // to allow to SSO from their IDP
scimPath: "/api/scim/v2.0",
clientSecretVerifier: process.env.NEXTAUTH_SECRET as string,
};
diff --git a/lib/swr/use-saml.ts b/lib/swr/use-saml.ts
new file mode 100644
index 00000000..29b7111c
--- /dev/null
+++ b/lib/swr/use-saml.ts
@@ -0,0 +1,39 @@
+import { useTeam } from "@/context/team-context";
+import type { SAMLSSORecord } from "@boxyhq/saml-jackson";
+import useSWR from "swr";
+
+import { fetcher } from "@/lib/utils";
+
+export default function useSAML() {
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const { data, isLoading, mutate } = useSWR<{
+ connections: SAMLSSORecord[];
+ issuer: string;
+ acs: string;
+ ssoEmailDomain: string | null;
+ ssoEnforcedAt: string | null;
+ slug: string | null;
+ }>(teamId ? `/api/teams/${teamId}/saml` : null, fetcher, {
+ keepPreviousData: true,
+ });
+
+ const configured = !!(data?.connections && data.connections.length > 0);
+
+ return {
+ saml: data,
+ connections: data?.connections ?? [],
+ issuer: data?.issuer ?? "",
+ acs: data?.acs ?? "",
+ ssoEmailDomain: data?.ssoEmailDomain ?? null,
+ ssoEnforcedAt: data?.ssoEnforcedAt ?? null,
+ slug: data?.slug ?? null,
+ provider: configured
+ ? data!.connections[0].idpMetadata?.provider ?? null
+ : null,
+ configured,
+ loading: isLoading,
+ mutate,
+ };
+}
diff --git a/lib/swr/use-scim.ts b/lib/swr/use-scim.ts
new file mode 100644
index 00000000..d215f90d
--- /dev/null
+++ b/lib/swr/use-scim.ts
@@ -0,0 +1,29 @@
+import { useTeam } from "@/context/team-context";
+import type { Directory } from "@boxyhq/saml-jackson";
+import useSWR from "swr";
+
+import { fetcher } from "@/lib/utils";
+
+export default function useSCIM() {
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const { data, isLoading, mutate } = useSWR<{ directories: Directory[] }>(
+ teamId ? `/api/teams/${teamId}/directory-sync` : null,
+ fetcher,
+ {
+ keepPreviousData: true,
+ },
+ );
+
+ const configured = !!(data?.directories && data.directories.length > 0);
+
+ return {
+ scim: data,
+ directories: data?.directories ?? [],
+ provider: configured ? data!.directories[0].type : null,
+ configured,
+ loading: isLoading,
+ mutate,
+ };
+}
diff --git a/next.config.mjs b/next.config.mjs
index 25d8613a..e29327dd 100644
--- a/next.config.mjs
+++ b/next.config.mjs
@@ -2,6 +2,7 @@
const nextConfig = {
reactStrictMode: true,
pageExtensions: ["js", "jsx", "ts", "tsx", "mdx"],
+ transpilePackages: ["@boxyhq/saml-jackson"],
images: {
minimumCacheTTL: 2592000, // 30 days
remotePatterns: prepareRemotePatterns(),
@@ -150,6 +151,11 @@ const nextConfig = {
experimental: {
outputFileTracingIncludes: {
"/api/mupdf/*": ["./node_modules/mupdf/dist/*.wasm"],
+ // Jackson SAML token route needs jose + openid-client for crypto
+ "/api/auth/saml/token": [
+ "./node_modules/jose/**/*",
+ "./node_modules/openid-client/**/*",
+ ],
},
missingSuspenseWithCSRBailout: false,
},
@@ -161,6 +167,13 @@ const nextConfig = {
"@google-cloud/kms": false,
"@google-cloud/secret-manager": false,
};
+
+ // Suppress critical dependency warnings from Jackson's dynamic requires
+ config.module = {
+ ...config.module,
+ exprContextCritical: false,
+ };
+
return config;
},
};
diff --git a/package-lock.json b/package-lock.json
index 575e6b4c..75ca0cec 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -17,7 +17,7 @@
"@aws-sdk/cloudfront-signer": "^3.978.0",
"@aws-sdk/lib-storage": "^3.982.0",
"@aws-sdk/s3-request-presigner": "^3.982.0",
- "@boxyhq/saml-jackson": "^1.52.2",
+ "@boxyhq/saml-jackson": "1.52.1",
"@calcom/embed-react": "^1.5.3",
"@chronark/zod-bird": "^0.3.10",
"@dnd-kit/core": "^6.3.1",
@@ -30,7 +30,7 @@
"@next-auth/prisma-adapter": "^1.0.7",
"@next/third-parties": "^16.1.6",
"@pdf-lib/fontkit": "^1.1.1",
- "@prisma/client": "^6.5.0",
+ "@prisma/client": "^6.3.1",
"@radix-ui/react-accordion": "^1.2.12",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-avatar": "^1.1.11",
@@ -174,7 +174,7 @@
"patch-package": "^8.0.1",
"prettier": "^3.8.1",
"prettier-plugin-tailwindcss": "^0.7.2",
- "prisma": "^6.5.0",
+ "prisma": "^6.3.1",
"typescript": "^5"
},
"engines": {
@@ -3514,9 +3514,9 @@
}
},
"node_modules/@boxyhq/saml-jackson": {
- "version": "1.52.2",
- "resolved": "https://registry.npmjs.org/@boxyhq/saml-jackson/-/saml-jackson-1.52.2.tgz",
- "integrity": "sha512-il8VEpaEHBBSeT7cbRmXYO32+PsmRp9urMB5C9ON7QB66XU0VVS9WKaVJROMLVf6QhqETRbSnluSaoevsuPHog==",
+ "version": "1.52.1",
+ "resolved": "https://registry.npmjs.org/@boxyhq/saml-jackson/-/saml-jackson-1.52.1.tgz",
+ "integrity": "sha512-wowZ5SDmHy0Uhgi6GkbLkh0UXUy8UCwZQXifk+iENauPm0RAxmM8UAFyj5k8rd8iEwN3SMdEJAFyg11hr60JAg==",
"license": "Apache 2.0",
"dependencies": {
"@aws-sdk/client-dynamodb": "3.817.0",
@@ -6485,9 +6485,9 @@
"license": "MIT"
},
"node_modules/@prisma/client": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.5.0.tgz",
- "integrity": "sha512-M6w1Ql/BeiGoZmhMdAZUXHu5sz5HubyVcKukbLs3l0ELcQb8hTUJxtGEChhv4SVJ0QJlwtLnwOLgIRQhpsm9dw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@prisma/client/-/client-6.3.1.tgz",
+ "integrity": "sha512-ARAJaPs+eBkemdky/XU3cvGRl+mIPHCN2lCXsl5Vlb0E2gV+R6IN7aCI8CisRGszEZondwIsW9Iz8EJkTdykyA==",
"hasInstallScript": true,
"license": "Apache-2.0",
"engines": {
@@ -6506,65 +6506,54 @@
}
}
},
- "node_modules/@prisma/config": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/@prisma/config/-/config-6.5.0.tgz",
- "integrity": "sha512-sOH/2Go9Zer67DNFLZk6pYOHj+rumSb0VILgltkoxOjYnlLqUpHPAN826vnx8HigqnOCxj9LRhT6U7uLiIIWgw==",
- "devOptional": true,
- "license": "Apache-2.0",
- "dependencies": {
- "esbuild": ">=0.12 <1",
- "esbuild-register": "3.6.0"
- }
- },
"node_modules/@prisma/debug": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.5.0.tgz",
- "integrity": "sha512-fc/nusYBlJMzDmDepdUtH9aBsJrda2JNErP9AzuHbgUEQY0/9zQYZdNlXmKoIWENtio+qarPNe/+DQtrX5kMcQ==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@prisma/debug/-/debug-6.3.1.tgz",
+ "integrity": "sha512-RrEBkd+HLZx+ydfmYT0jUj7wjLiS95wfTOSQ+8FQbvb6vHh5AeKfEPt/XUQ5+Buljj8hltEfOslEW57/wQIVeA==",
"devOptional": true,
"license": "Apache-2.0"
},
"node_modules/@prisma/engines": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.5.0.tgz",
- "integrity": "sha512-FVPQYHgOllJklN9DUyujXvh3hFJCY0NX86sDmBErLvoZjy2OXGiZ5FNf3J/C4/RZZmCypZBYpBKEhx7b7rEsdw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@prisma/engines/-/engines-6.3.1.tgz",
+ "integrity": "sha512-sXdqEVLyGAJ5/iUoG/Ea5AdHMN71m6PzMBWRQnLmhhOejzqAaEr8rUd623ql6OJpED4s/U4vIn4dg1qkF7vGag==",
"devOptional": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
- "@prisma/debug": "6.5.0",
- "@prisma/engines-version": "6.5.0-73.173f8d54f8d52e692c7e27e72a88314ec7aeff60",
- "@prisma/fetch-engine": "6.5.0",
- "@prisma/get-platform": "6.5.0"
+ "@prisma/debug": "6.3.1",
+ "@prisma/engines-version": "6.3.0-17.acc0b9dd43eb689cbd20c9470515d719db10d0b0",
+ "@prisma/fetch-engine": "6.3.1",
+ "@prisma/get-platform": "6.3.1"
}
},
"node_modules/@prisma/engines-version": {
- "version": "6.5.0-73.173f8d54f8d52e692c7e27e72a88314ec7aeff60",
- "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.5.0-73.173f8d54f8d52e692c7e27e72a88314ec7aeff60.tgz",
- "integrity": "sha512-iK3EmiVGFDCmXjSpdsKGNqy9hOdLnvYBrJB61far/oP03hlIxrb04OWmDjNTwtmZ3UZdA5MCvI+f+3k2jPTflQ==",
+ "version": "6.3.0-17.acc0b9dd43eb689cbd20c9470515d719db10d0b0",
+ "resolved": "https://registry.npmjs.org/@prisma/engines-version/-/engines-version-6.3.0-17.acc0b9dd43eb689cbd20c9470515d719db10d0b0.tgz",
+ "integrity": "sha512-R/ZcMuaWZT2UBmgX3Ko6PAV3f8//ZzsjRIG1eKqp3f2rqEqVtCv+mtzuH2rBPUC9ujJ5kCb9wwpxeyCkLcHVyA==",
"devOptional": true,
"license": "Apache-2.0"
},
"node_modules/@prisma/fetch-engine": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.5.0.tgz",
- "integrity": "sha512-3LhYA+FXP6pqY8FLHCjewyE8pGXXJ7BxZw2rhPq+CZAhvflVzq4K8Qly3OrmOkn6wGlz79nyLQdknyCG2HBTuA==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@prisma/fetch-engine/-/fetch-engine-6.3.1.tgz",
+ "integrity": "sha512-HOf/0umOgt+/S2xtZze+FHKoxpVg4YpVxROr6g2YG09VsI3Ipyb+rGvD6QGbCqkq5NTWAAZoOGNL+oy7t+IhaQ==",
"devOptional": true,
"license": "Apache-2.0",
"dependencies": {
- "@prisma/debug": "6.5.0",
- "@prisma/engines-version": "6.5.0-73.173f8d54f8d52e692c7e27e72a88314ec7aeff60",
- "@prisma/get-platform": "6.5.0"
+ "@prisma/debug": "6.3.1",
+ "@prisma/engines-version": "6.3.0-17.acc0b9dd43eb689cbd20c9470515d719db10d0b0",
+ "@prisma/get-platform": "6.3.1"
}
},
"node_modules/@prisma/get-platform": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.5.0.tgz",
- "integrity": "sha512-xYcvyJwNMg2eDptBYFqFLUCfgi+wZLcj6HDMsj0Qw0irvauG4IKmkbywnqwok0B+k+W+p+jThM2DKTSmoPCkzw==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/@prisma/get-platform/-/get-platform-6.3.1.tgz",
+ "integrity": "sha512-AYLq6Hk9xG73JdLWJ3Ip9Wg/vlP7xPvftGBalsPzKDOHr/ImhwJ09eS8xC2vNT12DlzGxhfk8BkL0ve2OriNhQ==",
"devOptional": true,
"license": "Apache-2.0",
"dependencies": {
- "@prisma/debug": "6.5.0"
+ "@prisma/debug": "6.3.1"
}
},
"node_modules/@protobufjs/aspromise": {
@@ -14450,19 +14439,6 @@
"@esbuild/win32-x64": "0.25.10"
}
},
- "node_modules/esbuild-register": {
- "version": "3.6.0",
- "resolved": "https://registry.npmjs.org/esbuild-register/-/esbuild-register-3.6.0.tgz",
- "integrity": "sha512-H2/S7Pm8a9CL1uhp9OvjwrBh5Pvx0H8qVOxNu8Wed9Y7qv56MPtq+GGM8RJpq6glYJn9Wspr8uw7l55uyinNeg==",
- "devOptional": true,
- "license": "MIT",
- "dependencies": {
- "debug": "^4.3.4"
- },
- "peerDependencies": {
- "esbuild": ">=0.12 <1"
- }
- },
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
@@ -21964,15 +21940,14 @@
"integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew=="
},
"node_modules/prisma": {
- "version": "6.5.0",
- "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.5.0.tgz",
- "integrity": "sha512-yUGXmWqv5F4PByMSNbYFxke/WbnyTLjnJ5bKr8fLkcnY7U5rU9rUTh/+Fja+gOrRxEgtCbCtca94IeITj4j/pg==",
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/prisma/-/prisma-6.3.1.tgz",
+ "integrity": "sha512-JKCZWvBC3enxk51tY4TWzS4b5iRt4sSU1uHn2I183giZTvonXaQonzVtjLzpOHE7qu9MxY510kAtFGJwryKe3Q==",
"devOptional": true,
"hasInstallScript": true,
"license": "Apache-2.0",
"dependencies": {
- "@prisma/config": "6.5.0",
- "@prisma/engines": "6.5.0"
+ "@prisma/engines": "6.3.1"
},
"bin": {
"prisma": "build/index.js"
diff --git a/package.json b/package.json
index 06e2d90e..77e2fa87 100644
--- a/package.json
+++ b/package.json
@@ -28,7 +28,7 @@
"@aws-sdk/cloudfront-signer": "^3.978.0",
"@aws-sdk/lib-storage": "^3.982.0",
"@aws-sdk/s3-request-presigner": "^3.982.0",
- "@boxyhq/saml-jackson": "^1.52.2",
+ "@boxyhq/saml-jackson": "1.52.1",
"@calcom/embed-react": "^1.5.3",
"@chronark/zod-bird": "^0.3.10",
"@dnd-kit/core": "^6.3.1",
@@ -41,7 +41,7 @@
"@next-auth/prisma-adapter": "^1.0.7",
"@next/third-parties": "^16.1.6",
"@pdf-lib/fontkit": "^1.1.1",
- "@prisma/client": "^6.5.0",
+ "@prisma/client": "^6.3.1",
"@radix-ui/react-accordion": "^1.2.12",
"@radix-ui/react-alert-dialog": "^1.1.15",
"@radix-ui/react-avatar": "^1.1.11",
@@ -185,7 +185,7 @@
"patch-package": "^8.0.1",
"prettier": "^3.8.1",
"prettier-plugin-tailwindcss": "^0.7.2",
- "prisma": "^6.5.0",
+ "prisma": "^6.3.1",
"typescript": "^5"
},
"overrides": {
diff --git a/pages/api/auth/[...nextauth].ts b/pages/api/auth/[...nextauth].ts
index 6fae7b1e..13094895 100644
--- a/pages/api/auth/[...nextauth].ts
+++ b/pages/api/auth/[...nextauth].ts
@@ -1,6 +1,7 @@
import { NextApiRequest, NextApiResponse } from "next";
import { checkRateLimit, rateLimiters } from "@/ee/features/security";
+import { isSamlEnforcedForEmailDomain } from "@/lib/api/teams/is-saml-enforced-for-email-domain";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import PasskeyProvider from "@teamhanko/passkeys-next-auth-provider";
import NextAuth, { type NextAuthOptions } from "next-auth";
@@ -104,6 +105,58 @@ export const authOptions: NextAuthOptions = {
return user;
},
}),
+ // ─── SP-Initiated SAML SSO (OAuth flow with PKCE + state) ───
+ // Used when user clicks "Continue with SSO" on the login page.
+ // NextAuth handles PKCE and state validation automatically.
+ {
+ id: "saml",
+ name: "BoxyHQ SAML",
+ type: "oauth",
+ version: "2.0",
+ checks: ["pkce", "state"],
+ authorization: {
+ url: `${process.env.NEXTAUTH_URL}/api/auth/saml/authorize`,
+ params: {
+ scope: "",
+ response_type: "code",
+ provider: "saml",
+ },
+ },
+ token: {
+ url: `${process.env.NEXTAUTH_URL}/api/auth/saml/token`,
+ params: { grant_type: "authorization_code" },
+ },
+ userinfo: `${process.env.NEXTAUTH_URL}/api/auth/saml/userinfo`,
+ profile: async (profile) => {
+ let existingUser = await prisma.user.findUnique({
+ where: { email: profile.email },
+ });
+
+ if (!existingUser) {
+ existingUser = await prisma.user.create({
+ data: {
+ email: profile.email,
+ name: `${profile.firstName || ""} ${profile.lastName || ""}`.trim(),
+ },
+ });
+ }
+
+ return {
+ id: existingUser.id,
+ name: existingUser.name,
+ email: existingUser.email,
+ image: existingUser.image,
+ };
+ },
+ options: {
+ clientId: "dummy",
+ clientSecret: process.env.NEXTAUTH_SECRET as string,
+ },
+ allowDangerousEmailAccountLinking: true,
+ },
+ // ─── IdP-Initiated SAML SSO (Credentials provider) ───
+ // Used when user clicks the app tile in their IdP dashboard.
+ // Jackson redirects with a code to /auth/saml, which then calls signIn("saml-idp", { code }).
CredentialsProvider({
id: "saml-idp",
name: "IdP Login",
@@ -116,68 +169,56 @@ export const authOptions: NextAuthOptions = {
try {
const { oauthController } = await jackson();
- // Exchange the authorization code for an access token
const { access_token } = await oauthController.token({
code: credentials.code,
grant_type: "authorization_code",
redirect_uri: process.env.NEXTAUTH_URL!,
- client_id: "dummy", // Jackson uses tenant+product, not traditional client_id
+ client_id: "dummy",
client_secret: process.env.NEXTAUTH_SECRET!,
});
if (!access_token) return null;
- // Fetch user info from Jackson
const userInfo = await oauthController.userInfo(access_token);
if (!userInfo) return null;
- // userInfo contains: id, email, firstName, lastName, requested.tenant, requested.product
const { email, firstName, lastName, requested } = userInfo as any;
-
if (!email) return null;
const name = [firstName, lastName].filter(Boolean).join(" ") || email;
- // Upsert user in the main DB
const user = await prisma.user.upsert({
where: { email },
- create: {
- email,
- name,
- },
- update: {
- name: name || undefined,
- },
+ create: { email, name },
+ update: { name: name || undefined },
});
- // If we have tenant info, ensure user is a member of the workspace (team)
+ // If we have tenant info, ensure user is a member of the workspace
const tenant = requested?.tenant;
if (tenant) {
- const existingMembership = await prisma.userTeam.findUnique({
+ await prisma.userTeam.upsert({
where: {
userId_teamId: {
userId: user.id,
teamId: tenant,
},
},
+ update: {},
+ create: {
+ userId: user.id,
+ teamId: tenant,
+ role: "MEMBER",
+ },
});
-
- if (!existingMembership) {
- await prisma.userTeam.create({
- data: {
- userId: user.id,
- teamId: tenant,
- role: "MEMBER",
- },
- });
- }
}
return {
id: user.id,
email: user.email,
name: user.name,
- };
+ // Pass profile for signIn callback to access tenant
+ profile: userInfo,
+ } as any;
} catch (error) {
console.error("[SAML] Error during SAML authorization:", error);
return null;
@@ -194,7 +235,6 @@ export const authOptions: NextAuthOptions = {
httpOnly: true,
sameSite: "lax",
path: "/",
- // When working on localhost, the cookie domain must be omitted entirely (https://stackoverflow.com/a/1188145)
domain: VERCEL_DEPLOYMENT ? ".papermark.com" : undefined,
secure: VERCEL_DEPLOYMENT,
},
@@ -210,7 +250,10 @@ export const authOptions: NextAuthOptions = {
token.user = user;
}
// Track SAML provider on the token
- if (account?.provider === "saml-idp" && user) {
+ if (
+ (account?.provider === "saml" || account?.provider === "saml-idp") &&
+ user
+ ) {
token.provider = "saml";
}
// refresh the user data
@@ -226,7 +269,6 @@ export const authOptions: NextAuthOptions = {
}
if (refreshedUser?.email !== user.email) {
- // if user has changed email, delete all accounts for the user
if (user.id && refreshedUser.email) {
await prisma.account.deleteMany({
where: { userId: user.id },
@@ -259,7 +301,7 @@ export const authOptions: NextAuthOptions = {
body: {
userId: message.user.id,
},
- delay: 15 * 60, // 15 minutes
+ delay: 15 * 60,
});
},
},
@@ -270,7 +312,7 @@ const getAuthOptions = (req: NextApiRequest): NextAuthOptions => {
...authOptions,
callbacks: {
...authOptions.callbacks,
- signIn: async ({ user }) => {
+ signIn: async ({ user, account, profile }) => {
if (!user.email || (await isBlacklistedEmail(user.email))) {
await identifyUser(user.email ?? user.id);
await trackAnalytics({
@@ -281,6 +323,92 @@ const getAuthOptions = (req: NextApiRequest): NextAuthOptions => {
return false;
}
+ // ─── SSO Enforcement ───
+ // If user is NOT signing in via SAML, check if their domain requires SSO
+ if (
+ account?.provider !== "saml" &&
+ account?.provider !== "saml-idp"
+ ) {
+ const ssoEnforced = await isSamlEnforcedForEmailDomain(user.email);
+ if (ssoEnforced) {
+ throw new Error("require-saml-sso");
+ }
+ }
+
+ // ─── SAML user → email domain validation + workspace membership ───
+ if (
+ account?.provider === "saml" ||
+ account?.provider === "saml-idp"
+ ) {
+ // Get the SAML profile — comes from different places depending on provider
+ let samlProfile: any;
+ if (account.provider === "saml-idp") {
+ // IdP-initiated: we attached the Jackson userInfo to user.profile
+ samlProfile = (user as any).profile;
+ } else {
+ // SP-initiated OAuth: NextAuth passes the raw Jackson userInfo as `profile`
+ samlProfile = profile;
+ }
+
+ const tenant = samlProfile?.requested?.tenant;
+ if (tenant) {
+ // ─── Email domain validation ───
+ // Verify the SAML user's email domain matches the team's ssoEmailDomain.
+ // This prevents a misconfigured IdP from injecting users from unexpected domains.
+ const team = await prisma.team.findUnique({
+ where: { id: tenant },
+ select: { ssoEmailDomain: true },
+ });
+
+ if (team?.ssoEmailDomain) {
+ const userEmailDomain = user.email
+ .split("@")[1]
+ ?.toLowerCase();
+ if (
+ userEmailDomain !==
+ team.ssoEmailDomain.toLowerCase()
+ ) {
+ console.warn(
+ `[SAML] Rejected: user ${user.email} domain does not match team ssoEmailDomain ${team.ssoEmailDomain}`,
+ );
+ return false;
+ }
+ }
+
+ // ─── Auto-join workspace ───
+ await prisma.userTeam
+ .upsert({
+ where: {
+ userId_teamId: {
+ userId: user.id,
+ teamId: tenant,
+ },
+ },
+ update: {},
+ create: {
+ userId: user.id,
+ teamId: tenant,
+ role: "MEMBER",
+ },
+ })
+ .catch(() => {
+ // Team may not exist, that's ok
+ });
+
+ // Clean up any pending invitations for this user
+ await prisma.invitation
+ .deleteMany({
+ where: {
+ email: user.email,
+ teamId: tenant,
+ },
+ })
+ .catch(() => {
+ // No invitation to clean up
+ });
+ }
+ }
+
// Apply rate limiting for signin attempts
try {
if (req) {
@@ -295,7 +423,7 @@ const getAuthOptions = (req: NextApiRequest): NextAuthOptions => {
message: `Rate limit exceeded for IP ${clientIP} during signin attempt`,
type: "error",
});
- return false; // Block the signin
+ return false;
}
}
} catch (error) {}
@@ -306,7 +434,6 @@ const getAuthOptions = (req: NextApiRequest): NextAuthOptions => {
events: {
...authOptions.events,
signIn: async (message) => {
- // Identify and track sign-in without blocking the event flow
await Promise.allSettled([
identifyUser(message.user.email ?? message.user.id),
trackAnalytics({
@@ -317,7 +444,6 @@ const getAuthOptions = (req: NextApiRequest): NextAuthOptions => {
if (message.isNewUser) {
const { dub_id } = req.cookies;
- // Only fire lead event if Dub is enabled
if (dub_id && process.env.DUB_API_KEY) {
try {
await dub.track.lead({
diff --git a/pages/api/auth/saml/authorize.ts b/pages/api/auth/saml/authorize.ts
deleted file mode 100644
index 958807fa..00000000
--- a/pages/api/auth/saml/authorize.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-
-import { jackson } from "@/lib/jackson";
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- if (req.method !== "GET") {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-
- try {
- const { oauthController } = await jackson();
-
- const { redirect_url } = await oauthController.authorize(
- req.query as any,
- );
-
- if (!redirect_url) {
- return res.status(400).json({ error: "No redirect URL returned" });
- }
-
- return res.redirect(302, redirect_url);
- } catch (error: any) {
- console.error("[SAML] Authorize error:", error);
- return res.status(500).json({
- error: error.message || "Internal server error",
- });
- }
-}
diff --git a/pages/api/auth/saml/callback.ts b/pages/api/auth/saml/callback.ts
deleted file mode 100644
index 61b771d3..00000000
--- a/pages/api/auth/saml/callback.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-
-import { jackson } from "@/lib/jackson";
-
-// Disable body parsing — we need the raw form data
-export const config = {
- api: {
- bodyParser: true,
- },
-};
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- if (req.method !== "POST") {
- res.setHeader("Allow", ["POST"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-
- try {
- const { oauthController } = await jackson();
-
- const { RelayState, SAMLResponse } = req.body;
-
- const { redirect_url } = await oauthController.samlResponse({
- RelayState,
- SAMLResponse,
- });
-
- if (!redirect_url) {
- return res.status(400).json({ error: "No redirect URL returned" });
- }
-
- return res.redirect(302, redirect_url);
- } catch (error: any) {
- console.error("[SAML] Callback error:", error);
- return res.status(500).json({
- error: error.message || "Internal server error",
- });
- }
-}
diff --git a/pages/api/auth/saml/check.ts b/pages/api/auth/saml/check.ts
deleted file mode 100644
index 042096c8..00000000
--- a/pages/api/auth/saml/check.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-
-import prisma from "@/lib/prisma";
-
-// Check if SAML is configured for a given email domain
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- if (req.method !== "GET") {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-
- try {
- const { email } = req.query as { email: string };
-
- if (!email) {
- return res.status(400).json({ error: "Email is required" });
- }
-
- const domain = email.split("@")[1];
- if (!domain) {
- return res.status(400).json({ error: "Invalid email" });
- }
-
- // Find a team that has SAML enabled and is associated with this email domain
- // We look for teams where the user's email domain matches
- const teamsWithSaml = await prisma.team.findMany({
- where: {
- samlEnabled: true,
- },
- select: {
- id: true,
- name: true,
- samlProvider: true,
- },
- });
-
- // Check if any team has a user with this domain
- for (const team of teamsWithSaml) {
- const membership = await prisma.userTeam.findFirst({
- where: {
- teamId: team.id,
- user: {
- email: {
- endsWith: `@${domain}`,
- },
- },
- },
- });
-
- if (membership) {
- return res.status(200).json({
- hasSaml: true,
- teamId: team.id,
- teamName: team.name,
- provider: team.samlProvider,
- });
- }
- }
-
- return res.status(200).json({ hasSaml: false });
- } catch (error: any) {
- console.error("[SAML] Check error:", error);
- return res.status(500).json({
- error: error.message || "Internal server error",
- });
- }
-}
diff --git a/pages/api/auth/saml/token.ts b/pages/api/auth/saml/token.ts
deleted file mode 100644
index e218597d..00000000
--- a/pages/api/auth/saml/token.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-
-import { jackson } from "@/lib/jackson";
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- if (req.method !== "POST") {
- res.setHeader("Allow", ["POST"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-
- try {
- const { oauthController } = await jackson();
-
- const response = await oauthController.token(req.body);
- return res.status(200).json(response);
- } catch (error: any) {
- console.error("[SAML] Token error:", error);
- return res.status(500).json({
- error: error.message || "Internal server error",
- });
- }
-}
diff --git a/pages/api/auth/saml/userinfo.ts b/pages/api/auth/saml/userinfo.ts
deleted file mode 100644
index 8fac833d..00000000
--- a/pages/api/auth/saml/userinfo.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-
-import { jackson } from "@/lib/jackson";
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- if (req.method !== "GET") {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-
- try {
- const { oauthController } = await jackson();
-
- const token = req.headers.authorization?.replace("Bearer ", "");
- if (!token) {
- return res.status(401).json({ error: "Unauthorized" });
- }
-
- const userInfo = await oauthController.userInfo(token);
- return res.status(200).json(userInfo);
- } catch (error: any) {
- console.error("[SAML] UserInfo error:", error);
- return res.status(500).json({
- error: error.message || "Internal server error",
- });
- }
-}
diff --git a/pages/api/scim/v2.0/[...path].ts b/pages/api/scim/v2.0/[...path].ts
deleted file mode 100644
index 7dc1d21d..00000000
--- a/pages/api/scim/v2.0/[...path].ts
+++ /dev/null
@@ -1,195 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-
-import { jackson } from "@/lib/jackson";
-import prisma from "@/lib/prisma";
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- try {
- const { directorySyncController } = await jackson();
-
- // Build the full path from the catch-all segments
- const pathSegments = req.query.path as string[];
- // pathSegments: [directoryId, "Users" | "Groups", resourceId?]
-
- const directoryId = pathSegments[0] || "";
- const resourceType = pathSegments[1] || ""; // "Users" or "Groups"
- const resourceId = pathSegments[2] || undefined;
-
- // Extract the authorization header (Bearer token from IdP)
- const authorization = req.headers.authorization || "";
-
- // Parse request body for POST/PUT/PATCH
- let body: any = {};
- if (["POST", "PUT", "PATCH"].includes(req.method || "")) {
- body = req.body || {};
- }
-
- // Build query params
- const query: Record<string, string> = {};
- Object.entries(req.query).forEach(([key, value]) => {
- if (key !== "path" && typeof value === "string") {
- query[key] = value;
- }
- });
-
- const response = await directorySyncController.requests.handle(
- {
- method: req.method as "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
- body,
- query,
- directoryId,
- resourceType,
- resourceId,
- apiSecret: authorization.replace("Bearer ", ""),
- },
- handleSCIMEvents,
- );
-
- return res.status(response.status).json(response.data || {});
- } catch (error: any) {
- console.error("[SCIM] Request error:", error);
- return res.status(500).json({
- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
- detail: error.message || "Internal server error",
- status: 500,
- });
- }
-}
-
-// SCIM Event Handler — sync changes to the main app DB
-async function handleSCIMEvents(event: any) {
- const { event: eventType, data, tenant } = event;
-
- try {
- switch (eventType) {
- case "user.created": {
- // A new user was provisioned from the IdP
- console.log(
- `[SCIM] User created: ${data.email} for tenant ${tenant}`,
- );
-
- if (data.email) {
- // Create or find the user
- const user = await prisma.user.upsert({
- where: { email: data.email },
- create: {
- email: data.email,
- name: [data.first_name, data.last_name]
- .filter(Boolean)
- .join(" "),
- },
- update: {},
- });
-
- // Add user to the team if not already a member
- const existingMembership = await prisma.userTeam.findUnique({
- where: {
- userId_teamId: {
- userId: user.id,
- teamId: tenant,
- },
- },
- });
-
- if (!existingMembership) {
- await prisma.userTeam.create({
- data: {
- userId: user.id,
- teamId: tenant,
- role: "MEMBER",
- },
- });
- }
- }
- break;
- }
-
- case "user.updated": {
- // User attributes changed in the IdP
- console.log(
- `[SCIM] User updated: ${data.email} for tenant ${tenant}`,
- );
-
- if (data.email) {
- await prisma.user.update({
- where: { email: data.email },
- data: {
- name: [data.first_name, data.last_name]
- .filter(Boolean)
- .join(" "),
- },
- }).catch(() => {
- // User might not exist yet
- console.warn(
- `[SCIM] Could not update user ${data.email} — user not found`,
- );
- });
- }
- break;
- }
-
- case "user.deleted": {
- // User deprovisioned / deactivated in the IdP
- console.log(
- `[SCIM] User deleted: ${data.email} for tenant ${tenant}`,
- );
-
- if (data.email) {
- const user = await prisma.user.findUnique({
- where: { email: data.email },
- });
-
- if (user) {
- // Remove user from the team (don't delete the user account)
- await prisma.userTeam
- .delete({
- where: {
- userId_teamId: {
- userId: user.id,
- teamId: tenant,
- },
- },
- })
- .catch(() => {
- console.warn(
- `[SCIM] Could not remove team membership for ${data.email}`,
- );
- });
- }
- }
- break;
- }
-
- case "group.created":
- case "group.updated":
- case "group.deleted": {
- // Handle group sync if needed
- console.log(
- `[SCIM] Group event ${eventType} for tenant ${tenant}`,
- );
- break;
- }
-
- case "group.user_added": {
- // User added to a group in the IdP
- console.log(
- `[SCIM] User added to group for tenant ${tenant}`,
- );
- break;
- }
-
- case "group.user_removed": {
- // User removed from a group in the IdP
- console.log(
- `[SCIM] User removed from group for tenant ${tenant}`,
- );
- break;
- }
- }
- } catch (error) {
- console.error(`[SCIM] Error handling event ${eventType}:`, error);
- }
-}
diff --git a/pages/api/teams/[teamId]/directory-sync/index.ts b/pages/api/teams/[teamId]/directory-sync/index.ts
deleted file mode 100644
index 67f7e846..00000000
--- a/pages/api/teams/[teamId]/directory-sync/index.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-
-import { getServerSession } from "next-auth/next";
-
-import { errorhandler } from "@/lib/errorHandler";
-import { jackson } from "@/lib/jackson";
-import prisma from "@/lib/prisma";
-import { CustomUser } from "@/lib/types";
-
-import { authOptions } from "../../../auth/[...nextauth]";
-
-export default async function handle(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).end("Unauthorized");
- }
-
- const userId = (session.user as CustomUser).id;
- const { teamId } = req.query as { teamId: string };
-
- // Verify user has access to the team and is an admin
- const teamAccess = await prisma.userTeam.findUnique({
- where: {
- userId_teamId: {
- userId,
- teamId,
- },
- },
- select: { role: true },
- });
-
- if (!teamAccess) {
- return res.status(401).end("Unauthorized");
- }
-
- if (teamAccess.role !== "ADMIN") {
- return res
- .status(403)
- .json({ error: "Only admins can manage Directory Sync" });
- }
-
- if (req.method === "GET") {
- // GET /api/teams/:teamId/directory-sync — list directory sync connections
- try {
- const { directorySyncController } = await jackson();
-
- const { data, error } =
- await directorySyncController.directories.getByTenantAndProduct(
- teamId,
- process.env.JACKSON_PRODUCT!,
- );
-
- if (error) {
- return res.status(400).json({ error: error.message });
- }
-
- return res.status(200).json(data);
- } catch (error) {
- errorhandler(error, res);
- }
- } else if (req.method === "POST") {
- // POST /api/teams/:teamId/directory-sync — create directory sync connection
- try {
- const { directorySyncController } = await jackson();
-
- const { name, type, webhook_url, webhook_secret } = req.body;
-
- const { data, error } =
- await directorySyncController.directories.create({
- tenant: teamId,
- product: process.env.JACKSON_PRODUCT!,
- name: name || "Directory Sync",
- type: type || "azure-scim-v2",
- webhook_url: webhook_url || undefined,
- webhook_secret: webhook_secret || undefined,
- });
-
- if (error) {
- return res.status(400).json({ error: error.message });
- }
-
- // Mark team as SCIM-enabled
- await prisma.team.update({
- where: { id: teamId },
- data: {
- scimEnabled: true,
- scimProvider: type || "azure-scim-v2",
- scimDirectoryId: (data as any)?.id || null,
- },
- });
-
- // data contains: id, scim.endpoint, scim.secret
- return res.status(201).json(data);
- } catch (error) {
- errorhandler(error, res);
- }
- } else if (req.method === "DELETE") {
- // DELETE /api/teams/:teamId/directory-sync — delete directory sync connection
- try {
- const { directorySyncController } = await jackson();
-
- const { directoryId } = req.body;
-
- if (!directoryId) {
- return res.status(400).json({ error: "directoryId is required" });
- }
-
- const { error } =
- await directorySyncController.directories.delete(directoryId);
-
- if (error) {
- return res.status(400).json({ error: error.message });
- }
-
- // Check remaining directories
- const { data: remaining } =
- await directorySyncController.directories.getByTenantAndProduct(
- teamId,
- process.env.JACKSON_PRODUCT!,
- );
-
- if (
- !remaining ||
- (Array.isArray(remaining) && remaining.length === 0)
- ) {
- await prisma.team.update({
- where: { id: teamId },
- data: {
- scimEnabled: false,
- scimProvider: null,
- scimDirectoryId: null,
- },
- });
- }
-
- return res.status(200).json({ ok: true });
- } catch (error) {
- errorhandler(error, res);
- }
- } else {
- res.setHeader("Allow", ["GET", "POST", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-}
diff --git a/pages/api/teams/[teamId]/saml/index.ts b/pages/api/teams/[teamId]/saml/index.ts
deleted file mode 100644
index ca9685b1..00000000
--- a/pages/api/teams/[teamId]/saml/index.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-
-import { getServerSession } from "next-auth/next";
-
-import { errorhandler } from "@/lib/errorHandler";
-import { jackson } from "@/lib/jackson";
-import prisma from "@/lib/prisma";
-import { CustomUser } from "@/lib/types";
-
-import { authOptions } from "../../../auth/[...nextauth]";
-
-export default async function handle(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).end("Unauthorized");
- }
-
- const userId = (session.user as CustomUser).id;
- const { teamId } = req.query as { teamId: string };
-
- // Verify user has access to the team and is an admin
- const teamAccess = await prisma.userTeam.findUnique({
- where: {
- userId_teamId: {
- userId,
- teamId,
- },
- },
- select: { role: true },
- });
-
- if (!teamAccess) {
- return res.status(401).end("Unauthorized");
- }
-
- if (teamAccess.role !== "ADMIN") {
- return res.status(403).json({ error: "Only admins can manage SAML SSO" });
- }
-
- if (req.method === "GET") {
- // GET /api/teams/:teamId/saml — list SAML connections
- try {
- const { apiController } = await jackson();
-
- const connections = await apiController.getConnections({
- tenant: teamId,
- product: process.env.JACKSON_PRODUCT!,
- });
-
- return res.status(200).json(connections);
- } catch (error) {
- errorhandler(error, res);
- }
- } else if (req.method === "POST") {
- // POST /api/teams/:teamId/saml — create a new SAML connection
- try {
- const { apiController } = await jackson();
-
- const { rawMetadata, metadataUrl, name, description } = req.body;
-
- if (!rawMetadata && !metadataUrl) {
- return res.status(400).json({
- error:
- "Either rawMetadata or metadataUrl is required to configure SAML",
- });
- }
-
- const connection = await apiController.createSAMLConnection({
- defaultRedirectUrl: `${process.env.NEXTAUTH_URL}/auth/saml`,
- redirectUrl: JSON.stringify([
- `${process.env.NEXTAUTH_URL}`,
- `${process.env.NEXTAUTH_URL}/auth/saml`,
- ]),
- tenant: teamId,
- product: process.env.JACKSON_PRODUCT!,
- rawMetadata: rawMetadata || undefined,
- metadataUrl: metadataUrl || undefined,
- name: name || "SAML SSO",
- description: description || "SAML Single Sign-On",
- });
-
- // Mark team as SAML-enabled in the main DB
- const samlProvider = name?.toLowerCase().includes("okta")
- ? "okta"
- : name?.toLowerCase().includes("google")
- ? "google"
- : name?.toLowerCase().includes("entra") ||
- name?.toLowerCase().includes("azure")
- ? "azure"
- : "custom";
-
- await prisma.team.update({
- where: { id: teamId },
- data: {
- samlEnabled: true,
- samlProvider,
- samlConnectionId: (connection as any).clientID || null,
- },
- });
-
- return res.status(201).json(connection);
- } catch (error) {
- errorhandler(error, res);
- }
- } else if (req.method === "DELETE") {
- // DELETE /api/teams/:teamId/saml — remove a SAML connection
- try {
- const { apiController } = await jackson();
-
- const { clientID, clientSecret } = req.body;
-
- if (!clientID || !clientSecret) {
- return res
- .status(400)
- .json({ error: "clientID and clientSecret are required" });
- }
-
- await apiController.deleteConnections({
- clientID,
- clientSecret,
- });
-
- // Check if there are remaining connections
- const remaining = await apiController.getConnections({
- tenant: teamId,
- product: process.env.JACKSON_PRODUCT!,
- });
-
- if (!remaining || (Array.isArray(remaining) && remaining.length === 0)) {
- await prisma.team.update({
- where: { id: teamId },
- data: {
- samlEnabled: false,
- samlProvider: null,
- samlConnectionId: null,
- },
- });
- }
-
- return res.status(200).json({ ok: true });
- } catch (error) {
- errorhandler(error, res);
- }
- } else {
- res.setHeader("Allow", ["GET", "POST", "DELETE"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-}
diff --git a/pages/settings/billing.tsx b/pages/settings/billing.tsx
index 9e5a44a9..2ca10217 100644
--- a/pages/settings/billing.tsx
+++ b/pages/settings/billing.tsx
@@ -7,6 +7,7 @@ import { sendGTMEvent } from "@next/third-parties/google";
import { toast } from "sonner";
import { useAnalytics } from "@/lib/analytics";
+import { useIsAdmin } from "@/lib/hooks/use-is-admin";
import { usePlan } from "@/lib/swr/use-billing";
import UpgradePlanContainer from "@/components/billing/upgrade-plan-container";
@@ -23,6 +24,14 @@ export default function Billing() {
const teamId = teamInfo?.currentTeam?.id;
const { plan } = usePlan();
+ const { isAdmin, loading: isAdminLoading } = useIsAdmin();
+
+ // Redirect non-admin users to general settings
+ useEffect(() => {
+ if (!isAdminLoading && !isAdmin) {
+ router.replace("/settings/general");
+ }
+ }, [isAdmin, isAdminLoading, router]);
useEffect(() => {
if (router.query.success) {
@@ -49,6 +58,15 @@ export default function Billing() {
}
}, [router.query]);
+ // Show nothing while checking admin status
+ if (isAdminLoading || !isAdmin) {
+ return (
+ <AppLayout>
+ <div />
+ </AppLayout>
+ );
+ }
+
return (
<>
<GTMComponent />
diff --git a/pages/settings/billing/invoices.tsx b/pages/settings/billing/invoices.tsx
index 38d3a96e..b7dbbb10 100644
--- a/pages/settings/billing/invoices.tsx
+++ b/pages/settings/billing/invoices.tsx
@@ -1,7 +1,10 @@
import { useRouter } from "next/router";
+import { useEffect } from "react";
+
import { Download, FileText, Loader2 } from "lucide-react";
+import { useIsAdmin } from "@/lib/hooks/use-is-admin";
import { useInvoices } from "@/lib/swr/use-invoices";
import AppLayout from "@/components/layouts/app";
@@ -20,6 +23,14 @@ import {
export default function Invoices() {
const router = useRouter();
const { invoices, loading, error } = useInvoices();
+ const { isAdmin, loading: isAdminLoading } = useIsAdmin();
+
+ // Redirect non-admin users to general settings
+ useEffect(() => {
+ if (!isAdminLoading && !isAdmin) {
+ router.replace("/settings/general");
+ }
+ }, [isAdmin, isAdminLoading, router]);
const formatCurrency = (amount: number, currency: string) => {
return new Intl.NumberFormat("en-US", {
@@ -48,6 +59,15 @@ export default function Invoices() {
}
};
+ // Show nothing while checking admin status
+ if (isAdminLoading || !isAdmin) {
+ return (
+ <AppLayout>
+ <div />
+ </AppLayout>
+ );
+ }
+
return (
<AppLayout>
<main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
diff --git a/pages/settings/security.tsx b/pages/settings/security.tsx
index 4143cc3f..904f9efa 100644
--- a/pages/settings/security.tsx
+++ b/pages/settings/security.tsx
@@ -1,200 +1,207 @@
-import { useCallback, useEffect, useState } from "react";
+import { useRouter } from "next/router";
+
+import { useEffect } from "react";
import { useTeam } from "@/context/team-context";
-import { Shield, FolderSync, Info } from "lucide-react";
+import {
+ DirectorySyncConfigModal,
+ SAMLConfigModal,
+ SSOEnforcementToggle,
+} from "@/ee/features/security/sso";
+import { FolderSync, Info, Shield } from "lucide-react";
+
+import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";
+import { useIsAdmin } from "@/lib/hooks/use-is-admin";
import AppLayout from "@/components/layouts/app";
import { SettingsHeader } from "@/components/settings/settings-header";
-import { DirectorySyncConfigModal } from "@/components/settings/security/directory-sync-config-modal";
-import { SAMLConfigModal } from "@/components/settings/security/saml-config-modal";
+
+const SSO_ELIGIBLE_PLANS = ["datarooms-premium", "datarooms-premium+old"];
export default function SecuritySettings() {
+ const router = useRouter();
const teamInfo = useTeam();
const teamId = teamInfo?.currentTeam?.id;
+ const teamPlan = teamInfo?.currentTeam?.plan;
+ const { isFeatureEnabled } = useFeatureFlags();
+ const { isAdmin, loading: isAdminLoading } = useIsAdmin();
- const [samlConnections, setSamlConnections] = useState<any[]>([]);
- const [directories, setDirectories] = useState<any[]>([]);
- const [loadingSaml, setLoadingSaml] = useState(true);
- const [loadingScim, setLoadingScim] = useState(true);
-
- const fetchSamlConnections = useCallback(async () => {
- if (!teamId) return;
- try {
- setLoadingSaml(true);
- const res = await fetch(`/api/teams/${teamId}/saml`);
- if (res.ok) {
- const data = await res.json();
- setSamlConnections(Array.isArray(data) ? data : []);
- }
- } catch (error) {
- console.error("Failed to fetch SAML connections:", error);
- } finally {
- setLoadingSaml(false);
- }
- }, [teamId]);
-
- const fetchDirectories = useCallback(async () => {
- if (!teamId) return;
- try {
- setLoadingScim(true);
- const res = await fetch(`/api/teams/${teamId}/directory-sync`);
- if (res.ok) {
- const data = await res.json();
- setDirectories(Array.isArray(data) ? data : []);
- }
- } catch (error) {
- console.error("Failed to fetch directory sync:", error);
- } finally {
- setLoadingScim(false);
+ // Redirect non-admin users to general settings
+ useEffect(() => {
+ if (!isAdminLoading && !isAdmin) {
+ router.replace("/settings/general");
}
- }, [teamId]);
+ }, [isAdmin, isAdminLoading, router]);
- useEffect(() => {
- fetchSamlConnections();
- fetchDirectories();
- }, [fetchSamlConnections, fetchDirectories]);
+ // Show nothing while checking admin status
+ if (isAdminLoading || !isAdmin) {
+ return (
+ <AppLayout>
+ <div />
+ </AppLayout>
+ );
+ }
+
+ const isSSOFeatureEnabled = isFeatureEnabled("sso");
+ const isPlanEligible = teamPlan
+ ? SSO_ELIGIBLE_PLANS.includes(teamPlan)
+ : false;
+ const canAccessSSO = isSSOFeatureEnabled && isPlanEligible;
return (
<AppLayout>
<main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
<SettingsHeader />
- {/* SAML SSO Section */}
- <div className="rounded-lg border border-muted p-6 sm:p-10">
- <div className="space-y-6">
+ {!canAccessSSO ? (
+ <div className="rounded-lg border border-muted p-6 sm:p-10">
<div className="flex items-start space-x-3">
<Shield className="mt-0.5 h-5 w-5 text-muted-foreground" />
<div className="space-y-1">
<h2 className="text-xl font-medium">
- SAML Single Sign-On (SSO)
+ SAML SSO &amp; SCIM Directory Sync
</h2>
<p className="text-sm text-muted-foreground">
- Allow team members to sign in using your organization&apos;s
- Identity Provider (IdP) such as Microsoft Entra ID, Okta, or
- Google Workspace.
+ Enterprise security features including SAML Single Sign-On and
+ SCIM directory sync are available as an add-on on the
+ Datarooms Premium plan.
</p>
+ {!isPlanEligible && (
+ <p className="mt-2 text-sm text-muted-foreground">
+ <a
+ href="/settings/billing"
+ className="font-medium underline"
+ >
+ Upgrade to Datarooms Premium
+ </a>{" "}
+ to add SSO for your team.
+ </p>
+ )}
+ {isPlanEligible && !isSSOFeatureEnabled && (
+ <p className="mt-2 text-sm text-muted-foreground">
+ SSO is not yet enabled for your team. Please contact support
+ to enable it.
+ </p>
+ )}
</div>
</div>
+ </div>
+ ) : (
+ <>
+ {/* SAML SSO Section */}
+ <div className="rounded-lg border border-muted p-6 sm:p-10">
+ <div className="space-y-6">
+ <div className="flex items-start space-x-3">
+ <Shield className="mt-0.5 h-5 w-5 text-muted-foreground" />
+ <div className="space-y-1">
+ <h2 className="text-xl font-medium">
+ SAML Single Sign-On (SSO)
+ </h2>
+ <p className="text-sm text-muted-foreground">
+ Allow team members to sign in using your
+ organization&apos;s Identity Provider (IdP) such as
+ Microsoft Entra ID, Okta, or Google Workspace.
+ </p>
+ </div>
+ </div>
+
+ {teamId ? (
+ <SAMLConfigModal teamId={teamId} />
+ ) : (
+ <div className="text-sm text-muted-foreground">
+ Select a team to manage SAML SSO settings.
+ </div>
+ )}
- {loadingSaml ? (
- <div className="flex items-center justify-center py-8">
- <div className="text-sm text-muted-foreground">
- Loading SAML configuration...
+ {/* SSO Enforcement Toggle */}
+ {teamId && <SSOEnforcementToggle teamId={teamId} />}
+
+ <div className="flex items-start space-x-2 rounded-md border bg-muted/30 p-3">
+ <Info className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="text-xs text-muted-foreground">
+ <p className="font-medium">
+ Setting up SAML SSO with Microsoft Entra ID:
+ </p>
+ <ol className="mt-1 list-inside list-decimal space-y-1">
+ <li>Create an Enterprise Application in Azure Portal</li>
+ <li>
+ Configure Single Sign-On &rarr; SAML with the Entity ID
+ and ACS URL shown above
+ </li>
+ <li>
+ Copy the App Federation Metadata URL from SAML
+ Certificates
+ </li>
+ <li>Paste it in the configuration dialog above</li>
+ <li>Assign users and groups to the application</li>
+ </ol>
+ </div>
</div>
</div>
- ) : teamId ? (
- <SAMLConfigModal
- teamId={teamId}
- connections={samlConnections}
- onUpdate={fetchSamlConnections}
- />
- ) : (
- <div className="text-sm text-muted-foreground">
- Select a team to manage SAML SSO settings.
- </div>
- )}
-
- {/* Help text */}
- <div className="flex items-start space-x-2 rounded-md border bg-muted/30 p-3">
- <Info className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
- <div className="text-xs text-muted-foreground">
- <p className="font-medium">
- Setting up SAML SSO with Microsoft Entra ID:
- </p>
- <ol className="mt-1 list-inside list-decimal space-y-1">
- <li>
- Create an Enterprise Application in Azure Portal
- </li>
- <li>
- Configure Single Sign-On → SAML with the Entity ID and ACS
- URL shown above
- </li>
- <li>
- Copy the App Federation Metadata URL from SAML Certificates
- </li>
- <li>
- Paste it in the configuration dialog above
- </li>
- <li>
- Assign users and groups to the application
- </li>
- </ol>
- </div>
</div>
- </div>
- </div>
- {/* Directory Sync Section */}
- <div className="rounded-lg border border-muted p-6 sm:p-10">
- <div className="space-y-6">
- <div className="flex items-start space-x-3">
- <FolderSync className="mt-0.5 h-5 w-5 text-muted-foreground" />
- <div className="space-y-1">
- <h2 className="text-xl font-medium">
- SCIM Directory Sync
- </h2>
- <p className="text-sm text-muted-foreground">
- Automatically provision and deprovision team members from your
- Identity Provider. When users are added or removed in your
- IdP, they&apos;ll be automatically synced to this team.
- </p>
- </div>
- </div>
+ {/* Directory Sync Section */}
+ <div className="rounded-lg border border-muted p-6 sm:p-10">
+ <div className="space-y-6">
+ <div className="flex items-start space-x-3">
+ <FolderSync className="mt-0.5 h-5 w-5 text-muted-foreground" />
+ <div className="space-y-1">
+ <h2 className="text-xl font-medium">SCIM Directory Sync</h2>
+ <p className="text-sm text-muted-foreground">
+ Automatically provision and deprovision team members from
+ your Identity Provider. When users are added or removed in
+ your IdP, they&apos;ll be automatically synced to this
+ team.
+ </p>
+ </div>
+ </div>
+
+ {teamId ? (
+ <DirectorySyncConfigModal teamId={teamId} />
+ ) : (
+ <div className="text-sm text-muted-foreground">
+ Select a team to manage Directory Sync settings.
+ </div>
+ )}
- {loadingScim ? (
- <div className="flex items-center justify-center py-8">
- <div className="text-sm text-muted-foreground">
- Loading directory sync configuration...
+ <div className="flex items-start space-x-2 rounded-md border bg-muted/30 p-3">
+ <Info className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="text-xs text-muted-foreground">
+ <p className="font-medium">
+ Setting up SCIM with Microsoft Entra ID:
+ </p>
+ <ol className="mt-1 list-inside list-decimal space-y-1">
+ <li>
+ Create a directory sync connection above to get
+ credentials
+ </li>
+ <li>
+ In Azure Portal &rarr; Enterprise Application &rarr;
+ Provisioning
+ </li>
+ <li>Set Provisioning Mode to &quot;Automatic&quot;</li>
+ <li>
+ Paste the SCIM Base URL as Tenant URL and Bearer Token
+ as Secret Token
+ </li>
+ <li>
+ Click &quot;Test Connection&quot; to verify, then Save
+ </li>
+ <li>
+ Turn provisioning Status to &quot;On&quot; and assign
+ users
+ </li>
+ </ol>
+ <p className="mt-2 italic">
+ Note: Azure SCIM provisioning can take 20-40 minutes for
+ the initial sync cycle.
+ </p>
+ </div>
</div>
</div>
- ) : teamId ? (
- <DirectorySyncConfigModal
- teamId={teamId}
- directories={directories}
- onUpdate={fetchDirectories}
- />
- ) : (
- <div className="text-sm text-muted-foreground">
- Select a team to manage Directory Sync settings.
- </div>
- )}
-
- {/* Help text */}
- <div className="flex items-start space-x-2 rounded-md border bg-muted/30 p-3">
- <Info className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
- <div className="text-xs text-muted-foreground">
- <p className="font-medium">
- Setting up SCIM with Microsoft Entra ID:
- </p>
- <ol className="mt-1 list-inside list-decimal space-y-1">
- <li>
- Create a directory sync connection above to get credentials
- </li>
- <li>
- In Azure Portal → Enterprise Application → Provisioning
- </li>
- <li>
- Set Provisioning Mode to &quot;Automatic&quot;
- </li>
- <li>
- Paste the SCIM Base URL as Tenant URL and Bearer Token as
- Secret Token
- </li>
- <li>
- Click &quot;Test Connection&quot; to verify, then Save
- </li>
- <li>
- Turn provisioning Status to &quot;On&quot; and assign users
- </li>
- </ol>
- <p className="mt-2 italic">
- Note: Azure SCIM provisioning can take 20-40 minutes for the
- initial sync cycle.
- </p>
- </div>
</div>
- </div>
- </div>
+ </>
+ )}
</main>
</AppLayout>
);
diff --git a/prisma/migrations/20260210000000_add_saml_scim_to_team/migration.sql b/prisma/migrations/20260210000000_add_saml_scim_to_team/migration.sql
index 124561c6..01dd3539 100644
--- a/prisma/migrations/20260210000000_add_saml_scim_to_team/migration.sql
+++ b/prisma/migrations/20260210000000_add_saml_scim_to_team/migration.sql
@@ -1,10 +1,14 @@
--- AlterTable: Add SAML/SCIM fields to Team
-ALTER TABLE "Team" ADD COLUMN "samlEnabled" BOOLEAN NOT NULL DEFAULT false;
-ALTER TABLE "Team" ADD COLUMN "samlProvider" TEXT;
-ALTER TABLE "Team" ADD COLUMN "samlConnectionId" TEXT;
-ALTER TABLE "Team" ADD COLUMN "scimEnabled" BOOLEAN NOT NULL DEFAULT false;
-ALTER TABLE "Team" ADD COLUMN "scimProvider" TEXT;
-ALTER TABLE "Team" ADD COLUMN "scimDirectoryId" TEXT;
+-- AlterTable: Add slug and SSO fields to Team
+ALTER TABLE "Team" ADD COLUMN "slug" TEXT;
+ALTER TABLE "Team" ADD COLUMN "ssoEnabled" BOOLEAN NOT NULL DEFAULT false;
+ALTER TABLE "Team" ADD COLUMN "ssoEmailDomain" TEXT;
+ALTER TABLE "Team" ADD COLUMN "ssoEnforcedAt" TIMESTAMP(3);
+
+-- CreateIndex: unique slug for SSO login
+CREATE UNIQUE INDEX "Team_slug_key" ON "Team"("slug");
+
+-- CreateIndex: unique email domain for SSO
+CREATE UNIQUE INDEX "Team_ssoEmailDomain_key" ON "Team"("ssoEmailDomain");
-- CreateTable: Jackson SAML/SCIM internal tables
CREATE TABLE "jackson_index" (
diff --git a/prisma/schema/team.prisma b/prisma/schema/team.prisma
index dbf69837..94b5a9dd 100644
--- a/prisma/schema/team.prisma
+++ b/prisma/schema/team.prisma
@@ -1,6 +1,7 @@
model Team {
id String @id @default(cuid())
name String
+ slug String? @unique // Optional human-readable identifier (e.g. "acme"), used for SSO login
users UserTeam[]
documents Document[]
folders Folder[]
@@ -26,8 +27,8 @@ model Team {
installedIntegrations InstalledIntegration[]
- links Link[]
- views View[]
+ links Link[]
+ views View[]
workflows Workflow[]
plan String @default("free")
@@ -43,19 +44,14 @@ model Team {
limits Json? // Plan limits // {datarooms: 1, users: 1, domains: 1, customDomainOnPro: boolean, customDomainInDataroom: boolean}
// team settings
- enableExcelAdvancedMode Boolean @default(false) // Enable Excel advanced mode for all documents in the team
+ enableExcelAdvancedMode Boolean @default(false) // Enable Excel advanced mode for all documents in the team
replicateDataroomFolders Boolean @default(true) // Replicate dataroom folder structure in "All Documents"
- timezone String @default("Etc/UTC") // Team-wide timezone for analytics display (IANA timezone identifier)
+ timezone String @default("Etc/UTC") // Team-wide timezone for analytics display (IANA timezone identifier)
- // SAML SSO
- samlEnabled Boolean @default(false) // Whether SAML SSO is enabled
- samlProvider String? // IdP provider: "azure", "okta", "google", "custom"
- samlConnectionId String? // Jackson SAML connection client_id
-
- // SCIM Directory Sync
- scimEnabled Boolean @default(false) // Whether SCIM directory sync is enabled
- scimProvider String? // Directory provider: "azure-scim-v2", "okta-scim-v2", etc.
- scimDirectoryId String? // Jackson directory sync ID
+ // SSO (SAML/SCIM via BoxyHQ Jackson)
+ ssoEnabled Boolean @default(false) // Feature flag: team has access to SSO
+ ssoEmailDomain String? @unique // Email domain enforced for SSO (e.g. "acme.com")
+ ssoEnforcedAt DateTime? // When set, all users with this domain MUST use SSO
// AI agents
agentsEnabled Boolean @default(false) // Enable AI agents for the team