Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

911 B
Raw Blame
import { Types } from 'mongoose';
import { PrincipalType } from 'librechat-data-provider';

/**
 * Normalizes a principalId to the correct type for MongoDB queries and storage.
 * USER and GROUP principals are stored as ObjectIds; ROLE principals are strings.
 * Ensures a string caller ID is cast to ObjectId so it matches documents written
 * by `grantCapability` — which always stores user/group IDs as ObjectIds to match
 * what `getUserPrincipals` returns.
 */
export const normalizePrincipalId = (
  principalId: string | Types.ObjectId,
  principalType: PrincipalType,
): string | Types.ObjectId => {
  if (typeof principalId === 'string' && principalType !== PrincipalType.ROLE) {
    if (!Types.ObjectId.isValid(principalId)) {
      throw new TypeError(`Invalid ObjectId string for ${principalType}: "${principalId}"`);
    }
    return new Types.ObjectId(principalId);
  }
  return principalId;
};