$ show LibreChat-AI/LibreChat
LibreChat is a self-hosted, multi-tenant AI chat platform that unifies access to major LLM providers (OpenAI, Anthropic, Google, AWS Bedrock, Azure, and custom OpenAI-compatible endpoints) through a single web interface. The architecture is a monolithic Express.js/Node.js backend serving a React (Vite) SPA, backed by MongoDB (Mongoose), Redis for caching/rate-limiting, MeiliSearch for full-text search, and PostgreSQL (pgvector) for RAG embeddings. The codebase is organized as a monorepo with shared packages: `data-schemas` (Mongoose models/methods with multi-tenant isolation), `data-provider` (Zod schemas, API types, React Query hooks), `api` (MCP management, streaming, auth, SSRF protection), and `client` (reusable React component library). Key data flows include: user requests hitting Express routes, middleware performing JWT/OAuth/LDAP/SAML auth and RBAC checks, agent orchestration via `@librechat/agents` with tool execution (MCP, code interpreter, web search), and SSE streaming with resumable stream support via Redis-backed job management. The system implements a sophisticated multi-tenant isolation layer using Mongoose plugins (`tenantIsolation`) that automatically scope queries by tenant, an ACL/permissions system with bit-flag-based permission checks, and SSRF protection with DNS resolution validation for MCP server URLs. The MCP (Model Context Protocol) subsystem is particularly well-developed, featuring OAuth flow management with reconnection tracking, tool discovery, and both stdio and HTTP/SSE transport support. The streaming architecture supports horizontal scaling with Redis-backed event transport and job stores, enabling resumable streams across multiple server instances.
The LLM identified 6 files worth highlighting for reuse:
Implements comprehensive SSRF protection with DNS resolution validation. `resolveHostnameSSRF` performs actual DNS lookups to detect hostnames resolving to private IPs, with an admin-configurable exemption list (`allowedAddresses`) that supports host:port granularity. `isSSRFTarget` blocks private IPs, localhost, internal Docker/K8s service names, and .internal/.local TLDs. `isDomainAllowedCore` provides a unified domain validation engine supporting wildcard subdomains, protocol restrictions (HTTP-only for actions, HTTP/WS for MCP), and explicit port matching against admin-configured allowlists. The `parseDomainSpec` helper normalizes domain specifications including protocol, port, and wildcard handling. This is a reusable, well-structured security module that could be extracted for any application accepting user-provided URLs.
A Mongoose plugin that enforces automatic tenant scoping on all database queries. Applied to nearly every model in the system, it injects `tenantId` filters into find, update, aggregate, and delete operations at the query level, preventing cross-tenant data leakage. The plugin is intentionally excluded from `SystemGrant` and `AuditLog` models where cross-tenant queries are needed by design. This is a clean implementation of the tenant-per-database-row isolation pattern that could be extracted and reused in any multi-tenant Mongoose application.
Manages the lifecycle of AI generation jobs with support for resumable SSE streams. Implements a job store abstraction (`IJobStore`) with Redis and in-memory backends, and an event transport (`IEventTransport`) for publishing stream events. The `subscribeWithResume` method enables clients to reconnect to in-progress streams by replaying missed events and sending a sync event with the current state. Supports horizontal scaling where stream events are published to Redis and consumed by any server instance. The `abortJob` method handles graceful cancellation with partial response persistence. This is a well-abstracted streaming architecture that separates job storage, event transport, and job management concerns.
Implements a three-version encryption scheme supporting backward-compatible key rotation. v1 uses AES-CBC with a fixed key/IV (legacy), v2 uses AES-CBC with a random IV prepended to the ciphertext, and v3 uses AES-256-CTR with a `v3:` prefix for format detection. The decrypt functions auto-detect the version and route to the appropriate decryption path. This pattern of versioned encryption with automatic format detection is reusable for any system that needs to rotate encryption keys while maintaining backward compatibility with existing encrypted data.
A hardened HTTP fetch implementation for MCP OAuth flows that prevents SSRF attacks during the OAuth token exchange and discovery phases. Validates that OAuth redirect URLs and token endpoints don't resolve to private/internal IP addresses before making outbound requests. Integrates with the admin-configured `allowedAddresses` exemption list. This component demonstrates a security-first approach to implementing OAuth client flows where user-configured OAuth endpoints could otherwise be weaponized for SSRF attacks.
A generic distributed state machine for managing multi-step flows (primarily OAuth flows for MCP servers). Uses Keyv cache as a backing store with configurable TTL, supporting PENDING/COMPLETED/FAILED states with metadata. The `waitForCompletion` method allows callers to block until a flow reaches a terminal state, with timeout handling. This is a clean, reusable pattern for managing asynchronous multi-step workflows in a distributed environment where state must survive process restarts.