Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add SAML/SCIM admin UI, security settings page, and SSO login
Cursor Agentaa42266e3f98
diff --git a/app/(auth)/auth/saml/page-client.tsx b/app/(auth)/auth/saml/page-client.tsxnew file mode 100644index 00000000..c6a3f600--- /dev/null+++ b/app/(auth)/auth/saml/page-client.tsx@@ -0,0 +1,65 @@+"use client";++import { useRouter, useSearchParams } from "next/navigation";++import { useEffect, useState } from "react";++import { signIn } from "next-auth/react";++export default function SAMLCallbackClient() {+ const searchParams = useSearchParams();+ const router = useRouter();+ const [status, setStatus] = useState<"loading" | "error">("loading");+ const [errorMessage, setErrorMessage] = useState<string>("");++ useEffect(() => {+ const code = searchParams.get("code");+ if (code) {+ // Use NextAuth's signIn with the saml-idp credentials provider+ signIn("saml-idp", {+ code,+ redirect: false,+ }).then((result) => {+ if (result?.ok) {+ router.push("/dashboard");+ } else {+ setStatus("error");+ setErrorMessage(+ result?.error || "SSO authentication failed. Please try again.",+ );+ }+ });+ } else {+ setStatus("error");+ setErrorMessage("No authorization code received from your identity provider.");+ }+ }, [searchParams, router]);++ if (status === "error") {+ return (+ <div className="flex min-h-screen items-center justify-center">+ <div className="mx-auto max-w-md text-center">+ <h2 className="text-xl font-semibold text-gray-900">+ SSO Login Failed+ </h2>+ <p className="mt-2 text-sm text-gray-600">{errorMessage}</p>+ <button+ onClick={() => router.push("/login")}+ className="mt-4 rounded-md bg-gray-900 px-4 py-2 text-sm text-white hover:bg-gray-800"+ >+ Return to Login+ </button>+ </div>+ </div>+ );+ }++ return (+ <div className="flex min-h-screen items-center justify-center">+ <div className="mx-auto max-w-md text-center">+ <div className="mx-auto mb-4 h-8 w-8 animate-spin rounded-full border-2 border-gray-300 border-t-gray-900" />+ <p className="text-sm text-gray-600">Completing SSO login...</p>+ </div>+ </div>+ );+}diff --git a/app/(auth)/auth/saml/page.tsx b/app/(auth)/auth/saml/page.tsxnew file mode 100644index 00000000..1842badc--- /dev/null+++ b/app/(auth)/auth/saml/page.tsx@@ -0,0 +1,12 @@+import { Metadata } from "next";++import SAMLCallbackClient from "./page-client";++export const metadata: Metadata = {+ title: "SSO Login | Papermark",+ description: "Completing SSO login",+};++export default function SAMLCallbackPage() {+ return <SAMLCallbackClient />;+}diff --git a/app/(auth)/login/page-client.tsx b/app/(auth)/login/page-client.tsxindex 15ca6263..6b8b8e93 100644--- a/app/(auth)/login/page-client.tsx+++ b/app/(auth)/login/page-client.tsx@@ -12,6 +12,7 @@ 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,6 +213,21 @@ export default function Login() {</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><p className="mt-10 w-full max-w-md px-4 text-xs text-muted-foreground sm:px-12">By clicking continue, you acknowledge that you have read and agreeto Papermark's{" "}diff --git a/components/auth/sso-login.tsx b/components/auth/sso-login.tsxnew file mode 100644index 00000000..32b51323--- /dev/null+++ b/components/auth/sso-login.tsx@@ -0,0 +1,100 @@+"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.tsxnew file mode 100644index 00000000..d18f5e08--- /dev/null+++ b/components/settings/security/directory-sync-config-modal.tsx@@ -0,0 +1,381 @@+"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'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'll+ receive a SCIM 2.0 Base URL and Bearer Token. Add these to+ your Identity Provider'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/security/saml-config-modal.tsx b/components/settings/security/saml-config-modal.tsxnew file mode 100644index 00000000..7d76e28d--- /dev/null+++ b/components/settings/security/saml-config-modal.tsx@@ -0,0 +1,381 @@+"use client";++import { useState } from "react";++import { Copy, Shield, 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 SAMLConnection {+ clientID: string;+ clientSecret: string;+ name?: string;+ description?: string;+ idpMetadata?: {+ provider?: string;+ };+}++interface SAMLConfigModalProps {+ teamId: string;+ connections: SAMLConnection[];+ onUpdate: () => void;+}++export function SAMLConfigModal({+ teamId,+ connections,+ onUpdate,+}: SAMLConfigModalProps) {+ const [open, setOpen] = useState(false);+ const [loading, setLoading] = useState(false);+ const [provider, setProvider] = useState("azure");+ 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 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;++ async function handleSubmit(e: React.FormEvent) {+ e.preventDefault();+ setLoading(true);++ try {+ const body: Record<string, string> = {+ name: providerName,+ description: `SAML SSO via ${providerName}`,+ };++ if (inputMode === "url") {+ if (!metadataUrl) {+ toast.error("Please enter a metadata URL");+ setLoading(false);+ return;+ }+ body.metadataUrl = metadataUrl;+ } else {+ if (!rawMetadata) {+ toast.error("Please enter the XML metadata");+ setLoading(false);+ return;+ }+ body.rawMetadata = rawMetadata;+ }++ const res = await fetch(`/api/teams/${teamId}/saml`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });++ if (!res.ok) {+ const data = await res.json();+ throw new Error(data.error || "Failed to create SAML connection");+ }++ toast.success("SAML SSO configured successfully!");+ setOpen(false);+ setMetadataUrl("");+ setRawMetadata("");+ onUpdate();+ } catch (error: any) {+ toast.error(error.message || "Failed to configure SAML SSO");+ } finally {+ setLoading(false);+ }+ }++ async function handleDelete(connection: SAMLConnection) {+ if (+ !confirm(+ "Are you sure you want to remove this SAML connection? Users will no longer be able to sign in via SSO.",+ )+ ) {+ return;+ }++ try {+ const res = await fetch(`/api/teams/${teamId}/saml`, {+ method: "DELETE",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ clientID: connection.clientID,+ clientSecret: connection.clientSecret,+ }),+ });++ if (!res.ok) {+ const data = await res.json();+ throw new Error(data.error || "Failed to delete SAML connection");+ }++ toast.success("SAML connection removed");+ onUpdate();+ } catch (error: any) {+ toast.error(error.message || "Failed to remove SAML connection");+ }+ }++ function copyToClipboard(text: string, label: string) {+ navigator.clipboard.writeText(text);+ toast.success(`${label} copied to clipboard`);+ }++ return (+ <div className="space-y-4">+ {/* Existing connections */}+ {connections.length > 0 && (+ <div className="space-y-3">+ {connections.map((conn) => (+ <div+ key={conn.clientID}+ className="flex items-center justify-between rounded-lg border p-4"+ >+ <div className="space-y-1">+ <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"}+ </span>+ </div>+ <p className="text-xs text-muted-foreground">+ Client ID: {conn.clientID}+ </p>+ </div>+ <Button+ variant="ghost"+ size="sm"+ className="text-destructive hover:text-destructive"+ onClick={() => handleDelete(conn)}+ >+ <Trash2 className="h-4 w-4" />+ </Button>+ </div>+ ))}+ </div>+ )}++ {/* IdP Configuration Info */}+ {connections.length > 0 && (+ <div className="rounded-lg border bg-muted/50 p-4">+ <h4 className="mb-2 text-sm font-medium">+ Identity Provider Configuration+ </h4>+ <p className="mb-3 text-xs text-muted-foreground">+ Use these values when configuring your Identity Provider:+ </p>+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <div>+ <Label className="text-xs font-medium">+ Entity ID (Identifier)+ </Label>+ <p className="text-xs text-muted-foreground">{entityId}</p>+ </div>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => copyToClipboard(entityId, "Entity ID")}+ >+ <Copy className="h-3 w-3" />+ </Button>+ </div>+ <div className="flex items-center justify-between">+ <div>+ <Label className="text-xs font-medium">+ Reply URL (ACS URL)+ </Label>+ <p className="text-xs text-muted-foreground">{acsUrl}</p>+ </div>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => copyToClipboard(acsUrl, "ACS URL")}+ >+ <Copy className="h-3 w-3" />+ </Button>+ </div>+ </div>+ </div>+ )}++ {/* Add new connection dialog */}+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild>+ <Button className="w-full" variant={connections.length > 0 ? "outline" : "default"}>+ <Shield className="mr-2 h-4 w-4" />+ {connections.length > 0+ ? "Add Another Connection"+ : "Configure SAML SSO"}+ </Button>+ </DialogTrigger>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>Configure SAML Single Sign-On</DialogTitle>+ <DialogDescription>+ Connect your Identity Provider to enable SSO for your team.+ </DialogDescription>+ </DialogHeader>++ <form onSubmit={handleSubmit} className="space-y-4">+ {/* Step 1: Show ACS URL and Entity ID */}+ <div className="rounded-lg border bg-muted/50 p-3">+ <p className="mb-2 text-xs font-medium text-muted-foreground">+ Step 1: Add these to your IdP's SAML configuration+ </p>+ <div className="space-y-2">+ <div className="flex items-center justify-between text-xs">+ <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}+ </code>+ <button+ type="button"+ onClick={() => copyToClipboard(entityId, "Entity ID")}+ className="text-muted-foreground hover:text-foreground"+ >+ <Copy className="h-3 w-3" />+ </button>+ </div>+ </div>+ <div className="flex items-center justify-between text-xs">+ <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}+ </code>+ <button+ type="button"+ onClick={() => copyToClipboard(acsUrl, "ACS URL")}+ className="text-muted-foreground hover:text-foreground"+ >+ <Copy className="h-3 w-3" />+ </button>+ </div>+ </div>+ </div>+ </div>++ {/* Step 2: Provider selection */}+ <div className="space-y-2">+ <Label>SAML 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>++ {/* 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")}+ >+ XML+ </button>+ </div>+ </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+ type="button"+ variant="outline"+ onClick={() => setOpen(false)}+ >+ Cancel+ </Button>+ <Button type="submit" loading={loading} disabled={loading}>+ Save Configuration+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/components/settings/settings-header.tsx b/components/settings/settings-header.tsxindex 4b1052b5..11d0a4be 100644--- a/components/settings/settings-header.tsx+++ b/components/settings/settings-header.tsx@@ -78,6 +78,11 @@ export function SettingsHeader() {segment: "incoming-webhooks",disabled: !features?.incomingWebhooks,},+ {+ label: "Security",+ href: `/settings/security`,+ segment: "security",+ },{label: "Billing",href: `/settings/billing`,diff --git a/components/sidebar/app-sidebar.tsx b/components/sidebar/app-sidebar.tsxindex bd9e41d7..5dfbc323 100644--- a/components/sidebar/app-sidebar.tsx+++ b/components/sidebar/app-sidebar.tsx@@ -201,6 +201,11 @@ 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",diff --git a/pages/settings/security.tsx b/pages/settings/security.tsxnew file mode 100644index 00000000..4143cc3f--- /dev/null+++ b/pages/settings/security.tsx@@ -0,0 +1,201 @@+import { useCallback, useEffect, useState } from "react";++import { useTeam } from "@/context/team-context";+import { Shield, FolderSync, Info } from "lucide-react";++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";++export default function SecuritySettings() {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ 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);+ }+ }, [teamId]);++ useEffect(() => {+ fetchSamlConnections();+ fetchDirectories();+ }, [fetchSamlConnections, fetchDirectories]);++ 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">+ <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's+ Identity Provider (IdP) such as Microsoft Entra ID, Okta, or+ Google Workspace.+ </p>+ </div>+ </div>++ {loadingSaml ? (+ <div className="flex items-center justify-center py-8">+ <div className="text-sm text-muted-foreground">+ Loading SAML configuration...+ </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'll be automatically synced to this team.+ </p>+ </div>+ </div>++ {loadingScim ? (+ <div className="flex items-center justify-center py-8">+ <div className="text-sm text-muted-foreground">+ Loading directory sync configuration...+ </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 "Automatic"+ </li>+ <li>+ Paste the SCIM Base URL as Tenant URL and Bearer Token as+ Secret Token+ </li>+ <li>+ Click "Test Connection" to verify, then Save+ </li>+ <li>+ Turn provisioning Status to "On" 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.sqlnew file mode 100644index 00000000..c01a2cab--- /dev/null+++ b/prisma/migrations/20260210000000_add_saml_scim_to_team/migration.sql@@ -0,0 +1,7 @@+-- AlterTable+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;diff --git a/prisma/schema/team.prisma b/prisma/schema/team.prismaindex 1f59f670..dbf69837 100644--- a/prisma/schema/team.prisma+++ b/prisma/schema/team.prisma@@ -47,6 +47,16 @@ model 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)+ // 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+// AI agentsagentsEnabled Boolean @default(false) // Enable AI agents for the teamvectorStoreId String? // OpenAI vector store ID for team-level document search