Skip to content

feat(EE): LDAP integration - #1515

Merged
Philipinho merged 11 commits into
mainfrom
feat/ldap
Sep 2, 2025
Merged

Philipinho merged 11 commits into
mainfrom
feat/ldap

Conversation

@Philipinho

@Philipinho Philipinho commented Sep 1, 2025 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • LDAP / Active Directory SSO: create/configure providers in the admin UI and sign in via an in‑app LDAP modal (preserves workspace context); post-login routes handle MFA challenge/setup.
    • Admin: full LDAP provider editing UI with advanced TLS and mapping options.
  • Style

    • SSO buttons show provider-specific icons (including LDAP); improved input autofocus/data-autofocus across MFA screens.
  • Bug Fixes

    • MFA backup codes and disable/regenerate flows only prompt for password when required; language selector guarded when user absent.

@coderabbitai

coderabbitai Bot commented Sep 1, 2025 •

Copy link
Copy Markdown

Walkthrough

Adds LDAP SSO end-to-end: client UI (LDAP login modal, SSO list changes, LDAP provider form), client LDAP auth service and types, server DB migration/types/repos, server ldap dependency, and MFA UI/logic adjustments for password gating and autofocus attributes.

Changes

Cohort / File(s) Summary
LDAP client auth (modal + SSO entry)
apps/client/src/ee/components/ldap-login-modal.tsx, apps/client/src/ee/components/sso-login.tsx
New LdapLoginModal with zod validation and ldapLogin call; SSO login opens modal for LDAP providers instead of redirecting; icon mapping and modal state added.
Client LDAP service
apps/client/src/ee/security/services/ldap-auth-service.ts
New ldapLogin service that POSTs to /sso/ldap/{providerId}/login and returns ILoginResponse.
SSO provider management (LDAP)
apps/client/src/ee/security/components/create-sso-provider.tsx, apps/client/src/ee/security/components/sso-ldap-form.tsx, apps/client/src/ee/security/components/sso-provider-modal.tsx
Add LDAP creation menu item, new SsoLDAPForm for editing LDAP config, and render LDAP form in provider modal.
Security constants/types (client)
apps/client/src/ee/security/contants.ts, apps/client/src/ee/security/types/security.types.ts
Add SSO_PROVIDER.LDAP and add LDAP configuration fields to IAuthProvider.
MFA autofocus tweaks
apps/client/src/ee/mfa/components/mfa-backup-code-input.tsx, apps/client/src/ee/mfa/components/mfa-challenge.tsx, apps/client/src/ee/mfa/components/mfa-setup-modal.tsx
Add data-autofocus attributes to inputs/PinInput; no behavior changes.
MFA conditional password requirement
apps/client/src/ee/mfa/components/mfa-backup-codes-modal.tsx, apps/client/src/ee/mfa/components/mfa-disable-modal.tsx
Use useCurrentUser to compute requiresPassword (!hasGeneratedPassword), dynamic zod schema, conditionally render PasswordInput, send confirmPassword only when required.
User state/types (client)
apps/client/src/features/user/atoms/current-user-atom.ts, apps/client/src/features/user/types/user.types.ts
Replace optics-derived atoms with plain atom((get)=>...) that support reads and writes; add optional hasGeneratedPassword?: boolean to IUser.
Server auth changes
apps/server/src/core/auth/services/auth.service.ts
Set hasGeneratedPassword: false on user when changing or resetting password.
DB migration + types + repo (server)
apps/server/src/database/migrations/20250831T202306-ldap-auth.ts, apps/server/src/database/types/db.d.ts, apps/server/src/database/repos/user/user.repo.ts
Migration adds has_generated_password to users, multiple LDAP columns to auth_providers, uses text-workaround for enum; server DB types updated for LDAP fields and type: string; repo baseFields includes hasGeneratedPassword.
Server dependencies and submodule
apps/server/package.json, apps/server/src/ee
Add ldapts dependency and update EE submodule pointer.
UI toggle label fixes (OIDC / SAML)
apps/client/src/ee/security/components/sso-oidc-form.tsx, apps/client/src/ee/security/components/sso-saml-form.tsx
Swapped labels/bindings for the two Group toggles so labels match groupSync vs allowSignup.
Form resolver import adjustments
apps/client/src/ee/security/components/allowed-domains.tsx, apps/client/src/features/workspace/components/settings/components/workspace-name-form.tsx
Move zodResolver import from @mantine/form to external mantine-form-zod-resolver; useForm remains from @mantine/form.
MFA service/types optional confirmPassword
apps/client/src/ee/mfa/services/mfa-service.ts, apps/client/src/ee/mfa/types/mfa.types.ts
regenerateBackupCodes and MfaDisableRequest.confirmPassword changed to accept optional confirmPassword?: string.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI as Client UI (SsoLogin)
  participant Modal as LdapLoginModal
  participant API as Client LDAP Service
  participant Srv as Server /sso/ldap/:id/login

  User->>UI: Click LDAP provider
  UI->>Modal: Open with provider + workspaceId
  User->>Modal: Submit username/password
  Modal->>API: ldapLogin({username,password,providerId,workspaceId})
  API->>Srv: POST /sso/ldap/:id/login {username,password}
  Srv-->>API: ILoginResponse { userHasMfa | requiresMfaSetup | success }
  API-->>Modal: ILoginResponse
  alt userHasMfa
    Modal->>UI: Close modal
    UI->>User: Navigate to MFA challenge
  else requiresMfaSetup
    Modal->>UI: Close modal
    UI->>User: Navigate to MFA setup
  else success
    Modal->>UI: Close modal
    UI->>User: Navigate HOME
  end
  opt error
    Srv-->>API: Error
    API-->>Modal: Error
    Modal->>User: Show error notification
  end
Loading
sequenceDiagram
  autonumber
  participant Client as MFA Modal
  participant Store as CurrentUser atom
  participant Server as API Mutation

  Client->>Store: Read user.hasGeneratedPassword
  Store-->>Client: hasGeneratedPassword (bool|undefined)
  alt requiresPassword = !hasGeneratedPassword
    Client->>Client: Render PasswordInput (autoFocus + data-autofocus)
    Client->>Server: mutate({ confirmPassword })
  else
    Client->>Client: Hide PasswordInput
    Client->>Server: mutate({})
  end
  Server-->>Client: Success / Error
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

EE

Poem

I hopped through LDAP tunnels bright,
Modal doors swung open light.
MFA checks and password chores,
New fields, migrations, code galore.
Carrots, schemas, ship in sight — hop hop! 🥕🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/ldap

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Comment on lines +28 to +32
window.location.href = buildSsoLoginUrl({
providerId: provider.id,
type: provider.type,
workspaceId: data.id,
});

Check failure

Code scanning / CodeQL

Client-side cross-site scripting

Cross-site scripting vulnerability due to [user-provided value](1).

Copilot Autofix

AI over 1 year ago

To fix this issue, we should ensure that the configuration values used to construct redirect URLs are strictly validated and restricted. Allow only safe, trusted URLs for redirection, and never permit arbitrary values controlled through the environment or client config to influence the redirect destination.

The specific fix is to validate the APP_URL (and any equivalent config) before using it to construct a redirect. The safest is to only allow same-origin redirects, or, if cross-origin is required, to explicitly validate the URL against a whitelist of trusted domains. In the context of this codebase, we can fix this by:

  1. Ensuring that URL config values (such as APP_URL, COLLAB_URL, etc.) are restricted before their use:
    • Parse them as URLs, and validate that their protocol is http(s), and that their hostname matches an expected pattern (e.g., equals window.location.hostname, or a whitelist).
    • If validation fails, fall back to using a known safe value, or block the redirect.
  2. Implement a utility function (e.g., sanitizeAppUrl) in config.ts to validate URLs retrieved from config/environment, and invoke this function in any exported function that currently uses getConfigValue to retrieve a potentially tainted URL.

Files to edit:
Edits are required in apps/client/src/lib/config.ts (for sanitization of config URL access) and potentially in apps/client/src/ee/security/sso.utils.ts if there are direct usages. The TSX component (sso-login.tsx) does not require changes if the underlying utility is sanitized.

Methods/definitions:

  • Add a sanitizeAppUrl(url: string): string method.
  • Use this method for every occasion a config-derived URL (like APP_URL) is accessed, e.g., in getServerAppUrl().

Suggested changeset 2
apps/client/src/lib/config.ts
Outside changed files

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/apps/client/src/lib/config.ts b/apps/client/src/lib/config.ts
--- a/apps/client/src/lib/config.ts
+++ b/apps/client/src/lib/config.ts
@@ -16,7 +16,8 @@
 }
 
 export function getServerAppUrl(): string {
-  return getConfigValue("APP_URL");
+  // Only allow URLs with http(s) protocol and (optionally) verify host match or whitelist.
+  return sanitizeAppUrl(getConfigValue("APP_URL"));
 }
 
 export function getBackendUrl(): string {
EOF
@@ -16,7 +16,8 @@
}

export function getServerAppUrl(): string {
return getConfigValue("APP_URL");
// Only allow URLs with http(s) protocol and (optionally) verify host match or whitelist.
return sanitizeAppUrl(getConfigValue("APP_URL"));
}

export function getBackendUrl(): string {
apps/client/src/ee/security/sso.utils.ts
Outside changed files

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/apps/client/src/ee/security/sso.utils.ts b/apps/client/src/ee/security/sso.utils.ts
--- a/apps/client/src/ee/security/sso.utils.ts
+++ b/apps/client/src/ee/security/sso.utils.ts
@@ -1,5 +1,6 @@
 import { SSO_PROVIDER } from "@/ee/security/contants.ts";
 import { getAppUrl, getServerAppUrl } from "@/lib/config.ts";
+import { sanitizeAppUrl } from "@/lib/config.ts";
 
 export function buildCallbackUrl(opts: {
   providerId: string;
@@ -25,7 +26,7 @@
   if (type === SSO_PROVIDER.GOOGLE) {
     return `${getServerAppUrl()}/api/sso/${type}/login?workspaceId=${workspaceId}`;
   }
-  return `${domain}/api/sso/${type}/${providerId}/login`;
+  return `${sanitizeAppUrl(domain)}/api/sso/${type}/${providerId}/login`;
 }
 
 export function getGoogleSignupUrl(): string {
EOF
@@ -1,5 +1,6 @@
import { SSO_PROVIDER } from "@/ee/security/contants.ts";
import { getAppUrl, getServerAppUrl } from "@/lib/config.ts";
import { sanitizeAppUrl } from "@/lib/config.ts";

export function buildCallbackUrl(opts: {
providerId: string;
@@ -25,7 +26,7 @@
if (type === SSO_PROVIDER.GOOGLE) {
return `${getServerAppUrl()}/api/sso/${type}/login?workspaceId=${workspaceId}`;
}
return `${domain}/api/sso/${type}/${providerId}/login`;
return `${sanitizeAppUrl(domain)}/api/sso/${type}/${providerId}/login`;
}

export function getGoogleSignupUrl(): string {
Copilot is powered by AI and may make mistakes. Always verify output.
Comment on lines +28 to +32
window.location.href = buildSsoLoginUrl({
providerId: provider.id,
type: provider.type,
workspaceId: data.id,
});

Check warning

Code scanning / CodeQL

Client-side URL redirect

Untrusted URL redirection depends on a [user-provided value](1).

Copilot Autofix

AI over 1 year ago

To fix this problem, the application should not perform client-side redirects to domains or hosts that are not trusted, even if they are specified in environmental variables or config. Validation should be enforced: when constructing a redirect URL, the app should ensure the domain/host portion is in a set of allowed (hardcoded or strictly verified) values, and not allow arbitrary values (even from config/environment). The fix is to ensure, within buildSsoLoginUrl, that the used domain (from getAppUrl() / getServerAppUrl()) is safe and matches a set of allowed hosts (ideally, making sure it doesn't allow redirection to external domains).

Steps:

  • In apps/client/src/ee/security/sso.utils.ts, validate the value returned by getServerAppUrl() and getAppUrl().
  • Implement a host/domain allow-list: Compare the host from the computed URL to the current location's host, or a set of trusted hosts.
  • Only generate and use SSO login URLs if the domain is trusted; otherwise, prevent the redirect (optionally, log/report an error).
  • Optionally, define a helper function to validate domains, and use this in SSO URL construction.

Only touch code visible in the snippets.


Suggested changeset 1
apps/client/src/ee/security/sso.utils.ts
Outside changed files

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/apps/client/src/ee/security/sso.utils.ts b/apps/client/src/ee/security/sso.utils.ts
--- a/apps/client/src/ee/security/sso.utils.ts
+++ b/apps/client/src/ee/security/sso.utils.ts
@@ -1,6 +1,17 @@
 import { SSO_PROVIDER } from "@/ee/security/contants.ts";
 import { getAppUrl, getServerAppUrl } from "@/lib/config.ts";
 
+// Allow-list for trusted hosts. Only allow current host or hardcoded trust.
+function isTrustedHost(urlStr: string): boolean {
+  try {
+    const url = new URL(urlStr, window.location.origin);
+    // Allow only if matches current host (strictest, can be extended if needed)
+    return url.host === window.location.host;
+  } catch {
+    return false;
+  }
+}
+
 export function buildCallbackUrl(opts: {
   providerId: string;
   type: SSO_PROVIDER;
@@ -21,11 +32,20 @@
 }): string {
   const { providerId, type, workspaceId } = opts;
   const domain = getAppUrl();
-
   if (type === SSO_PROVIDER.GOOGLE) {
-    return `${getServerAppUrl()}/api/sso/${type}/login?workspaceId=${workspaceId}`;
+    const googleUrl = `${getServerAppUrl()}/api/sso/${type}/login?workspaceId=${workspaceId}`;
+    if (!isTrustedHost(googleUrl)) {
+      console.error("Attempted redirect to untrusted SSO login host:", googleUrl);
+      throw new Error("Untrusted SSO login URL");
+    }
+    return googleUrl;
   }
-  return `${domain}/api/sso/${type}/${providerId}/login`;
+  const loginUrl = `${domain}/api/sso/${type}/${providerId}/login`;
+  if (!isTrustedHost(loginUrl)) {
+    console.error("Attempted redirect to untrusted SSO login host:", loginUrl);
+    throw new Error("Untrusted SSO login URL");
+  }
+  return loginUrl;
 }
 
 export function getGoogleSignupUrl(): string {
EOF
@@ -1,6 +1,17 @@
import { SSO_PROVIDER } from "@/ee/security/contants.ts";
import { getAppUrl, getServerAppUrl } from "@/lib/config.ts";

// Allow-list for trusted hosts. Only allow current host or hardcoded trust.
function isTrustedHost(urlStr: string): boolean {
try {
const url = new URL(urlStr, window.location.origin);
// Allow only if matches current host (strictest, can be extended if needed)
return url.host === window.location.host;
} catch {
return false;
}
}

export function buildCallbackUrl(opts: {
providerId: string;
type: SSO_PROVIDER;
@@ -21,11 +32,20 @@
}): string {
const { providerId, type, workspaceId } = opts;
const domain = getAppUrl();

if (type === SSO_PROVIDER.GOOGLE) {
return `${getServerAppUrl()}/api/sso/${type}/login?workspaceId=${workspaceId}`;
const googleUrl = `${getServerAppUrl()}/api/sso/${type}/login?workspaceId=${workspaceId}`;
if (!isTrustedHost(googleUrl)) {
console.error("Attempted redirect to untrusted SSO login host:", googleUrl);
throw new Error("Untrusted SSO login URL");
}
return googleUrl;
}
return `${domain}/api/sso/${type}/${providerId}/login`;
const loginUrl = `${domain}/api/sso/${type}/${providerId}/login`;
if (!isTrustedHost(loginUrl)) {
console.error("Attempted redirect to untrusted SSO login host:", loginUrl);
throw new Error("Untrusted SSO login URL");
}
return loginUrl;
}

export function getGoogleSignupUrl(): string {
Copilot is powered by AI and may make mistakes. Always verify output.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 15

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
apps/server/src/database/repos/user/user.repo.ts (1)

111-126: Add hasGeneratedPassword flag to new user inserts
In apps/server/src/database/repos/user/user.repo.ts’s insertUser, include hasGeneratedPassword: false in the InsertableUser object to avoid NULL and ensure correct MFA gating.

       lastLoginAt: new Date(),
+      // User supplied a password during sign-up → not generated
+      hasGeneratedPassword: false,

Verified insertUser is only invoked from signup, admin creation, and workspace invitation flows—no SSO/OAuth paths exist. If SSO user creation is added later, explicitly set hasGeneratedPassword: true there.

apps/server/src/core/auth/services/auth.service.ts (2)

186-195: Revoke sessions (or bump tokenVersion) within the passwordReset transaction (apps/server/src/core/auth/services/auth.service.ts:186–195). After deleting the reset tokens in executeTx, invalidate all existing sessions by incrementing the user’s tokenVersion (or explicitly revoking refresh tokens) to ensure the password reset and session revocation occur atomically.


105-113: Revoke existing sessions on password change
apps/server/src/core/auth/services/auth.service.ts (lines 105–113): After updating the password and clearing hasGeneratedPassword, implement logic to invalidate all active sessions or refresh tokens (e.g. bump a tokenVersion or call a revoke routine) so that any previously issued tokens can no longer be used.

🧹 Nitpick comments (25)
apps/client/src/ee/mfa/components/mfa-setup-modal.tsx (1)

233-241: data-autofocus duplication with autoFocus

If data-autofocus is solely for E2E selectors, keep it; otherwise it’s redundant with autoFocus. Consider adding a short comment to clarify its test purpose to avoid future cleanup.

apps/client/src/ee/mfa/components/mfa-challenge.tsx (1)

96-104: Consistent test hook attribute

Same note as setup modal: keeping both autoFocus and data-autofocus is fine if the latter is used by tests. Otherwise, it’s redundant.

apps/client/src/ee/mfa/components/mfa-backup-code-input.tsx (1)

47-49: Prefer data-autofocus over autoFocus to avoid double focus/hydration quirks

Mantine’s FocusTrap honors data-autofocus; keeping both can cause focus flicker and SSR hydration warnings. Rely on data-autofocus only. Optionally, help autofill by adding autoComplete="one-time-code" and disable spellcheck.

-        autoFocus
         data-autofocus
+        autoComplete="one-time-code"
+        spellCheck={false}
apps/client/src/ee/security/services/ldap-auth-service.ts (1)

4-9: workspaceId is collected but never sent

Either include it in the request (if backend expects it) or drop it from the payload/type to avoid drift.

Option A — include as query param:

-  const response = await api.post<ILoginResponse>(
-    `/sso/ldap/${data.providerId}/login`,
+  const response = await api.post<ILoginResponse>(
+    `/sso/ldap/${data.providerId}/login?workspaceId=${encodeURIComponent(data.workspaceId)}`,
     requestData
   );

Option B — remove it entirely:

-interface ILdapLogin {
+interface ILdapLogin {
   username: string;
   password: string;
   providerId: string;
-  workspaceId: string;
 }

(Clean up call sites accordingly.)

apps/client/src/ee/security/components/create-sso-provider.tsx (1)

43-54: DRY up provider creation handlers

handleCreateSAML/OIDC/LDAP duplicate the same mutate/open flow. Consider a single helper to reduce maintenance.

Example:

+  const handleCreate = async (type: SSO_PROVIDER, name: string) => {
+    try {
+      const newProvider = await createSsoProviderMutation.mutateAsync({ type, name });
+      setProvider(newProvider);
+      open();
+    } catch (error) {
+      console.error(`Failed to create ${name} provider`, error);
+    }
+  };

-  const handleCreateLDAP = async () => {
-    try {
-      const newProvider = await createSsoProviderMutation.mutateAsync({
-        type: SSO_PROVIDER.LDAP,
-        name: "LDAP",
-      });
-      setProvider(newProvider);
-      open();
-    } catch (error) {
-      console.error("Failed to create LDAP provider", error);
-    }
-  };
+  const handleCreateLDAP = () => handleCreate(SSO_PROVIDER.LDAP, "LDAP");
+  const handleCreateSAML = () => handleCreate(SSO_PROVIDER.SAML, "SAML");
+  const handleCreateOIDC = () => handleCreate(SSO_PROVIDER.OIDC, "OIDC");
apps/client/src/ee/mfa/components/mfa-backup-codes-modal.tsx (2)

45-52: Localize the validation message

User-facing error should use t(...) for consistency with the rest of the modal.

-        confirmPassword: z.string().min(1, { message: "Password is required" }),
+        confirmPassword: z.string().min(1, { message: t("Password is required") }),

128-137: Prefer data-autofocus; add autoComplete for better UX

Rely on Mantine’s data-autofocus and add autoComplete="current-password"; consider disabling while pending.

                 <PasswordInput
                   label={t("Confirm password")}
                   placeholder={t("Enter your password")}
                   variant="filled"
                   {...form.getInputProps("confirmPassword")}
-                  autoFocus
                   data-autofocus
+                  autoComplete="current-password"
+                  disabled={regenerateMutation.isPending}
                 />
apps/client/src/features/user/atoms/current-user-atom.ts (1)

10-18: Optional: add explicit generics to avoid exported type emit issues

Making types explicit can prevent TS4023-style “cannot be named” errors in emitted d.ts when these atoms are exported.

-import { ICurrentUser } from "@/features/user/types/user.types";
+import { ICurrentUser, IUser, IWorkspace } from "@/features/user/types/user.types";

-export const userAtom = atom((get) => {
+export const userAtom = atom<IUser | null>((get) => {
   const currentUser = get(currentUserAtom);
   return currentUser?.user ?? null;
 });

-export const workspaceAtom = atom((get) => {
+export const workspaceAtom = atom<IWorkspace | null>((get) => {
   const currentUser = get(currentUserAtom);
   return currentUser?.workspace ?? null;
 });
apps/client/src/ee/mfa/components/mfa-disable-modal.tsx (3)

32-41: Avoid requiring a password while current user is still loading; localize validation message.

  • When currentUser is undefined, !currentUser?.user?.hasGeneratedPassword evaluates to true and shows a password field prematurely.
  • The Zod error string isn’t localized.

Apply:

-  const requiresPassword = !currentUser?.user?.hasGeneratedPassword;
+  const requiresPassword = currentUser?.user?.hasGeneratedPassword === false;

-        confirmPassword: z.string().min(1, { message: "Password is required" }),
+        confirmPassword: z.string().min(1, { message: t("Password is required") }),

99-115: Remove duplicate autofocus and set autocomplete for better UX.

autoFocus + data-autofocus is redundant in Mantine modals. Add autoComplete.

-              <PasswordInput
+              <PasswordInput
                 label={t("Password")}
                 placeholder={t("Enter your password")}
                 {...form.getInputProps("confirmPassword")}
-                autoFocus
                 data-autofocus
+                autoComplete="current-password"
               />

64-70: Confirm backend accepts empty payload & trims password

  • Verify the /mfa/disable endpoint on the server tolerates an empty body ({}) for SSO users; if it doesn’t, gate the submit button until requiresPassword is resolved.
  • Trim values.confirmPassword before sending to avoid false negatives.
apps/server/src/database/repos/user/user.repo.ts (1)

40-58: Double-check exposure of hasGeneratedPassword in public list/get endpoints.

If any API returns baseFields to non-admin consumers, ensure this field is acceptable to expose.

Also applies to: 60-78

apps/server/src/database/migrations/20250831T202306-ldap-auth.ts (1)

5-11: Type column enum → text → enum: add a CHECK constraint (optional) and confirm app/types alignment.

After switching to text, consider adding a CHECK to restrict values (('saml','oidc','google','ldap')) to preserve integrity. Also verify application types and queries no longer assume the enum type. Down migration will fail if any other unexpected values exist.

Example (optional):

ALTER TABLE auth_providers
  ADD CONSTRAINT auth_providers_type_check
  CHECK (type IN ('saml','oidc','google','ldap'));

Also applies to: 59-66

apps/client/src/ee/security/components/sso-provider-modal.tsx (1)

43-45: LDAP branch wiring — LGTM.

Modal now supports LDAP configuration via SsoLDAPForm.

You can reduce branching by mapping provider type → component.

-      {provider.type === SSO_PROVIDER.LDAP && (
-        <SsoLDAPForm provider={provider} onClose={onClose} />
-      )}
+      {{
+        [SSO_PROVIDER.SAML]: SsoSamlForm,
+        [SSO_PROVIDER.OIDC]: SsoOIDCForm,
+        [SSO_PROVIDER.GOOGLE]: SsoGoogleForm,
+        [SSO_PROVIDER.LDAP]: SsoLDAPForm,
+      }[provider.type]?.({ provider, onClose })}
apps/client/src/ee/components/sso-login.tsx (1)

36-43: Icon mapping LGTM; consider a simple map for extensibility.

Example:

const IconByType = {
  [SSO_PROVIDER.GOOGLE]: <GoogleIcon size={16} />,
  [SSO_PROVIDER.LDAP]: <IconServer size={16} />,
} as const;
apps/client/src/ee/security/components/sso-ldap-form.tsx (3)

219-223: Disable Save while mutating to prevent double-submit.

-            <Button type="submit" disabled={!form.isDirty()}>
+            <Button
+              type="submit"
+              disabled={!form.isDirty() || updateSsoProviderMutation.isPending}
+            >

If using React Query v4, replace isPending with isLoading.


47-61: Avoid echoing secrets back to users.

Pre-filling ldapBindPassword can imply server returns secrets. Prefer empty initial value and only send password if user changes it.

Proposed:

-      ldapBindPassword: provider.ldapBindPassword || "",
+      ldapBindPassword: "",

Server/API should treat empty/missing as “no change”.

Also applies to: 133-139


148-153: Clarify filter placeholder.

Consider showing example with uid/mail and note that {{username}} is substituted server-side.

apps/client/src/ee/security/types/security.types.ts (1)

12-19: Type safety for LDAP fields.

  • Avoid any for ldapUserAttributes; prefer a concrete shape or unknown.
  • Consider making ldapBindPassword optional/read-write only to avoid implying it’s returned by GET.
-  ldapUserAttributes: any;
+  ldapUserAttributes?: Record<string, unknown> | null;
-  ldapBindPassword: string;
+  ldapBindPassword?: string;
apps/client/src/ee/components/ldap-login-modal.tsx (6)

13-16: Localize all user‑facing strings (schema messages, title, placeholders, fallback error)

Several strings bypass i18n. Move schema inside the component to access t and translate messages, title, placeholders, and the default error message.

-const formSchema = z.object({
-  username: z.string().min(1, { message: "Username is required" }),
-  password: z.string().min(1, { message: "Password is required" }),
-});
+// (inside component, after `const { t } = useTranslation();`)
+const formSchema = z.object({
+  username: z.string().min(1, { message: t("Username is required") }),
+  password: z.string().min(1, { message: t("Password is required") }),
+});
 const form = useForm({
-  validate: zodResolver(formSchema),
+  validate: zodResolver(formSchema),
   initialValues: {
     username: "",
     password: "",
   },
 });
-const errorMessage =
-  err.response?.data?.message || "Authentication failed";
+const errorMessage =
+  err.response?.data?.message || t("Authentication failed");
- title={`LDAP Login - ${provider.name}`}
+ title={t("LDAP Login - {{provider}}", { provider: provider.name })}
- placeholder="Enter your LDAP username"
+ placeholder={t("Enter your LDAP username")}
- placeholder={t("Enter your LDAP password")}
+ placeholder={t("Enter your LDAP password")}
- {t("Sign in with LDAP")}
+ {t("Sign in with LDAP")}

Also applies to: 36-42, 72-74, 93-95, 101-103, 110-112, 118-119


34-35: Inline-surface errors or drop unused state

error state is set but never rendered. Either remove it and rely on notifications, or render an inline alert below inputs (recommended for accessibility).

Option A – render inline Alert:

-import { Modal, TextInput, PasswordInput, Button, Stack } from "@mantine/core";
+import { Modal, TextInput, PasswordInput, Button, Stack, Alert } from "@mantine/core";
           <PasswordInput
             label={t("LDAP password")}
             placeholder={t("Enter your LDAP password")}
             variant="filled"
             disabled={isLoading}
             {...form.getInputProps("password")}
           />
+          {error && (
+            <Alert color="red" variant="light" role="alert">
+              {error}
+            </Alert>
+          )}
 
           <Button type="submit" fullWidth mt="md" loading={isLoading}>
             {t("Sign in with LDAP")}
           </Button>

Option B – remove error state entirely:

-const [error, setError] = useState<string | null>(null);
+// removed unused error state

- setError(null);
+ // removed

- setError(errorMessage);
+ // removed

Also applies to: 76-79, 116-120, 2-2


90-95: Prevent closing while loading to avoid state updates after unmount

If the user closes the modal during an in‑flight request, subsequent setState calls can target an unmounted tree. Disable closing while isLoading.

 <Modal
   opened={opened}
   onClose={handleClose}
   title={`LDAP Login - ${provider.name}`}
   size="md"
+  closeOnClickOutside={!isLoading}
+  closeOnEscape={!isLoading}
+  withCloseButton={!isLoading}
 >

Follow‑up (optional, stronger): add request cancellation via AbortController in ldapLogin (accept an optional signal) and pass it from the modal; I can draft the service change if you want.


99-107: Improve UX/security with explicit autocomplete attributes

Help browsers fill the right fields and avoid unexpected autofill.

 <TextInput
   id="ldap-username"
-  type="text"
+  type="text"
   label={t("LDAP username")}
-  placeholder={t("Enter your LDAP username")}
+  placeholder={t("Enter your LDAP username")}
   variant="filled"
   disabled={isLoading}
   data-autofocus
+  autoComplete="username"
   {...form.getInputProps("username")}
 />
 
 <PasswordInput
   label={t("LDAP password")}
   placeholder={t("Enter your LDAP password")}
   variant="filled"
   disabled={isLoading}
+  autoComplete="current-password"
   {...form.getInputProps("password")}
 />

Also applies to: 109-115


44-47: Type handleSubmit from the Zod schema

Avoid duplicating shapes; infer from formSchema.

-const handleSubmit = async (values: {
-  username: string;
-  password: string;
-}) => {
+type FormValues = z.infer<typeof formSchema>;
+const handleSubmit = async (values: FormValues) => {

4-4: Use internal zodResolver from @mantine/form
Replace in apps/client/src/ee/components/ldap-login-modal.tsx (line 4):

- import { zodResolver } from "mantine-form-zod-resolver";
+ import { zodResolver } from "@mantine/form";

Apply the same change to other files importing from mantine-form-zod-resolver (e.g. invite-sign-up-form.tsx, embed-view.tsx) and remove the mantine-form-zod-resolver dependency.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5968764 and b19049e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (21)
  • apps/client/src/ee/components/ldap-login-modal.tsx (1 hunks)
  • apps/client/src/ee/components/sso-login.tsx (1 hunks)
  • apps/client/src/ee/mfa/components/mfa-backup-code-input.tsx (1 hunks)
  • apps/client/src/ee/mfa/components/mfa-backup-codes-modal.tsx (4 hunks)
  • apps/client/src/ee/mfa/components/mfa-challenge.tsx (1 hunks)
  • apps/client/src/ee/mfa/components/mfa-disable-modal.tsx (3 hunks)
  • apps/client/src/ee/mfa/components/mfa-setup-modal.tsx (1 hunks)
  • apps/client/src/ee/security/components/create-sso-provider.tsx (3 hunks)
  • apps/client/src/ee/security/components/sso-ldap-form.tsx (1 hunks)
  • apps/client/src/ee/security/components/sso-provider-modal.tsx (2 hunks)
  • apps/client/src/ee/security/contants.ts (1 hunks)
  • apps/client/src/ee/security/services/ldap-auth-service.ts (1 hunks)
  • apps/client/src/ee/security/types/security.types.ts (1 hunks)
  • apps/client/src/features/user/atoms/current-user-atom.ts (1 hunks)
  • apps/client/src/features/user/types/user.types.ts (1 hunks)
  • apps/server/package.json (1 hunks)
  • apps/server/src/core/auth/services/auth.service.ts (2 hunks)
  • apps/server/src/database/migrations/20250831T202306-ldap-auth.ts (1 hunks)
  • apps/server/src/database/repos/user/user.repo.ts (1 hunks)
  • apps/server/src/database/types/db.d.ts (2 hunks)
  • apps/server/src/ee (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (8)
apps/client/src/ee/security/services/ldap-auth-service.ts (1)
apps/client/src/features/auth/types/auth.types.ts (1)
  • ILoginResponse (42-47)
apps/client/src/ee/security/components/sso-provider-modal.tsx (1)
apps/client/src/ee/security/components/sso-ldap-form.tsx (1)
  • SsoLDAPForm (43-228)
apps/client/src/ee/components/ldap-login-modal.tsx (2)
apps/client/src/ee/security/types/security.types.ts (1)
  • IAuthProvider (3-29)
apps/client/src/ee/security/services/ldap-auth-service.ts (1)
  • ldapLogin (11-23)
apps/client/src/ee/components/sso-login.tsx (5)
apps/client/src/features/workspace/queries/workspace-query.ts (1)
  • useWorkspacePublicDataQuery (40-48)
apps/client/src/ee/security/types/security.types.ts (1)
  • IAuthProvider (3-29)
apps/client/src/ee/security/sso.utils.ts (1)
  • buildSsoLoginUrl (17-29)
apps/client/src/components/icons/google-icon.tsx (1)
  • GoogleIcon (7-33)
apps/client/src/ee/components/ldap-login-modal.tsx (1)
  • LdapLoginModal (25-124)
apps/client/src/ee/security/components/sso-ldap-form.tsx (2)
apps/client/src/ee/security/types/security.types.ts (1)
  • IAuthProvider (3-29)
apps/client/src/ee/security/queries/security-query.ts (1)
  • useUpdateSsoProviderMutation (53-69)
apps/client/src/ee/mfa/components/mfa-disable-modal.tsx (1)
apps/client/src/features/user/hooks/use-current-user.ts (1)
  • useCurrentUser (5-12)
apps/client/src/features/user/atoms/current-user-atom.ts (1)
apps/client/src/features/user/types/user.types.ts (1)
  • ICurrentUser (26-29)
apps/client/src/ee/mfa/components/mfa-backup-codes-modal.tsx (1)
apps/client/src/features/user/hooks/use-current-user.ts (1)
  • useCurrentUser (5-12)
🪛 GitHub Check: CodeQL
apps/client/src/ee/components/sso-login.tsx

[failure] 28-32: Client-side cross-site scripting
Cross-site scripting vulnerability due to user-provided value.


[warning] 28-32: Client-side URL redirect
Untrusted URL redirection depends on a user-provided value.

🔇 Additional comments (13)
apps/client/src/ee/security/contants.ts (1)

5-5: All SSO provider guards now handle LDAP. Verified that provider modals, login routing, icon rendering, and URL builders include LDAP via explicit branches or default cases.

apps/client/src/ee/security/services/ldap-auth-service.ts (1)

11-23: LGTM: straightforward service wrapper

Minimal payload, typed response, and no credential logging. Looks good as-is assuming interceptors handle errors/credentials.

apps/client/src/ee/security/components/create-sso-provider.tsx (2)

4-4: LGTM: icon import matches new LDAP menu item

Import is correct and used consistently.


88-93: LGTM: LDAP menu item wiring is correct

Handler, label, and icon align with the new flow.

apps/client/src/ee/mfa/components/mfa-backup-codes-modal.tsx (1)

61-63: LGTM: optional payload shape matches server-side expectation

Typing (data: { confirmPassword?: string }) aligns with the conditional send in handleRegenerate.

apps/client/src/ee/mfa/components/mfa-disable-modal.tsx (1)

18-18: LGTM on adding current-user hook.

The dependency direction is clean and localized to the modal.

apps/server/src/database/types/db.d.ts (1)

64-73: No code currently selects or logs LDAP secrets (ldapBindPassword, ldapTlsCaCert); no action required in this change.

apps/server/src/database/repos/user/user.repo.ts (1)

37-38: Including hasGeneratedPassword in baseFields makes sense.

Keeps client state in sync without extra selects.

apps/client/src/ee/security/components/sso-provider-modal.tsx (1)

8-8: Import looks correct; ensure tree-shake/build includes the new form.

Verify SsoLDAPForm default/named export matches and the path is valid in the workspace.

apps/client/src/ee/components/sso-login.tsx (2)

48-58: Modal lifecycle handling looks solid.

State reset on close prevents stale provider leakage. No concerns.


60-81: UI gating logic LGTM.

Cloud/license checks and non-enforced SSO divider behavior look consistent with existing patterns.

apps/client/src/ee/security/types/security.types.ts (1)

3-11: Confirm server/client enum alignment.

Ensure server’s provider.type values (including LDAP) match SSO_PROVIDER at runtime to avoid deserialization issues.

apps/client/src/ee/components/ldap-login-modal.tsx (1)

59-69: MFA branching and navigation look solid

Clear, readable post‑auth flow mirroring regular login. Good job on parity.

Comment thread apps/server/src/database/types/db.d.ts Resolved
Comment thread apps/server/src/database/types/db.d.ts Resolved
Comment thread apps/server/src/ee Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
apps/client/src/ee/security/components/sso-oidc-form.tsx (1)

118-125: Reduce duplication with a tiny ToggleRow helper (optional).

Both forms repeat the same label+switch row.

Example (outside diff scope):

function ToggleRow({ label, name }: { label: string; name: keyof SSOFormValues }) {
  const { t } = useTranslation();
  const form = useFormContext<SSOFormValues>();
  return (
    <Group justify="space-between">
      <div>{t(label)}</div>
      <Switch className={classes.switch} {...form.getInputProps(name, { type: "checkbox" })} />
    </Group>
  );
}

Then replace the two groups with:

<ToggleRow label="Group sync" name="groupSync" />
<ToggleRow label="Allow signup" name="allowSignup" />

Also applies to: 127-134

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b19049e and 499b907.

📒 Files selected for processing (4)
  • apps/client/src/ee/security/components/sso-ldap-form.tsx (1 hunks)
  • apps/client/src/ee/security/components/sso-oidc-form.tsx (1 hunks)
  • apps/client/src/ee/security/components/sso-saml-form.tsx (1 hunks)
  • apps/server/src/ee (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/server/src/ee
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/client/src/ee/security/components/sso-ldap-form.tsx
🔇 Additional comments (2)
apps/client/src/ee/security/components/sso-saml-form.tsx (1)

132-132: Label/binding alignment looks correct.

"Group sync" now pairs with groupSync. Same pattern applied below for "Allow signup".

apps/client/src/ee/security/components/sso-oidc-form.tsx (1)

119-119: Label/binding alignment looks correct.

"Group sync" now pairs with groupSync. Same pattern applied below for "Allow signup".

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (1)
apps/server/src/database/migrations/20250831T202306-ldap-auth.ts (1)

12-17: Good fix on NOT NULL + default; move IF NOT EXISTS to the correct builder.

You addressed the earlier feedback on nullability/defaults. However, ifNotExists() belongs to the addColumn builder, not the column definition builder.

   await db.schema
     .alterTable('users')
-    .addColumn('has_generated_password', 'boolean', (col) =>
-      col.notNull().defaultTo(false).ifNotExists(),
-    )
+    .addColumn('has_generated_password', 'boolean', (col) =>
+      col.notNull().defaultTo(false),
+    )
+    .ifNotExists()
     .execute();
🧹 Nitpick comments (3)
apps/server/src/database/migrations/20250831T202306-ldap-auth.ts (3)

4-11: Consider a CHECK constraint or enum recreation to preserve data integrity.

Switching auth_providers.type to text removes type safety. If the intent is long-term flexibility, add a CHECK constraint restricting to supported values (e.g., 'saml','oidc','google','ldap'). If enums are still desirable, recreate the enum including 'ldap' and cast to it post-migration.

Example (optional):

+  await sql`
+    ALTER TABLE auth_providers
+    ADD CONSTRAINT auth_providers_type_check
+    CHECK (type IN ('saml','oidc','google','ldap'));
+  `.execute(db);

36-68: Down migration may fail if any unexpected type values exist.

You only delete type = 'ldap', but casting back to enum will fail for any other stray strings. Either expand the delete to remove all non-enum values or guard with a pre-check.

Optional safer variant:

-  await db.deleteFrom('auth_providers').where('type', '=', 'ldap').execute();
+  await sql`
+    DELETE FROM auth_providers
+    WHERE type NOT IN ('saml','oidc','google')
+  `.execute(db);

Also consider dropping the optional CHECK constraint (if added) before recreating the enum.


4-4: Tighten the comment to reflect intent.

Current note implies a temporary step; if text is the permanent choice, clarify to avoid confusion for future maintainers.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 499b907 and d42c718.

📒 Files selected for processing (2)
  • apps/server/src/database/migrations/20250831T202306-ldap-auth.ts (1 hunks)
  • apps/server/src/ee (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/server/src/ee

@Philipinho
Philipinho merged commit dcbb65d into main Sep 2, 2025
@Philipinho Philipinho added the EE Enterprise edition label Sep 2, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

♻️ Duplicate comments (1)
apps/client/src/ee/components/ldap-login-modal.tsx (1)

11-11: Resolved: dropped .ts extension from import

The import now omits the .ts extension as previously requested. Good fix.

🧹 Nitpick comments (10)
apps/client/src/ee/mfa/services/mfa-service.ts (1)

39-41: Ergonomics: default the optional-arg parameter to {}

Callers shouldn’t need to pass {} when no password is required. Defaulting the param keeps the API tidy and avoids accidental undefined spreads.

Apply:

-export async function regenerateBackupCodes(data: {
-  confirmPassword?: string;
-}): Promise<MfaBackupCodesResponse> {
+export async function regenerateBackupCodes(
+  data: { confirmPassword?: string } = {},
+): Promise<MfaBackupCodesResponse> {
apps/client/src/ee/security/components/allowed-domains.tsx (2)

22-23: Remove redundant state/handler; getInputProps already wires value/onChange.

onChange={setDomains} is overridden by {...form.getInputProps("emailDomains")}, so setDomains never runs. Drop both the state and the prop to avoid confusion.

-  const [, setDomains] = useState<string[]>([]);
...
-          onChange={setDomains}
           {...form.getInputProps("emailDomains")}

Also applies to: 74-76


58-61: Internationalize static copy.

Wrap the strings with t(...) for consistency with the rest of the component.

-        <Text size="md">Allowed email domains</Text>
+        <Text size="md">{t("Allowed email domains")}</Text>
         <Text size="sm" c="dimmed">
-          Only users with email addresses from these domains can signup via SSO.
+          {t("Only users with email addresses from these domains can signup via SSO.")}
         </Text>
apps/client/src/features/workspace/components/settings/components/workspace-name-form.tsx (2)

15-16: Trim input before validation.

Prevents names that are only whitespace from passing .min(1).

-  name: z.string().min(1),
+  name: z.string().trim().min(1),

29-30: Avoid uncontrolled→controlled warnings.

Default name to "" when workspace?.name is undefined.

-      name: workspace?.name,
+      name: workspace?.name ?? "",
apps/client/src/features/user/components/account-language.tsx (1)

31-38: Handle null from Select onChange and avoid redundant updates.

Mantine’s onChange can pass null; also skip work if the language didn’t change.

Apply:

-  const handleChange = async (value: string) => {
+  const handleChange = async (value: string | null) => {
+    if (!value || value === language) return;
     const updatedUser = await updateUser({ locale: value });
 
     setLanguage(value);
     setUser(updatedUser);
 
     i18n.changeLanguage(value);
   };
apps/client/src/ee/components/ldap-login-modal.tsx (4)

73-73: Localize remaining UI strings

Translate the modal title and fallback error for consistency with the rest of the component.

-        err.response?.data?.message || "Authentication failed";
+        err.response?.data?.message || t("Authentication failed");
@@
-      title={`LDAP Login - ${provider.name}`}
+      title={t("LDAP Login - {{name}}", { name: provider.name })}

Also applies to: 93-93


99-107: Improve UX: add autocomplete/name attrs and surface server error inline

Enable browser autofill and show server error beneath the password field.

           <TextInput
             id="ldap-username"
-            type="text"
+            name="username"
+            type="text"
             label={t("LDAP username")}
-            placeholder="Enter your LDAP username"
+            placeholder={t("Enter your LDAP username")}
+            autoComplete="username"
             variant="filled"
             disabled={isLoading}
             data-autofocus
             {...form.getInputProps("username")}
           />
@@
-          <PasswordInput
-            label={t("LDAP password")}
-            placeholder={t("Enter your LDAP password")}
-            variant="filled"
-            disabled={isLoading}
-            {...form.getInputProps("password")}
-          />
+          <PasswordInput
+            id="ldap-password"
+            name="password"
+            label={t("LDAP password")}
+            placeholder={t("Enter your LDAP password")}
+            autoComplete="current-password"
+            variant="filled"
+            disabled={isLoading}
+            {...form.getInputProps("password")}
+            error={error || form.getInputProps("password").error}
+          />

Also applies to: 109-115


44-47: Type form values from schema

Keeps values type in sync with the zod schema.

-  const handleSubmit = async (values: {
-    username: string;
-    password: string;
-  }) => {
+  const handleSubmit = async (values: z.infer<typeof formSchema>) => {

13-16: Consider i18n for validation messages

The zod messages are hardcoded. Option: define the schema inside the component (or via a factory) so t is available.

Example (inside component):

const formSchema = useMemo(
  () =>
    z.object({
      username: z.string().min(1, { message: t("Username is required") }),
      password: z.string().min(1, { message: t("Password is required") }),
    }),
  [t]
);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d42c718 and fca6ce2.

📒 Files selected for processing (8)
  • apps/client/src/ee/components/ldap-login-modal.tsx (1 hunks)
  • apps/client/src/ee/mfa/components/mfa-backup-codes-modal.tsx (4 hunks)
  • apps/client/src/ee/mfa/services/mfa-service.ts (1 hunks)
  • apps/client/src/ee/mfa/types/mfa.types.ts (1 hunks)
  • apps/client/src/ee/security/components/allowed-domains.tsx (1 hunks)
  • apps/client/src/features/user/atoms/current-user-atom.ts (1 hunks)
  • apps/client/src/features/user/components/account-language.tsx (1 hunks)
  • apps/client/src/features/workspace/components/settings/components/workspace-name-form.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/client/src/ee/mfa/components/mfa-backup-codes-modal.tsx
🧰 Additional context used
🧬 Code graph analysis (2)
apps/client/src/ee/components/ldap-login-modal.tsx (2)
apps/client/src/ee/security/types/security.types.ts (1)
  • IAuthProvider (3-29)
apps/client/src/ee/security/services/ldap-auth-service.ts (1)
  • ldapLogin (11-23)
apps/client/src/features/user/atoms/current-user-atom.ts (2)
apps/client/src/features/user/types/user.types.ts (2)
  • ICurrentUser (26-29)
  • IUser (3-24)
apps/client/src/features/workspace/types/workspace.types.ts (1)
  • IWorkspace (3-25)
🔇 Additional comments (4)
apps/client/src/ee/mfa/types/mfa.types.ts (1)

49-50: Add clarifying TSDoc for confirmPassword optionality

Add a short comment above the optional confirmPassword in MfaDisableRequest (and likewise above the inline { confirmPassword?: string } in regenerateBackupCodes) to indicate it should only be sent when requiresPassword is true and otherwise omitted entirely:

 export interface MfaDisableRequest {
+  /** Include only when the user has a generated password; omit the field entirely otherwise. */
   confirmPassword?: string;
 }

Manually verify with the backend that both /mfa/disable and /mfa/generate-backup-codes accept missing confirmPassword without returning a 400.

apps/client/src/features/workspace/components/settings/components/workspace-name-form.tsx (1)

8-9: Import migration to mantine-form-zod-resolver looks correct.

Pattern matches the other file; no behavior change expected.

apps/client/src/features/user/atoms/current-user-atom.ts (1)

11-24: Writable derived atoms resolve prior setter breakage.

Read/write wrappers over currentUserAtom for user/workspace look correct and address the earlier read-only regression.

Also applies to: 27-40

apps/client/src/ee/components/ldap-login-modal.tsx (1)

18-23: Remove workspaceId from props and payload

  • Drop workspaceId from LdapLoginModalProps and from the ldapLogin({ … }) call.
  • Change provider: IAuthProvider to Pick<IAuthProvider, "id" | "name"> (only provider.id is used).
  • Verify no other code passes workspaceId into ldapLogin.

Comment on lines +3 to +4
import { useForm } from "@mantine/form";
import { zodResolver } from "mantine-form-zod-resolver";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Import migration looks good; confirm dependency and repo-wide consistency.

Usage with validate: zodResolver(formSchema) remains compatible.

Run to verify the dependency is declared and legacy imports are gone:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Check dependency presence"
fd -a package.json | xargs -I{} sh -c 'jq -r --arg f "{}" '"'"'(.name // "unknown") + " -> " + ((.dependencies["mantine-form-zod-resolver"] // .devDependencies["mantine-form-zod-resolver"] // "absent"))'"'"' "{}"'

echo "Find any legacy imports from @mantine/form"
rg -nP 'zodResolver\s*}\s*from\s*["'\'']@mantine/form["'\'']' -S || true

echo "Find new imports from mantine-form-zod-resolver"
rg -nP 'from\s*["'\'']mantine-form-zod-resolver["'\'']' -S || true

Length of output: 3890


Migrate remaining legacy imports of zodResolver. There are 17 instances of

import { useForm, zodResolver } from "@mantine/form";

under apps/client/src; update each to

import { zodResolver } from "mantine-form-zod-resolver";

(Client’s package.json already declares the new resolver.)

🤖 Prompt for AI Agents
In apps/client/src/ee/security/components/allowed-domains.tsx around lines 3 to
4, the file still imports zodResolver from "@mantine/form"; update the import so
zodResolver comes from "mantine-form-zod-resolver" (leave useForm import as-is
if used or remove zodResolver from the @mantine/form import), ensuring the
module path is changed to the new package declared in package.json and that no
duplicate imports remain.

Comment on lines +11 to 25
export const userAtom = atom(
(get) => {
const currentUser = get(currentUserAtom);
return currentUser?.user ?? null;
},
(get, set, newUser: IUser) => {
const currentUser = get(currentUserAtom);
if (currentUser) {
set(currentUserAtom, {
...currentUser,
user: newUser,
});
}
}
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Check for functional setter usage before merging.

If any component calls setUser(prev => …) or setWorkspace(prev => …), the current write signatures (IUser/IWorkspace only) would break without the above change.

Run:

Also applies to: 27-41


🏁 Script executed:

#!/bin/bash
# Find functional updates passed to setUser/setWorkspace
rg -nP -C2 '\bset(User|Workspace)\s*\(\s*(?:\w+\s*=>|\([^)]*\)\s*=>)'
# Find direct writes that would still work
rg -nP -C2 '\bset(User|Workspace)\s*\(\s*{'

Length of output: 600


Support functional updates in userAtom or refactor call sites.

Detected setUser((prev) => ({ ...prev, avatarUrl: avatar.fileName })) in apps/client/src/features/user/components/account-avatar.tsx:29; the current setter signature only accepts IUser and will break. Update the setter in apps/client/src/features/user/atoms/current-user-atom.ts to accept both IUser and (prev: IUser) => IUser or refactor the call site.

🤖 Prompt for AI Agents
In apps/client/src/features/user/atoms/current-user-atom.ts around lines 11 to
25, the setter currently only accepts an IUser and will break call sites that
pass a functional updater; change the setter signature to accept newUser: IUser
| ((prev: IUser | null) => IUser) and inside the setter detect if newUser is a
function, call it with the previous user (currentUser?.user ?? null) to compute
the next user, then set currentUserAtom with the merged object as before; ensure
types are updated accordingly and handle null previous user safely.

🛠️ Refactor suggestion

Strengthen typing and support functional updates to avoid breaking call-sites.

Type the atom generics and accept functional updates (prev => next) to remain compatible with common useAtom setter patterns and to avoid stale reads by updating via prev.

Apply:

-export const userAtom = atom(
-  (get) => {
-    const currentUser = get(currentUserAtom);
-    return currentUser?.user ?? null;
-  },
-  (get, set, newUser: IUser) => {
-    const currentUser = get(currentUserAtom);
-    if (currentUser) {
-      set(currentUserAtom, {
-        ...currentUser,
-        user: newUser,
-      });
-    }
-  }
-);
+export const userAtom = atom<IUser | null, IUser | ((prev: IUser | null) => IUser)>(
+  (get) => get(currentUserAtom)?.user ?? null,
+  (_get, set, update) => {
+    set(currentUserAtom, (prev) => {
+      if (!prev) return prev;
+      const nextUser =
+        typeof update === "function"
+          ? (update as (p: IUser | null) => IUser)(prev.user ?? null)
+          : update;
+      if (prev.user === nextUser) return prev;
+      return { ...prev, user: nextUser };
+    });
+  }
+);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const userAtom = atom(
(get) => {
const currentUser = get(currentUserAtom);
return currentUser?.user ?? null;
},
(get, set, newUser: IUser) => {
const currentUser = get(currentUserAtom);
if (currentUser) {
set(currentUserAtom, {
...currentUser,
user: newUser,
});
}
}
);
export const userAtom = atom<IUser | null, IUser | ((prev: IUser | null) => IUser)>(
(get) => get(currentUserAtom)?.user ?? null,
(_get, set, update) => {
set(currentUserAtom, (prev) => {
if (!prev) return prev;
const nextUser =
typeof update === "function"
? (update as (p: IUser | null) => IUser)(prev.user ?? null)
: update;
if (prev.user === nextUser) return prev;
return { ...prev, user: nextUser };
});
}
);
🤖 Prompt for AI Agents
In apps/client/src/features/user/atoms/current-user-atom.ts around lines 11 to
25, the atom is untyped and its write handler only accepts a concrete IUser,
breaking common useAtom setter patterns and preventing functional updates; add
explicit atom generics (state type and setter type) and change the setter to
accept either an IUser or an updater function (prev => next), compute the next
user by calling the updater when newUser is a function (passing
currentUser?.user ?? null), then set currentUserAtom with the merged object only
if next is not undefined, preserving existing currentUser shape.

Comment on lines +27 to 41
export const workspaceAtom = atom(
(get) => {
const currentUser = get(currentUserAtom);
return currentUser?.workspace ?? null;
},
(get, set, newWorkspace: IWorkspace) => {
const currentUser = get(currentUserAtom);
if (currentUser) {
set(currentUserAtom, {
...currentUser,
workspace: newWorkspace,
});
}
}
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Mirror the improvements for workspaceAtom.

Same typing and functional-update compatibility plus prev-based write to prevent races.

Apply:

-export const workspaceAtom = atom(
-  (get) => {
-    const currentUser = get(currentUserAtom);
-    return currentUser?.workspace ?? null;
-  },
-  (get, set, newWorkspace: IWorkspace) => {
-    const currentUser = get(currentUserAtom);
-    if (currentUser) {
-      set(currentUserAtom, {
-        ...currentUser,
-        workspace: newWorkspace,
-      });
-    }
-  }
-);
+export const workspaceAtom = atom<IWorkspace | null, IWorkspace | ((prev: IWorkspace | null) => IWorkspace)>(
+  (get) => get(currentUserAtom)?.workspace ?? null,
+  (_get, set, update) => {
+    set(currentUserAtom, (prev) => {
+      if (!prev) return prev;
+      const nextWorkspace =
+        typeof update === "function"
+          ? (update as (p: IWorkspace | null) => IWorkspace)(prev.workspace ?? null)
+          : update;
+      if (prev.workspace === nextWorkspace) return prev;
+      return { ...prev, workspace: nextWorkspace };
+    });
+  }
+);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const workspaceAtom = atom(
(get) => {
const currentUser = get(currentUserAtom);
return currentUser?.workspace ?? null;
},
(get, set, newWorkspace: IWorkspace) => {
const currentUser = get(currentUserAtom);
if (currentUser) {
set(currentUserAtom, {
...currentUser,
workspace: newWorkspace,
});
}
}
);
export const workspaceAtom = atom<
IWorkspace | null,
IWorkspace | ((prev: IWorkspace | null) => IWorkspace)
>(
(get) => get(currentUserAtom)?.workspace ?? null,
(_get, set, update) => {
set(currentUserAtom, (prev) => {
if (!prev) return prev;
const nextWorkspace =
typeof update === "function"
? (update as (p: IWorkspace | null) => IWorkspace)(prev.workspace ?? null)
: update;
if (prev.workspace === nextWorkspace) return prev;
return { ...prev, workspace: nextWorkspace };
});
}
);
🤖 Prompt for AI Agents
In apps/client/src/features/user/atoms/current-user-atom.ts around lines 27-41,
the workspaceAtom lacks explicit typing and doesn't support functional updates
or a previous-based write which can cause race conditions; update the atom
signature to declare the read type as IWorkspace | null and the write argument
to accept either an IWorkspace or a function (prev: IWorkspace | null) =>
IWorkspace, and in the setter perform a prev-based update of currentUserAtom by
reading the latest currentUser, computing the nextWorkspace by calling the
updater function when needed, and then setting currentUserAtom to a new object
with workspace replaced (safely handling null/undefined currentUser).

Comment on lines 27 to 29
const [language, setLanguage] = useState(
user?.locale === "en" ? "en-US" : user.locale,
user?.locale === "en" ? "en-US" : user?.locale,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

State desync on hydration: initialize language when user.locale becomes available.

When user is null initially (atomWithStorage rehydration), language stays undefined and Select shows "en-US" even if the actual locale differs. Sync on user.locale changes.

Apply:

-import { useState } from "react";
+import { useEffect, useState } from "react";
@@
-  const [language, setLanguage] = useState(
-    user?.locale === "en" ? "en-US" : user?.locale,
-  );
+  const [language, setLanguage] = useState<string | undefined>(
+    user?.locale === "en" ? "en-US" : user?.locale,
+  );
+  useEffect(() => {
+    const normalized = user?.locale === "en" ? "en-US" : user?.locale;
+    setLanguage(normalized);
+  }, [user?.locale]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const [language, setLanguage] = useState(
user?.locale === "en" ? "en-US" : user.locale,
user?.locale === "en" ? "en-US" : user?.locale,
);
// apps/client/src/features/user/components/account-language.tsx
import { useEffect, useState } from "react";
// …
- const [language, setLanguage] = useState(
- user?.locale === "en" ? "en-US" : user?.locale,
const [language, setLanguage] = useState<string | undefined>(
user?.locale === "en" ? "en-US" : user?.locale,
);
useEffect(() => {
const normalized = user?.locale === "en" ? "en-US" : user?.locale;
setLanguage(normalized);
}, [user?.locale]);
// …
🤖 Prompt for AI Agents
In apps/client/src/features/user/components/account-language.tsx around lines 27
to 29, the language state is initialized from user?.locale but remains stale
when user is null during atomWithStorage rehydration; add logic to update
language whenever user?.locale becomes available (e.g., use an effect that sets
setLanguage(user?.locale === "en" ? "en-US" : user?.locale) when user?.locale
changes) and ensure the initial value falls back to "en-US" so the Select
reflects the true locale after hydration.

github-actions Bot added a commit to antiagingrecord/docmost that referenced this pull request Oct 9, 2025
4231ba9 Merge commit '042836cb6d7cc1f71af3ce44c7957f8abbbf8f25' into feat/aar_edition
042836c sync
4f1f0ba fix
3164b69 feat: api keys management (EE) (docmost#1665)
16c1e86 fix comment space
c9b1cad sync
bf8cf62 feat: Typesense search driver (EE) (docmost#1664)
5a2e16a Merge commit '31350303760163384113bf49d07127e886f94907' into feat/aar_edition
3bc710d Adds CLAUDE.md documentation
16914f1 Block search for non-indexed shares
ca75e29 Set default page mode to Read
3135030 fix editor converter (docmost#1647)
3fae41a fix: editor performance improvements (docmost#1648)
b50e256 sync
1f3b0c7 cloud fix
3c4cab0 v0.23.2
4de25a8 invalidate queries on space deletion
cf5bbb1 fix import html processing
ac17521 sync
9ac180f fix: enhance page import (docmost#1570)
46669fe (cloud) disable page sharing in trial mode
fe6ecdf fix: update combobox props in SpaceSelect component (docmost#1564)
04ae1d7 Allow lastColumnResizable in table
1280f96 feat: implement space and workspace icons (docmost#1558)
61d1cf8 fix: reset file inputs after import
f413720 - sync - reinstantiate S3 client to fix file upload errors during import - delete import zip file after use
8e16ad9 v0.23.1
7ada3cb fix: page import task (docmost#1551)
47c5417 sync
dc06502 sync
091e790 fix attachment search in cloud
ae24ea2 v0.23.0
9df6061 lock file
31053e2 update mermaid
eb8e850 use debug
c99bfb8 make print better
26ea04e sync
6cc58c5 sync
7d2ff34 UI fixes
b08d37f fix
d43ee77 remove debug log
5d91eb4 feat: queue imported attachments for indexing
3e9f6b1 Remove version from docker-compose.yml [deprecated] (docmost#1011)
db55de9 feat: progressive web app (docmost#614)
1919eba New Crowdin updates (docmost#1522)
7951b2e New Crowdin updates (docmost#1509)
73b78f6 more translations
cf7534d fix version display
adec36d fix: adjust margins - use default browser highlight background
f9e1080 sync
00e499b Fixing extra page bug on print (docmost#1478)
5ee6e46 checkbox aligned to text (docmost#1486)
1f797c3 fix: confluence drawio import (docmost#1518)
f12866c feat(EE): full-text search in attachments (docmost#1502)
dcbb65d feat(EE): LDAP integration (docmost#1515)
5968764 feat: emoji callout icon (docmost#1323)
242fb6b fix: set mermaid theme based on computed color scheme (docmost#1438)
74cd890 feat(EE): implement SSO group sync for SAML and OIDC (docmost#1452)
509622a ignore type error
937386e fix: hide table handles in readonly mode
60a373f fix: readonly editor table responsiveness
73ee6ee feat: subpages (child pages) list node (docmost#1462)
7d1e5bc feat: table row/column drag and drop (docmost#1467)
aa58e27 fix: exclude deleted pages (docmost#1494)
08135a2 sync
d92a942 sync
5012a68 sync
5a33777 feat: debug mode env variable (docmost#1450)
3b85f4b fix: enforce C collation for page position ordering to ensure consistent behavior in Postgres 17+ (docmost#1446)
cb2a039 fix: invalidate trashed page from tree state
95b7be6 fix: hide trash from can view permission (docmost#1445)
b0c5572 fix nested taskList in markdown export (docmost#1443)
dddfd48 feat: add attachments support for single page exports (docmost#1440)
aa6eec7 fix: exclude trashed pages from position generation
97a7701 fix local storage copy function (docmost#1442)
b97eb85 sync

git-subtree-dir: vendor/app
git-subtree-split: 4231ba9
@Philipinho
Philipinho deleted the feat/ldap branch December 14, 2025 19:07
nulluserid pushed a commit to N2con-Inc/docmost that referenced this pull request Dec 17, 2025
* LDAP - WIP

* WIP

* add hasGeneratedPassword

* fix jotai atom

* - don't require password confirmation for MFA is user has auto generated password (LDAP)
- cleanups

* fix

* reorder

* update migration

* update default

* fix type error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

EE Enterprise edition

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants