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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🔭 feat: Admin Config Read APIs (Resolved and Effective Config, Scope Catalog, Env Status) (#17383)
Danny Avilaf05f50460a34
diff --git a/api/server/controllers/PluginController.js b/api/server/controllers/PluginController.jsindex b59fe26e65..d01eac6c38 100644--- a/api/server/controllers/PluginController.js+++ b/api/server/controllers/PluginController.js@@ -1,10 +1,5 @@const { logger } = require('@librechat/data-schemas');-const {- getToolkitKey,- checkPluginAuth,- filterUniquePlugins,- filterGitHubComparePlugins,-} = require('@librechat/api');+const { listAvailableTools } = require('@librechat/api');const { getCachedTools, setCachedTools } = require('~/server/services/Config');const { availableTools, toolkits } = require('~/app/clients/tools');const { getAppConfig } = require('~/server/services/Config');@@ -33,12 +28,6 @@ const getAvailableTools = async (req, res) => {toolDefinitions = appConfig.availableTools;}- const uniquePlugins = filterUniquePlugins(- filterGitHubComparePlugins(availableTools, appConfig?.githubCompare),- );- const toolDefKeysList = toolDefinitions ? Object.keys(toolDefinitions) : null;- const toolDefKeys = toolDefKeysList ? new Set(toolDefKeysList) : null;-/*** `getAvailableTools` serves BOTH tool dialogs — /api/agents/tools and* /api/assistants/tools. Tools flagged `agentsOnly` in the manifest (e.g.@@ -47,27 +36,13 @@ const getAvailableTools = async (req, res) => {* run to pause and no resume surface, so attaching one there guarantees a* permanent tool error. Scope them out of the assistants listing by route.*/- const isAssistantsRoute = req.baseUrl?.includes('/assistants') === true;-- const toolsOutput = [];- for (const plugin of uniquePlugins) {- if (plugin.agentsOnly === true && isAssistantsRoute) {- continue;- }- const isToolDefined = toolDefKeys?.has(plugin.pluginKey) === true;- const isToolkit =- plugin.toolkit === true &&- toolDefKeysList != null &&- toolDefKeysList.some(- (key) => getToolkitKey({ toolkits, toolName: key }) === plugin.pluginKey,- );-- if (!isToolDefined && !isToolkit) {- continue;- }-- toolsOutput.push(checkPluginAuth(plugin) ? { ...plugin, authenticated: true } : plugin);- }+ const toolsOutput = listAvailableTools({+ manifest: availableTools,+ toolkits,+ toolDefinitions,+ githubCompare: appConfig?.githubCompare,+ forAssistants: req.baseUrl?.includes('/assistants') === true,+ });res.status(200).json(toolsOutput);} catch (error) {diff --git a/api/server/routes/admin/config.js b/api/server/routes/admin/config.jsindex 44a33d29c9..8c4d4ef38c 100644--- a/api/server/routes/admin/config.js+++ b/api/server/routes/admin/config.js@@ -1,5 +1,10 @@const express = require('express');-const { createAdminConfigHandlers, rejectUnsafeConfigKeys } = require('@librechat/api');+const {+ rejectUnsafeConfigKeys,+ createAdminConfigHandlers,+ createAdminConfigReadHandlers,+ createAdminConfigCatalogHandlers,+} = require('@librechat/api');const { SystemCapabilities } = require('@librechat/data-schemas');const {hasCapability,@@ -10,10 +15,16 @@ const {} = require('~/server/middleware/roles/capabilities');const {getAppConfig,+ getCachedTools,overrideCacheTtl,+ loadConfigModels,+ loadDefaultModels,+ getEndpointsConfig,reloadConfigCaches,+ resolveConfigLayers,invalidateConfigCaches,} = require('~/server/services/Config');+const { availableTools, toolkits } = require('~/app/clients/tools');const { requireJwtAuth } = require('~/server/middleware');const db = require('~/models');@@ -43,11 +54,43 @@ const handlers = createAdminConfigHandlers({overrideEnvAllowlist: process.env.CONFIG_OVERRIDE_ENV_ALLOWLIST,});+const readHandlers = createAdminConfigReadHandlers({+ findConfigByPrincipal: db.findConfigByPrincipal,+ hasAnyConfigReadAccess,+ getReadableConfigSections,+ hasCapability,+ resolveConfigLayers,+ principalExists: db.principalExists,+ findPartitionUser: db.findPartitionUser,+ getUserPrincipals: db.getUserPrincipals,+ getApplicableConfigs: db.getApplicableConfigs,+});++const catalogHandlers = createAdminConfigCatalogHandlers({+ hasAnyConfigReadAccess,+ getReadableConfigSections,+ hasConfigCapability,+ getAppConfig,+ getEndpointsConfig,+ loadDefaultModels,+ loadConfigModels,+ getCachedTools,+ toolManifest: availableTools,+ toolkits,+ principalExists: db.principalExists,+ listAllConfigs: db.listAllConfigs,+ overrideEnvAllowlist: process.env.CONFIG_OVERRIDE_ENV_ALLOWLIST,+});+router.use(requireJwtAuth, requireAdminAccess, rejectUnsafeConfigKeys);router.get('/', handlers.listConfigs);router.get('/meta', handlers.getConfigMeta);router.get('/base', handlers.getBaseConfig);+router.get('/catalog', catalogHandlers.getConfigCatalog);+router.get('/env-status', catalogHandlers.getEnvStatus);+router.get('/effective', readHandlers.getEffectiveConfig);+router.get('/resolved/:principalType/:principalId', readHandlers.getResolvedConfig);router.post('/reload', handlers.reloadConfig);router.get('/:principalType/:principalId', handlers.getConfig);router.put('/:principalType/:principalId', handlers.upsertConfigOverrides);diff --git a/api/server/routes/admin/config.test.js b/api/server/routes/admin/config.test.jsindex 8ce98a4c66..55d9183ae4 100644--- a/api/server/routes/admin/config.test.js+++ b/api/server/routes/admin/config.test.js@@ -25,6 +25,10 @@ const mockDb = {deleteConfig: jest.fn(),toggleConfigActiveTracked: jest.fn(),recordAuditEntry: jest.fn(),+ principalExists: jest.fn(async () => true),+ findPartitionUser: jest.fn(async () => null),+ getUserPrincipals: jest.fn(async () => []),+ getApplicableConfigs: jest.fn(async () => []),};jest.mock('~/server/middleware', () => ({ requireJwtAuth: mockRequireJwtAuth }));@@ -39,11 +43,18 @@ jest.mock('~/server/middleware/roles/capabilities', () => ({jest.mock('~/server/services/Config', () => ({getAppConfig: jest.fn(async () => ({ config: {} })),+ resolveConfigLayers: jest.fn(async () => ({ yaml: {}, merged: {}, resolved: {}, layers: [] })),+ getEndpointsConfig: jest.fn(async () => ({})),+ loadDefaultModels: jest.fn(async () => ({})),+ loadConfigModels: jest.fn(async () => ({})),+ getCachedTools: jest.fn(async () => ({})),overrideCacheTtl: 15_000,invalidateConfigCaches: jest.fn(async () => undefined),reloadConfigCaches: jest.fn(async () => ({ cleared: true, broadcast: 'sent' })),}));+jest.mock('~/app/clients/tools', () => ({ availableTools: [], toolkits: [] }));+jest.mock('~/models', () => mockDb);/** The app-level order of `api/server/index.js`: body parsing, writable query, sanitizer, router. */@@ -76,6 +87,7 @@ describe('admin config routes', () => {beforeEach(() => {hasAdminAccess = true;+ mockDb.listAllConfigs.mockResolvedValue([]);mockDb.findConfigByPrincipal.mockResolvedValue(null);mockDb.writeConfigDocument.mockImplementation(async (principalType, principalId, draft) => ({_id: 'c1',@@ -163,7 +175,53 @@ describe('admin config routes', () => {maxPatchEntries: 100,maxChangeOps: 1000,overrideCacheTtlMs: 15_000,+ catalogModelsTtlMs: 120_000,+ });+ });++ it.each([+ '/api/admin/config/catalog',+ '/api/admin/config/env-status',+ '/api/admin/config/resolved/role/USER',+ '/api/admin/config/effective?userId=0123456789abcdef01234567',+ ])('serves the read view %s behind the same auth', async (path) => {+ const anonymous = await request(app).get(path);+ hasAdminAccess = false;+ const withoutAccess = await request(app).get(path).set('authorization', 'Bearer admin');++ expect(anonymous.status).toBe(401);+ expect(withoutAccess.status).toBe(403);+ });++ it('serves the catalog to a client that sends no User-Agent', async () => {+ const response = await request(app)+ .get('/api/admin/config/catalog?principalType=role&principalId=USER')+ .set('authorization', 'Bearer admin')+ .unset('User-Agent')+ .expect(200);++ expect(response.body).toMatchObject({ principalType: 'role', principalId: 'USER' });+ expect(response.body.endpoints).toBeDefined();+ });++ it('routes the resolved, effective and env status views to their handlers', async () => {+ const auth = (path) => request(app).get(path).set('authorization', 'Bearer admin');++ const resolved = await auth('/api/admin/config/resolved/role/USER').expect(200);+ expect(resolved.body).toEqual({+ principalType: 'role',+ principalId: 'USER',+ yaml: {},+ layers: [],+ resolved: {},});++ const effective = await auth('/api/admin/config/effective?userId=0123456789abcdef01234567');+ expect(effective.status).toBe(404);+ expect(effective.body.code).toBe('USER_NOT_FOUND');++ const envStatus = await auth('/api/admin/config/env-status').expect(200);+ expect(envStatus.body.vars).toBeDefined();});it('reloads the config behind the same auth, through the Config service reload', async () => {diff --git a/api/server/services/Config/__tests__/EndpointService.env.spec.js b/api/server/services/Config/__tests__/EndpointService.env.spec.jsnew file mode 100644index 0000000000..86a3691818--- /dev/null+++ b/api/server/services/Config/__tests__/EndpointService.env.spec.js@@ -0,0 +1,45 @@+const { BUILT_IN_ENDPOINT_ENV } = require('@librechat/api');+require('librechat-data-provider');+require('@librechat/data-schemas');+require('~/server/utils/handleText');++/**+ * The env names these services read decide whether a built-in endpoint is served, so the admin+ * catalog and env status (`BUILT_IN_ENDPOINT_ENV`) must name each of them. Their dependencies+ * load above, so only the services' own reads are recorded.+ */+describe('built-in endpoint env names', () => {+ const originalEnv = process.env;++ afterEach(() => {+ process.env = originalEnv;+ });++ it('are all listed by the admin catalog', async () => {+ const read = new Set();+ process.env = new Proxy(+ {},+ {+ get(target, key) {+ if (typeof key === 'string') {+ read.add(key);+ }+ return Reflect.get(target, key);+ },+ },+ );+ const loadAsyncEndpoints = require('../loadAsyncEndpoints');+ await loadAsyncEndpoints();+ process.env = originalEnv;++ const listed = new Set(Object.values(BUILT_IN_ENDPOINT_ENV).flat());+ expect([...read]).toEqual(+ expect.arrayContaining([+ 'ANTHROPIC_API_KEY',+ 'ANTHROPIC_USE_VERTEX',+ 'GOOGLE_SERVICE_KEY_FILE',+ ]),+ );+ expect([...read].filter((name) => !listed.has(name))).toEqual([]);+ });+});diff --git a/api/server/services/Config/app.js b/api/server/services/Config/app.jsindex d769134b72..c4230ba4c6 100644--- a/api/server/services/Config/app.js+++ b/api/server/services/Config/app.js@@ -73,6 +73,7 @@ const appConfigService = createAppConfigService({});const {getAppConfig,+ resolveConfigLayers,clearAppConfigCache,clearOverrideCache,reloadBaseConfig,@@ -124,6 +125,7 @@ function reloadConfigCaches(tenantId) {module.exports = {getAppConfig,+ resolveConfigLayers,overrideCacheTtl,invalidateConfigCaches,reloadConfigCaches,diff --git a/librechat.example.yaml b/librechat.example.yamlindex 5207e790c2..7e747b02fb 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -752,6 +752,11 @@ actions:# Definition of custom endpointsendpoints:+ # (optional) How long the admin config catalog reuses a scope's model lists while its endpoint+ # config is unchanged, in milliseconds. Defaults to 120000 (two minutes), at most 3600000 (one+ # hour); 0 resolves them on every read (a fetched list may still come from the two-minute+ # model-list cache). Only librechat.yaml sets it.+ # catalogModelsTtlMs: 120000# assistants:# disableBuilder: false # Disable Assistants Builder Interface by setting to `true`# pollIntervalMs: 3000 # Polling interval for checking assistant updatesdiff --git a/packages/api/src/admin/catalog.spec.ts b/packages/api/src/admin/catalog.spec.tsnew file mode 100644index 0000000000..8488efdb9a--- /dev/null+++ b/packages/api/src/admin/catalog.spec.ts@@ -0,0 +1,565 @@+process.env.CREDS_KEY =+ process.env.CREDS_KEY ?? '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';++import { PrincipalType, EModelEndpoint } from 'librechat-data-provider';+import type {+ AppConfig,+ ConfigRecord,+ ConfigOverrideLayer,+ AdminConfigCatalogResponse,+ AdminConfigEnvStatusResponse,+} from '@librechat/data-schemas';+import type { DeepPartial, TCustomConfig, TPlugin } from 'librechat-data-provider';+import type { Response } from 'express';+import type { FetchModelsParams } from '~/endpoints/models';+import type { AdminConfigCatalogDeps, CatalogScopeRequest } from './catalog';+import type { ServerRequest } from '~/types/http';++type DataSchemas = typeof import('@librechat/data-schemas');++interface MockRes {+ statusCode: number;+ body: Record<string, unknown> | undefined;+ status: jest.Mock;+ json: jest.Mock;+}++const ROLE = PrincipalType.ROLE;+const GATEWAY_SECRET = 'gateway-secret-env-value';++const YAML: DeepPartial<TCustomConfig> = {+ version: '1.3.0',+ cache: true,+ endpoints: {+ custom: [+ {+ name: 'Gateway',+ apiKey: '${GATEWAY_KEY}',+ baseURL: 'https://gateway.example.com/v1',+ headers: { 'X-User': '{{LIBRECHAT_USER_EMAIL}}' },+ models: { default: ['gpt-4o'], fetch: true },+ },+ {+ name: 'BYOK',+ apiKey: 'user_provided',+ baseURL: 'https://byok.example.com/v1',+ models: { default: ['byok-default'], fetch: true },+ },+ ],+ },+ mcpServers: {+ docs: { type: 'streamable-http', url: 'https://docs.example.com/mcp', title: 'Docs' },+ legacy: { url: 'https://legacy.example.com/sse' },+ local: { command: 'node', args: ['server.js'] },+ },+ webSearch: { searxngInstanceUrl: '${SEARXNG_INSTANCE_URL}' },+};++let dataSchemas: DataSchemas;+let createAdminConfigCatalogHandlers: typeof import('./catalog').createAdminConfigCatalogHandlers;+let BUILT_IN_ENDPOINT_ENV: typeof import('./catalog').BUILT_IN_ENDPOINT_ENV;+let ENDPOINT_CREDENTIAL_ENV_NAMES: readonly string[];+let appConfig: AppConfig;+let documents: ConfigOverrideLayer[];++const ENV_KEYS = [+ 'ANTHROPIC_USE_VERTEX',+ 'ENDPOINTS',+ 'GATEWAY_KEY',+ 'OPENAI_API_KEY',+ 'OPENAI_MODELS',+ 'TENANT_ISOLATION_STRICT',+ 'PROFILE_ONLY_NAME',+];+const savedEnv = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]]));++function mockReq(overrides: Record<string, unknown> = {}): ServerRequest {+ return {+ user: { id: 'admin-1', role: 'ADMIN', _id: { toString: () => 'admin-1' } },+ params: {},+ body: {},+ query: {},+ headers: {},+ ...overrides,+ } as Partial<ServerRequest> as ServerRequest;+}++function mockRes(): Response & MockRes {+ const res: MockRes = {+ statusCode: 200,+ body: undefined,+ status: jest.fn((code: number) => {+ res.statusCode = code;+ return res;+ }),+ json: jest.fn((data: MockRes['body']) => {+ res.body = data;+ return res;+ }),+ };+ return res as Partial<Response> as Response & MockRes;+}++function roleDocument(+ principalId: string,+ overrides: Record<string, unknown>,+ tombstones?: string[],+) {+ return {+ _id: `doc-${principalId}`,+ principalType: ROLE,+ principalId,+ priority: 10,+ overrides,+ tombstones,+ isActive: true,+ } as ConfigOverrideLayer;+}++/** Real config resolution, endpoint config and model loaders; only the provider HTTP is faked. */+async function createDeps(extra: Partial<AdminConfigCatalogDeps> = {}) {+ const { createAppConfigService } = await import('~/app/service');+ const { createEndpointsConfigService, createLoadConfigModels, configuredModelList } =+ await import('~/endpoints/config');+ const { getOpenAIModels } = await import('~/endpoints/models');+ const store = new Map<string, unknown>();+ const service = createAppConfigService({+ loadBaseConfig: async () => structuredClone(appConfig),+ setCachedTools: async () => undefined,+ getCache: () => ({+ get: async (key: string) => store.get(key),+ set: async (key: string, value: unknown) => {+ store.set(key, value);+ },+ delete: async (key: string) => store.delete(key),+ }),+ cacheKeys: { APP_CONFIG: 'app_config' },+ getApplicableConfigs: async (principals = []) =>+ documents.filter(+ (doc) =>+ dataSchemas.isBaseConfigPrincipal(doc) ||+ principals.some(+ ({ principalType, principalId }) =>+ principalType === doc.principalType && String(principalId) === doc.principalId,+ ),+ ),+ getUserPrincipals: async () => [],+ });+ const getAppConfig = jest.fn(service.getAppConfig);+ const { getEndpointsConfig } = createEndpointsConfigService({+ getAppConfig,+ loadDefaultEndpointsConfig: async () => ({+ [EModelEndpoint.openAI]: { userProvide: false, order: 0 },+ [EModelEndpoint.agents]: { userProvide: false, order: 1 },+ }),+ });+ const fetchModels = jest.fn(async ({ name }: FetchModelsParams) => [`${name}-fetched`]);+ const getUserKeyValues = jest.fn(async () => ({ apiKey: 'a-user-key' }));+ const loadConfigModels = createLoadConfigModels({ getAppConfig, getUserKeyValues, fetchModels });+ const loadDefaultModels = jest.fn(async (req: CatalogScopeRequest) => ({+ [EModelEndpoint.openAI]: await getOpenAIModels({+ configuredModels: configuredModelList(req.config, EModelEndpoint.openAI),+ }),+ }));+ const deps: AdminConfigCatalogDeps = {+ hasAnyConfigReadAccess: async () => true,+ getReadableConfigSections: async (_user, sections) => ({+ broad: true,+ sections: new Set(sections),+ }),+ hasConfigCapability: async () => true,+ getAppConfig,+ getEndpointsConfig: (req) => getEndpointsConfig(req as ServerRequest),+ loadDefaultModels,+ loadConfigModels: (req) => loadConfigModels(req as ServerRequest),+ getCachedTools: async () => ({ calculator: {}, image_gen_oai: {} }),+ toolManifest: [+ { name: 'Calculator', pluginKey: 'calculator', description: 'Math' },+ { name: 'Not loaded', pluginKey: 'not_loaded' },+ {+ name: 'Keyed',+ pluginKey: 'image_gen_oai',+ authConfig: [{ authField: 'GATEWAY_KEY', label: 'Key', description: 'Key' }],+ },+ ] as TPlugin[],+ toolkits: [],+ principalExists: async (_type, id) => id !== 'ghost',+ listAllConfigs: async () => documents as ConfigRecord[],+ overrideEnvAllowlist: 'ALLOWLISTED_NAME',+ ...extra,+ };+ return { deps, fetchModels, getUserKeyValues, getAppConfig, loadDefaultModels };+}++async function catalog(query: Record<string, string>, extra: Partial<AdminConfigCatalogDeps> = {}) {+ const created = await createDeps(extra);+ const handlers = createAdminConfigCatalogHandlers(created.deps);+ const res = mockRes();+ await handlers.getConfigCatalog(mockReq({ query }), res);+ return { ...created, handlers, res, body: res.body as AdminConfigCatalogResponse };+}++beforeAll(async () => {+ dataSchemas = await import('@librechat/data-schemas');+ jest.spyOn(dataSchemas.logger, 'warn').mockReturnValue(dataSchemas.logger);+ jest.spyOn(dataSchemas.logger, 'info').mockReturnValue(dataSchemas.logger);+ jest.spyOn(dataSchemas.logger, 'error').mockReturnValue(dataSchemas.logger);+ ({ createAdminConfigCatalogHandlers, BUILT_IN_ENDPOINT_ENV } = await import('./catalog'));+ ({ ENDPOINT_CREDENTIAL_ENV_NAMES } = await import('~/app/allowlist'));+ appConfig = await dataSchemas.AppService({ config: structuredClone(YAML) });+});++beforeEach(() => {+ for (const key of ENV_KEYS) {+ delete process.env[key];+ }+ process.env.GATEWAY_KEY = GATEWAY_SECRET;+ process.env.OPENAI_MODELS = 'gpt-env-a,gpt-env-b';+ documents = [+ roleDocument(dataSchemas.BASE_CONFIG_PRINCIPAL_ID, {}),+ roleDocument(+ 'editors',+ {+ endpoints: {+ openAI: { models: ['gpt-4.1'] },+ custom: [+ {+ name: 'Extra',+ apiKey: 'extra-key',+ baseURL: 'https://extra.example.com/v1',+ models: { default: ['extra-1'] },+ },+ { name: 'NoKey', baseURL: 'https://nokey.example.com', models: { default: ['n'] } },+ ],+ },+ mcpServers: { added: { type: 'sse', url: 'https://added.example.com/sse' } },+ },+ ['mcpServers.docs'],+ ),+ ];+});++afterAll(() => {+ for (const [key, value] of Object.entries(savedEnv)) {+ if (value === undefined) {+ delete process.env[key];+ } else {+ process.env[key] = value;+ }+ }+ jest.restoreAllMocks();+});++describe('GET /catalog', () => {+ it('lists what the Base scope serves by default, resolved from the stored documents', async () => {+ const { res, body, getAppConfig } = await catalog({});+ expect(res.statusCode).toBe(200);+ expect(body.principalType).toBe(ROLE);+ expect(body.principalId).toBe(dataSchemas.BASE_CONFIG_PRINCIPAL_ID);+ expect(getAppConfig).toHaveBeenCalledWith(+ expect.objectContaining({ bypassOverrideCache: true, skipRuntimeAugmentation: true }),+ );+ expect(body.endpoints?.Gateway).toMatchObject({+ enabled: true,+ custom: true,+ envVars: ['GATEWAY_KEY'],+ });+ expect(body.endpoints).not.toHaveProperty('Extra');+ expect(body.mcpServers?.map(({ name }) => name)).toEqual(['docs', 'legacy', 'local']);+ });++ it('resolves a role scope as that role gets it, its own endpoints and hidden servers included', async () => {+ const { body } = await catalog({ principalType: ROLE, principalId: 'editors' });+ expect(body.endpoints?.Extra).toMatchObject({ enabled: true, custom: true, envVars: [] });+ expect(body.endpoints?.NoKey).toEqual({+ enabled: false,+ custom: true,+ envVars: [],+ reason: 'missing_api_key',+ });+ expect(body.mcpServers).toEqual([+ { name: 'legacy', transport: 'sse', source: 'yaml', processBacked: false },+ { name: 'local', transport: 'stdio', source: 'yaml', processBacked: true },+ { name: 'added', transport: 'sse', source: 'override', processBacked: false },+ ]);+ });++ it('reports built-in endpoints that are not served, with why and the env names they read', async () => {+ const { body } = await catalog({});+ expect(body.endpoints?.[EModelEndpoint.openAI]).toMatchObject({ enabled: true });+ expect(body.endpoints?.[EModelEndpoint.anthropic]).toEqual({+ enabled: false,+ custom: false,+ envVars: ['ANTHROPIC_API_KEY', 'ANTHROPIC_USE_VERTEX'],+ reason: 'missing_credentials',+ });+ process.env.ENDPOINTS = 'openAI,agents';+ const listed = await catalog({});+ expect(listed.body.endpoints?.[EModelEndpoint.google]?.reason).toBe('not_listed');+ });++ it('lists each endpoint models as served, configured and by default', async () => {+ const base = await catalog({});+ expect(base.body.models?.[EModelEndpoint.openAI]).toEqual({+ served: ['gpt-env-a', 'gpt-env-b'],+ defaults: ['gpt-env-a', 'gpt-env-b'],+ });+ expect(base.body.models?.Gateway).toEqual({+ served: ['Gateway-fetched'],+ configured: ['gpt-4o'],+ defaults: ['Gateway-fetched'],+ });++ const role = await catalog({ principalType: ROLE, principalId: 'editors' });+ expect(role.body.models?.[EModelEndpoint.openAI]).toEqual({+ served: ['gpt-4.1'],+ configured: ['gpt-4.1'],+ defaults: ['gpt-env-a', 'gpt-env-b'],+ });+ expect(role.body.models?.Extra).toEqual({ served: ['extra-1'], configured: ['extra-1'] });+ });++ it('never loads models with a user key or the caller identity', async () => {+ const { body, fetchModels, getUserKeyValues } = await catalog({});+ expect(body.models?.BYOK).toEqual({ served: ['byok-default'], configured: ['byok-default'] });+ expect(getUserKeyValues).not.toHaveBeenCalled();+ expect(fetchModels).toHaveBeenCalledTimes(1);+ const [params] = fetchModels.mock.calls[0];+ expect(params).toMatchObject({ name: 'Gateway', apiKey: GATEWAY_SECRET });+ expect(params.user).toBeUndefined();+ expect(JSON.stringify(params.userObject)).not.toContain('admin');+ });++ it('reuses a scope model lists until its endpoint config changes or they expire', async () => {+ const { handlers, fetchModels } = await catalog({});+ const read = () => handlers.getConfigCatalog(mockReq({ query: {} }), mockRes());+ await read();+ expect(fetchModels).toHaveBeenCalledTimes(1);++ documents[0] = roleDocument(dataSchemas.BASE_CONFIG_PRINCIPAL_ID, {+ endpoints: { custom: [{ name: 'Gateway', headers: { 'X-Team': 'b' } }] },+ });+ await read();+ expect(fetchModels).toHaveBeenCalledTimes(2);++ const now = Date.now();+ const clock = jest.spyOn(Date, 'now').mockReturnValue(now + 3 * 60_000);+ await read();+ clock.mockRestore();+ expect(fetchModels).toHaveBeenCalledTimes(3);+ });++ describe('with a model-list lifetime in librechat.yaml', () => {+ let original: AppConfig;++ async function withLifetime(catalogModelsTtlMs: number) {+ appConfig = await dataSchemas.AppService({+ config: {+ ...structuredClone(YAML),+ endpoints: { ...structuredClone(YAML.endpoints), catalogModelsTtlMs },+ },+ });+ const { handlers, fetchModels } = await catalog({});+ const read = (query: Record<string, string> = {}) =>+ handlers.getConfigCatalog(mockReq({ query }), mockRes());+ return { read, fetchModels };+ }++ beforeEach(() => {+ original = appConfig;+ });++ afterEach(() => {+ appConfig = original;+ });++ it('keeps a scope model lists for that lifetime, or loads them on every read at zero', async () => {+ const long = await withLifetime(10 * 60_000);+ const now = Date.now();+ const clock = jest.spyOn(Date, 'now').mockReturnValue(now + 3 * 60_000);+ try {+ await long.read();+ expect(long.fetchModels).toHaveBeenCalledTimes(1);+ clock.mockReturnValue(now + 11 * 60_000);+ await long.read();+ expect(long.fetchModels).toHaveBeenCalledTimes(2);+ } finally {+ clock.mockRestore();+ }++ const none = await withLifetime(0);+ await none.read();+ expect(none.fetchModels).toHaveBeenCalledTimes(2);+ });++ it('keeps the lifetime librechat.yaml sets whatever a profile says', async () => {+ documents[1] = roleDocument('editors', { endpoints: { catalogModelsTtlMs: 0 } });+ const kept = await withLifetime(10 * 60_000);+ const editors = { principalType: ROLE, principalId: 'editors' };+ await kept.read(editors);+ await kept.read(editors);+ expect(kept.fetchModels).toHaveBeenCalledTimes(2);+ });+ });++ it('reports each duplicated custom endpoint name from the definition the endpoint config serves', async () => {+ const original = appConfig;+ const endpoint = (name: string, key: string, models: string[], iconURL?: string) => ({+ name,+ apiKey: `\${${key}}`,+ baseURL: `https://${key.toLowerCase()}.example.com/v1`,+ models: { default: models },+ ...(iconURL && { iconURL }),+ });+ appConfig = await dataSchemas.AppService({+ config: {+ ...structuredClone(YAML),+ endpoints: {+ custom: [+ endpoint('Ollama', 'FIRST_OLLAMA_KEY', ['first-model'], 'first.png'),+ endpoint('ollama', 'LAST_OLLAMA_KEY', ['last-model'], 'last.png'),+ endpoint('Kept', 'SERVED_KEY', ['kept-model']),+ { name: 'Kept', apiKey: '${UNSERVED_KEY}' },+ { name: 'Unserved', apiKey: '${FIRST_UNSERVED_KEY}' },+ { name: 'Unserved', baseURL: 'https://unserved.example.com/v1' },+ ],+ },+ },+ });+ try {+ const { body } = await catalog({});+ expect(body.endpoints?.ollama).toMatchObject({+ enabled: true,+ envVars: ['LAST_OLLAMA_KEY'],+ config: { iconURL: 'last.png' },+ });+ expect(body.endpoints).not.toHaveProperty('Ollama');+ expect(body.models?.ollama).toEqual({ served: ['last-model'], configured: ['last-model'] });+ expect(body.endpoints?.Kept).toMatchObject({ enabled: true, envVars: ['SERVED_KEY'] });+ expect(body.models?.Kept).toEqual({ served: ['kept-model'], configured: ['kept-model'] });+ expect(body.endpoints?.Unserved).toEqual({+ enabled: false,+ custom: true,+ envVars: [],+ reason: 'missing_api_key',+ });+ } finally {+ appConfig = original;+ }+ });++ it('lists the tools the server loaded, marking those it holds the credentials of', async () => {+ const { body } = await catalog({});+ expect(body.tools).toEqual([+ { pluginKey: 'calculator', name: 'Calculator', description: 'Math' },+ { pluginKey: 'image_gen_oai', name: 'Keyed', authenticated: true },+ ]);+ });++ it('leaves out each part the caller cannot read', async () => {+ const { body } = await catalog(+ {},+ {+ getReadableConfigSections: async () => ({+ broad: false,+ sections: new Set(['mcpServers']),+ }),+ },+ );+ expect(Object.keys(body)).toEqual(['principalType', 'principalId', 'mcpServers']);+ expect(JSON.stringify(body)).not.toContain(GATEWAY_SECRET);+ });++ it('answers 403 without config read access, 400 for a half-named principal, 404 for a missing one', async () => {+ const forbidden = await catalog({}, { hasAnyConfigReadAccess: async () => false });+ expect(forbidden.res.statusCode).toBe(403);+ expect((await catalog({ principalType: ROLE })).res.statusCode).toBe(400);+ expect((await catalog({ principalType: 'tenant', principalId: 'x' })).res.statusCode).toBe(400);+ const missing = await catalog({ principalType: ROLE, principalId: 'ghost' });+ expect(missing.res.statusCode).toBe(404);+ });++ it('names every endpoint credential overrides may reference under a built-in endpoint', () => {+ const listed = new Set(Object.values(BUILT_IN_ENDPOINT_ENV).flat());+ expect(ENDPOINT_CREDENTIAL_ENV_NAMES.filter((name) => !listed.has(name))).toEqual([]);+ });+});++describe('GET /env-status', () => {+ async function envStatus(extra: Partial<AdminConfigCatalogDeps> = {}) {+ const { deps } = await createDeps(extra);+ const res = mockRes();+ await createAdminConfigCatalogHandlers(deps).getEnvStatus(mockReq(), res);+ return { res, body: res.body as AdminConfigEnvStatusResponse };+ }++ beforeEach(() => {+ documents.push(+ roleDocument('profile', {+ endpoints: {+ custom: [{ name: 'Gateway', headers: { 'X-Profile': '${PROFILE_ONLY_NAME}' } }],+ },+ }),+ );+ process.env.PROFILE_ONLY_NAME = 'profile-value';+ process.env.OPENAI_API_KEY = 'user_provided';+ });++ it('reports whether each referenced name is set, never its value', async () => {+ const { res, body } = await envStatus();+ expect(res.statusCode).toBe(200);+ expect(body.vars.GATEWAY_KEY).toEqual({ set: true, sources: ['yaml'] });+ expect(body.vars.SEARXNG_INSTANCE_URL).toEqual({ set: false, sources: ['yaml'] });+ expect(body.vars.SERPER_API_KEY).toEqual({ set: false, sources: ['default'] });+ expect(body.vars.OPENAI_API_KEY).toEqual({+ set: true,+ userProvided: true,+ sources: ['endpoint'],+ });+ expect(body.vars.ANTHROPIC_USE_VERTEX).toEqual({ set: false, sources: ['endpoint'] });+ expect(body.vars.ALLOWLISTED_NAME).toEqual({ set: false, sources: ['allowlist'] });+ expect(body.vars.PROFILE_ONLY_NAME).toEqual({ set: true, sources: ['override'] });+ expect(body.vars).not.toHaveProperty('OPENAI_MODELS');+ const text = JSON.stringify(body);+ expect(text).not.toContain(GATEWAY_SECRET);+ expect(text).not.toContain('profile-value');+ });++ it('adds the names profiles reference only for broad managers, outside strict isolation', async () => {+ const reader = await envStatus({+ hasConfigCapability: async (_user, section) => section != null,+ });+ expect(reader.body.vars).not.toHaveProperty('PROFILE_ONLY_NAME');+ process.env.TENANT_ISOLATION_STRICT = 'true';+ const strict = await envStatus();+ expect(strict.body.vars).not.toHaveProperty('PROFILE_ONLY_NAME');+ });++ it('shows a section-scoped reader only the names of the sections it can read', async () => {+ const { body } = await envStatus({+ getReadableConfigSections: async () => ({ broad: false, sections: new Set(['webSearch']) }),+ });+ expect(body.vars.SEARXNG_INSTANCE_URL).toBeDefined();+ expect(body.vars).not.toHaveProperty('GATEWAY_KEY');+ expect(body.vars).not.toHaveProperty('OPENAI_API_KEY');+ expect(body.vars).not.toHaveProperty('ALLOWLISTED_NAME');+ });++ it('never lists an infrastructure secret, whatever references it', async () => {+ const original = appConfig;+ appConfig = await dataSchemas.AppService({+ config: { ...structuredClone(YAML), ocr: { apiKey: '${CREDS_KEY}' } },+ });+ try {+ const { body } = await envStatus();+ expect(body.vars).not.toHaveProperty('CREDS_KEY');+ } finally {+ appConfig = original;+ }+ });++ it('answers 403 without config read access', async () => {+ const { res } = await envStatus({ hasAnyConfigReadAccess: async () => false });+ expect(res.statusCode).toBe(403);+ });+});diff --git a/packages/api/src/admin/catalog.ts b/packages/api/src/admin/catalog.tsnew file mode 100644index 0000000000..b126f0e2d6--- /dev/null+++ b/packages/api/src/admin/catalog.ts@@ -0,0 +1,642 @@+import { createHash } from 'node:crypto';+import { logger, isBaseConfigPrincipal, BASE_CONFIG_PRINCIPAL_ID } from '@librechat/data-schemas';+import {+ AuthType,+ PrincipalType,+ EModelEndpoint,+ isSensitiveEnvVar,+ extractEnvVariable,+ getEnabledEndpoints,+ normalizeEndpointName,+ isProcessMCPServerConfig,+} from 'librechat-data-provider';+import type {+ AppConfig,+ ConfigRecord,+ ConfigSection,+ AdminCatalogTool,+ AdminConfigEnvSource,+ AdminConfigEnvStatus,+ AdminCatalogModels,+ AdminCatalogEndpoint,+ AdminCatalogMcpServer,+ AdminCatalogEndpointReason,+ AdminConfigCatalogResponse,+ AdminConfigEnvStatusResponse,+} from '@librechat/data-schemas';+import type {+ TPlugin,+ TEndpoint,+ TModelsConfig,+ TCustomConfig,+ TEndpointsConfig,+} from 'librechat-data-provider';+import type { Response } from 'express';+import type { CapabilityUser } from '~/middleware/capabilities';+import type { GetAppConfigOptions } from '~/app/service';+import type { ManifestTool } from '~/tools/available';+import type { ServerRequest } from '~/types/http';+import {+ parseEnvAllowlist,+ collectEnvReferenceSections,+ collectDefaultEnvReferenceSections,+} from '~/app/allowlist';+import {+ canReadSection,+ getCapabilityUser,+ validatePrincipalType,+ principalNotFoundResponse,+} from './config';+import { resolveServedCustomEndpoints } from '~/endpoints/custom/config';+import { listAvailableTools } from '~/tools/available';+import { getSafeErrorMetadata } from '~/utils/errors';+import { resolveConfigSecret } from './secrets';+import { getCatalogModelsTtlMs } from './meta';+import { isUserProvided } from '~/utils';++/**+ * Who a scope's endpoint, model and tool lists are resolved for: the scope, never a user. It has+ * no user id, so nothing reads a user's stored keys, and header templates that name a user+ * resolve to nothing instead of to the admin's identity.+ */+export interface CatalogScopeUser {+ tenantId?: string;+ role?: string;+}++/** The request-like argument the endpoint and model loaders read: a scope's config and user. */+export interface CatalogScopeRequest {+ config: AppConfig;+ user: CatalogScopeUser;+}++export interface AdminConfigCatalogDeps {+ hasAnyConfigReadAccess: (user: CapabilityUser) => Promise<boolean>;+ getReadableConfigSections: (+ user: CapabilityUser,+ sections: ConfigSection[],+ ) => Promise<{ broad: boolean; sections: Set<string> }>;+ hasConfigCapability: (+ user: CapabilityUser,+ section: ConfigSection | null,+ verb?: 'manage' | 'read',+ ) => Promise<boolean>;+ /** The resolved config, as the app config service serves it (secrets decrypted). */+ getAppConfig: (options: GetAppConfigOptions) => Promise<AppConfig>;+ /** What `GET /api/endpoints` serves for a request's config. */+ getEndpointsConfig: (req: CatalogScopeRequest) => Promise<TEndpointsConfig>;+ /** The built-in endpoints' models for a request's config (`loadDefaultModels`). */+ loadDefaultModels: (req: CatalogScopeRequest) => Promise<TModelsConfig>;+ /** The configured and custom endpoints' models for a request's config (`loadConfigModels`). */+ loadConfigModels: (req: CatalogScopeRequest) => Promise<TModelsConfig>;+ /** The tool definitions the server loaded (the tool cache). */+ getCachedTools?: () => Promise<Record<string, unknown> | null | undefined>;+ /** The tool manifest and its toolkits (`api/app/clients/tools`). */+ toolManifest?: ManifestTool[];+ toolkits?: TPlugin[];+ /** Whether the principal exists in the caller's tenant partition (`principalExists`). */+ principalExists?: (principalType: PrincipalType, principalId: string) => Promise<boolean>;+ /** Every config document of the caller's partition, for the env names profiles reference. */+ listAllConfigs?: () => Promise<ConfigRecord[]>;+ /** `CONFIG_OVERRIDE_ENV_ALLOWLIST`, as the app config service is given it. */+ overrideEnvAllowlist?: string;+}++/**+ * The env names that decide whether each built-in endpoint is served, and with which credentials+ * or base URL: every name `api/server/services/Config/EndpointService.js` and+ * `loadAsyncEndpoints.js` read (`ANTHROPIC_USE_VERTEX` serves Anthropic without a key). Every+ * name overrides may reference as an endpoint credential (`ENDPOINT_CREDENTIAL_ENV_NAMES`) is+ * here.+ */+export const BUILT_IN_ENDPOINT_ENV: Readonly<Record<string, readonly string[]>> = {+ [EModelEndpoint.openAI]: ['OPENAI_API_KEY', 'OPENAI_REVERSE_PROXY'],+ [EModelEndpoint.agents]: [],+ [EModelEndpoint.assistants]: ['ASSISTANTS_API_KEY', 'ASSISTANTS_BASE_URL'],+ [EModelEndpoint.azureAssistants]: ['AZURE_ASSISTANTS_API_KEY', 'AZURE_ASSISTANTS_BASE_URL'],+ [EModelEndpoint.azureOpenAI]: ['AZURE_API_KEY', 'AZURE_OPENAI_BASEURL'],+ [EModelEndpoint.google]: ['GOOGLE_KEY', 'GOOGLE_SERVICE_KEY_FILE'],+ [EModelEndpoint.anthropic]: ['ANTHROPIC_API_KEY', 'ANTHROPIC_USE_VERTEX'],+ [EModelEndpoint.bedrock]: [+ 'BEDROCK_AWS_BEARER_TOKEN',+ 'BEDROCK_AWS_ACCESS_KEY_ID',+ 'BEDROCK_AWS_SECRET_ACCESS_KEY',+ 'BEDROCK_AWS_SESSION_TOKEN',+ 'BEDROCK_AWS_PROFILE',+ 'BEDROCK_AWS_DEFAULT_REGION',+ ],+};++/** Built-in endpoints whose configured `models` list replaces the provider's list. */+const MODEL_LIST_ENDPOINTS: readonly string[] = [+ EModelEndpoint.openAI,+ EModelEndpoint.google,+ EModelEndpoint.anthropic,+ EModelEndpoint.bedrock,+];++/** Most scopes whose model lists are kept at once; the oldest is dropped first. */+const MAX_CACHED_SCOPES = 100;++const ENV_REFERENCE = /\$\{([^}]+)\}/g;++type CachedModels = { expires: number; models: Promise<Record<string, AdminCatalogModels>> };++function isSet(value: string | undefined): boolean {+ return value != null && value.trim() !== '';+}++function namesOf(models: unknown): string[] | undefined {+ if (!Array.isArray(models)) {+ return undefined;+ }+ return models.flatMap((model) => {+ if (typeof model === 'string') {+ return [model];+ }+ const name = (model as { name?: unknown } | null)?.name;+ return typeof name === 'string' ? [name] : [];+ });+}++function referencedEnvNames(...values: unknown[]): string[] {+ const names = new Set<string>();+ for (const value of values) {+ if (typeof value === 'string') {+ for (const match of value.matchAll(ENV_REFERENCE)) {+ names.add(match[1]);+ }+ }+ }+ return [...names];+}++/** Whether a custom endpoint fetches its models with a key and URL the server holds. */+function fetchesWithServerKey(endpoint: Partial<TEndpoint>): boolean {+ return (+ endpoint.models?.fetch === true &&+ !isUserProvided(resolveConfigSecret(endpoint.apiKey) ?? '') &&+ !isUserProvided(extractEnvVariable(endpoint.baseURL ?? ''))+ );+}++function getCustomEndpoints(config: AppConfig): TEndpoint[] {+ const custom = config.endpoints?.custom;+ return Array.isArray(custom) ? (custom as TEndpoint[]) : [];+}++/**+ * The definition the catalog reports for each custom endpoint name: the one the endpoint config+ * serves under that name (`resolveServedCustomEndpoints`), or the last definition of a name it+ * serves none of.+ */+function resolveCustomEndpoints(config: AppConfig): Map<string, Partial<TEndpoint>> {+ const custom = getCustomEndpoints(config);+ const served = resolveServedCustomEndpoints(custom);+ const resolved = new Map<string, Partial<TEndpoint>>();+ for (const endpoint of custom) {+ const name = normalizeEndpointName(endpoint.name ?? '');+ if (name !== '') {+ resolved.set(name, served.get(name) ?? endpoint);+ }+ }+ return resolved;+}++/** `config` without the model lists of built-in endpoints, so their defaults load instead. */+function withoutModelLists(config: AppConfig): AppConfig {+ const endpoints = config.endpoints;+ if (!endpoints) {+ return config;+ }+ const next: Record<string, unknown> = { ...endpoints };+ for (const name of MODEL_LIST_ENDPOINTS) {+ const entry = next[name] as { models?: unknown } | undefined;+ if (entry != null && Array.isArray(entry.models)) {+ const { models: _configured, ...rest } = entry;+ next[name] = rest;+ }+ }+ return { ...config, endpoints: next as AppConfig['endpoints'] };+}++/**+ * `config` with the configured list left out of each custom endpoint that fetches its models with+ * the server's key, so the loader reports what the fetch returns rather than the fallback.+ */+function withoutFetchFallbacks(config: AppConfig): AppConfig {+ const custom = getCustomEndpoints(config);+ if (!custom.some(fetchesWithServerKey)) {+ return config;+ }+ return {+ ...config,+ endpoints: {+ ...config.endpoints,+ custom: custom.map((endpoint) => {+ if (!fetchesWithServerKey(endpoint)) {+ return endpoint;+ }+ const { default: _fallback, ...models } = endpoint.models ?? {};+ return { ...endpoint, models: { ...models, fetch: true } };+ }),+ } as AppConfig['endpoints'],+ };+}++/** Why a custom endpoint the endpoint config leaves out is not served. */+function getCustomReason(endpoint: Partial<TEndpoint>): AdminCatalogEndpointReason {+ if (!endpoint.apiKey) {+ return 'missing_api_key';+ }+ if (!endpoint.baseURL) {+ return 'missing_base_url';+ }+ return 'missing_models';+}++function getMcpTransport(server: Record<string, unknown>): AdminCatalogMcpServer['transport'] {+ if (isProcessMCPServerConfig(server)) {+ return 'stdio';+ }+ switch (server.type) {+ case 'streamable-http':+ case 'http':+ return 'streamable-http';+ case 'websocket':+ return 'websocket';+ case 'sse':+ return 'sse';+ default:+ return typeof server.url === 'string' && /^wss?:\/\//i.test(server.url) ? 'websocket' : 'sse';+ }+}++/** The MCP servers a scope's config defines (librechat.yaml's and its profiles'), unhidden. */+function listMcpServers(config: AppConfig): AdminCatalogMcpServer[] {+ const servers = (config.mcpConfig ?? {}) as Record<string, unknown>;+ const yaml = (config.config?.mcpServers ?? {}) as Record<string, unknown>;+ return Object.entries(servers).flatMap(([name, value]) => {+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {+ return [];+ }+ const server = value as Record<string, unknown>;+ return [+ {+ name,+ ...(typeof server.title === 'string' && { title: server.title }),+ transport: getMcpTransport(server),+ source: Object.prototype.hasOwnProperty.call(yaml, name) ? 'yaml' : 'override',+ processBacked: isProcessMCPServerConfig(server),+ },+ ];+ });+}++function toCatalogTool(tool: TPlugin): AdminCatalogTool {+ return {+ pluginKey: tool.pluginKey,+ name: tool.name,+ ...(tool.description != null && { description: tool.description }),+ ...(tool.icon != null && { icon: tool.icon }),+ ...(tool.authenticated === true && { authenticated: true }),+ ...(tool.toolkit === true && { toolkit: true }),+ };+}++/** The `getAppConfig` options that resolve a scope as its users get it, never from a cache. */+function toScopeOptions(+ principalType: PrincipalType,+ principalId: string,+ tenantId: string | undefined,+): GetAppConfigOptions {+ const options: GetAppConfigOptions = {+ tenantId,+ bypassOverrideCache: true,+ skipRuntimeAugmentation: true,+ };+ if (isBaseConfigPrincipal({ principalType, principalId })) {+ return options;+ }+ if (principalType === PrincipalType.ROLE) {+ return { ...options, role: principalId };+ }+ return { ...options, resolvedPrincipals: [{ principalType, principalId }] };+}++/**+ * The deployment views the admin panel builds its pickers and status badges from, resolved for a+ * scope instead of for the signed-in admin: `GET /catalog` (`catalogApi`) and `GET /env-status`+ * (`envStatus`). Neither runs the end-user routes' browser checks, so a server-side client can+ * call them without forwarding a User-Agent.+ */+export function createAdminConfigCatalogHandlers(deps: AdminConfigCatalogDeps): {+ getConfigCatalog: (req: ServerRequest, res: Response) => Promise<Response>;+ getEnvStatus: (req: ServerRequest, res: Response) => Promise<Response>;+} {+ const {+ hasAnyConfigReadAccess,+ getReadableConfigSections,+ hasConfigCapability,+ getAppConfig,+ getEndpointsConfig,+ loadDefaultModels,+ loadConfigModels,+ getCachedTools,+ toolManifest = [],+ toolkits = [],+ principalExists,+ listAllConfigs,+ overrideEnvAllowlist,+ } = deps;++ const envAllowlist = parseEnvAllowlist(overrideEnvAllowlist);+ const modelsCache = new Map<string, CachedModels>();++ function buildEndpoints(+ config: AppConfig,+ served: TEndpointsConfig,+ ): Record<string, AdminCatalogEndpoint> {+ const listed = new Set(getEnabledEndpoints());+ const listsEndpoints = isSet(process.env.ENDPOINTS);+ const endpoints: Record<string, AdminCatalogEndpoint> = {};+ for (const [name, envVars] of Object.entries(BUILT_IN_ENDPOINT_ENV)) {+ const entry = served?.[name];+ endpoints[name] = {+ enabled: entry != null,+ custom: false,+ envVars: [...envVars],+ ...(entry != null+ ? { config: entry }+ : { reason: listsEndpoints && !listed.has(name) ? 'not_listed' : 'missing_credentials' }),+ };+ }+ for (const [name, endpoint] of resolveCustomEndpoints(config)) {+ const entry = served?.[name];+ endpoints[name] = {+ enabled: entry != null,+ custom: true,+ envVars: referencedEnvNames(endpoint.apiKey, endpoint.baseURL),+ ...(entry != null ? { config: entry } : { reason: getCustomReason(endpoint) }),+ };+ }+ return endpoints;+ }++ async function loadModels(+ request: CatalogScopeRequest,+ ): Promise<Record<string, AdminCatalogModels>> {+ const [defaults, configured] = await Promise.all([+ loadDefaultModels({ ...request, config: withoutModelLists(request.config) }),+ loadConfigModels({ ...request, config: withoutFetchFallbacks(request.config) }),+ ]);+ const custom = resolveCustomEndpoints(request.config);+ const models: Record<string, AdminCatalogModels> = {};+ for (const name of new Set([+ ...Object.keys(defaults ?? {}),+ ...Object.keys(configured ?? {}),+ ])) {+ const endpoint = custom.get(name);+ const loaded = configured?.[name];+ if (endpoint == null) {+ const fallback = defaults?.[name] ?? [];+ models[name] = {+ served: loaded ?? fallback,+ ...(loaded && { configured: loaded }),+ defaults: fallback,+ };+ continue;+ }+ const list = namesOf(endpoint.models?.default);+ if (!fetchesWithServerKey(endpoint)) {+ models[name] = { served: loaded ?? list ?? [], ...(list && { configured: list }) };+ continue;+ }+ const fetched = loaded ?? [];+ models[name] = {+ served: fetched.length > 0 ? fetched : (list ?? []),+ ...(list && { configured: list }),+ defaults: fetched,+ };+ }+ return models;+ }++ /**+ * A scope's model lists, reused for the lifetime librechat.yaml gives them+ * (`getCatalogModelsTtlMs`, none at `0`) while its endpoint config (and so every provider+ * request) is the same: a save that changes an endpoint resolves anew, and reads of one scope in+ * a row share one round of provider requests. Only a hash of the config is kept.+ */+ function getModels(+ request: CatalogScopeRequest,+ scope: string,+ ): Promise<Record<string, AdminCatalogModels>> {+ const ttlMs = getCatalogModelsTtlMs(request.config);+ if (ttlMs === 0) {+ return loadModels(request);+ }+ const key = createHash('sha256')+ .update(JSON.stringify([scope, request.user, request.config.endpoints ?? null]))+ .digest('hex');+ const now = Date.now();+ const cached = modelsCache.get(key);+ if (cached && cached.expires > now) {+ return cached.models;+ }+ modelsCache.delete(key);+ if (modelsCache.size >= MAX_CACHED_SCOPES) {+ const oldest = modelsCache.keys().next().value;+ if (oldest !== undefined) {+ modelsCache.delete(oldest);+ }+ }+ const models = loadModels(request);+ modelsCache.set(key, { expires: now + ttlMs, models });+ models.catch(() => {+ if (modelsCache.get(key)?.models === models) {+ modelsCache.delete(key);+ }+ });+ return models;+ }++ async function listTools(config: AppConfig): Promise<AdminCatalogTool[]> {+ const toolDefinitions = (await getCachedTools?.()) ?? config.availableTools;+ return listAvailableTools({+ manifest: toolManifest,+ toolkits,+ toolDefinitions,+ githubCompare: config.githubCompare,+ }).map(toCatalogTool);+ }++ /**+ * GET /catalog?principalType=&principalId= — the endpoints, models, MCP servers and tools a+ * scope serves (Base when no principal is named), resolved as `getAppConfig` resolves it for+ * that scope from the stored documents, never the override cache. Model lists are never loaded+ * with a user's stored key. A part is left out unless the caller can read its section.+ */+ async function getConfigCatalog(req: ServerRequest, res: Response): Promise<Response> {+ try {+ const query = req.query as Record<string, unknown>;+ const principalType = query.principalType ?? PrincipalType.ROLE;+ const principalId = query.principalId ?? BASE_CONFIG_PRINCIPAL_ID;+ if (+ typeof principalType !== 'string' ||+ typeof principalId !== 'string' ||+ principalId === '' ||+ (query.principalType == null) !== (query.principalId == null) ||+ !validatePrincipalType(principalType)+ ) {+ return res.status(400).json({ error: 'Invalid principal', code: 'INVALID_PRINCIPAL' });+ }+ const user = getCapabilityUser(req);+ if (!user) {+ return res.status(401).json({ error: 'Authentication required' });+ }+ if (!(await hasAnyConfigReadAccess(user))) {+ return res.status(403).json({ error: 'Insufficient permissions' });+ }+ const isBase = isBaseConfigPrincipal({ principalType, principalId });+ const [readable, exists] = await Promise.all([+ getReadableConfigSections(user, [+ 'endpoints',+ 'mcpServers',+ 'filteredTools',+ 'includedTools',+ ]),+ isBase || !principalExists ? true : principalExists(principalType, principalId),+ ]);+ if (!exists) {+ return principalNotFoundResponse(res);+ }++ const config = await getAppConfig(toScopeOptions(principalType, principalId, user.tenantId));+ const request: CatalogScopeRequest = {+ config,+ user: {+ tenantId: user.tenantId,+ ...(principalType === PrincipalType.ROLE && !isBase && { role: principalId }),+ },+ };+ const readsEndpoints = canReadSection(readable, 'endpoints');+ const readsTools =+ canReadSection(readable, 'filteredTools') || canReadSection(readable, 'includedTools');+ const [served, models, tools] = await Promise.all([+ readsEndpoints ? getEndpointsConfig(request) : undefined,+ readsEndpoints ? getModels(request, `${principalType}:${principalId}`) : undefined,+ readsTools ? listTools(config) : undefined,+ ]);+ const body: AdminConfigCatalogResponse = {+ principalType,+ principalId,+ ...(served !== undefined && { endpoints: buildEndpoints(config, served) }),+ ...(models !== undefined && { models }),+ ...(tools !== undefined && { tools }),+ ...(canReadSection(readable, 'mcpServers') && { mcpServers: listMcpServers(config) }),+ };+ return res.status(200).json(body);+ } catch (error) {+ logger.error('[adminConfig] getConfigCatalog error:', getSafeErrorMetadata(error));+ return res.status(500).json({ error: 'Failed to load config catalog' });+ }+ }++ /** The env names stored profiles reference, by section; read only for broad managers. */+ async function getOverrideReferences(user: CapabilityUser): Promise<Map<string, Set<string>>> {+ if (+ !listAllConfigs ||+ process.env.TENANT_ISOLATION_STRICT === 'true' ||+ !(await hasConfigCapability(user, null, 'manage'))+ ) {+ return new Map();+ }+ const references = new Map<string, Set<string>>();+ for (const config of await listAllConfigs()) {+ for (const [name, sections] of collectEnvReferenceSections(config.overrides ?? {})) {+ const held = references.get(name) ?? new Set<string>();+ sections.forEach((section) => held.add(section));+ references.set(name, held);+ }+ }+ return references;+ }++ /**+ * GET /env-status — whether each env name the deployment's config uses is set on this server,+ * never its value: the names librechat.yaml references, the defaults it fills in (web search,+ * OCR), the built-in endpoints' credentials, `CONFIG_OVERRIDE_ENV_ALLOWLIST`, and, for broad+ * `manage:configs` holders outside strict tenant isolation, the names stored profiles+ * reference. A name used only in sections the caller cannot read is left out, as are the names+ * the allowlist and profiles add for a caller without broad read access, and infrastructure+ * secrets (`CREDS_KEY`, ...) whatever references them.+ */+ async function getEnvStatus(req: ServerRequest, res: Response): Promise<Response> {+ try {+ const user = getCapabilityUser(req);+ if (!user) {+ return res.status(401).json({ error: 'Authentication required' });+ }+ if (!(await hasAnyConfigReadAccess(user))) {+ return res.status(403).json({ error: 'Insufficient permissions' });+ }+ const [baseConfig, overrides] = await Promise.all([+ getAppConfig({ tenantId: user.tenantId, baseOnly: true }),+ getOverrideReferences(user),+ ]);+ const yaml: Partial<TCustomConfig> = baseConfig.config ?? {};+ const uses = new Map<string, { sources: Set<AdminConfigEnvSource>; sections: Set<string> }>();+ const add = (name: string, source: AdminConfigEnvSource, sections: Iterable<string>) => {+ if (isSensitiveEnvVar(name)) {+ return;+ }+ const use = uses.get(name) ?? { sources: new Set(), sections: new Set() };+ use.sources.add(source);+ for (const section of sections) {+ use.sections.add(section);+ }+ uses.set(name, use);+ };+ for (const [name, sections] of collectEnvReferenceSections(yaml)) {+ add(name, 'yaml', sections);+ }+ for (const [name, sections] of collectDefaultEnvReferenceSections(yaml)) {+ add(name, 'default', sections);+ }+ for (const name of Object.values(BUILT_IN_ENDPOINT_ENV).flat()) {+ add(name, 'endpoint', ['endpoints']);+ }+ for (const name of envAllowlist) {+ add(name, 'allowlist', []);+ }+ for (const [name, sections] of overrides) {+ add(name, 'override', sections);+ }++ const sections = new Set([...uses.values()].flatMap(({ sections: held }) => [...held]));+ const readable = await getReadableConfigSections(user, [...sections] as ConfigSection[]);+ const vars: Record<string, AdminConfigEnvStatus> = {};+ for (const [name, use] of [...uses].sort(([a], [b]) => a.localeCompare(b))) {+ const visible =+ readable.broad || [...use.sections].some((section) => canReadSection(readable, section));+ if (!visible) {+ continue;+ }+ const value = process.env[name];+ vars[name] = {+ set: isSet(value),+ ...(value?.trim() === AuthType.USER_PROVIDED && { userProvided: true }),+ sources: [...use.sources],+ };+ }+ const body: AdminConfigEnvStatusResponse = { vars };+ return res.status(200).json(body);+ } catch (error) {+ logger.error('[adminConfig] getEnvStatus error:', getSafeErrorMetadata(error));+ return res.status(500).json({ error: 'Failed to read env status' });+ }+ }++ return { getConfigCatalog, getEnvStatus };+}diff --git a/packages/api/src/admin/config.ts b/packages/api/src/admin/config.tsindex 1dcad3b809..f8123d97bc 100644--- a/packages/api/src/admin/config.ts+++ b/packages/api/src/admin/config.ts@@ -152,11 +152,11 @@ import {isWebSearchBindingPath,getWebSearchReentryIssues,} from './binding';+import { buildAdminConfigMeta, getCatalogModelsTtlMs } from './meta';import { createAdminAuditEmitter, configTarget } from './audit';import { DEFAULT_OVERRIDE_CACHE_TTL } from '~/app/service';import { getSafeErrorMetadata } from '~/utils/errors';import { mergeOverrideLayers } from '~/app/overrides';-import { buildAdminConfigMeta } from './meta';const UNSAFE_SEGMENTS = /(?:^|\.)(__[\w]*|constructor|prototype)(?:\.|$)/;const MAX_PATCH_ENTRIES = 100;@@ -704,7 +704,7 @@ const CONFIG_PRINCIPAL_TYPES = new Set([PrincipalType.ROLE,]);-function validatePrincipalType(value: string): value is PrincipalType {+export function validatePrincipalType(value: string): value is PrincipalType {return CONFIG_PRINCIPAL_TYPES.has(value as PrincipalType);}@@ -718,7 +718,7 @@ function invalidPriorityResponse(res: Response): Response {return res.status(400).json({ error: INVALID_PRIORITY_ERROR, code: 'INVALID_PRIORITY' });}-function principalNotFoundResponse(res: Response): Response {+export function principalNotFoundResponse(res: Response): Response {return res.status(404).json({ error: 'Principal not found', code: 'PRINCIPAL_NOT_FOUND' });}@@ -740,7 +740,7 @@ function principalModel(type: PrincipalType): PrincipalModel {}}-function getCapabilityUser(req: ServerRequest): CapabilityUser | null {+export function getCapabilityUser(req: ServerRequest): CapabilityUser | null {if (!req.user) {return null;}@@ -786,7 +786,7 @@ const APP_CONFIG_FIELD_TO_SECTION: Readonly<Record<string, string>> = {mcpConfig: 'mcpServers',};-type ReadableSections = { broad: boolean; sections: ReadonlySet<string> };+export type ReadableSections = { broad: boolean; sections: ReadonlySet<string> };/** Every section `configSchema` defines: a write resolves read access to all of them before it commits. */const CONFIG_SCHEMA_SECTIONS = Object.keys(configSchema.shape) as ConfigSection[];@@ -794,12 +794,12 @@ const FULL_READ_ACCESS: ReadableSections = { broad: true, sections: new Set() };/** Shows no section: an assign-only write stores an empty document. */const NO_READ_ACCESS: ReadableSections = { broad: false, sections: new Set() };-function canReadSection(readable: ReadableSections, section: string): boolean {+export function canReadSection(readable: ReadableSections, section: string): boolean {return readable.broad || readable.sections.has(section);}/** Strips every top-level key not in `preserveKeys` that `canRead` rejects. */-function filterSectionsByReadAccess<T extends Record<string, unknown>>(+export function filterSectionsByReadAccess<T extends Record<string, unknown>>(obj: T,canRead: (section: string) => boolean,preserveKeys: Set<string> = new Set(),@@ -813,7 +813,7 @@ function filterSectionsByReadAccess<T extends Record<string, unknown>>(return result as T;}-function filterConfigDocForReadAccess<T extends ConfigRecord>(+export function filterConfigDocForReadAccess<T extends ConfigRecord>(config: T,readable: ReadableSections,): T {@@ -856,7 +856,7 @@ function filterAppConfigForReadAccess(appConfig: AppConfig, readable: ReadableSe}/** All section names a config document's overrides/tombstones could reference. */-function collectConfigSections(config: ConfigRecord): string[] {+export function collectConfigSections(config: ConfigRecord): string[] {return [...Object.keys(config.overrides ?? {}),...(config.tombstones ?? []).map(getTopLevelSection),@@ -875,7 +875,7 @@ function collectAppConfigSections(appConfig: AppConfig): string[] {type ConfigResponse = ConfigRecord & { revision: ConfigRevision };/** The document as the admin API returns it: secrets redacted, with its revision. */-function redactConfigForResponse(config: ConfigRecord): ConfigResponse {+export function redactConfigForResponse(config: ConfigRecord): ConfigResponse {const safeConfig = JSON.parse(JSON.stringify(config)) as ConfigRecord;if (safeConfig.overrides) {safeConfig.overrides = withoutStoredSecretBindings(safeConfig.overrides);@@ -1985,12 +1985,6 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {logPrefix: '[adminConfig]',});- const meta = buildAdminConfigMeta({- maxPatchEntries: MAX_PATCH_ENTRIES,- maxChangeOps: MAX_CONFIG_CHANGE_OPS,- overrideCacheTtlMs,- });-function readStoredConfig(principalType: PrincipalType,principalId: string,@@ -2545,6 +2539,13 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {return res.status(403).json({ error: 'Insufficient permissions' });}+ const baseConfig = await getBaseAppConfig(user.tenantId);+ const meta = buildAdminConfigMeta({+ maxPatchEntries: MAX_PATCH_ENTRIES,+ maxChangeOps: MAX_CONFIG_CHANGE_OPS,+ overrideCacheTtlMs,+ catalogModelsTtlMs: getCatalogModelsTtlMs(baseConfig),+ });return res.status(200).json(meta);} catch (error) {logger.error('[adminConfig] getConfigMeta error:', getSafeErrorMetadata(error));diff --git a/packages/api/src/admin/index.ts b/packages/api/src/admin/index.tsindex 2e72421907..19e2c40611 100644--- a/packages/api/src/admin/index.ts+++ b/packages/api/src/admin/index.ts@@ -1,4 +1,6 @@export { createAdminConfigHandlers } from './config';+export { createAdminConfigReadHandlers } from './resolved';+export { createAdminConfigCatalogHandlers, BUILT_IN_ENDPOINT_ENV } from './catalog';export { createAdminLangfuseHandlers } from './langfuse';export { createAdminGrantsHandlers } from './grants';export { createAdminGroupsHandlers } from './groups';@@ -17,6 +19,8 @@ export {} from './audit';export { resolveConfigSecret, redactConfigSecretMaps } from './secrets';export type { AdminConfigDeps } from './config';+export type { AdminConfigReadDeps } from './resolved';+export type { AdminConfigCatalogDeps, CatalogScopeRequest, CatalogScopeUser } from './catalog';export type { AdminLangfuseDeps } from './langfuse';export type { AdminGrantsDeps, GrantPrincipalType } from './grants';export type { AdminGroupsDeps } from './groups';diff --git a/packages/api/src/admin/langfuse.handler.spec.ts b/packages/api/src/admin/langfuse.handler.spec.tsindex 6a97d9b63a..b99f0608b6 100644--- a/packages/api/src/admin/langfuse.handler.spec.ts+++ b/packages/api/src/admin/langfuse.handler.spec.ts@@ -1,6 +1,10 @@process.env.CREDS_KEY =process.env.CREDS_KEY ?? '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';+import type {+ TLangfuseUnavailableReason,+ TLangfuseUnavailableResponse,+} from 'librechat-data-provider';import type { Response } from 'express';import type { ServerRequest } from '~/types/http';@@ -123,6 +127,15 @@ function rehydrate(fields: Record<string, unknown>): Record<string, unknown> {return langfuse;}+/** The 404 a deployment without Langfuse connection settings answers, naming why. */+function unavailable(reason: TLangfuseUnavailableReason): TLangfuseUnavailableResponse {+ return {+ error: 'Langfuse connection settings are not available',+ code: 'LANGFUSE_UNAVAILABLE',+ reason,+ };+}+describe('createAdminLangfuseHandlers', () => {describe('connection availability gate', () => {it('rejects connection reads when deployment fanout is disabled', async () => {@@ -133,7 +146,7 @@ describe('createAdminLangfuseHandlers', () => {await handlers.getConnection(mockReq(), res);expect(res.statusCode).toBe(404);- expect(res.body).toEqual({ error: 'Langfuse connection settings are not available' });+ expect(res.body).toEqual(unavailable('fanout_disabled'));expect(deps.findConfigByPrincipal).not.toHaveBeenCalled();});@@ -148,7 +161,7 @@ describe('createAdminLangfuseHandlers', () => {);expect(res.statusCode).toBe(404);- expect(res.body).toEqual({ error: 'Langfuse connection settings are not available' });+ expect(res.body).toEqual(unavailable('fanout_disabled'));expect(deps.patchConfigFields).not.toHaveBeenCalled();});@@ -160,7 +173,7 @@ describe('createAdminLangfuseHandlers', () => {await handlers.getConnection(mockReq(), res);expect(res.statusCode).toBe(404);- expect(res.body).toEqual({ error: 'Langfuse connection settings are not available' });+ expect(res.body).toEqual(unavailable('fanout_disabled'));expect(deps.findConfigByPrincipal).not.toHaveBeenCalled();});@@ -176,7 +189,7 @@ describe('createAdminLangfuseHandlers', () => {);expect(res.statusCode).toBe(404);- expect(res.body).toEqual({ error: 'Langfuse connection settings are not available' });+ expect(res.body).toEqual(unavailable('fanout_disabled'));expect(deps.findConfigByPrincipal).not.toHaveBeenCalled();expect(global.fetch).not.toHaveBeenCalled();});@@ -189,7 +202,7 @@ describe('createAdminLangfuseHandlers', () => {await handlers.getConnection(mockReq(), res);expect(res.statusCode).toBe(404);- expect(res.body).toEqual({ error: 'Langfuse connection settings are not available' });+ expect(res.body).toEqual(unavailable('tenant_export_disabled'));expect(deps.findConfigByPrincipal).not.toHaveBeenCalled();});@@ -217,17 +230,22 @@ describe('createAdminLangfuseHandlers', () => {await handlers.getConnection(mockReq(), res);expect(res.statusCode).toBe(404);+ expect(res.body).toEqual(unavailable('env_credentials'));expect(deps.findConfigByPrincipal).not.toHaveBeenCalled();});- it('rejects settings when tracing is disabled', async () => {- process.env.LANGFUSE_TRACING_ENABLED = 'false';+ it.each([+ ['LANGFUSE_TRACING_ENABLED', 'false'],+ ['LANGFUSE_SAMPLE_RATE', '0'],+ ])('rejects settings when tracing is off (%s=%s)', async (key, value) => {+ process.env[key] = value;const { handlers, deps } = createHandlers();const res = mockRes();await handlers.getConnection(mockReq(), res);expect(res.statusCode).toBe(404);+ expect(res.body).toEqual(unavailable('tracing_disabled'));expect(deps.findConfigByPrincipal).not.toHaveBeenCalled();});});diff --git a/packages/api/src/admin/langfuse.ts b/packages/api/src/admin/langfuse.tsindex d519718485..29ae9305af 100644--- a/packages/api/src/admin/langfuse.ts+++ b/packages/api/src/admin/langfuse.ts@@ -12,6 +12,7 @@ import type {TLangfuseConnectionTestRequest,TLangfuseConnectionTestResponse,TLangfuseSessionLinkResponse,+ TLangfuseUnavailableResponse,} from 'librechat-data-provider';import type { ConfigRecord, MessageMethods } from '@librechat/data-schemas';import type { Response } from 'express';@@ -24,8 +25,8 @@ import {} from '~/langfuse/tenantDestinations';import { redirectPolicyFor, resolveLangfuseHeaders } from '~/langfuse/utils';import { decryptConfigSecret, encryptConfigSecretFields } from './secrets';+import { getLangfuseConnectionAvailability } from '~/langfuse/policy';import { scopeHeadersToDestination } from '~/langfuse/destinations';-import { isLangfuseConnectionAvailable } from '~/langfuse/policy';import { resolveLangfuseSession } from '~/langfuse/session';import { getSafeErrorMetadata } from '~/utils/errors';import { createAdminAuditEmitter } from './audit';@@ -137,12 +138,22 @@ function getConnectionChanges(return change ? [change, ...additionalChanges] : ['updated'];}+/**+ * 404 on a deployment that offers no Langfuse connection, with the reason (`tracing_disabled`,+ * `env_credentials`, `fanout_disabled`, `tenant_export_disabled`): every route here is behind the+ * Langfuse capability, so only its holders learn why.+ */function rejectWhenConnectionUnavailable(res: Response): Response | undefined {- if (isLangfuseConnectionAvailable()) {+ const availability = getLangfuseConnectionAvailability();+ if (availability.available) {return undefined;}-- return res.status(404).json({ error: 'Langfuse connection settings are not available' });+ const body: TLangfuseUnavailableResponse = {+ error: 'Langfuse connection settings are not available',+ code: 'LANGFUSE_UNAVAILABLE',+ reason: availability.reason,+ };+ return res.status(404).json(body);}type LangfuseVerificationFailure = {diff --git a/packages/api/src/admin/meta.spec.ts b/packages/api/src/admin/meta.spec.tsindex 40e465e113..a0622d41c6 100644--- a/packages/api/src/admin/meta.spec.ts+++ b/packages/api/src/admin/meta.spec.ts@@ -36,6 +36,10 @@ import {} from 'librechat-data-provider';import type {AdminConfigFeatureFlag,+ AdminResolvedConfigResponse,+ AdminConfigCatalogResponse,+ AdminEffectiveConfigResponse,+ AdminConfigEnvStatusResponse,ConfigOverrideLayer,ConfigPrincipal,AdminConfigMeta,@@ -60,7 +64,9 @@ import { resolvePreAuthAppConfig, resolvePreLoginAppConfig } from '~/app/resolveimport { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';import { createConfigCacheInvalidation } from '~/app/invalidation';import { createMCPPolicyResolver } from '~/mcp/registry/policy';+import { createAdminConfigCatalogHandlers } from './catalog';import { createEnvReferencePolicy } from '~/app/allowlist';+import { createAdminConfigReadHandlers } from './resolved';import { resolveTitleConfig } from '~/endpoints/config';import { createAppConfigService } from '~/app/service';import { mergeOverrideLayers } from '~/app/overrides';@@ -277,6 +283,16 @@ describe('GET /api/admin/config/meta', () => {expect(res.body).toEqual({ error: 'Failed to get config meta' });});+ it('reports the catalog model-list lifetime librechat.yaml sets', async () => {+ const getAppConfig = jest+ .fn()+ .mockResolvedValue({ config: {}, endpoints: { catalogModelsTtlMs: 600_000 } });+ const res = mockRes();+ await createHandlers({ getAppConfig }).getConfigMeta(mockReq(), res);+ expect((res.body as AdminConfigMeta).limits.catalogModelsTtlMs).toBe(600_000);+ expect(getAppConfig).toHaveBeenCalledWith(expect.objectContaining({ baseOnly: true }));+ });+it('keeps its response keys stable', async () => {const { status, meta } = await getMeta();expect(status).toBe(200);@@ -286,10 +302,12 @@ describe('GET /api/admin/config/meta', () => {expect(Object.keys(meta.features).sort()).toEqual(['awaitedInvalidation','azureGroupSecrets',+ 'catalogApi','changesBatch','deterministicPrecedence','dottedKeys','envAllowlist',+ 'envStatus','expectedRevision','preAuthBaseOverrides','principalCheck',@@ -298,6 +316,7 @@ describe('GET /api/admin/config/meta', () => {'readFilteredWriteResponses','recordSecrets','reloadRoute',+ 'resolvedApi','roleRenameMovesProfile','secretRebinding','sectionAllowlist',@@ -309,6 +328,7 @@ describe('GET /api/admin/config/meta', () => {maxPatchEntries: 100,maxChangeOps: 1000,overrideCacheTtlMs: 60_000,+ catalogModelsTtlMs: 120_000,});expect(Object.keys(meta.rules).sort()).toEqual(['acceptedSections',@@ -350,6 +370,9 @@ describe('GET /api/admin/config/meta', () => {yamlSecretPreview: true,envAllowlist: true,secretRebinding: true,+ resolvedApi: true,+ catalogApi: true,+ envStatus: true,reloadRoute: true,});});@@ -1516,6 +1539,152 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {restated.body?.ignored === undefined);},+ async resolvedApi() {+ const yaml = { interface: { customWelcome: 'From YAML' } };+ const role = storedConfig({ interface: { customWelcome: 'From role', prompts: false } });+ const cache = new Map<string, unknown>();+ const service = createAppConfigService({+ loadBaseConfig: async () =>+ ({+ config: yaml,+ interfaceConfig: { ...yaml.interface },+ }) as Partial<AppConfig> as AppConfig,+ setCachedTools: async () => undefined,+ getCache: () => ({+ get: async (key: string) => cache.get(key),+ set: async (key: string, value: unknown) => void cache.set(key, value),+ delete: async (key: string) => cache.delete(key),+ }),+ cacheKeys: { APP_CONFIG: 'app_config' },+ getApplicableConfigs: async () => [role],+ getUserPrincipals: async () => [],+ });+ const handlers = createAdminConfigReadHandlers({+ findConfigByPrincipal: async (type, id) =>+ type === role.principalType && id === role.principalId ? role : null,+ hasAnyConfigReadAccess: async () => true,+ getReadableConfigSections: async (_user, sections) => ({+ broad: true,+ sections: new Set(sections),+ }),+ hasCapability: async () => true,+ resolveConfigLayers: service.resolveConfigLayers,+ findPartitionUser: async (id) => (id === 'member' ? { id, role: 'r1' } : null),+ getUserPrincipals: async () => [{ principalType: PrincipalType.ROLE, principalId: 'r1' }],+ getApplicableConfigs: async () => [role],+ });+ const resolved = mockRes();+ await handlers.getResolvedConfig(+ mockReq({ params: { principalType: 'role', principalId: 'r1' } }),+ resolved,+ );+ const effective = mockRes();+ await handlers.getEffectiveConfig(mockReq({ query: { userId: 'member' } }), effective);+ const outside = mockRes();+ await handlers.getEffectiveConfig(mockReq({ query: { userId: 'stranger' } }), outside);+ const body = resolved.body as unknown as AdminResolvedConfigResponse;+ return (+ resolved.statusCode === 200 &&+ body.yaml.interface?.customWelcome === 'From YAML' &&+ body.resolved.interface?.customWelcome === 'From role' &&+ JSON.stringify(body.layers[0]?.ignored) ===+ JSON.stringify([+ {+ path: 'interface.prompts',+ segments: ['interface', 'prompts'],+ reason: 'interface_permission',+ },+ ]) &&+ effective.statusCode === 200 &&+ (effective.body as unknown as AdminEffectiveConfigResponse).resolved.interface+ ?.customWelcome === 'From role' &&+ outside.statusCode === 404 &&+ outside.body?.code === 'USER_NOT_FOUND'+ );+ },+ async catalogApi() {+ const config = {+ config: { mcpServers: { docs: { url: 'https://docs.example.com/mcp' } } },+ mcpConfig: { docs: { url: 'https://docs.example.com/mcp' } },+ endpoints: { custom: [{ name: 'Gateway', apiKey: 'k', baseURL: 'https://g.example.com' }] },+ } as Partial<AppConfig> as AppConfig;+ const getAppConfig = jest.fn().mockResolvedValue(config);+ const loaderUsers: unknown[] = [];+ const handlers = createAdminConfigCatalogHandlers({+ hasAnyConfigReadAccess: async () => true,+ getReadableConfigSections: async (_user, sections) => ({+ broad: true,+ sections: new Set(sections),+ }),+ hasConfigCapability: async () => true,+ getAppConfig,+ getEndpointsConfig: async ({ config: scoped }) =>+ scoped === config+ ? { Gateway: { type: EModelEndpoint.custom, userProvide: false, order: 0 } }+ : {},+ loadDefaultModels: async ({ user }) => {+ loaderUsers.push(user);+ return { openAI: ['gpt-default'] };+ },+ loadConfigModels: async ({ user }) => {+ loaderUsers.push(user);+ return { Gateway: ['g-1'] };+ },+ });+ const res = mockRes();+ await handlers.getConfigCatalog(+ mockReq({ query: { principalType: 'role', principalId: 'editors' }, headers: {} }),+ res,+ );+ const body = res.body as unknown as AdminConfigCatalogResponse;+ return (+ res.statusCode === 200 &&+ getAppConfig.mock.calls[0]?.[0]?.role === 'editors' &&+ getAppConfig.mock.calls[0]?.[0]?.bypassOverrideCache === true &&+ body.endpoints?.Gateway?.enabled === true &&+ body.endpoints?.anthropic?.reason === 'missing_credentials' &&+ JSON.stringify(body.models?.openAI) ===+ JSON.stringify({ served: ['gpt-default'], defaults: ['gpt-default'] }) &&+ body.mcpServers?.[0]?.source === 'yaml' &&+ loaderUsers.length === 2 &&+ loaderUsers.every((user) => !Object.prototype.hasOwnProperty.call(user, 'id'))+ );+ },+ async envStatus() {+ process.env.META_PROBE_SET_NAME = 'probe-secret-value';+ delete process.env.META_PROBE_UNSET_NAME;+ try {+ const handlers = createAdminConfigCatalogHandlers({+ hasAnyConfigReadAccess: async () => true,+ getReadableConfigSections: async (_user, sections) => ({+ broad: true,+ sections: new Set(sections),+ }),+ hasConfigCapability: async () => true,+ getAppConfig: async () =>+ ({+ config: {+ ocr: { apiKey: '${META_PROBE_SET_NAME}', baseURL: '${META_PROBE_UNSET_NAME}' },+ },+ }) as Partial<AppConfig> as AppConfig,+ getEndpointsConfig: async () => ({}),+ loadDefaultModels: async () => ({}),+ loadConfigModels: async () => ({}),+ });+ const res = mockRes();+ await handlers.getEnvStatus(mockReq(), res);+ const { vars } = res.body as unknown as AdminConfigEnvStatusResponse;+ return (+ res.statusCode === 200 &&+ vars.META_PROBE_SET_NAME?.set === true &&+ vars.META_PROBE_UNSET_NAME?.set === false &&+ vars.OPENAI_API_KEY != null &&+ !JSON.stringify(res.body).includes('probe-secret-value')+ );+ } finally {+ delete process.env.META_PROBE_SET_NAME;+ }+ },async reloadRoute() {/** Two instances, each loading librechat.yaml into its own cache, on one pub/sub channel. */const subscribers = new Set<EventEmitter>();diff --git a/packages/api/src/admin/meta.ts b/packages/api/src/admin/meta.tsindex a92a8a14f5..23be8bbf92 100644--- a/packages/api/src/admin/meta.ts+++ b/packages/api/src/admin/meta.ts@@ -9,11 +9,20 @@ import {PROCESS_MCP_SERVER_FIELDS,INTERFACE_PERMISSION_FIELDS,BASE_PRINCIPAL_CONFIG_SECTIONS,+ DEFAULT_CATALOG_MODELS_TTL_MS,RUNTIME_CONFIG_INTERFACE_FIELDS,} from 'librechat-data-provider';-import type { AdminConfigFeatures, AdminConfigMeta } from '@librechat/data-schemas';+import type { AppConfig, AdminConfigFeatures, AdminConfigMeta } from '@librechat/data-schemas';import { getConfigSecretRules } from './secrets';+/**+ * How long `GET /catalog` reuses a scope's model lists while its endpoint config is unchanged:+ * `endpoints.catalogModelsTtlMs`, which only librechat.yaml sets, or two minutes.+ */+export function getCatalogModelsTtlMs(config: AppConfig | undefined): number {+ return config?.endpoints?.catalogModelsTtlMs ?? DEFAULT_CATALOG_MODELS_TTL_MS;+}+/*** The admin config behaviours this server has. A change flips its own flag when it wires the* behaviour; `meta.spec.ts` checks every flag against the behaviour itself, so a flag cannot@@ -39,6 +48,9 @@ export const ADMIN_CONFIG_FEATURES: Readonly<AdminConfigFeatures> = {yamlSecretPreview: true,envAllowlist: true,secretRebinding: true,+ resolvedApi: true,+ catalogApi: true,+ envStatus: true,reloadRoute: true,};diff --git a/packages/api/src/admin/resolved.integration.spec.ts b/packages/api/src/admin/resolved.integration.spec.tsnew file mode 100644index 0000000000..21a2febde4--- /dev/null+++ b/packages/api/src/admin/resolved.integration.spec.ts@@ -0,0 +1,460 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { PrincipalModel, PrincipalType } from 'librechat-data-provider';+import type {+ AppConfig,+ SystemCapability,+ AdminResolvedConfigResponse,+ AdminEffectiveConfigResponse,+} from '@librechat/data-schemas';+import type { DeepPartial, TCustomConfig } from 'librechat-data-provider';+import type { Response } from 'express';+import type { ServerRequest } from '~/types/http';++process.env.CREDS_KEY =+ process.env.CREDS_KEY ?? '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';+process.env.CREDS_IV = process.env.CREDS_IV ?? '0123456789abcdef0123456789abcdef';++type DataSchemas = typeof import('@librechat/data-schemas');+type Methods = ReturnType<DataSchemas['createMethods']>;+type ReadDeps = Parameters<typeof import('./resolved').createAdminConfigReadHandlers>[0];+type AppConfigService = ReturnType<typeof import('~/app/service').createAppConfigService>;++interface MockRes {+ statusCode: number;+ body: Record<string, unknown> | undefined;+ status: jest.Mock;+ json: jest.Mock;+}++const ROLE = PrincipalType.ROLE;+const YAML_KEY = 'yaml-gateway-literal-key';+const BASE_KEY = 'sk-base-entered-secret-9876';++const YAML: DeepPartial<TCustomConfig> = {+ version: '1.3.0',+ cache: true,+ interface: { customWelcome: 'Hello from YAML' },+ registration: { socialLogins: ['github'] },+ endpoints: {+ custom: [+ {+ name: 'Gateway',+ apiKey: YAML_KEY,+ baseURL: 'https://gateway.example.com/v1',+ models: { default: ['gpt-4o'] },+ },+ ],+ },+};++let mongoServer: MongoMemoryServer;+let dataSchemas: DataSchemas;+let methods: Methods;+let service: AppConfigService;+let createAdminConfigReadHandlers: typeof import('./resolved').createAdminConfigReadHandlers;+let createAdminConfigHandlers: typeof import('./config').createAdminConfigHandlers;++function mockReq(overrides: Record<string, unknown> = {}): ServerRequest {+ return {+ user: { id: 'admin-1', role: 'ADMIN', _id: { toString: () => 'admin-1' } },+ params: {},+ body: {},+ query: {},+ ...overrides,+ } as Partial<ServerRequest> as ServerRequest;+}++function mockRes(): Response & MockRes {+ const res: MockRes = {+ statusCode: 200,+ body: undefined,+ status: jest.fn((code: number) => {+ res.statusCode = code;+ return res;+ }),+ json: jest.fn((data: MockRes['body']) => {+ res.body = data;+ return res;+ }),+ };+ return res as Partial<Response> as Response & MockRes;+}++function readHandlers(extra: Partial<ReadDeps> = {}) {+ return createAdminConfigReadHandlers({+ findConfigByPrincipal: methods.findConfigByPrincipal,+ hasAnyConfigReadAccess: async () => true,+ getReadableConfigSections: async (_user, sections) => ({+ broad: true,+ sections: new Set(sections),+ }),+ hasCapability: async () => true,+ resolveConfigLayers: service.resolveConfigLayers,+ principalExists: methods.principalExists,+ findPartitionUser: methods.findPartitionUser,+ getUserPrincipals: methods.getUserPrincipals,+ getApplicableConfigs: methods.getApplicableConfigs,+ ...extra,+ });+}++/** The real admin write path, so stored documents carry what the API stores (encrypted keys). */+async function patch(+ principalType: string,+ principalId: string,+ entries: Array<{ fieldPath: string; value: unknown }>,+ priority?: number,+): Promise<void> {+ const handlers = createAdminConfigHandlers({+ listAllConfigs: methods.listAllConfigs,+ findConfigByPrincipal: methods.findConfigByPrincipal,+ writeConfigDocument: methods.writeConfigDocument,+ unsetConfigField: methods.unsetConfigField,+ deleteConfig: methods.deleteConfig,+ toggleConfigActiveTracked: methods.toggleConfigActiveTracked,+ principalExists: methods.principalExists,+ hasConfigCapability: async () => true,+ hasAnyConfigReadAccess: async () => true,+ hasCapability: async () => true,+ getAppConfig: service.getAppConfig,+ invalidateConfigCaches: service.clearOverrideCache,+ });+ const res = mockRes();+ await handlers.patchConfigField(+ mockReq({ params: { principalType, principalId }, body: { entries, priority } }),+ res,+ );+ expect(res.statusCode).toBe(200);+}++async function getResolved(+ principalType: string,+ principalId: string,+ extra: Partial<ReadDeps> = {},+ user?: Record<string, unknown>,+): Promise<MockRes> {+ const res = mockRes();+ await readHandlers(extra).getResolvedConfig(+ mockReq({ params: { principalType, principalId }, ...(user && { user }) }),+ res,+ );+ return res;+}++async function getEffective(+ userId: string,+ extra: Partial<ReadDeps> = {},+ user?: Record<string, unknown>,+): Promise<MockRes> {+ const res = mockRes();+ await readHandlers(extra).getEffectiveConfig(+ mockReq({ query: { userId }, ...(user && { user }) }),+ res,+ );+ return res;+}++async function createUser(email: string, role = 'USER'): Promise<string> {+ const user = await new mongoose.models.User({ email, provider: 'local', role }).save();+ return user._id.toString();+}++async function createGroup(name: string, memberIds: string[]): Promise<string> {+ const group = await new mongoose.models.Group({ name, source: 'local', memberIds }).save();+ return group._id.toString();+}++beforeAll(async () => {+ jest.resetModules();+ dataSchemas = await import('@librechat/data-schemas');+ jest.spyOn(dataSchemas.logger, 'warn').mockReturnValue(dataSchemas.logger);+ jest.spyOn(dataSchemas.logger, 'info').mockReturnValue(dataSchemas.logger);+ jest.spyOn(dataSchemas.logger, 'error').mockReturnValue(dataSchemas.logger);+ ({ createAdminConfigReadHandlers } = await import('./resolved'));+ ({ createAdminConfigHandlers } = await import('./config'));+ const { createAppConfigService } = await import('~/app/service');++ mongoServer = await MongoMemoryServer.create();+ await mongoose.connect(mongoServer.getUri());+ dataSchemas.createModels(mongoose);+ methods = dataSchemas.createMethods(mongoose);++ const appConfig: AppConfig = await dataSchemas.AppService({ config: structuredClone(YAML) });+ const store = new Map<string, unknown>();+ service = createAppConfigService({+ loadBaseConfig: async () => structuredClone(appConfig),+ setCachedTools: async () => undefined,+ getCache: () => ({+ get: async (key: string) => store.get(key),+ set: async (key: string, value: unknown) => {+ store.set(key, value);+ },+ delete: async (key: string) => store.delete(key),+ opts: { store: { keys: () => store.keys() } },+ }),+ cacheKeys: { APP_CONFIG: 'app_config' },+ getApplicableConfigs: methods.getApplicableConfigs,+ getUserPrincipals: methods.getUserPrincipals,+ });+});++afterEach(async () => {+ await Promise.all(+ ['Config', 'User', 'Group', 'Role'].map((name) => mongoose.models[name].deleteMany({})),+ );+ await service.clearOverrideCache();+});++afterAll(async () => {+ await mongoose.disconnect();+ await mongoServer.stop();+});++describe('GET /resolved/:principalType/:principalId', () => {+ it('resolves a profile over librechat.yaml and Base, in merge order and librechat.yaml shape', async () => {+ await patch(ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID, [+ { fieldPath: 'interface.customWelcome', value: 'Hello from Base' },+ { fieldPath: 'registration.socialLogins', value: ['google'] },+ ]);+ await patch(ROLE, 'USER', [+ { fieldPath: 'interface.customWelcome', value: 'Hello, users' },+ { fieldPath: 'interface.prompts', value: false },+ ]);++ const res = await getResolved(ROLE, 'USER');+ const body = res.body as AdminResolvedConfigResponse;++ expect(res.statusCode).toBe(200);+ expect(body.yaml.interface?.customWelcome).toBe('Hello from YAML');+ expect(body.layers.map(({ principalId, priority }) => [principalId, priority])).toEqual([+ [dataSchemas.BASE_CONFIG_PRINCIPAL_ID, 0],+ ['USER', 10],+ ]);+ expect(body.layers[1].revision).toMatch(/^[0-9a-f]{24}:1$/);+ expect(body.resolved.interface?.customWelcome).toBe('Hello, users');+ expect(body.resolved.registration?.socialLogins).toEqual(['google']);+ expect(body.resolved).not.toHaveProperty('interfaceConfig');+ });++ it('shows a write the override cache has not caught up with', async () => {+ await patch(ROLE, 'USER', [{ fieldPath: 'interface.customWelcome', value: 'Before' }]);+ const cached = await service.getAppConfig({ role: 'USER' });+ expect(cached.interfaceConfig?.customWelcome).toBe('Before');+ /** Written below the admin API, so nothing clears the merged config the read above cached. */+ await methods.patchConfigFields(ROLE, 'USER', PrincipalModel.ROLE, {+ 'interface.customWelcome': 'After',+ });+ expect((await service.getAppConfig({ role: 'USER' })).interfaceConfig?.customWelcome).toBe(+ 'Before',+ );++ const body = (await getResolved(ROLE, 'USER')).body as AdminResolvedConfigResponse;+ expect(body.resolved.interface?.customWelcome).toBe('After');+ });++ it('lists an inactive profile without merging it', async () => {+ await patch(ROLE, 'USER', [{ fieldPath: 'interface.customWelcome', value: 'Inactive' }]);+ await methods.toggleConfigActive(ROLE, 'USER', false);++ const body = (await getResolved(ROLE, 'USER')).body as AdminResolvedConfigResponse;+ expect(body.layers).toEqual([+ expect.objectContaining({ principalId: 'USER', isActive: false, ignored: [] }),+ ]);+ expect(body.resolved.interface?.customWelcome).toBe('Hello from YAML');+ });++ it('resolves a principal without a profile to Base, and 404s one that does not exist', async () => {+ await patch(ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID, [+ { fieldPath: 'interface.customWelcome', value: 'Base' },+ ]);+ const userId = await createUser('[email protected]');++ const existing = await getResolved(PrincipalType.USER, userId);+ expect(existing.statusCode).toBe(200);+ expect((existing.body as AdminResolvedConfigResponse).resolved.interface?.customWelcome).toBe(+ 'Base',+ );++ const missing = await getResolved(+ PrincipalType.GROUP,+ new mongoose.Types.ObjectId().toString(),+ );+ expect(missing.statusCode).toBe(404);+ expect(missing.body).toEqual({ error: 'Principal not found', code: 'PRINCIPAL_NOT_FOUND' });+ });++ it('never returns a stored or librechat.yaml secret', async () => {+ await patch(ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID, [+ { fieldPath: 'endpoints.custom', value: [{ name: 'Gateway', apiKey: BASE_KEY }] },+ ]);++ const res = await getResolved(ROLE, 'USER');+ const body = res.body as AdminResolvedConfigResponse;+ const text = JSON.stringify(body);++ expect(text).not.toContain(BASE_KEY);+ expect(text).not.toContain(YAML_KEY);+ expect(text).not.toContain('v3:');+ expect(body.yaml.endpoints?.custom?.[0]).toMatchObject({ apiKeyPreview: '********' });+ expect(body.resolved.endpoints?.custom?.[0]).toMatchObject({+ apiKeyPreview: expect.stringContaining('9876'),+ });+ expect(body.layers[0].overrides.endpoints?.custom?.[0]).not.toHaveProperty('apiKey');+ });++ it('shows no preview for a stored key the merge drops', async () => {+ await patch(ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID, [+ { fieldPath: 'endpoints.custom', value: [{ name: 'Gateway', apiKey: BASE_KEY }] },+ ]);+ await patch(ROLE, 'USER', [+ {+ fieldPath: 'endpoints.custom',+ value: [{ name: 'Gateway', baseURL: 'https://collector.example.com/v1' }],+ },+ ]);++ const body = (await getResolved(ROLE, 'USER')).body as AdminResolvedConfigResponse;++ expect(body.layers[0].overrides.endpoints?.custom?.[0]).toMatchObject({+ apiKeyPreview: expect.stringContaining('9876'),+ });+ const gateway = body.resolved.endpoints?.custom?.[0];+ expect(gateway).toMatchObject({ baseURL: 'https://collector.example.com/v1' });+ expect(gateway).not.toHaveProperty('apiKeyPreview');+ expect(body.layers[1].ignored).toEqual([+ expect.objectContaining({+ reason: 'secret_rebinding',+ path: 'endpoints.custom["Gateway"].apiKey',+ }),+ ]);+ });++ it('shows a section-scoped reader only the sections it can read, its ignored parts included', async () => {+ await patch(ROLE, 'USER', [+ { fieldPath: 'interface.customWelcome', value: 'Role' },+ { fieldPath: 'registration.socialLogins', value: ['google'] },+ ]);+ await mongoose.models.Config.updateOne(+ { principalType: ROLE, principalId: 'USER' },+ { $set: { 'overrides.paths': { uploads: '/tmp/x' } } },+ );++ const res = await getResolved(ROLE, 'USER', {+ getReadableConfigSections: async () => ({ broad: false, sections: new Set(['interface']) }),+ });+ const body = res.body as AdminResolvedConfigResponse;++ expect(Object.keys(body.yaml)).toEqual(['interface']);+ expect(Object.keys(body.resolved)).toEqual(['interface']);+ expect(Object.keys(body.layers[0].overrides)).toEqual(['interface']);+ expect(body.layers[0].ignored).toEqual([]);++ const broad = (await getResolved(ROLE, 'USER')).body as AdminResolvedConfigResponse;+ expect(broad.layers[0].ignored).toEqual([+ { path: 'paths', segments: ['paths'], reason: 'unknown_section' },+ ]);+ });++ it('answers 403 without config read access, and 400 for an unknown principal type', async () => {+ const forbidden = await getResolved(ROLE, 'USER', {+ hasAnyConfigReadAccess: async () => false,+ });+ expect(forbidden.statusCode).toBe(403);+ const invalid = await getResolved('tenant', 'x');+ expect(invalid.statusCode).toBe(400);+ });++ it('answers 404 for a role of another tenant', async () => {+ await dataSchemas.tenantStorage.run({ tenantId: 'tenant-a' }, () =>+ new mongoose.models.Role({ name: 'tenant-a-editors' }).save(),+ );+ const res = await dataSchemas.tenantStorage.run({ tenantId: 'tenant-b' }, () =>+ getResolved(+ ROLE,+ 'tenant-a-editors',+ {},+ {+ id: 'admin-b',+ role: 'ADMIN',+ tenantId: 'tenant-b',+ },+ ),+ );+ expect(res.statusCode).toBe(404);+ });+});++describe('GET /effective?userId=', () => {+ it('resolves a user over Base, their role and both groups, in merge order', async () => {+ await new mongoose.models.Role({ name: 'EDITOR' }).save();+ const userId = await createUser('[email protected]', 'EDITOR');+ const early = await createGroup('Early', [userId]);+ const late = await createGroup('Late', [userId]);+ await patch(ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID, [+ { fieldPath: 'interface.customWelcome', value: 'Base' },+ ]);+ await patch(ROLE, 'EDITOR', [{ fieldPath: 'interface.customWelcome', value: 'Editor' }]);+ await patch(+ PrincipalType.GROUP,+ early,+ [{ fieldPath: 'registration.socialLogins', value: ['early'] }],+ 5,+ );+ await patch(+ PrincipalType.GROUP,+ late,+ [{ fieldPath: 'interface.customWelcome', value: 'Late group' }],+ 30,+ );++ const res = await getEffective(userId);+ const body = res.body as AdminEffectiveConfigResponse;++ expect(res.statusCode).toBe(200);+ expect(body.userId).toBe(userId);+ expect(+ body.layers.map(({ principalType, principalId }) => [principalType, principalId]),+ ).toEqual([+ [ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID],+ [PrincipalType.GROUP, early],+ [ROLE, 'EDITOR'],+ [PrincipalType.GROUP, late],+ ]);+ expect(body.principals).toEqual(+ expect.arrayContaining([+ { principalType: PrincipalType.USER, principalId: userId },+ { principalType: ROLE, principalId: 'EDITOR' },+ { principalType: PrincipalType.GROUP, principalId: early },+ { principalType: PrincipalType.GROUP, principalId: late },+ ]),+ );+ expect(body.resolved.interface?.customWelcome).toBe('Late group');+ expect(body.resolved.registration?.socialLogins).toEqual(['early']);+ });++ it('needs read:users and read:groups besides config read access', async () => {+ const userId = await createUser('[email protected]');+ const withoutGroups = await getEffective(userId, {+ hasCapability: async (_user, capability: SystemCapability) => capability === 'read:users',+ });+ expect(withoutGroups.statusCode).toBe(403);+ const withoutConfigs = await getEffective(userId, {+ hasAnyConfigReadAccess: async () => false,+ });+ expect(withoutConfigs.statusCode).toBe(403);+ expect((await getEffective('')).statusCode).toBe(400);+ });++ it('answers 404 for a user who is not in the caller tenant', async () => {+ const userId = await dataSchemas.tenantStorage.run({ tenantId: 'tenant-a' }, () =>+ createUser('[email protected]'),+ );+ const res = await dataSchemas.tenantStorage.run({ tenantId: 'tenant-b' }, () =>+ getEffective(userId, {}, { id: 'admin-b', role: 'ADMIN', tenantId: 'tenant-b' }),+ );+ expect(res.statusCode).toBe(404);+ expect(res.body).toEqual({ error: 'User not found', code: 'USER_NOT_FOUND' });+ expect((await getEffective(new mongoose.Types.ObjectId().toString())).statusCode).toBe(404);+ });+});diff --git a/packages/api/src/admin/resolved.ts b/packages/api/src/admin/resolved.tsnew file mode 100644index 0000000000..614f11ae76--- /dev/null+++ b/packages/api/src/admin/resolved.ts@@ -0,0 +1,297 @@+import { PrincipalType } from 'librechat-data-provider';+import {+ logger,+ SystemCapabilities,+ isBaseConfigPrincipal,+ sortByConfigPrecedence,+ BASE_CONFIG_PRINCIPAL_ID,+} from '@librechat/data-schemas';+import type {+ ConfigRecord,+ ConfigSection,+ AdminConfigLayer,+ SystemCapability,+ ConfigOverrideLayer,+ AdminConfigLayerIgnored,+ AdminResolvedConfigResponse,+ AdminEffectiveConfigResponse,+} from '@librechat/data-schemas';+import type { TCustomConfig } from 'librechat-data-provider';+import type { Response } from 'express';+import type { ResolveConfigLayersOptions, ResolvedConfigLayers } from '~/app/service';+import type { CapabilityUser } from '~/middleware/capabilities';+import type { ServerRequest } from '~/types/http';+import type { ReadableSections } from './config';+import {+ canReadSection,+ getCapabilityUser,+ collectConfigSections,+ validatePrincipalType,+ redactConfigForResponse,+ principalNotFoundResponse,+ filterSectionsByReadAccess,+ filterConfigDocForReadAccess,+} from './config';+import { redactConfigSecrets, redactResolvedConfigSecrets } from './secrets';+import { getSafeErrorMetadata } from '~/utils/errors';++/** A principal a user resolves to, as principal resolution returns it. */+interface ResolvedPrincipal {+ principalType: string;+ principalId?: { toString(): string } | string;+}++export interface AdminConfigReadDeps {+ findConfigByPrincipal: (+ principalType: PrincipalType,+ principalId: string,+ options?: { includeInactive?: boolean },+ ) => Promise<ConfigRecord | null>;+ hasAnyConfigReadAccess: (user: CapabilityUser) => Promise<boolean>;+ getReadableConfigSections: (+ user: CapabilityUser,+ sections: ConfigSection[],+ ) => Promise<{ broad: boolean; sections: Set<string> }>;+ hasCapability: (user: CapabilityUser, capability: SystemCapability) => Promise<boolean>;+ /**+ * Merges documents as the app config service merges a principal's, layer by layer+ * (`createAppConfigService().resolveConfigLayers`). Without it the read routes answer 501.+ */+ resolveConfigLayers?: (options: ResolveConfigLayersOptions) => Promise<ResolvedConfigLayers>;+ /** Whether the principal exists in the caller's tenant partition (`principalExists`). */+ principalExists?: (principalType: PrincipalType, principalId: string) => Promise<boolean>;+ /** A user of the caller's tenant partition, with what principal resolution reads of them. */+ findPartitionUser?: (+ userId: string,+ ) => Promise<{ id: string; role?: string; idOnTheSource?: string | null } | null>;+ /** The principals a user resolves to: the user, their role and their groups. */+ getUserPrincipals?: (params: {+ userId: string;+ role?: string | null;+ idOnTheSource?: string | null;+ }) => Promise<ResolvedPrincipal[]>;+ /** Base and the principals' active documents, from the caller's tenant partition. */+ getApplicableConfigs?: (+ principals: Array<{ principalType: string; principalId?: string }>,+ ) => Promise<ConfigRecord[]>;+}++/** A librechat.yaml-shaped tree as an admin read returns it: secrets redacted on a copy. */+function redactYamlTree(+ tree: Partial<TCustomConfig>,+ yamlConfig?: Partial<TCustomConfig>,+): Partial<TCustomConfig> {+ const copy = structuredClone(tree);+ redactConfigSecrets(copy, { previewPlaintext: yamlConfig != null, yamlConfig });+ redactResolvedConfigSecrets(copy);+ return copy;+}++function filterTree(+ tree: Partial<TCustomConfig>,+ readable: ReadableSections,+): Partial<TCustomConfig> {+ return filterSectionsByReadAccess(tree as Record<string, unknown>, (section) =>+ canReadSection(readable, section),+ ) as Partial<TCustomConfig>;+}++/** A document of a resolution as a profile read shows it, with what the merge left out of it. */+function toLayer(+ record: ConfigRecord,+ ignored: readonly AdminConfigLayerIgnored[],+ readable: ReadableSections,+): AdminConfigLayer {+ const shown = redactConfigForResponse(filterConfigDocForReadAccess(record, readable));+ return {+ principalType: shown.principalType,+ principalId: shown.principalId,+ priority: shown.priority,+ isActive: shown.isActive,+ revision: shown.revision,+ overrides: shown.overrides ?? {},+ tombstones: shown.tombstones ?? [],+ ignored: ignored.filter(({ segments }) => canReadSection(readable, segments[0] ?? '')),+ };+}++/**+ * The parts of a resolution every read route returns: librechat.yaml, the documents in merge+ * order (inactive ones too, which the merge skips) and the result, limited to the sections the+ * caller can read and redacted as reads redact.+ */+async function toResolvedBody(+ user: CapabilityUser,+ records: readonly ConfigRecord[],+ resolution: ResolvedConfigLayers,+ getReadableConfigSections: AdminConfigReadDeps['getReadableConfigSections'],+): Promise<Pick<AdminResolvedConfigResponse, 'yaml' | 'layers' | 'resolved'>> {+ const sections = new Set<string>([+ ...Object.keys(resolution.yaml),+ ...Object.keys(resolution.resolved),+ ...records.flatMap(collectConfigSections),+ ...resolution.layers.flatMap(({ ignored }) => ignored.map(({ segments }) => segments[0])),+ ]);+ const readable = await getReadableConfigSections(user, [...sections] as ConfigSection[]);+ const ignoredBy = new Map<ConfigOverrideLayer, AdminConfigLayerIgnored[]>(+ resolution.layers.map(({ layer, ignored }) => [layer, ignored]),+ );+ return {+ yaml: redactYamlTree(filterTree(resolution.yaml, readable)),+ layers: sortByConfigPrecedence(records).map((record) =>+ toLayer(record, ignoredBy.get(record) ?? [], readable),+ ),+ resolved: redactYamlTree(filterTree(resolution.resolved, readable), resolution.yaml),+ };+}++function toPrincipalId(principal: ResolvedPrincipal): string | undefined {+ return principal.principalId?.toString();+}++/**+ * Read-only views of what config documents resolve to, for the admin config API+ * (`resolvedApi`): one profile over Base, or one user over every profile that applies to them.+ * Neither reads or fills the override cache, so a read right after a write shows it.+ */+export function createAdminConfigReadHandlers(deps: AdminConfigReadDeps): {+ getResolvedConfig: (req: ServerRequest, res: Response) => Promise<Response>;+ getEffectiveConfig: (req: ServerRequest, res: Response) => Promise<Response>;+} {+ const {+ findConfigByPrincipal,+ hasAnyConfigReadAccess,+ getReadableConfigSections,+ hasCapability,+ resolveConfigLayers,+ principalExists,+ findPartitionUser,+ getUserPrincipals,+ getApplicableConfigs,+ } = deps;++ /**+ * GET /resolved/:principalType/:principalId — what a profile resolves to over librechat.yaml+ * and the Base document (Base alone for Base), in librechat.yaml shape, with each document and+ * what the merge does not apply of it. The profile's other principals vary per user and are+ * left out; `GET /effective` resolves a user. A principal with no document resolves to Base,+ * unless it does not exist in the caller's tenant (404 `PRINCIPAL_NOT_FOUND`).+ */+ async function getResolvedConfig(req: ServerRequest, res: Response): Promise<Response> {+ try {+ const { principalType, principalId } = req.params as {+ principalType: string;+ principalId: string;+ };+ if (!validatePrincipalType(principalType)) {+ return res.status(400).json({ error: 'Invalid principalType', code: 'INVALID_PRINCIPAL' });+ }+ const user = getCapabilityUser(req);+ if (!user) {+ return res.status(401).json({ error: 'Authentication required' });+ }+ if (!(await hasAnyConfigReadAccess(user))) {+ return res.status(403).json({ error: 'Insufficient permissions' });+ }+ if (!resolveConfigLayers) {+ return res.status(501).json({ error: 'Resolved config is not available' });+ }++ const isBase = isBaseConfigPrincipal({ principalType, principalId });+ const [base, target] = await Promise.all([+ isBase+ ? null+ : findConfigByPrincipal(PrincipalType.ROLE, BASE_CONFIG_PRINCIPAL_ID, {+ includeInactive: true,+ }),+ findConfigByPrincipal(principalType, principalId, { includeInactive: true }),+ ]);+ if (+ !target &&+ !isBase &&+ principalExists &&+ !(await principalExists(principalType, principalId))+ ) {+ return principalNotFoundResponse(res);+ }+ const records = [base, target].filter((record): record is ConfigRecord => record != null);+ const resolution = await resolveConfigLayers({+ tenantId: user.tenantId,+ configs: records.filter((record) => record.isActive),+ });+ const body: AdminResolvedConfigResponse = {+ principalType,+ principalId,+ ...(await toResolvedBody(user, records, resolution, getReadableConfigSections)),+ };+ return res.status(200).json(body);+ } catch (error) {+ logger.error('[adminConfig] getResolvedConfig error:', getSafeErrorMetadata(error));+ return res.status(500).json({ error: 'Failed to resolve config' });+ }+ }++ /**+ * GET /effective?userId= — what one user's requests resolve to: Base, then the active profiles+ * of their role, groups and their own, in merge order. Needs `read:users` and `read:groups`+ * besides config read access, since it shows the user's role and group memberships. A user who+ * is not in the caller's tenant answers 404 `USER_NOT_FOUND`.+ */+ async function getEffectiveConfig(req: ServerRequest, res: Response): Promise<Response> {+ try {+ const userId = (req.query as Record<string, unknown>).userId;+ if (typeof userId !== 'string' || userId === '') {+ return res.status(400).json({ error: 'userId is required', code: 'INVALID_USER_ID' });+ }+ const user = getCapabilityUser(req);+ if (!user) {+ return res.status(401).json({ error: 'Authentication required' });+ }+ const [canReadConfigs, canReadUsers, canReadGroups] = await Promise.all([+ hasAnyConfigReadAccess(user),+ hasCapability(user, SystemCapabilities.READ_USERS),+ hasCapability(user, SystemCapabilities.READ_GROUPS),+ ]);+ if (!canReadConfigs || !canReadUsers || !canReadGroups) {+ return res.status(403).json({ error: 'Insufficient permissions' });+ }+ if (+ !resolveConfigLayers ||+ !findPartitionUser ||+ !getUserPrincipals ||+ !getApplicableConfigs+ ) {+ return res.status(501).json({ error: 'Effective config is not available' });+ }++ const target = await findPartitionUser(userId);+ if (!target) {+ return res.status(404).json({ error: 'User not found', code: 'USER_NOT_FOUND' });+ }+ const principals = await getUserPrincipals({+ userId: target.id,+ role: target.role ?? null,+ idOnTheSource: target.idOnTheSource ?? null,+ });+ const named = principals.flatMap((principal) => {+ const id = toPrincipalId(principal);+ return id == null+ ? []+ : [{ principalType: principal.principalType as PrincipalType, principalId: id }];+ });+ const records = await getApplicableConfigs(named);+ const resolution = await resolveConfigLayers({ tenantId: user.tenantId, configs: records });+ const body: AdminEffectiveConfigResponse = {+ userId: target.id,+ principals: named,+ ...(await toResolvedBody(user, records, resolution, getReadableConfigSections)),+ };+ return res.status(200).json(body);+ } catch (error) {+ logger.error('[adminConfig] getEffectiveConfig error:', getSafeErrorMetadata(error));+ return res.status(500).json({ error: 'Failed to resolve effective config' });+ }+ }++ return { getResolvedConfig, getEffectiveConfig };+}diff --git a/packages/api/src/admin/secrets.ts b/packages/api/src/admin/secrets.tsindex 69fafd806e..22a97e5dca 100644--- a/packages/api/src/admin/secrets.ts+++ b/packages/api/src/admin/secrets.ts@@ -28,6 +28,11 @@ interface ConfigSecretFieldInput {opaque?: boolean;}+/** The key of the masked-preview companion stored beside the secret at `secretKey`. */+export function getSecretPreviewKey(secretKey: string): string {+ return `${secretKey}Preview`;+}+interface ConfigSecretField extends ConfigSecretFieldInput {/** Non-secret masked-preview companion, always the sibling `<field>Preview`. Written on encrypt, preserved by redaction. */previewPath: string;@@ -63,7 +68,7 @@ const CONFIG_SECRET_FIELDS: readonly ConfigSecretField[] = ({ path: 'endpoints.assistants.apiKey', allowEnvPlaceholder: true },{ path: 'endpoints.azureAssistants.apiKey', allowEnvPlaceholder: true },] satisfies ConfigSecretFieldInput[]-).map((field) => ({ ...field, previewPath: `${field.path}Preview` }));+).map((field) => ({ ...field, previewPath: getSecretPreviewKey(field.path) }));/*** Preview companions written under earlier naming conventions. Stripped from@@ -186,7 +191,7 @@ const RECORD_SECRET_FIELDS: readonly RecordSecretField[] = ().map((field) => ({...field,recordSegments: field.recordPath.split('.'),- previewKey: `${field.secretPath[field.secretPath.length - 1]}Preview`,+ previewKey: getSecretPreviewKey(field.secretPath[field.secretPath.length - 1]),}));/** The record secret's location as a pattern, `*` standing for the entry name. */diff --git a/packages/api/src/app/allowlist.ts b/packages/api/src/app/allowlist.tsindex defc7c398d..583f72f5f5 100644--- a/packages/api/src/app/allowlist.ts+++ b/packages/api/src/app/allowlist.ts@@ -1,6 +1,6 @@import isPlainObject from 'lodash/isPlainObject';import { EModelEndpoint, isSensitiveEnvVar } from 'librechat-data-provider';-import { loadOCRConfig, loadWebSearchConfig } from '@librechat/data-schemas';+import { getAtPath, loadOCRConfig, loadWebSearchConfig } from '@librechat/data-schemas';import type { ConfigOverrideIssue } from '@librechat/data-schemas';import type { TCustomConfig } from 'librechat-data-provider';import {@@ -202,6 +202,22 @@ export function collectEnvReferenceNames(value: unknown): Set<string> {return names;}+/**+ * Every env name `value` references where a reader expands it (as {@link collectEnvReferenceNames}+ * finds them), with the top-level sections it is referenced in.+ */+export function collectEnvReferenceSections(value: unknown): Map<string, Set<string>> {+ const sections = new Map<string, Set<string>>();+ visitExpandedStrings(value, (text, segments) => {+ for (const name of referencedNames(text, segments)) {+ const held = sections.get(name) ?? new Set<string>();+ held.add(segments[0]);+ sections.set(name, held);+ }+ });+ return sections;+}+/** Joins segments so that a key containing a dot never spells another location. */function locationKey(segments: readonly string[]): string {return segments.join('\u0000');@@ -246,6 +262,25 @@ function collectLoadedReferences(config: unknown): Map<string, Set<string>> {return references;}+/**+ * The env names loading librechat.yaml references where the YAML leaves a value unset (OCR's key,+ * the web search defaults such as `${SEARXNG_INSTANCE_URL}`), with their sections.+ */+export function collectDefaultEnvReferenceSections(config: unknown): Map<string, Set<string>> {+ const sections = new Map<string, Set<string>>();+ visitExpandedStrings(loadSectionsWithReferences(config), (text, segments) => {+ if (getAtPath(config, segments) !== undefined) {+ return;+ }+ for (const name of referencedNames(text, segments)) {+ const held = sections.get(name) ?? new Set<string>();+ held.add(segments[0]);+ sections.set(name, held);+ }+ });+ return sections;+}+/*** The allowlist: names librechat.yaml references (`config` is the raw YAML config), the* built-in endpoints' credential names and the operator's extra names, anywhere; and eachdiff --git a/packages/api/src/app/layers.spec.ts b/packages/api/src/app/layers.spec.tsnew file mode 100644index 0000000000..b90dfb3df4--- /dev/null+++ b/packages/api/src/app/layers.spec.ts@@ -0,0 +1,369 @@+process.env.CREDS_KEY =+ process.env.CREDS_KEY ?? '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';++import { PrincipalType } from 'librechat-data-provider';+import type {+ AppConfig,+ ConfigOverrideLayer,+ AdminConfigLayerIgnored,+} from '@librechat/data-schemas';+import type { DeepPartial, TCustomConfig } from 'librechat-data-provider';++type DataSchemas = typeof import('@librechat/data-schemas');+type Overrides = typeof import('./overrides');+type Service = typeof import('./service');+type Allowlist = typeof import('./allowlist');++/** Loaded after `CREDS_KEY` is set: the encryption key is read when data-schemas loads. */+let dataSchemas: DataSchemas;+let overrides: Overrides;+let createAppConfigService: Service['createAppConfigService'];+let createEnvReferencePolicy: Allowlist['createEnvReferencePolicy'];++const YAML: DeepPartial<TCustomConfig> = {+ version: '1.3.0',+ cache: true,+ interface: { customWelcome: 'Hello' },+ endpoints: {+ custom: [+ {+ name: 'Gateway',+ apiKey: 'yaml-gateway-key',+ baseURL: 'https://gateway.example.com/v1',+ models: { default: ['gpt-4o'] },+ },+ {+ name: 'Private',+ tenantId: 'other-tenant',+ apiKey: 'private-key',+ baseURL: 'https://private.example.com/v1',+ models: { default: ['p-1'] },+ },+ ],+ },+ mcpServers: {+ tools: {+ type: 'streamable-http',+ url: 'https://tools.example.com/mcp',+ apiKey: { source: 'admin', authorization_type: 'bearer', key: '${TOOLS_KEY}' },+ },+ },+};++let appConfig: AppConfig;++beforeAll(async () => {+ dataSchemas = await import('@librechat/data-schemas');+ overrides = await import('./overrides');+ ({ createAppConfigService } = await import('./service'));+ ({ createEnvReferencePolicy } = await import('./allowlist'));+ jest.spyOn(dataSchemas.logger, 'warn').mockReturnValue(dataSchemas.logger);+ jest.spyOn(dataSchemas.logger, 'info').mockReturnValue(dataSchemas.logger);+ appConfig = await dataSchemas.AppService({ config: structuredClone(YAML) });+});++afterAll(() => {+ jest.restoreAllMocks();+});++function layer(+ principalType: string,+ principalId: string,+ values: Record<string, unknown>,+ priority = 10,+): ConfigOverrideLayer {+ return {+ _id: `${principalType}-${principalId}`,+ principalType: principalType as PrincipalType,+ principalId,+ priority,+ overrides: values as Partial<TCustomConfig>,+ };+}++const role = (values: Record<string, unknown>) => layer(PrincipalType.ROLE, 'editors', values);+const base = (values: Record<string, unknown>) =>+ layer(PrincipalType.ROLE, dataSchemas.BASE_CONFIG_PRINCIPAL_ID, values, 0);++function reasons(ignored: readonly AdminConfigLayerIgnored[]): Array<[string, string]> {+ return ignored.map(({ path, reason }) => [path, reason]);+}++function policy() {+ return { envPolicy: createEnvReferencePolicy({ config: YAML }) };+}++describe('resolveOverrideLayers', () => {+ const cases: Array<[string, () => ConfigOverrideLayer[]]> = [+ ['no layers', () => []],+ [+ 'a custom endpoint moved without its key',+ () => [+ role({+ endpoints: {+ custom: [{ name: 'Gateway', baseURL: 'https://collector.example.com/v1' }],+ },+ }),+ ],+ ],+ [+ 'an MCP server moved without its key',+ () => [role({ mcpServers: { tools: { url: 'https://collector.example.com/mcp' } } })],+ ],+ [+ 'a disallowed env reference',+ () => [+ role({+ endpoints: {+ custom: [{ name: 'Gateway', headers: { 'X-Key': '${UNLISTED_SECRET}' } }],+ },+ }),+ ],+ ],+ [+ 'Base and a profile',+ () => [+ base({ interface: { customWelcome: 'Base' } }),+ role({ interface: { customWelcome: 'Role' } }),+ ],+ ],+ ];++ it.each(cases)('serves exactly what mergeOverrideLayers serves: %s', (_name, build) => {+ const configs = build();+ expect(overrides.resolveOverrideLayers(appConfig, configs, policy()).merged).toEqual(+ overrides.mergeOverrideLayers(appConfig, configs, policy()),+ );+ });++ it('drops a credential the layer sends elsewhere from the YAML-shaped result too', () => {+ const configs = cases[1][1]();+ const resolution = overrides.resolveOverrideLayers(appConfig, configs, policy());+ const gateway = resolution.resolved.endpoints?.custom?.[0];+ expect(gateway).toMatchObject({ baseURL: 'https://collector.example.com/v1', apiKey: '' });+ expect(reasons(resolution.layers[0].ignored)).toEqual([+ ['endpoints.custom["Gateway"].apiKey', 'secret_rebinding'],+ ]);+ expect(resolution.layers[0].layer).toBe(configs[0]);+ });++ it('drops an MCP credential moved to a new URL, under librechat.yaml keys', () => {+ const resolution = overrides.resolveOverrideLayers(appConfig, cases[2][1](), policy());+ expect(resolution.resolved.mcpServers?.tools).toMatchObject({+ url: 'https://collector.example.com/mcp',+ apiKey: { key: '' },+ });+ expect(reasons(resolution.layers[0].ignored)).toEqual([+ ['mcpServers.tools.apiKey.key', 'secret_rebinding'],+ ]);+ });++ it('leaves out the stored preview of a credential the merge drops', () => {+ const resolution = overrides.resolveOverrideLayers(+ appConfig,+ [+ base({+ endpoints: {+ custom: [{ name: 'Gateway', apiKey: 'base-gateway-2222', apiKeyPreview: '...2222' }],+ },+ mcpServers: { tools: { apiKey: { key: 'base-tools-3333', keyPreview: '...3333' } } },+ webSearch: { searxngApiKey: 'base-search-4444', searxngApiKeyPreview: '...4444' },+ }),+ role({+ endpoints: {+ custom: [{ name: 'Gateway', baseURL: 'https://collector.example.com/v1' }],+ },+ mcpServers: { tools: { url: 'https://collector.example.com/mcp' } },+ webSearch: { searxngInstanceUrl: 'https://collector.example.com/search' },+ }),+ ],+ policy(),+ );+ const gateway = resolution.resolved.endpoints?.custom?.[0];+ expect(gateway).toMatchObject({ baseURL: 'https://collector.example.com/v1', apiKey: '' });+ expect(gateway).not.toHaveProperty('apiKeyPreview');+ expect(resolution.resolved.mcpServers?.tools?.apiKey).toEqual(+ expect.objectContaining({ key: '' }),+ );+ expect(resolution.resolved.mcpServers?.tools?.apiKey).not.toHaveProperty('keyPreview');+ expect(resolution.resolved.webSearch).toEqual({+ searxngInstanceUrl: 'https://collector.example.com/search',+ });+ expect(reasons(resolution.layers[1].ignored)).toEqual(+ expect.arrayContaining([+ ['endpoints.custom["Gateway"].apiKey', 'secret_rebinding'],+ ['mcpServers.tools.apiKey.key', 'secret_rebinding'],+ ['webSearch.searxngApiKey', 'secret_rebinding'],+ ]),+ );+ });++ it('keeps the stored preview of a credential the merge applies', () => {+ const resolution = overrides.resolveOverrideLayers(+ appConfig,+ [+ base({+ endpoints: {+ custom: [{ name: 'Gateway', apiKey: 'base-gateway-2222', apiKeyPreview: '...2222' }],+ },+ }),+ role({ endpoints: { custom: [{ name: 'Gateway', models: { default: ['gpt-4.1'] } }] } }),+ ],+ policy(),+ );+ expect(resolution.resolved.endpoints?.custom?.[0]).toMatchObject({+ apiKey: 'base-gateway-2222',+ apiKeyPreview: '...2222',+ });+ });++ it('resolves a disallowed env reference to nothing and reports it on the document as written', () => {+ const configs = cases[3][1]();+ const resolution = overrides.resolveOverrideLayers(appConfig, configs, policy());+ expect(resolution.resolved.endpoints?.custom?.[0]?.headers).toEqual({ 'X-Key': '' });+ expect(resolution.layers[0].layer).toBe(configs[0]);+ expect(resolution.layers[0].ignored).toEqual([+ {+ path: 'endpoints.custom.0.headers.X-Key',+ segments: ['endpoints', 'custom', '0', 'headers', 'X-Key'],+ reason: 'env_reference_not_allowed',+ },+ ]);+ });++ it('leaves out the destination fingerprints stored beside secrets', () => {+ const resolution = overrides.resolveOverrideLayers(+ appConfig,+ [+ role({+ endpoints: {+ custom: [{ name: 'Gateway', apiKey: 'role-key', apiKeyBinding: 'fingerprint' }],+ },+ }),+ ],+ policy(),+ );+ expect(resolution.resolved.endpoints?.custom?.[0]).not.toHaveProperty('apiKeyBinding');+ });+});++function createService(configs: ConfigOverrideLayer[]) {+ const store = new Map<string, unknown>();+ const cache = {+ get: jest.fn(async (key: string) => store.get(key)),+ set: jest.fn(async (key: string, value: unknown) => {+ store.set(key, value);+ }),+ delete: jest.fn(async (key: string) => store.delete(key)),+ };+ const getApplicableConfigs = jest.fn(async () => configs);+ const service = createAppConfigService({+ loadBaseConfig: async () => structuredClone(appConfig),+ setCachedTools: async () => undefined,+ getCache: () => cache,+ cacheKeys: { APP_CONFIG: 'app_config' },+ getApplicableConfigs,+ getUserPrincipals: async () => [{ principalType: PrincipalType.ROLE, principalId: 'editors' }],+ });+ return { ...service, cache, getApplicableConfigs };+}++const INVALID_THEME = {+ version: 1,+ name: 'broken',+ modes: { light: { colors: { 'surface-primary': '999 0 0' } } },+};++describe('createAppConfigService().resolveConfigLayers', () => {+ it('merges exactly as getAppConfig serves the same documents', async () => {+ const configs = [+ base({ interface: { customWelcome: 'Base' } }),+ role({+ endpoints: {+ custom: [+ { name: 'Gateway', baseURL: 'https://collector.example.com/v1' },+ {+ name: 'Private',+ apiKey: 'k',+ baseURL: 'https://shadow.example.com',+ models: { default: ['x'] },+ },+ ],+ },+ }),+ ];+ const service = createService(configs);+ const served = await service.getAppConfig({+ role: 'editors',+ tenantId: 'mine',+ bypassOverrideCache: true,+ skipRuntimeAugmentation: true,+ });+ const resolution = await service.resolveConfigLayers({ tenantId: 'mine', configs });+ expect(resolution.merged).toEqual(served);+ });++ it('never reads or fills the override cache', async () => {+ const service = createService([role({ interface: { customWelcome: 'Role' } })]);+ await service.resolveConfigLayers({ configs: [role({ interface: { customWelcome: 'Now' } })] });+ const overrideKeys = (calls: unknown[][]) =>+ calls.filter(([key]) => String(key).startsWith('_OVERRIDE_'));+ expect(overrideKeys(service.cache.get.mock.calls)).toEqual([]);+ expect(overrideKeys(service.cache.set.mock.calls)).toEqual([]);+ expect(service.getApplicableConfigs).not.toHaveBeenCalled();+ });++ it('returns librechat.yaml as the tenant sees it, without another tenant endpoint', async () => {+ const service = createService([]);+ const resolution = await service.resolveConfigLayers({ tenantId: 'mine', configs: [] });+ expect(resolution.yaml.endpoints?.custom?.map((endpoint) => endpoint.name)).toEqual([+ 'Gateway',+ ]);+ expect(resolution.resolved).toBe(resolution.yaml);+ expect(resolution.layers).toEqual([]);+ });++ it('leaves out an endpoint scoped to another tenant, and the specs that use it', async () => {+ const configs = [+ role({+ endpoints: {+ custom: [+ {+ name: 'Private',+ apiKey: 'k',+ baseURL: 'https://shadow.example.com',+ models: { default: ['x'] },+ },+ ],+ },+ modelSpecs: {+ list: [+ { name: 'shadow', label: 'Shadow', preset: { endpoint: 'Private', model: 'x' } },+ { name: 'kept', label: 'Kept', preset: { endpoint: 'Gateway', model: 'gpt-4o' } },+ ],+ },+ }),+ ];+ const resolution = await createService(configs).resolveConfigLayers({+ tenantId: 'mine',+ configs,+ });+ expect(resolution.resolved.endpoints?.custom?.map((endpoint) => endpoint.name)).toEqual([+ 'Gateway',+ ]);+ expect(resolution.resolved.modelSpecs?.list?.map((spec) => spec.name)).toEqual(['kept']);+ expect(resolution.merged.modelSpecs?.list?.map((spec) => spec.name)).toEqual(['kept']);+ expect(reasons(resolution.layers[0].ignored)).toEqual([+ ['endpoints.custom.0', 'tenant_hidden'],+ ['modelSpecs.list.0', 'tenant_hidden'],+ ]);+ });++ it('shows the librechat.yaml theme where a profile theme fails the client rules', async () => {+ const configs = [role({ interface: { customWelcome: 'Role', theme: INVALID_THEME } })];+ const resolution = await createService(configs).resolveConfigLayers({ configs });+ expect(resolution.merged.interfaceConfig?.theme).toEqual(appConfig.interfaceConfig?.theme);+ expect(resolution.resolved.interface).toEqual({ customWelcome: 'Role' });+ expect(reasons(resolution.layers[0].ignored)).toEqual([['interface.theme', 'invalid_theme']]);+ });+});diff --git a/packages/api/src/app/overrides.ts b/packages/api/src/app/overrides.tsindex 54cfdddd08..cf02fa84a8 100644--- a/packages/api/src/app/overrides.ts+++ b/packages/api/src/app/overrides.ts@@ -1,9 +1,26 @@-import { mergeConfigOverrides } from '@librechat/data-schemas';-import type { AppConfig, ConfigOverrideLayer } from '@librechat/data-schemas';+import {+ getAtPath,+ setAtPath,+ unsetAtPath,+ foldConfigMergeKey,+ resolveConfigLayers,+ mergeConfigOverrides,+} from '@librechat/data-schemas';+import type {+ AppConfig,+ ConfigOverrideLayer,+ AdminConfigLayerIgnored,+ ConfigLayersResolution,+} from '@librechat/data-schemas';+import type { TCustomConfig } from 'librechat-data-provider';import type { EnvReferencePolicy } from './allowlist';import type { SecretRebinding } from './rebinding';-import { createSecretRebindingGuard, withoutSecretBindings } from './rebinding';-import { resolveRuntimeConfigSecrets } from '~/admin/secrets';+import {+ withoutSecretBindings,+ createSecretRebindingGuard,+ withoutStoredSecretBindings,+} from './rebinding';+import { getSecretPreviewKey, resolveRuntimeConfigSecrets } from '~/admin/secrets';import { neutralizeEnvReferences } from './allowlist';export interface OverrideMergeOptions {@@ -56,3 +73,213 @@ export function resolveConfigOverrides(): AppConfig {return resolveRuntimeConfigSecrets(mergeOverrideLayers(baseConfig, layers, options));}++/** {@link resolveOverrideLayers}' result: a {@link ConfigLayersResolution} under admin policies. */+export type OverrideLayersResolution = ConfigLayersResolution;++/** Where a reference the env policy neutralized sat in a layer's overrides, and what it held. */+function findNeutralized(+ written: unknown,+ neutralized: unknown,+ segments: readonly string[] = [],+): AdminConfigLayerIgnored[] {+ if (written === neutralized) {+ return [];+ }+ if (typeof written === 'string') {+ return [+ {+ path: segments.join('.'),+ segments: [...segments],+ reason: 'env_reference_not_allowed',+ },+ ];+ }+ if (written == null || typeof written !== 'object' || neutralized == null) {+ return [];+ }+ const writtenRecord = written as Record<string, unknown>;+ const neutralizedRecord = neutralized as Record<string, unknown>;+ return Object.keys(writtenRecord).flatMap((key) =>+ findNeutralized(writtenRecord[key], neutralizedRecord[key], [...segments, key]),+ );+}++const CUSTOM_ENDPOINTS_PATH = 'endpoints.custom';+const AZURE_GROUP_MAP: readonly string[] = ['endpoints', 'azureOpenAI', 'groupMap'];++function asRecord(value: unknown): Record<string, unknown> | null {+ return value != null && typeof value === 'object' && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : null;+}++/** The index of the entry of a list keyed by `field` whose key `matches`. */+function findEntryIndex(list: unknown, field: string, matches: (key: string) => boolean): number {+ if (!Array.isArray(list)) {+ return -1;+ }+ return list.findIndex((item) => {+ const key = asRecord(item)?.[field];+ return typeof key === 'string' && matches(key);+ });+}++/**+ * The concrete location in `tree` of a rebinding's YAML location (`SecretRebinding.segments`), or+ * `null` when the tree holds no such entry: a custom endpoint is found by the name the merge+ * folds; in the served config an MCP server is under `mcpConfig`; in the YAML-shaped result an+ * Azure `groupMap` group the merge resolved from `groups` is that group's entry.+ */+function locateRebinding(+ tree: unknown,+ segments: readonly string[],+ shape: 'served' | 'resolved',+): string[] | null {+ const [section, field, name, ...rest] = segments;+ if (`${section}.${field}` === CUSTOM_ENDPOINTS_PATH && name != null) {+ const identity = foldConfigMergeKey(CUSTOM_ENDPOINTS_PATH, name);+ const index = findEntryIndex(+ getAtPath(tree, [section, field]),+ 'name',+ (key) => foldConfigMergeKey(CUSTOM_ENDPOINTS_PATH, key) === identity,+ );+ return index < 0 ? null : [section, field, String(index), ...rest];+ }+ if (section === 'mcpServers' && shape === 'served') {+ return ['mcpConfig', ...segments.slice(1)];+ }+ const groupMapDepth = AZURE_GROUP_MAP.length;+ const isGroupMap = AZURE_GROUP_MAP.every((segment, index) => segments[index] === segment);+ if (shape === 'resolved' && isGroupMap && segments.length > groupMapDepth) {+ const group = segments[groupMapDepth];+ if (asRecord(getAtPath(tree, [...AZURE_GROUP_MAP, group])) != null) {+ return [...segments];+ }+ const groups = [...AZURE_GROUP_MAP.slice(0, -1), 'groups'];+ const index = findEntryIndex(getAtPath(tree, groups), 'group', (key) => key === group);+ return index < 0 ? null : [...groups, String(index), ...segments.slice(groupMapDepth + 1)];+ }+ return [...segments];+}++/**+ * `resolved` without the masked preview stored beside the credential at `target`+ * (`getSecretPreviewKey`): the merge dropped that credential, and a preview left beside it+ * would read as a key that applies.+ */+function withoutDroppedPreview(+ resolved: Partial<TCustomConfig>,+ target: readonly string[],+): Partial<TCustomConfig> {+ if (target.length === 0) {+ return resolved;+ }+ const preview = [...target.slice(0, -1), getSecretPreviewKey(target[target.length - 1])];+ if (getAtPath(resolved, preview) === undefined) {+ return resolved;+ }+ return unsetAtPath(resolved as Record<string, unknown>, preview) as Partial<TCustomConfig>;+}++/**+ * The YAML-shaped result with a rebinding's outcome copied from the served config: the dropped+ * credential (`''`, without its stored preview) or the destination set back. A location the+ * result holds no parent for (an AppConfig-only field such as `vertexConfig`) is left as it is.+ */+function replayRebinding(+ resolved: Partial<TCustomConfig>,+ merged: AppConfig,+ { kind, segments }: SecretRebinding,+): Partial<TCustomConfig> {+ const target = locateRebinding(resolved, segments, 'resolved');+ const source = locateRebinding(merged, segments, 'served');+ if (target == null || source == null || target.length === 0) {+ return resolved;+ }+ const parent = getAtPath(resolved, target.slice(0, -1));+ if (parent == null || typeof parent !== 'object') {+ return resolved;+ }+ const value = getAtPath(merged, source);+ const root = resolved as Record<string, unknown>;+ let replayed: Partial<TCustomConfig>;+ if (value === undefined) {+ replayed = Array.isArray(parent)+ ? resolved+ : (unsetAtPath(root, target) as Partial<TCustomConfig>);+ } else {+ replayed = setAtPath(root, target, value) as Partial<TCustomConfig>;+ }+ return kind === 'secret' ? withoutDroppedPreview(replayed, target) : replayed;+}++function principalKey(layer: ConfigOverrideLayer): string {+ return `${layer.principalType}:${layer.principalId?.toString()}`;+}++/**+ * {@link mergeOverrideLayers}, tracked: `merged` is exactly what it returns, `resolved` the same+ * merge in librechat.yaml shape (`resolveConfigLayers`), with each credential the rebinding guard+ * drops and each destination it sets back applied to it as well, and each layer (the document as+ * given, before env references are neutralized) lists what the merge does not apply of it, its+ * disallowed env references and rebound credentials included. Destination fingerprints are left+ * out of `resolved`, as reads leave them out.+ */+export function resolveOverrideLayers(+ baseConfig: AppConfig,+ layers: readonly ConfigOverrideLayer[],+ options: OverrideMergeOptions,+): OverrideLayersResolution {+ const originals = new Map<ConfigOverrideLayer, ConfigOverrideLayer>();+ const extra = new Map<string, AdminConfigLayerIgnored[]>();+ const neutralized = layers.map((layer) => {+ const overrides = neutralizeEnvReferences(layer.overrides, options.envPolicy);+ if (overrides === layer.overrides) {+ return layer;+ }+ const next = { ...layer, overrides };+ originals.set(next, layer);+ extra.set(principalKey(layer), findNeutralized(layer.overrides, overrides));+ return next;+ });+ const rebindings: SecretRebinding[] = [];+ const unboundKeys: string[][] = [];+ const { onRebinding } = options;+ const result = resolveConfigLayers(baseConfig, neutralized, {+ afterLayer: createSecretRebindingGuard((rebinding) => {+ rebindings.push(rebinding);+ onRebinding?.(rebinding);+ }),+ onWebSearchKeyUnbound: ({ layer, apiKey }) => {+ const segments = ['webSearch', apiKey];+ unboundKeys.push(segments);+ onRebinding?.({ layer, kind: 'secret', segments, path: segments.join('.') });+ },+ });+ const merged = withoutSecretBindings(result.merged);+ let resolved = unboundKeys.reduce(+ (tree, segments) => withoutDroppedPreview(tree, segments),+ result.resolved,+ );+ for (const rebinding of rebindings) {+ resolved = replayRebinding(resolved, merged, rebinding);+ const key = principalKey(rebinding.layer);+ extra.set(key, [+ ...(extra.get(key) ?? []),+ {+ path: rebinding.path,+ segments: [...rebinding.segments],+ reason: rebinding.kind === 'secret' ? 'secret_rebinding' : 'destination_restored',+ },+ ]);+ }+ return {+ merged,+ resolved: withoutStoredSecretBindings(resolved),+ layers: result.layers.map(({ layer, ignored }) => ({+ layer: originals.get(layer) ?? layer,+ ignored: [...ignored, ...(extra.get(principalKey(layer)) ?? [])],+ })),+ };+}diff --git a/packages/api/src/app/service.ts b/packages/api/src/app/service.tsindex 281ff99d8e..565d337e58 100644--- a/packages/api/src/app/service.ts+++ b/packages/api/src/app/service.ts@@ -14,15 +14,21 @@ import {normalizeEndpointName,setMaxSubagents,} from 'librechat-data-provider';-import type { AppConfig, ConfigOverrideLayer } from '@librechat/data-schemas';+import type {+ AppConfig,+ ConfigOverrideLayer,+ ConfigLayerResolution,+ AdminConfigLayerIgnored,+} from '@librechat/data-schemas';+import type { TCustomConfig } from 'librechat-data-provider';import type { Types } from 'mongoose';import type { CustomConfigLoadMode, ConfigLoadFailure, ConfigLoadResult } from './loader';import type { EnvReferencePolicy } from './allowlist';import type { SecretRebinding } from './rebinding';import { createEnvReferencePolicy, parseEnvAllowlist } from './allowlist';+import { mergeOverrideLayers, resolveOverrideLayers } from './overrides';import { resolveRuntimeConfigSecrets } from '~/admin/secrets';import { normalizeEndpointReferences } from './references';-import { mergeOverrideLayers } from './overrides';import { getConfigLoadFailure } from './loader';import { checkAppConfigTheme } from './theme';@@ -198,6 +204,92 @@ function checkOverrideTheme(baseConfig: AppConfig, merged: AppConfig): AppConfigreturn { ...merged, interfaceConfig: { ...merged.interfaceConfig, theme: baseTheme } };}+function toLayerIgnored(+ segments: string[],+ reason: AdminConfigLayerIgnored['reason'],+): AdminConfigLayerIgnored {+ return { path: segments.join('.'), segments, reason };+}++function asList(value: unknown): unknown[] {+ return Array.isArray(value) ? value : [];+}++function entryName(value: unknown, field: string): string | undefined {+ const name =+ value != null && typeof value === 'object' ? (value as Record<string, unknown>)[field] : null;+ return typeof name === 'string' ? name : undefined;+}++/**+ * A librechat.yaml-shaped resolution with the theme `checkOverrideTheme` set back: when the+ * served merge fell back to the base theme because an override's theme fails the client's+ * rules, the resolution shows librechat.yaml's theme, and the last layer that wrote one says so.+ */+function replayThemeFallback(+ resolved: Partial<TCustomConfig>,+ layers: ConfigLayerResolution[],+ yaml: Partial<TCustomConfig>,+): Partial<TCustomConfig> {+ const writer = [...layers]+ .reverse()+ .find(({ layer }) => (layer.overrides as Partial<TCustomConfig>)?.interface?.theme != null);+ writer?.ignored.push(toLayerIgnored(['interface', 'theme'], 'invalid_theme'));+ const { theme: _rejected, ...rest } = resolved.interface ?? {};+ const theme = yaml.interface?.theme;+ return {+ ...resolved,+ interface: theme === undefined ? rest : { ...rest, theme },+ } as Partial<TCustomConfig>;+}++/**+ * A librechat.yaml-shaped resolution scoped to the tenant as `scopeCustomEndpoints` scopes the+ * served merge: custom endpoints `hidden` names, or another tenant's, are left out, with the+ * model specs that use them, and each layer that wrote one of those says so.+ */+function scopeResolvedEndpoints(+ resolved: Partial<TCustomConfig>,+ layers: ConfigLayerResolution[],+ tenantId: string | undefined,+ hidden: ReadonlySet<string>,+): Partial<TCustomConfig> {+ const custom = resolved.endpoints?.custom;+ const scoped = scopeEndpointList(custom, tenantId, hidden);+ const modelSpecs = scopeModelSpecs(resolved.modelSpecs as AppConfig['modelSpecs'], hidden);+ if (scoped === custom && modelSpecs === resolved.modelSpecs) {+ return resolved;+ }+ const kept = new Set(scoped ?? []);+ const removed = new Set(+ (custom ?? [])+ .filter((endpoint) => !kept.has(endpoint))+ .map((endpoint) => normalizeEndpointName(endpoint.name ?? '')),+ );+ const isHidden = (name: string | undefined) =>+ name != null &&+ (removed.has(normalizeEndpointName(name)) || hidden.has(normalizeEndpointName(name)));+ for (const { layer, ignored } of layers) {+ const overrides = layer.overrides as Partial<TCustomConfig> | undefined;+ asList(overrides?.endpoints?.custom).forEach((entry, index) => {+ if (isHidden(entryName(entry, 'name'))) {+ ignored.push(toLayerIgnored(['endpoints', 'custom', String(index)], 'tenant_hidden'));+ }+ });+ asList(overrides?.modelSpecs?.list).forEach((spec, index) => {+ const preset = (spec as { preset?: unknown } | null)?.preset;+ if (isHidden(entryName(preset, 'endpoint'))) {+ ignored.push(toLayerIgnored(['modelSpecs', 'list', String(index)], 'tenant_hidden'));+ }+ });+ }+ return {+ ...resolved,+ ...(scoped !== custom && { endpoints: { ...resolved.endpoints, custom: scoped } }),+ ...(modelSpecs !== resolved.modelSpecs && { modelSpecs }),+ } as Partial<TCustomConfig>;+}+/*** Materializes inferable model-spec fields (an omitted `preset.endpoint` for* agent specs) so every consumer of the effective config reads complete specs.@@ -291,6 +383,31 @@ export interface GetAppConfigOptions {bypassOverrideCache?: boolean;}+/** What `resolveConfigLayers` resolves: one set of override documents, as `getAppConfig` merges them. */+export interface ResolveConfigLayersOptions {+ tenantId?: string;+ /** The documents to merge, active ones only, as `getApplicableConfigs` returns them. */+ configs: readonly ConfigOverrideLayer[];+}++/** A merge of override documents, served and in librechat.yaml shape, and what each layer lost. */+export interface ResolvedConfigLayers {+ /**+ * librechat.yaml as the tenant sees it (the raw config, without YAML custom endpoints and+ * model specs scoped to another tenant): what every layer merges over.+ */+ yaml: Partial<TCustomConfig>;+ /**+ * What `getAppConfig` serves for these documents, before runtime augmentation, with stored+ * secrets as stored (not decrypted).+ */+ merged: AppConfig;+ /** The same merge in librechat.yaml shape. */+ resolved: Partial<TCustomConfig>;+ /** Each document, in merge order, with what the merge does not apply of it. */+ layers: ConfigLayerResolution[];+}+export interface AppConfigUserLike {/** Resolved app user id. */id?: string;@@ -412,6 +529,8 @@ function createRebindingWarner(): (rebinding: SecretRebinding) => void {export function createAppConfigService(deps: AppConfigServiceDeps): {getAppConfig: (options?: GetAppConfigOptions) => Promise<AppConfig>;+ /** One set of override documents merged as `getAppConfig` merges them, layer by layer. */+ resolveConfigLayers: (options: ResolveConfigLayersOptions) => Promise<ResolvedConfigLayers>;clearAppConfigCache: () => Promise<void>;clearOverrideCache: (tenantId?: string) => Promise<void>;/** Loads librechat.yaml again on this instance and resolves with the outcome; never rejects. */@@ -822,6 +941,65 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {return await augment(withRuntimeSecrets(merged));}+ /**+ * Merges `configs` exactly as `getAppConfig` merges a principal's documents (the same base+ * config, tenant scoping, env policy and secret rebinding, theme check and endpoint scoping),+ * never reading or writing the override cache, and reports the merge in librechat.yaml shape+ * with what each layer could not apply (`resolveOverrideLayers`). Admin reads use it to show+ * what a profile, or a user, resolves to. The YAML-shaped result replays the theme fallback and+ * the tenant scoping; spec endpoint materialization and endpoint reference normalization rename+ * values for the runtime and are left out of it, as are the interface defaults AppService+ * derives.+ */+ async function resolveConfigLayers(+ options: ResolveConfigLayersOptions,+ ): Promise<ResolvedConfigLayers> {+ const { tenantId, configs } = options;+ const ambientTenantId = getTenantId();+ const requestedTenantId = tenantId === SYSTEM_TENANT_ID ? undefined : tenantId;+ const effectiveTenantId =+ ambientTenantId && ambientTenantId !== SYSTEM_TENANT_ID ? ambientTenantId : requestedTenantId;+ if (effectiveTenantId && effectiveTenantId !== ambientTenantId) {+ return tenantStorage.run({ ...tenantStorage.getStore(), tenantId: effectiveTenantId }, () =>+ resolveConfigLayers(options),+ );+ }++ const baseConfig = await ensureBaseConfig();+ const scopedBaseConfig = await scopeBaseConfig(baseConfig, effectiveTenantId);+ const yaml: Partial<TCustomConfig> = scopedBaseConfig.config ?? {};+ if (configs.length === 0) {+ return { yaml, merged: scopedBaseConfig, resolved: yaml, layers: [] };+ }+ const hiddenEndpoints = hiddenCustomEndpoints(baseConfig, effectiveTenantId);+ const resolution = resolveOverrideLayers(scopedBaseConfig, configs, {+ envPolicy: getEnvPolicy(baseConfig, scopedBaseConfig, effectiveTenantId),+ onRebinding: warnRebinding,+ });+ const completed = completeEffectiveConfig(resolution.merged);+ const checked = checkOverrideTheme(scopedBaseConfig, completed);+ const baseTheme = scopedBaseConfig.interfaceConfig?.theme;+ let resolved = resolution.resolved;+ if (+ checked.interfaceConfig?.theme === baseTheme &&+ completed.interfaceConfig?.theme !== baseTheme+ ) {+ resolved = replayThemeFallback(resolved, resolution.layers, yaml);+ }+ resolved = scopeResolvedEndpoints(+ resolved,+ resolution.layers,+ effectiveTenantId,+ hiddenCustomEndpoints(checked, effectiveTenantId, hiddenEndpoints),+ );+ return {+ yaml,+ merged: scopeCustomEndpoints(checked, effectiveTenantId, hiddenEndpoints),+ resolved,+ layers: resolution.layers,+ };+ }+/*** Clear the base config cache. Per-user/role override caches (`_OVERRIDE_:*`)* are NOT flushed — they expire naturally via `overrideCacheTtl`. After calling this,@@ -882,6 +1060,7 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {return {getAppConfig,+ resolveConfigLayers,clearAppConfigCache,clearOverrideCache,reloadBaseConfig,diff --git a/packages/api/src/endpoints/config/models.ts b/packages/api/src/endpoints/config/models.tsindex c524e31f4a..49dd07f6a6 100644--- a/packages/api/src/endpoints/config/models.ts+++ b/packages/api/src/endpoints/config/models.ts@@ -12,6 +12,7 @@ import type { ServerRequest, GetUserKeyValuesFunction, UserKeyValues } from '~/timport type { FetchModelsParams } from '~/endpoints/models';import type { GetAppConfigOptions } from '~/app/service';import { fetchModels as defaultFetchModels } from '~/endpoints/models';+import { isServedCustomEndpoint } from '~/endpoints/custom/config';import { getTokenConfigKey } from '~/endpoints/custom/initialize';import { getAppConfigOptionsFromUser } from '~/app/service';@@ -117,12 +118,7 @@ export function createLoadConfigModels(deps: LoadConfigModelsDeps) {}const customEndpoints = (appConfig.endpoints[EModelEndpoint.custom] as TEndpoint[]).filter(- (endpoint) =>- endpoint.baseURL &&- endpoint.apiKey &&- endpoint.name &&- endpoint.models &&- (endpoint.models.fetch || endpoint.models.default),+ isServedCustomEndpoint,);const fetchPromisesMap: Record<string, Promise<string[]>> = {};diff --git a/packages/api/src/endpoints/custom/config.spec.ts b/packages/api/src/endpoints/custom/config.spec.tsindex 5a4a8e9a5d..1492f1e868 100644--- a/packages/api/src/endpoints/custom/config.spec.ts+++ b/packages/api/src/endpoints/custom/config.spec.ts@@ -1,6 +1,10 @@import { AuthType, EModelEndpoint, ReasoningParameterFormat } from 'librechat-data-provider';import type { TCustomEndpoints } from 'librechat-data-provider';-import { loadCustomEndpointsConfig, usesOpenRouterCatalog } from './config';+import {+ usesOpenRouterCatalog,+ loadCustomEndpointsConfig,+ resolveServedCustomEndpoints,+} from './config';const baseEndpoint = {apiKey: 'sk-test',@@ -278,6 +282,32 @@ describe('loadCustomEndpointsConfig – user credential prompts', () => {});});+describe('resolveServedCustomEndpoints', () => {+ const endpoints = [+ { ...baseEndpoint, name: 'Ollama', iconURL: 'first.png' },+ { ...baseEndpoint, name: 'Gateway', iconURL: 'gateway.png' },+ { ...baseEndpoint, name: 'ollama', iconURL: 'last.png' },+ { name: 'Gateway', apiKey: 'sk-unserved', iconURL: 'unserved.png' },+ { name: 'Unserved', apiKey: 'sk-test' },+ ];++ it('resolves each served name to its last served definition, in first-served order', () => {+ const served = resolveServedCustomEndpoints(endpoints);+ expect([...served.keys()]).toEqual(['ollama', 'Gateway']);+ expect(served.get('ollama')?.iconURL).toBe('last.png');+ expect(served.get('Gateway')?.iconURL).toBe('gateway.png');+ });++ it('is the definition the endpoint config serves under each name', () => {+ const config = loadCustomEndpointsConfig(endpoints as TCustomEndpoints);+ const served = resolveServedCustomEndpoints(endpoints);+ expect(Object.keys(config ?? {})).toEqual([...served.keys()]);+ for (const [name, endpoint] of served) {+ expect(config?.[name]?.iconURL).toBe(endpoint.iconURL);+ }+ });+});+describe('usesOpenRouterCatalog', () => {const OR = 'https://openrouter.ai/api/v1';const uses = (endpoint: Record<string, unknown>, baseURL: string = OR) =>diff --git a/packages/api/src/endpoints/custom/config.ts b/packages/api/src/endpoints/custom/config.tsindex 66625b7598..a2321facf7 100644--- a/packages/api/src/endpoints/custom/config.ts+++ b/packages/api/src/endpoints/custom/config.ts@@ -106,6 +106,43 @@ export function resolveCustomEndpointParameters(return withOpenRouterReasoning(endpoint, resolvedBaseURL);}+/** A custom endpoint definition the endpoint and model loaders serve. */+export type ServedCustomEndpoint = Partial<TEndpoint> &+ Pick<TEndpoint, 'name' | 'apiKey' | 'baseURL'>;++/**+ * Whether the endpoint and model loaders serve a custom endpoint definition: it names its base+ * URL and API key, and a model list or a fetch.+ */+export function isServedCustomEndpoint(+ endpoint: Partial<TEndpoint>,+): endpoint is ServedCustomEndpoint {+ return Boolean(+ endpoint.baseURL &&+ endpoint.apiKey &&+ endpoint.name &&+ endpoint.models &&+ (endpoint.models.fetch || endpoint.models.default),+ );+}++/**+ * The definition each served custom endpoint name resolves to, by served name (`Ollama` is served+ * as `ollama`): the last served definition of that name, which is the one `/api/endpoints` reports.+ * Names keep the order they are first served in.+ */+export function resolveServedCustomEndpoints(+ endpoints: readonly Partial<TEndpoint>[],+): Map<string, ServedCustomEndpoint> {+ const served = new Map<string, ServedCustomEndpoint>();+ for (const endpoint of endpoints) {+ if (isServedCustomEndpoint(endpoint)) {+ served.set(normalizeEndpointName(endpoint.name), endpoint);+ }+ }+ return served;+}+/*** Load config endpoints from the cached configuration object* @param customEndpointsConfig - The configuration object@@ -120,31 +157,12 @@ export function loadCustomEndpointsConfig(const customEndpointsConfig: TCustomEndpointsConfig = {};if (Array.isArray(customEndpoints)) {- const filteredEndpoints = customEndpoints.filter(- (endpoint) =>- endpoint.baseURL &&- endpoint.apiKey &&- endpoint.name &&- endpoint.models &&- (endpoint.models.fetch || endpoint.models.default),- );-- for (let i = 0; i < filteredEndpoints.length; i++) {- const endpoint = filteredEndpoints[i] as TEndpoint;- const {- baseURL,- apiKey,- name: configName,- iconURL,- modelDisplayLabel,- customParams,- provider,- dropParams,- } = endpoint;- const name = normalizeEndpointName(configName);-- const resolvedApiKey = extractEnvVariable(apiKey ?? '');- const resolvedBaseURL = extractEnvVariable(baseURL ?? '');+ for (const [name, endpoint] of resolveServedCustomEndpoints(customEndpoints)) {+ const { baseURL, apiKey, iconURL, modelDisplayLabel, customParams, provider, dropParams } =+ endpoint;++ const resolvedApiKey = extractEnvVariable(apiKey);+ const resolvedBaseURL = extractEnvVariable(baseURL);const userProvideURL = isUserProvided(resolvedBaseURL);/**diff --git a/packages/api/src/langfuse/policy.ts b/packages/api/src/langfuse/policy.tsindex dfa4265efa..6e1af0365f 100644--- a/packages/api/src/langfuse/policy.ts+++ b/packages/api/src/langfuse/policy.ts@@ -1,4 +1,5 @@import { isForcedTemporaryRetention } from 'librechat-data-provider';+import type { TLangfuseUnavailableReason } from 'librechat-data-provider';import type { AppConfig } from '@librechat/data-schemas';import { isFalseEnv, isTrueEnv } from './utils';import { normalizeString } from '~/utils/text';@@ -94,12 +95,36 @@ export function isLangfuseTraceSampled(traceId: string): boolean {return traceIdAccumulation(traceId) < Math.floor(sampleRate * MAX_TRACE_ID_ACCUMULATION);}-export function isLangfuseConnectionAvailable(): boolean {+/** Whether the deployment offers Langfuse connection settings, and if not, why. */+export type LangfuseConnectionAvailability =+ | { available: true }+ | { available: false; reason: TLangfuseUnavailableReason };++/**+ * Whether admins can store a Langfuse connection: tracing is on, and either traces route per+ * tenant through a fanout collector that exports to tenants' projects, or a single-tenant+ * deployment has no Langfuse credentials in its environment (which would take the connection's+ * place). Otherwise the reason names the setting that stops it.+ */+export function getLangfuseConnectionAvailability(): LangfuseConnectionAvailability {if (!isLangfuseTracingEnabled()) {- return false;+ return { available: false, reason: 'tracing_disabled' };}if (usesLangfuseMultiTenantRouting()) {- return isLangfuseFanoutEnabled() && isLangfuseTenantExportEnabled();+ if (!isLangfuseFanoutEnabled()) {+ return { available: false, reason: 'fanout_disabled' };+ }+ if (!isLangfuseTenantExportEnabled()) {+ return { available: false, reason: 'tenant_export_disabled' };+ }+ return { available: true };}- return !hasLangfuseEnvCredentials();+ if (hasLangfuseEnvCredentials()) {+ return { available: false, reason: 'env_credentials' };+ }+ return { available: true };+}++export function isLangfuseConnectionAvailable(): boolean {+ return getLangfuseConnectionAvailability().available;}diff --git a/packages/api/src/tools/available.ts b/packages/api/src/tools/available.tsnew file mode 100644index 0000000000..a4996ae9fb--- /dev/null+++ b/packages/api/src/tools/available.ts@@ -0,0 +1,57 @@+import type { TCustomConfig, TPlugin } from 'librechat-data-provider';+import { checkPluginAuth, filterUniquePlugins, getToolkitKey } from './format';+import { filterGitHubComparePlugins } from './compare';++/** A tool manifest entry: a plugin, and whether only the agents runtime can run it. */+export type ManifestTool = TPlugin & { agentsOnly?: boolean };++export interface ListAvailableToolsParams {+ /** The tool manifest (`api/app/clients/tools/manifest.json`). */+ manifest: ManifestTool[];+ /** The manifest entries that are toolkits, whose tools are defined under prefixed names. */+ toolkits: TPlugin[];+ /** The tool definitions the server loaded, by name (the tool cache). */+ toolDefinitions: Record<string, unknown> | null | undefined;+ /** The requester's `githubCompare` config: the compare tool is listed only when enabled. */+ githubCompare?: TCustomConfig['githubCompare'];+ /**+ * Leaves out the tools only the agents runtime can run (`agentsOnly`, such as+ * `ask_user_question`), for the Assistants tool dialog.+ */+ forAssistants?: boolean;+}++/**+ * The manifest tools a server offers: each unique manifest entry the loaded definitions define,+ * by its own key or (a toolkit) through a tool under its prefix, marked `authenticated` when the+ * server holds every credential it needs. This is what `GET /api/agents/tools` lists.+ */+export function listAvailableTools({+ manifest,+ toolkits,+ toolDefinitions,+ githubCompare,+ forAssistants = false,+}: ListAvailableToolsParams): ManifestTool[] {+ const plugins: ManifestTool[] = filterUniquePlugins(+ filterGitHubComparePlugins(manifest, githubCompare),+ );+ const definedKeys = toolDefinitions ? Object.keys(toolDefinitions) : null;+ const defined = definedKeys ? new Set(definedKeys) : null;+ const tools: ManifestTool[] = [];+ for (const plugin of plugins) {+ if (plugin.agentsOnly === true && forAssistants) {+ continue;+ }+ const isDefined = defined?.has(plugin.pluginKey) === true;+ const isToolkit =+ plugin.toolkit === true &&+ definedKeys != null &&+ definedKeys.some((key) => getToolkitKey({ toolkits, toolName: key }) === plugin.pluginKey);+ if (!isDefined && !isToolkit) {+ continue;+ }+ tools.push(checkPluginAuth(plugin) ? { ...plugin, authenticated: true } : plugin);+ }+ return tools;+}diff --git a/packages/api/src/tools/index.ts b/packages/api/src/tools/index.tsindex c8cb7fe004..630201e75b 100644--- a/packages/api/src/tools/index.ts+++ b/packages/api/src/tools/index.ts@@ -7,3 +7,4 @@ export * from './definitions';export * from './classification';export * from './rolePermissions';export * from './compare';+export * from './available';diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.tsindex 09afd487bd..e7662fb55f 100644--- a/packages/data-provider/src/config.spec.ts+++ b/packages/data-provider/src/config.spec.ts@@ -1987,6 +1987,23 @@ describe('any custom endpoint is document-supported regardless of name', () => {);});+describe('endpoints.catalogModelsTtlMs', () => {+ const parse = (catalogModelsTtlMs: unknown) =>+ configSchema.safeParse({ version: '1.0', endpoints: { catalogModelsTtlMs } });++ it('accepts zero up to one hour of whole milliseconds', () => {+ for (const value of [0, 120_000, 3_600_000]) {+ expect(parse(value).success).toBe(true);+ }+ });++ it('rejects negative, fractional and longer lifetimes', () => {+ for (const value of [-1, 1.5, 3_600_001, '120000']) {+ expect(parse(value).success).toBe(false);+ }+ });+});+describe('allowedAddressesSchema', () => {describe('accepts valid entries', () => {it.each([diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 9329263d23..65a5184966 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -124,14 +124,20 @@ export const BASE_PRINCIPAL_CONFIG_SECTIONS = ['langfuse'] as const;* or tenant config document can neither change nor remove them. The pull request provider and* host decide where the deployment's token is sent, the OAuth app which credentials users grant* and which environment secret is sent with them, and the shared cache's slot count where every- * replica looks for a shared answer. */+ * replica looks for a shared answer. The admin catalog's model-list lifetime is one value for the+ * whole deployment, which `GET /api/admin/config/meta` reports. */export const BASE_ONLY_CONFIG_PATHS = ['endpoints.agents.pullRequests.provider','endpoints.agents.pullRequests.host','endpoints.agents.pullRequests.oauth','endpoints.agents.pullRequests.sharedCacheSlots',+ 'endpoints.catalogModelsTtlMs',] as const;+/** How long the admin config catalog reuses a scope's model lists unless+ * `endpoints.catalogModelsTtlMs` sets it: the two minutes a provider's model list is cached for. */+export const DEFAULT_CATALOG_MODELS_TTL_MS = 120_000;+export const defaultRetrievalModels = ['gpt-4o','o1-preview-2024-09-12',@@ -4478,6 +4484,13 @@ export const configSchema = z.object({endpoints: z.object({allowedAddresses: allowedAddressesSchema,+ /**+ * Milliseconds the admin config catalog (`GET /api/admin/config/catalog`) reuses a scope's+ * model lists while its endpoint config is unchanged, up to one hour; `0` resolves them on+ * every read, where a fetched list may still come from the two-minute model-list cache.+ * Only librechat.yaml sets it. Omission keeps `DEFAULT_CATALOG_MODELS_TTL_MS` (two minutes).+ */+ catalogModelsTtlMs: z.number().int().min(0).max(3_600_000).optional(),/*** Defaults applied to every endpoint. Omit-based, so options added to* `baseEndpointSchema` are inherited here automatically — no list todiff --git a/packages/data-provider/src/types.ts b/packages/data-provider/src/types.tsindex d1c8adfab1..eef6a008cb 100644--- a/packages/data-provider/src/types.ts+++ b/packages/data-provider/src/types.ts@@ -1330,6 +1330,29 @@ export type TLangfuseConnectionStatus = {updatedAt?: string;};+/**+ * Why a deployment offers no Langfuse connection settings, from its environment:+ * - `tracing_disabled`: `LANGFUSE_TRACING_ENABLED=false`, or `LANGFUSE_SAMPLE_RATE` is 0;+ * - `env_credentials`: a single-tenant deployment traces with `LANGFUSE_PUBLIC_KEY` and+ * `LANGFUSE_SECRET_KEY`, which take the place of a stored connection;+ * - `fanout_disabled`: traces route per tenant (`TENANT_ISOLATION_STRICT`) but the fanout+ * collector is off (`LANGFUSE_FANOUT_ENABLED` with `LANGFUSE_FANOUT_COLLECTOR_URL`);+ * - `tenant_export_disabled`: the fanout collector runs, but+ * `LANGFUSE_FANOUT_TENANT_EXPORT_DISABLED=true` stops the export to tenants' own projects.+ */+export type TLangfuseUnavailableReason =+ | 'tracing_disabled'+ | 'env_credentials'+ | 'fanout_disabled'+ | 'tenant_export_disabled';++/** 404 from the admin Langfuse connection routes on a deployment that offers no connection. */+export type TLangfuseUnavailableResponse = {+ error: string;+ code: 'LANGFUSE_UNAVAILABLE';+ reason: TLangfuseUnavailableReason;+};+export type TLangfuseDestinationOption = {key: string;baseUrl: string;diff --git a/packages/data-schemas/src/app/endpoints.ts b/packages/data-schemas/src/app/endpoints.tsindex 70a5376528..7a54f64342 100644--- a/packages/data-schemas/src/app/endpoints.ts+++ b/packages/data-schemas/src/app/endpoints.ts@@ -21,6 +21,7 @@ export const loadEndpoints = (agentsDefaults?: Partial<TAgentsEndpoint>,): {allowedAddresses?: string[];+ catalogModelsTtlMs?: number;openAI?: Partial<import('librechat-data-provider').TEndpoint>;google?: Partial<import('librechat-data-provider').TEndpoint>;bedrock?: Partial<import('librechat-data-provider').TEndpoint>;@@ -105,5 +106,9 @@ export const loadEndpoints = (loadedEndpoints.allowedAddresses = endpoints.allowedAddresses;}+ if (endpoints?.catalogModelsTtlMs !== undefined) {+ loadedEndpoints.catalogModelsTtlMs = endpoints.catalogModelsTtlMs;+ }+return loadedEndpoints;};diff --git a/packages/data-schemas/src/app/resolution.layers.spec.ts b/packages/data-schemas/src/app/resolution.layers.spec.tsnew file mode 100644index 0000000000..3f75944dcf--- /dev/null+++ b/packages/data-schemas/src/app/resolution.layers.spec.ts@@ -0,0 +1,429 @@+import { PrincipalType } from 'librechat-data-provider';+import type { DeepPartial, TCustomConfig } from 'librechat-data-provider';+import type { AppConfig, AdminConfigLayerIgnored } from '~/types';+import type { ConfigOverrideLayer } from './resolution';+import { mergeConfigOverrides, resolveConfigLayers, resolveRawConfig } from './resolution';+import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';+import { AppService } from './service';+import logger from '~/config/winston';++type Overrides = Record<string, unknown>;++function layer(+ principalType: string,+ principalId: string,+ overrides: Overrides,+ options: { priority?: number; tombstones?: string[]; id?: string } = {},+): ConfigOverrideLayer {+ return {+ _id: options.id ?? `${principalType}-${principalId}`,+ principalType: principalType as PrincipalType,+ principalId,+ priority: options.priority ?? 10,+ overrides: overrides as Partial<TCustomConfig>,+ tombstones: options.tombstones,+ };+}++const base = (overrides: Overrides, tombstones?: string[]) =>+ layer(PrincipalType.ROLE, BASE_CONFIG_PRINCIPAL_ID, overrides, { priority: 0, tombstones });+const role = (overrides: Overrides, tombstones?: string[]) =>+ layer(PrincipalType.ROLE, 'editors', overrides, { priority: 10, tombstones });+const group = (overrides: Overrides, tombstones?: string[]) =>+ layer(PrincipalType.GROUP, 'g1', overrides, { priority: 20, tombstones });++const YAML: DeepPartial<TCustomConfig> = {+ version: '1.3.0',+ cache: true,+ interface: {+ customWelcome: 'Hello from YAML',+ schedules: false,+ theme: {+ version: 1,+ name: 'yaml-theme',+ modes: {+ light: { colors: { 'surface-primary': '255 255 255' } },+ dark: { colors: { 'surface-primary': '0 0 0' } },+ },+ },+ },+ registration: { socialLogins: ['github'] },+ endpoints: {+ custom: [+ {+ name: 'Ollama',+ apiKey: 'ollama',+ baseURL: 'http://ollama:11434/v1',+ models: { default: ['llama3'], fetch: false },+ },+ {+ name: 'Gateway',+ apiKey: '${GATEWAY_KEY}',+ baseURL: 'https://gateway.example.com/v1',+ models: { default: ['gpt-4o'] },+ },+ ],+ agents: {+ pullRequests: { provider: 'github', host: 'github.com' },+ } as never,+ },+ mcpServers: {+ docs: { type: 'streamable-http', url: 'https://docs.example.com/mcp' },+ local: { type: 'stdio', command: 'node', args: ['server.js'] },+ },+ webSearch: {+ searxngInstanceUrl: '${SEARXNG_INSTANCE_URL}',+ searxngApiKey: '${SEARXNG_API_KEY}',+ },+ filters: { messages: { pii: { action: 'audit' } } } as never,+};++const ROLE_THEME = {+ version: 1,+ name: 'role-theme',+ modes: { dark: { colors: { 'surface-primary': '10 10 10' } } },+};++let appConfig: AppConfig;++beforeAll(async () => {+ jest.spyOn(logger, 'warn').mockReturnValue(logger);+ jest.spyOn(logger, 'info').mockReturnValue(logger);+ appConfig = await AppService({ config: structuredClone(YAML) });+});++afterAll(() => {+ jest.restoreAllMocks();+});++function ignoredOf(resolution: ReturnType<typeof resolveConfigLayers>, index: number) {+ return resolution.layers[index].ignored;+}++function reasons(ignored: AdminConfigLayerIgnored[]): Array<[string, string]> {+ return ignored.map(({ path, reason }) => [path, reason]);+}++function toIgnoredTombstone(+ path: string,+ reason: AdminConfigLayerIgnored['reason'],+): AdminConfigLayerIgnored {+ return { path, segments: path.split('.'), reason, tombstone: true };+}++/** Layer sets the merge applies differently, each exercising one of its rules. */+const PARITY_CASES: Array<[string, () => ConfigOverrideLayer[]]> = [+ ['no layers', () => []],+ ['a plain section', () => [role({ interface: { customWelcome: 'Hi role' } })]],+ [+ 'interface permissions, composite permission fields and runtime toggles',+ () => [+ role({+ interface: {+ customWelcome: 'Hi',+ prompts: false,+ mcpServers: { use: false, placeholder: 'Pick a server' },+ schedules: true,+ },+ }),+ ],+ ],+ ['an atomic theme', () => [role({ interface: { theme: ROLE_THEME } })]],+ [+ 'custom endpoints merged by folded name',+ () => [+ base({ endpoints: { custom: [{ name: 'ollama', baseURL: 'http://other:11434/v1' }] } }),+ role({+ endpoints: {+ custom: [+ {+ name: 'Extra',+ apiKey: 'k',+ baseURL: 'https://extra.example.com',+ models: { default: ['m'] },+ },+ ],+ },+ }),+ ],+ ],+ [+ 'tombstones of YAML MCP servers, including a process-backed one',+ () => [role({}, ['mcpServers.docs', 'mcpServers.local'])],+ ],+ [+ 'process MCP overrides',+ () => [role({ mcpServers: { local: { args: ['other.js'] }, extra: { command: 'x' } } })],+ ],+ [+ 'invalid overrides, unknown sections and base-only sections',+ () => [+ role({+ registration: { socialLogins: 'not-a-list' },+ paths: { uploads: '/tmp' },+ filters: { messages: { pii: { action: 'block' } } },+ langfuse: { enabled: true },+ }),+ ],+ ],+ [+ 'web search keys whose URL another layer decides',+ () => [+ base({ webSearch: { searxngApiKey: 'base-key' } }),+ role({ webSearch: { searxngInstanceUrl: 'https://search.example.com' } }),+ ],+ ],+ ['a runtime stop', () => [role({ interface: { schedules: true } })]],+ [+ 'base-only fields',+ () => [+ role({ endpoints: { agents: { pullRequests: { host: 'evil.example.com' } } } }),+ group({}, ['endpoints.agents.pullRequests.provider']),+ ],+ ],+ [+ 'tombstones above base-only fields and a runtime stop',+ () => [+ role({}, ['endpoints.agents.pullRequests']),+ group({ interface: { customWelcome: 'Hi group' } }, ['interface.schedules']),+ ],+ ],+ [+ 'Azure groups, valid and not',+ () => [+ base({+ endpoints: {+ azureOpenAI: {+ groups: [+ {+ group: 'east',+ apiKey: 'k',+ instanceName: 'east',+ version: '2024-02-01',+ models: { 'gpt-4o': { deploymentName: 'gpt-4o' } },+ },+ ],+ },+ },+ }),+ role({+ endpoints: {+ azureOpenAI: { groups: [{ group: 'west', apiKey: 'k', models: { 'gpt-4o': true } }] },+ },+ }),+ ],+ ],+ [+ 'precedence: Base first whatever its priority',+ () => [+ role({ interface: { customWelcome: 'role' } }),+ layer(+ PrincipalType.ROLE,+ BASE_CONFIG_PRINCIPAL_ID,+ { interface: { customWelcome: 'base' } },+ { priority: 999 },+ ),+ ],+ ],+];++describe('resolveConfigLayers', () => {+ it.each(PARITY_CASES)('merges exactly as mergeConfigOverrides: %s', (_name, build) => {+ const configs = build();+ expect(resolveConfigLayers(appConfig, configs).merged).toEqual(+ mergeConfigOverrides(appConfig, configs),+ );+ });++ it('returns librechat.yaml in its own shape when no layer applies', () => {+ const { resolved, layers } = resolveConfigLayers(appConfig, []);+ expect(resolved).toEqual(YAML);+ expect(layers).toEqual([]);+ });++ it('lists layers in merge order, Base first whatever its priority', () => {+ const configs = PARITY_CASES.find(([name]) => name.startsWith('precedence'))![1]();+ const { layers, resolved } = resolveConfigLayers(appConfig, configs);+ expect(layers.map(({ layer: l }) => l.principalId)).toEqual([+ BASE_CONFIG_PRINCIPAL_ID,+ 'editors',+ ]);+ expect(layers[0].layer).toBe(configs[1]);+ expect(resolved.interface?.customWelcome).toBe('role');+ });++ it('resolves in librechat.yaml keys, never the AppConfig names', () => {+ const { resolved } = resolveConfigLayers(appConfig, [+ role({ interface: { customWelcome: 'Hi' }, mcpServers: { extra: { url: 'https://x/mcp' } } }),+ ]);+ expect(resolved).not.toHaveProperty('interfaceConfig');+ expect(resolved).not.toHaveProperty('mcpConfig');+ expect(resolved.interface?.customWelcome).toBe('Hi');+ expect(Object.keys(resolved.mcpServers ?? {})).toEqual(['docs', 'local', 'extra']);+ });++ it('drops interface permissions as the merge does, and reports each', () => {+ const configs = PARITY_CASES[2][1]();+ const resolution = resolveConfigLayers(appConfig, configs);+ expect(resolution.resolved.interface).toMatchObject({+ customWelcome: 'Hi',+ mcpServers: { placeholder: 'Pick a server' },+ });+ expect(resolution.resolved.interface).not.toHaveProperty('prompts');+ expect(reasons(ignoredOf(resolution, 0))).toEqual(+ expect.arrayContaining([+ ['interface.prompts', 'interface_permission'],+ ['interface.mcpServers.use', 'interface_permission'],+ ]),+ );+ });++ it('replaces a theme whole, as the merge does', () => {+ const { resolved } = resolveConfigLayers(appConfig, PARITY_CASES[3][1]());+ expect(resolved.interface?.theme).toEqual(ROLE_THEME);+ });++ it('merges custom endpoints by the name the runtime folds, keeping the YAML spelling', () => {+ const { resolved } = resolveConfigLayers(appConfig, PARITY_CASES[4][1]());+ const custom = resolved.endpoints?.custom ?? [];+ expect(custom.map((endpoint) => endpoint.name)).toEqual(['Ollama', 'Gateway', 'Extra']);+ expect(custom[0]).toMatchObject({ apiKey: 'ollama', baseURL: 'http://other:11434/v1' });+ });++ it('hides a tombstoned YAML MCP server but keeps a process-backed one, as the merge does', () => {+ const resolution = resolveConfigLayers(appConfig, PARITY_CASES[5][1]());+ expect(Object.keys(resolution.resolved.mcpServers ?? {})).toEqual(['local']);+ expect(Object.keys(resolution.merged.mcpConfig ?? {})).toEqual(['local']);+ });++ it('reports process-backed MCP overrides and leaves the YAML server as written', () => {+ const resolution = resolveConfigLayers(appConfig, PARITY_CASES[6][1]());+ expect(resolution.resolved.mcpServers?.local).toEqual(YAML.mcpServers?.local);+ expect(resolution.resolved.mcpServers).not.toHaveProperty('extra');+ expect(reasons(ignoredOf(resolution, 0))).toEqual([+ ['mcpServers.local', 'process_mcp_server'],+ ['mcpServers.extra', 'process_mcp_server'],+ ]);+ });++ it('reports invalid overrides, unknown, base-only and Base-only sections, and applies none', () => {+ const resolution = resolveConfigLayers(appConfig, PARITY_CASES[7][1]());+ expect(resolution.resolved.registration).toEqual(YAML.registration);+ expect(resolution.resolved.filters).toEqual(YAML.filters);+ expect(resolution.resolved).not.toHaveProperty('paths');+ expect(resolution.resolved).not.toHaveProperty('langfuse');+ const ignored = ignoredOf(resolution, 0);+ expect(reasons(ignored)).toEqual(+ expect.arrayContaining([+ ['paths', 'unknown_section'],+ ['registration.socialLogins', 'invalid_override'],+ ['filters', 'base_only_section'],+ ['langfuse', 'base_principal_section'],+ ]),+ );+ expect(ignored.find(({ reason }) => reason === 'invalid_override')?.code).toBeTruthy();+ });++ it('withholds a web search key from the URL another layer decides, on the URL writer', () => {+ const resolution = resolveConfigLayers(appConfig, PARITY_CASES[8][1]());+ expect(resolution.resolved.webSearch).toEqual({+ searxngInstanceUrl: 'https://search.example.com',+ });+ expect(resolution.merged.webSearch).not.toHaveProperty('searxngApiKey');+ expect(reasons(ignoredOf(resolution, 1))).toEqual([+ ['webSearch.searxngApiKey', 'secret_rebinding'],+ ]);+ expect(ignoredOf(resolution, 0)).toEqual([]);+ });++ it('keeps an interface feature librechat.yaml turns off, off', () => {+ const resolution = resolveConfigLayers(appConfig, PARITY_CASES[9][1]());+ expect(resolution.resolved.interface?.schedules).toBe(false);+ expect(reasons(ignoredOf(resolution, 0))).toEqual([['interface.schedules', 'runtime_stop']]);+ });++ it('keeps base-only fields at their librechat.yaml value, for writes and tombstones', () => {+ const resolution = resolveConfigLayers(appConfig, PARITY_CASES[10][1]());+ expect(resolution.resolved.endpoints?.agents).toEqual(YAML.endpoints?.agents);+ expect(ignoredOf(resolution, 0)).toEqual([+ expect.objectContaining({+ path: 'endpoints.agents.pullRequests.host',+ reason: 'base_only_path',+ }),+ ]);+ expect(ignoredOf(resolution, 1)).toEqual([+ expect.objectContaining({+ path: 'endpoints.agents.pullRequests.provider',+ reason: 'base_only_path',+ tombstone: true,+ }),+ ]);+ });++ it('keeps what librechat.yaml holds under a tombstone above it, and reports each kept field', () => {+ const configs = PARITY_CASES.find(([name]) => name.startsWith('tombstones above'))![1]();+ const resolution = resolveConfigLayers(appConfig, configs);+ expect(resolution.merged.endpoints?.agents?.pullRequests).toMatchObject({+ provider: 'github',+ host: 'github.com',+ });+ expect(resolution.resolved.endpoints?.agents).toEqual(YAML.endpoints?.agents);+ expect(resolution.merged.interfaceConfig?.schedules).toBe(false);+ expect(resolution.resolved.interface).toMatchObject({+ customWelcome: 'Hi group',+ schedules: false,+ });+ expect(ignoredOf(resolution, 0)).toEqual([+ toIgnoredTombstone('endpoints.agents.pullRequests.provider', 'base_only_path'),+ toIgnoredTombstone('endpoints.agents.pullRequests.host', 'base_only_path'),+ ]);+ expect(ignoredOf(resolution, 1)).toEqual([+ toIgnoredTombstone('interface.schedules', 'runtime_stop'),+ ]);+ });++ it('reports a tombstone above base-only fields only for those librechat.yaml sets', () => {+ const resolution = resolveConfigLayers(appConfig, [role({}, ['endpoints.agents'])]);+ expect(resolution.resolved.endpoints?.agents).toEqual(YAML.endpoints?.agents);+ expect(reasons(ignoredOf(resolution, 0))).toEqual([+ ['endpoints.agents.pullRequests.provider', 'base_only_path'],+ ['endpoints.agents.pullRequests.host', 'base_only_path'],+ ]);+ });++ it('keeps Azure groups as written and reports groups the Azure clients never read', () => {+ const configs = PARITY_CASES.find(([name]) => name.startsWith('Azure groups'))![1]();+ const resolution = resolveConfigLayers(appConfig, configs);+ const azure = resolution.resolved.endpoints?.azureOpenAI;+ expect(azure?.groups?.map((entry) => entry.group)).toEqual(['west']);+ expect(azure).not.toHaveProperty('groupMap');+ expect(Object.keys(resolution.merged.endpoints?.azureOpenAI?.groupMap ?? {})).toEqual(['east']);+ expect(reasons(ignoredOf(resolution, 1))).toEqual([+ ['endpoints.azureOpenAI.groups', 'azure_groups_unresolved'],+ ]);+ });++ it('matches the validation floor where the merge applies a layer as written', () => {+ const configs = [+ base({ registration: { socialLogins: ['google'] } }),+ role(+ {+ endpoints: { custom: [{ name: 'Gateway', models: { default: ['gpt-4.1'] } }] },+ mcpServers: { docs: { timeout: 5000 } },+ },+ ['webSearch.searxngApiKey'],+ ),+ ];+ const yaml = appConfig.config as Partial<TCustomConfig>;+ expect(resolveConfigLayers(appConfig, configs).resolved).toEqual(+ resolveRawConfig(yaml, configs),+ );+ });++ it('never changes the documents it reads', () => {+ const configs = PARITY_CASES.flatMap(([, build]) => build());+ const before = structuredClone(configs);+ resolveConfigLayers(appConfig, configs);+ expect(configs).toEqual(before);+ });+});diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.tsindex 74e783b2e3..e4cc5239ca 100644--- a/packages/data-schemas/src/app/resolution.spec.ts+++ b/packages/data-schemas/src/app/resolution.spec.ts@@ -192,6 +192,18 @@ describe('mergeConfigOverrides', () => {).toEqual({ siteKey: 'yaml-site-key' });});+ it('keeps the admin catalog model-list lifetime on librechat.yaml', () => {+ const base = { endpoints: { catalogModelsTtlMs: 600_000 } } as unknown as AppConfig;+ const read = (configs: IConfig[]) => mergeConfigOverrides(base, configs).endpoints;++ expect(read([fakeConfig({ endpoints: { catalogModelsTtlMs: 0 } }, 10)])).toEqual({+ catalogModelsTtlMs: 600_000,+ });+ expect(+ read([fakeConfig({}, 0, ['endpoints.catalogModelsTtlMs'], BASE_CONFIG_PRINCIPAL_ID)]),+ ).toEqual({ catalogModelsTtlMs: 600_000 });+ });+it('keeps the pull request host from the base config whatever an override does', () => {const pullRequests = { host: 'ghe.example.com', allowedRepositories: ['acme/*'] };const base = { endpoints: { agents: { pullRequests } } } as unknown as AppConfig;diff --git a/packages/data-schemas/src/app/resolution.ts b/packages/data-schemas/src/app/resolution.tsindex 1a4306ab11..6c2cc8bd3b 100644--- a/packages/data-schemas/src/app/resolution.ts+++ b/packages/data-schemas/src/app/resolution.ts@@ -11,7 +11,14 @@ import {configSchema,} from 'librechat-data-provider';import type { TCustomConfig } from 'librechat-data-provider';-import type { AdminConfigMergeRules, AppConfig, Config, TWebSearchKeys } from '~/types';+import type {+ AdminConfigLayerIgnoreReason,+ AdminConfigLayerIgnored,+ AdminConfigMergeRules,+ TWebSearchKeys,+ AppConfig,+ Config,+} from '~/types';import type { AzureResolvedGroupField } from './azure';import type { ConfigFieldWrite } from './mutations';import {@@ -1208,6 +1215,7 @@ function omitPath(target: unknown, segments: string[]): unknown {function stripInvalidOverrides(config: ConfigOverrideLayer,base: Partial<TCustomConfig>,+ onStripped?: (issue: ConfigOverrideIssue) => void,): AnyObject {const principal = `${config.principalType}/${config.principalId}`;let stripped: unknown = combineStoredFoldedItems(config.overrides, principal);@@ -1222,6 +1230,7 @@ function stripInvalidOverrides(}if (issues.some((issue) => issue.segments.length === 0)) {logger.warn(`[mergeConfigOverrides] Ignoring malformed overrides document for ${principal}`);+ onStripped?.(toIssue([], issues.find((issue) => issue.segments.length === 0)?.code ?? ''));return {};}const before = stripped;@@ -1231,17 +1240,24 @@ function stripInvalidOverrides(`[mergeConfigOverrides] Ignoring invalid override "${path}" for ${principal} (${code})`,);stripped = omitPath(stripped, segments);+ onStripped?.(issues[index]);}if (stripped === before) {break;}}- const failing = new Set(- getConfigOverrideIssues(stripped, base).map((issue) => issue.segments[0]),- );+ const failing = new Map<string, string>();+ for (const issue of getConfigOverrideIssues(stripped, base)) {+ if (!failing.has(issue.segments[0])) {+ failing.set(issue.segments[0], issue.code);+ }+ }logger.warn(- `[mergeConfigOverrides] Ignoring still-invalid sections ${[...failing].join(', ')} for ${principal}`,+ `[mergeConfigOverrides] Ignoring still-invalid sections ${[...failing.keys()].join(', ')} for ${principal}`,);+ for (const [section, code] of failing) {+ onStripped?.(toIssue([section], code));+ }return Object.fromEntries(Object.entries(stripped as AnyObject).filter(([section]) => !failing.has(section)),);@@ -1559,6 +1575,109 @@ function withServedAzureModels<T extends AppConfig>(};}+/** What a tracked fold records about one layer (`resolveConfigLayers`). */+interface LayerTrack {+ /** The document as given. */+ layer: ConfigOverrideLayer;+ /** The document the fold read: `layer` with only accepted sections (`withAcceptedSections`). */+ accepted: ConfigOverrideLayer;+ /**+ * What its overrides contributed to the YAML-shaped result, under AppConfig section names:+ * invalid, base-only and filtered values removed, Azure `groups` as written.+ */+ contributed: AnyObject;+ /** The tombstones the fold applied, in librechat.yaml keys. */+ tombstoned: string[];+ ignored: AdminConfigLayerIgnored[];+}++/**+ * A fold's record of the YAML-shaped result and of what each layer could not apply. `resolved`+ * is `librechat.yaml` folded exactly as `merged` is (same tombstones, filters, merge keys and+ * atomic paths), kept under AppConfig section names (`interfaceConfig`, `mcpConfig`, ...) so the+ * merge rules address it as they address `merged`.+ */+interface FoldTracker {+ resolved: AnyObject;+ layers: LayerTrack[];+}++function toIgnored(+ segments: readonly string[],+ reason: AdminConfigLayerIgnoreReason,+ extra?: Pick<AdminConfigLayerIgnored, 'code' | 'tombstone'>,+): AdminConfigLayerIgnored {+ return { path: segments.join('.'), segments: [...segments], reason, ...extra };+}++/** `tree` with its top-level keys in AppConfig names (`interface` → `interfaceConfig`, ...). */+function toAppConfigKeys(tree: Partial<TCustomConfig>): AnyObject {+ const result: AnyObject = {};+ for (const [key, value] of Object.entries(tree)) {+ if (value !== undefined) {+ result[OVERRIDE_KEY_MAP[key as keyof typeof OVERRIDE_KEY_MAP] ?? key] = value;+ }+ }+ return result;+}++/** `tree` with its top-level keys back in librechat.yaml names. */+function toOverrideKeys(tree: AnyObject): Partial<TCustomConfig> {+ const result: AnyObject = {};+ for (const [key, value] of Object.entries(tree)) {+ if (value !== undefined) {+ result[OVERRIDE_SECTION_BY_APP_KEY.get(key) ?? key] = value;+ }+ }+ return result as Partial<TCustomConfig>;+}++/** Starts a layer's record with the sections `withAcceptedSections` left out of it. */+function startLayerTrack(+ tracker: FoldTracker,+ layer: ConfigOverrideLayer,+ accepted: ConfigOverrideLayer,+): LayerTrack {+ const ignored: AdminConfigLayerIgnored[] = [];+ if (accepted !== layer) {+ if (isPlainObject(layer.overrides)) {+ for (const key of Object.keys(layer.overrides)) {+ if (!isAcceptedOverrideSection(key)) {+ ignored.push(toIgnored([key], 'unknown_section'));+ }+ }+ }+ for (const path of Array.isArray(layer.tombstones) ? layer.tombstones : []) {+ if (typeof path === 'string' && !isAcceptedOverrideSection(path.split('.')[0])) {+ ignored.push(toIgnored(path.split('.'), 'unknown_section', { tombstone: true }));+ }+ }+ }+ const track: LayerTrack = { layer, accepted, contributed: {}, tombstoned: [], ignored };+ tracker.layers.push(track);+ return track;+}++/** The interface fields and sub-keys the permission filter removes from an interface override. */+function getInterfacePermissionRemovals(value: AnyObject): string[][] {+ const removed: string[][] = [];+ for (const [field, fieldVal] of Object.entries(value)) {+ if (!INTERFACE_PERMISSION_FIELDS.has(field)) {+ continue;+ }+ if (isPlainObject(fieldVal)) {+ for (const sub of Object.keys(fieldVal)) {+ if (PERMISSION_SUB_KEYS.has(sub)) {+ removed.push(['interface', field, sub]);+ }+ }+ } else if (!RUNTIME_CONFIG_INTERFACE_FIELDS.has(field)) {+ removed.push(['interface', field]);+ }+ }+ return removed;+}+/*** Folds override layers, in merge precedence order (`compareConfigPrecedence`), into* `merged`, the served config, and `raw`, the YAML-shaped config each layer is validated on@@ -1567,13 +1686,15 @@ function withServedAzureModels<T extends AppConfig>(* `groups` resolve into the fields the Azure clients read (`resolveLayerAzureGroups`).* `webSearchWriters` names the layer behind each paired web search field, by its position in* that order. `afterLayer` runs after each layer lands, and the next layer folds onto what it- * returns.+ * returns. With a `tracker`, the fold also keeps the YAML-shaped result the served config+ * corresponds to, and what of each layer it did not apply (`resolveConfigLayers`).*/function foldConfigLayers<T extends AnyObject>(initial: T,initialRaw: Partial<TCustomConfig>,configs: readonly ConfigOverrideLayer[],afterLayer?: (step: FoldStep<T>) => T,+ tracker?: FoldTracker,): { merged: T; raw: Partial<TCustomConfig>; webSearchWriters: WebSearchWriters } {const sorted = sortByConfigPrecedence(configs);let merged = initial;@@ -1581,6 +1702,7 @@ function foldConfigLayers<T extends AnyObject>(const webSearchWriters: WebSearchWriters = new Map();for (let order = 0; order < sorted.length; order++) {const config = withAcceptedSections(sorted[order]);+ const track = tracker && startLayerTrack(tracker, sorted[order], config);const below = merged;let contributed: AnyObject = {};const removed: string[] = [];@@ -1588,8 +1710,10 @@ function foldConfigLayers<T extends AnyObject>(if (Array.isArray(config.tombstones)) {const removal: WebSearchWriter = { config, order, removed: true };for (const path of config.tombstones) {+ if (typeof path !== 'string') {+ continue;+ }if (- typeof path === 'string' &&!isBaseOnlyOverridePath(path) &&(isBasePrincipal || !BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(path.split('.')[0]))) {@@ -1598,11 +1722,23 @@ function foldConfigLayers<T extends AnyObject>(removed.push(mappedPath);merged = deleteConfigPath(merged, mappedPath);raw = deletePath(raw as AnyObject, removedPath) as Partial<TCustomConfig>;+ if (tracker) {+ tracker.resolved = deleteConfigPath(tracker.resolved, mappedPath);+ }}if (path === AZURE_GROUPS_PATH) {merged = withoutAzureGroups(merged);}+ track?.tombstoned.push(path);recordWebSearchTombstone(webSearchWriters, path, removal);+ } else if (track) {+ track.ignored.push(+ toIgnored(+ path.split('.'),+ isBaseOnlyOverridePath(path) ? 'base_only_section' : 'base_principal_section',+ { tombstone: true },+ ),+ );}}}@@ -1611,11 +1747,27 @@ function foldConfigLayers<T extends AnyObject>(const remapped: AnyObject = {};const applied: AnyObject = {};let replacesAzureGroups = false;- for (const [key, value] of Object.entries(stripInvalidOverrides(config, raw))) {+ let writtenEndpoints: unknown;+ const valid = stripInvalidOverrides(+ config,+ raw,+ track &&+ ((issue) =>+ track.ignored.push(+ toIgnored(issue.segments, 'invalid_override', { code: issue.code }),+ )),+ );+ for (const [key, value] of Object.entries(valid)) {if (BASE_ONLY_OVERRIDE_SECTIONS.has(key) ||(!isBasePrincipal && BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(key))) {+ track?.ignored.push(+ toIgnored(+ [key],+ BASE_ONLY_OVERRIDE_SECTIONS.has(key) ? 'base_only_section' : 'base_principal_section',+ ),+ );continue;}applied[key] = value;@@ -1624,6 +1776,13 @@ function foldConfigLayers<T extends AnyObject>(remapped[mappedKey] = filterMCPServerOverrides(value, merged[mappedKey]);/** A server the filter removed must not complete a later layer's partial of it. */applied[key] = remapped[mappedKey];+ if (track && isPlainObject(value)) {+ for (const name of Object.keys(value)) {+ if (!hasOwn(remapped[mappedKey] as AnyObject, name)) {+ track.ignored.push(toIgnored([key, name], 'process_mcp_server'));+ }+ }+ }} else if (key === 'interface' &&value != null &&@@ -1660,10 +1819,17 @@ function foldConfigLayers<T extends AnyObject>(if (Object.keys(filtered).length > 0) {remapped[mappedKey] = filtered;}+ for (const segments of track ? getInterfacePermissionRemovals(value as AnyObject) : []) {+ track?.ignored.push(toIgnored(segments, 'interface_permission'));+ }} else if (key === 'endpoints') {const resolved = resolveLayerAzureGroups(value, config);remapped[mappedKey] = resolved ?? value;replacesAzureGroups = resolved != null;+ writtenEndpoints = value;+ if (track && resolved == null && hasAzureGroups(value)) {+ track.ignored.push(toIgnored(AZURE_GROUPS_PATH.split('.'), 'azure_groups_unresolved'));+ }} else {remapped[mappedKey] = value;}@@ -1672,6 +1838,9 @@ function foldConfigLayers<T extends AnyObject>(for (const path of AZURE_RESOLVED_PATHS) {merged = deletePath(merged, path);removed.push(path);+ if (tracker) {+ tracker.resolved = deletePath(tracker.resolved, path);+ }}}merged = deepMerge(merged, remapped);@@ -1682,6 +1851,11 @@ function foldConfigLayers<T extends AnyObject>(removed: false,});contributed = remapped;+ if (tracker && track) {+ track.contributed =+ writtenEndpoints === undefined ? remapped : { ...remapped, endpoints: writtenEndpoints };+ tracker.resolved = deepMerge(tracker.resolved, track.contributed);+ }}if (afterLayer) {@@ -1691,24 +1865,156 @@ function foldConfigLayers<T extends AnyObject>(return { merged, raw, webSearchWriters };}+/** Whether an `endpoints` override writes Azure `groups`. */+function hasAzureGroups(endpoints: unknown): boolean {+ const azure = isPlainObject(endpoints) ? endpoints[EModelEndpoint.azureOpenAI] : undefined;+ return isPlainObject(azure) && Array.isArray(azure.groups);+}++/** One layer of {@link resolveConfigLayers}: the document as given, and what the merge left out. */+export interface ConfigLayerResolution {+ layer: ConfigOverrideLayer;+ ignored: AdminConfigLayerIgnored[];+}++/** {@link resolveConfigLayers}' result. */+export interface ConfigLayersResolution {+ /** Exactly what {@link mergeConfigOverrides} returns for the same arguments. */+ merged: AppConfig;+ /** The same merge in librechat.yaml shape: `baseConfig.config` with every layer folded in. */+ resolved: Partial<TCustomConfig>;+ /** Every layer, in merge precedence order. */+ layers: ConfigLayerResolution[];+}++/** The layers of a tracked fold whose contribution holds a value at `segments` (AppConfig keys). */+function getWriters(tracker: FoldTracker, segments: readonly string[]): LayerTrack[] {+ return tracker.layers.filter((track) => getPath(track.contributed, [...segments]) !== undefined);+}+/**- * Merge DB config overrides into a base AppConfig.- *- * Configs merge in precedence order (`compareConfigPrecedence`): Base first, then ascending- * priority, then role < group < user, then document identity; the last layer wins. Each- * config's `overrides` is deep-merged into the base config in that order. A stored web search- * key is dropped when a layer other than its own decides the URL it is sent to, the Azure model- * lists name only models the merged groups serve, and Azure assistants none of those supports- * are turned off (`withServedAzureModels`).+ * The layers of a tracked fold that applied a tombstone at or under `path` (librechat.yaml keys),+ * or with `ancestors`, above it as well: a tombstone of `endpoints.agents` removes+ * `endpoints.agents.pullRequests.host` with the rest.*/-export function mergeConfigOverrides(+function getTombstoners(tracker: FoldTracker, path: string, ancestors: boolean): LayerTrack[] {+ return tracker.layers.filter((track) =>+ track.tombstoned.some(+ (tombstone) =>+ tombstone === path ||+ tombstone.startsWith(`${path}.`) ||+ (ancestors && path.startsWith(`${tombstone}.`)),+ ),+ );+}++/** Sets or removes (`undefined`) the value at `segments` of the tracker's resolved tree. */+function setResolved(tracker: FoldTracker, segments: readonly string[], value: unknown): void {+ tracker.resolved =+ value === undefined+ ? deletePath(tracker.resolved, segments.join('.'))+ : (setPath(tracker.resolved, [...segments], value) as AnyObject);+}++/**+ * Replays on the YAML-shaped result what {@link withServedAzureModels} did to the served config:+ * an Azure model list a layer wrote directly, narrowed to what the merged groups serve, and+ * `assistants` turned off when none of them supports assistants.+ */+function replayAzureServed(tracker: FoldTracker, before: AppConfig, after: AppConfig): void {+ const segments = AZURE_CONFIG_PATH.split('.');+ const served = getPath(after, segments);+ const resolved = getPath(tracker.resolved, segments);+ if (served === getPath(before, segments) || !isPlainObject(served) || !isPlainObject(resolved)) {+ return;+ }+ for (const field of ['assistants', 'modelNames', 'assistantModels', 'assistantGroups']) {+ if (!hasOwn(resolved, field) || isSameJson(resolved[field], served[field])) {+ continue;+ }+ setResolved(tracker, [...segments, field], served[field]);+ const writers =+ field === 'assistants'+ ? getWriters(tracker, segments)+ : getWriters(tracker, [...segments, field]);+ for (const track of writers) {+ track.ignored.push(toIgnored([...segments, field], 'azure_unserved'));+ }+ }+}++/**+ * Replays on the YAML-shaped result what {@link preserveRuntimeStops} did to the served config:+ * an interface feature the base config turns off stays off, in the shape the layers left it, or+ * `false` where a tombstone removed it. Each layer that wrote it or tombstoned it, or anything+ * above or below it, is told.+ */+function replayRuntimeStops(tracker: FoldTracker, baseConfig: AppConfig): void {+ const baseInterface = (baseConfig as unknown as AnyObject).interfaceConfig;+ const resolvedInterface = tracker.resolved.interfaceConfig;+ if (!isPlainObject(baseInterface) || !isPlainObject(resolvedInterface)) {+ return;+ }+ for (const key of RUNTIME_CONFIG_INTERFACE_FIELDS) {+ if (!isRuntimeDisabled(baseInterface[key]) || isRuntimeDisabled(resolvedInterface[key])) {+ continue;+ }+ const current = resolvedInterface[key];+ setResolved(+ tracker,+ ['interfaceConfig', key],+ isPlainObject(current) ? { ...current, use: false } : false,+ );+ const segments = ['interface', key];+ for (const track of getWriters(tracker, ['interfaceConfig', key])) {+ track.ignored.push(toIgnored(segments, 'runtime_stop'));+ }+ for (const track of getTombstoners(tracker, segments.join('.'), true)) {+ track.ignored.push(toIgnored(segments, 'runtime_stop', { tombstone: true }));+ }+ }+}++/**+ * Replays on the YAML-shaped result what {@link preserveBaseOnlyPaths} did to the served config:+ * each base-only field keeps the value `librechat.yaml` gives it. A layer is told when it wrote+ * one, tombstoned one or anything below it, or tombstoned anything above one `librechat.yaml`+ * sets, as write responses tell it (`base_only_path`).+ */+function replayBaseOnlyPaths(tracker: FoldTracker, baseYaml: Partial<TCustomConfig>): void {+ for (const path of BASE_ONLY_CONFIG_PATHS) {+ const segments = path.split('.');+ const value = getPath(baseYaml, segments);+ const writers = getWriters(tracker, segments);+ const tombstoners = getTombstoners(tracker, path, value !== undefined);+ if (writers.length === 0 && tombstoners.length === 0) {+ continue;+ }+ setResolved(tracker, segments, value);+ for (const track of writers) {+ track.ignored.push(toIgnored(segments, 'base_only_path'));+ }+ for (const track of tombstoners) {+ track.ignored.push(toIgnored(segments, 'base_only_path', { tombstone: true }));+ }+ }+}++function isSameJson(a: unknown, b: unknown): boolean {+ return JSON.stringify(a) === JSON.stringify(b);+}++/**+ * The merge {@link mergeConfigOverrides} runs, and with a `tracker` the YAML-shaped result and+ * each layer's unapplied parts, replaying on that result each step the served config takes+ * after the fold.+ */+function mergeLayers(baseConfig: AppConfig,configs: readonly ConfigOverrideLayer[],- options: MergeConfigOverridesOptions = {},+ options: MergeConfigOverridesOptions,+ tracker?: FoldTracker,): AppConfig {- if (!configs || configs.length === 0) {- return baseConfig;- }const { afterLayer } = options;const folded = foldConfigLayers({ ...baseConfig },@@ -1732,13 +2038,86 @@ export function mergeConfigOverrides(},});}),+ tracker,);- const merged = bindWebSearchKeys(- withServedAzureModels(folded.merged, configs),- folded.webSearchWriters,- options.onWebSearchKeyUnbound,- );- return preserveBaseOnlyPaths(baseConfig, preserveRuntimeStops(baseConfig, merged));+ const served = withServedAzureModels(folded.merged, configs);+ if (tracker) {+ replayAzureServed(tracker, folded.merged, served);+ }+ const unbound: WebSearchKeyUnbound[] = [];+ const onUnbound =+ tracker || options.onWebSearchKeyUnbound+ ? (binding: WebSearchKeyUnbound) => {+ unbound.push(binding);+ options.onWebSearchKeyUnbound?.(binding);+ }+ : undefined;+ const bound = bindWebSearchKeys(served, folded.webSearchWriters, onUnbound);+ if (tracker) {+ for (const { layer, apiKey } of unbound) {+ setResolved(tracker, ['webSearch', apiKey], bound.webSearch?.[apiKey]);+ tracker.layers+ .find((track) => track.accepted === layer)+ ?.ignored.push(toIgnored(['webSearch', apiKey], 'secret_rebinding'));+ }+ replayRuntimeStops(tracker, baseConfig);+ replayBaseOnlyPaths(tracker, baseConfig.config ?? {});+ }+ return preserveBaseOnlyPaths(baseConfig, preserveRuntimeStops(baseConfig, bound));+}++/**+ * Merge DB config overrides into a base AppConfig.+ *+ * Configs merge in precedence order (`compareConfigPrecedence`): Base first, then ascending+ * priority, then role < group < user, then document identity; the last layer wins. Each+ * config's `overrides` is deep-merged into the base config in that order. A stored web search+ * key is dropped when a layer other than its own decides the URL it is sent to, the Azure model+ * lists name only models the merged groups serve, and Azure assistants none of those supports+ * are turned off (`withServedAzureModels`).+ */+export function mergeConfigOverrides(+ baseConfig: AppConfig,+ configs: readonly ConfigOverrideLayer[],+ options: MergeConfigOverridesOptions = {},+): AppConfig {+ if (!configs || configs.length === 0) {+ return baseConfig;+ }+ return mergeLayers(baseConfig, configs, options);+}++/**+ * {@link mergeConfigOverrides}, and what it amounts to in librechat.yaml shape: `resolved` is+ * `baseConfig.config` (the raw librechat.yaml) with each layer's tombstones and overrides folded+ * in under the merge's own rules (precedence, merge keys, atomic paths, accepted, base-only and+ * Base-only sections, invalid-override stripping, process MCP servers, the interface permission+ * filter), followed by the steps the served config takes after the fold: Azure model lists the+ * merged groups do not serve, web search keys withheld from a URL another layer decides, runtime+ * stops and base-only fields. Each layer lists what of it the merge does not apply as written.+ *+ * Not replayed, because they are AppService derivations librechat.yaml never holds: the fields+ * Azure `groups` resolve to (`groupMap`, `modelNames`, ...; `resolved` keeps the `groups`), and+ * the `afterLayer` policy a caller adds (the admin API replays its secret rebinding itself).+ */+export function resolveConfigLayers(+ baseConfig: AppConfig,+ configs: readonly ConfigOverrideLayer[],+ options: MergeConfigOverridesOptions = {},+): ConfigLayersResolution {+ const tracker: FoldTracker = {+ resolved: toAppConfigKeys(baseConfig.config ?? {}),+ layers: [],+ };+ if (!configs || configs.length === 0) {+ return { merged: baseConfig, resolved: toOverrideKeys(tracker.resolved), layers: [] };+ }+ const merged = mergeLayers(baseConfig, configs, options, tracker);+ return {+ merged,+ resolved: toOverrideKeys(tracker.resolved),+ layers: tracker.layers.map(({ layer, ignored }) => ({ layer, ignored })),+ };}/**diff --git a/packages/data-schemas/src/app/service.spec.ts b/packages/data-schemas/src/app/service.spec.tsindex e052e5065b..fa7250a86d 100644--- a/packages/data-schemas/src/app/service.spec.ts+++ b/packages/data-schemas/src/app/service.spec.ts@@ -348,6 +348,22 @@ describe('AppService credential write format', () => {});});+describe('AppService admin catalog model-list lifetime', () => {+ it('carries a configured lifetime onto the app config, zero included', async () => {+ for (const catalogModelsTtlMs of [0, 600_000]) {+ const result = await AppService({+ config: { endpoints: { catalogModelsTtlMs } } as DeepPartial<TCustomConfig>,+ });+ expect(result.endpoints?.catalogModelsTtlMs).toBe(catalogModelsTtlMs);+ }+ });++ it('leaves it unset when librechat.yaml does not set it', async () => {+ const result = await AppService({ config: { endpoints: {} } as DeepPartial<TCustomConfig> });+ expect(result.endpoints).not.toHaveProperty('catalogModelsTtlMs');+ });+});+describe('AppService conversation list limits', () => {it('carries the configured filter limits onto the app config', async () => {const result = await AppService({diff --git a/packages/data-schemas/src/methods/principal.spec.ts b/packages/data-schemas/src/methods/principal.spec.tsindex 096c75d105..ee043796ea 100644--- a/packages/data-schemas/src/methods/principal.spec.ts+++ b/packages/data-schemas/src/methods/principal.spec.ts@@ -139,3 +139,40 @@ describe('principalExists', () => {findOne.mockRestore();});});++describe('findPartitionUser', () => {+ it('returns what principal resolution reads, only for a user of the caller partition', async () => {+ const platform = await seedPrincipals('platform');+ const tenant = await inTenant('tenant-a', async () => {+ const user = await new mongoose.models.User({+ email: '[email protected]',+ provider: 'openid',+ role: 'EDITOR',+ idOnTheSource: 'entra-oid',+ }).save();+ return user._id.toString();+ });++ expect(await methods.findPartitionUser(platform.userId)).toEqual({+ id: platform.userId,+ role: SystemRoles.USER,+ idOnTheSource: null,+ });+ expect(await methods.findPartitionUser(tenant)).toBeNull();+ expect(await inTenant('tenant-a', () => methods.findPartitionUser(tenant))).toEqual({+ id: tenant,+ role: 'EDITOR',+ idOnTheSource: 'entra-oid',+ });+ expect(await inTenant('tenant-b', () => methods.findPartitionUser(tenant))).toBeNull();+ expect(await inTenant('tenant-a', () => methods.findPartitionUser(platform.userId))).toBeNull();+ });++ it('answers null without a query for an id that cannot name a user', async () => {+ const findOne = jest.spyOn(mongoose.models.User, 'findOne');+ expect(await methods.findPartitionUser('not-an-id')).toBeNull();+ expect(await methods.findPartitionUser('F6E5D4C3B2A1F6E5D4C3B2A1')).toBeNull();+ expect(findOne).not.toHaveBeenCalled();+ findOne.mockRestore();+ });+});diff --git a/packages/data-schemas/src/methods/principal.ts b/packages/data-schemas/src/methods/principal.tsindex 690bd1e43e..cc3152f962 100644--- a/packages/data-schemas/src/methods/principal.ts+++ b/packages/data-schemas/src/methods/principal.ts@@ -5,8 +5,16 @@ import { isCanonicalObjectIdString } from '~/utils/objectId';const systemRoleNames: ReadonlySet<string> = new Set(Object.values(SystemRoles));+/** What principal resolution reads of a user: their role and external identity. */+export interface PartitionUser {+ id: string;+ role?: string;+ idOnTheSource?: string | null;+}+export interface PrincipalMethods {principalExists: (principalType: PrincipalType, principalId: string) => Promise<boolean>;+ findPartitionUser: (userId: string) => Promise<PartitionUser | null>;}/** Principal lookups that stay in the caller's tenant partition. */@@ -53,5 +61,25 @@ export function createPrincipalMethods(mongoose: typeof import('mongoose')): Pri}}- return { principalExists };+ /**+ * A user of the caller's tenant partition (`tenantPartitionFilter`), by canonical ObjectId, with+ * the fields principal resolution reads (`getUserPrincipals`); `null` when the partition holds+ * no such user, as for a user of another tenant.+ */+ async function findPartitionUser(userId: string): Promise<PartitionUser | null> {+ if (!isCanonicalObjectIdString(userId)) {+ return null;+ }+ const model = mongoose.models.User as Model<{ role?: string; idOnTheSource?: string | null }>;+ const user = await model+ .findOne({ _id: userId, ...tenantPartitionFilter('findPartitionUser') })+ .select('role idOnTheSource')+ .lean();+ if (user == null) {+ return null;+ }+ return { id: userId, role: user.role, idOnTheSource: user.idOnTheSource ?? null };+ }++ return { principalExists, findPartitionUser };}diff --git a/packages/data-schemas/src/types/admin.ts b/packages/data-schemas/src/types/admin.tsindex 47d5e92039..b030aa33fa 100644--- a/packages/data-schemas/src/types/admin.ts+++ b/packages/data-schemas/src/types/admin.ts@@ -1,4 +1,9 @@-import type { PrincipalType, PrincipalModel, TCustomConfig } from 'librechat-data-provider';+import type {+ PrincipalType,+ PrincipalModel,+ TCustomConfig,+ TConfig,+} from 'librechat-data-provider';/* ── Capability types (defined alongside the SystemCapabilities constant) ── */@@ -282,6 +287,218 @@ export type AdminConfigChangeErrorResponse = {skipped?: AdminConfigChangesResponse['skipped'];};+/* ── Admin config read APIs (resolved, effective, catalog, env status) ── */++/**+ * Why the merge leaves out part of a config document, or applies it otherwise than written, as a+ * resolution reports it on the document's layer:+ * - `unknown_section`: a top-level key or tombstone outside `configSchema` (`sectionAllowlist`).+ * - `invalid_override`: a value that fails the schema over the layers below it; `code` is the+ * schema issue's code.+ * - `base_only_section`: a section only `librechat.yaml` sets (`filters`, `turnstile`, ...).+ * - `base_principal_section`: a section only the Base document holds (`langfuse`), in another.+ * - `base_only_path`: a field only `librechat.yaml` sets (`rules.baseOnlyPaths`); it keeps the+ * `librechat.yaml` value.+ * - `process_mcp_server`: an MCP server `librechat.yaml` runs as a local process.+ * - `interface_permission`: an interface field that is a role permission.+ * - `runtime_stop`: an interface feature `librechat.yaml` turns off, which stays off.+ * - `azure_groups_unresolved`: Azure `groups` that do not resolve (a duplicate group or model, a+ * model without a deployment or version), which the Azure clients never read.+ * - `azure_unserved`: an Azure model list, or `assistants`, the merged groups do not serve.+ * - `secret_rebinding`: a credential the merge drops, or (`destination_restored`) a destination+ * it sets back, because the credential would be sent somewhere it was not entered for+ * (`secretRebinding`).+ * - `env_reference_not_allowed`: a `${NAME}` reference outside the env allowlist (`envAllowlist`),+ * which resolves to nothing.+ * - `invalid_theme`: an `interface.theme` the client would reject; `librechat.yaml`'s applies.+ * - `tenant_hidden`: a custom endpoint `librechat.yaml` scopes to another tenant, or a model+ * spec that uses one.+ */+export type AdminConfigLayerIgnoreReason =+ | 'unknown_section'+ | 'invalid_override'+ | 'base_only_section'+ | 'base_principal_section'+ | 'base_only_path'+ | 'process_mcp_server'+ | 'interface_permission'+ | 'runtime_stop'+ | 'azure_groups_unresolved'+ | 'azure_unserved'+ | 'secret_rebinding'+ | 'destination_restored'+ | 'env_reference_not_allowed'+ | 'invalid_theme'+ | 'tenant_hidden';++/**+ * Part of a layer the merge does not apply as written. `segments` locate it in librechat.yaml+ * keys: in the document's overrides (array items by index), or for a credential or destination+ * the merge drops or sets back, as write responses name it (a custom endpoint by its name). A+ * tombstone above a `base_only_path` field or a `runtime_stop` feature names that field, which+ * the merge keeps while it removes the rest (write responses name a base-only field the same way).+ */+export type AdminConfigLayerIgnored = {+ path: string;+ segments: string[];+ reason: AdminConfigLayerIgnoreReason;+ /** The schema issue code of an `invalid_override`. */+ code?: string;+ /** Set when it is one of the document's tombstones rather than an override. */+ tombstone?: true;+};++/**+ * One config document of a resolution, as a read of it returns it (filtered to the sections the+ * caller can read, secrets redacted), with what the merge does not apply of it.+ */+export type AdminConfigLayer = {+ principalType: PrincipalType;+ principalId: string;+ priority: number;+ /** An inactive document is listed but not merged. */+ isActive: boolean;+ revision: string;+ overrides: Partial<TCustomConfig>;+ tombstones: string[];+ ignored: AdminConfigLayerIgnored[];+};++/**+ * 200 from `GET /api/admin/config/resolved/:principalType/:principalId` (`resolvedApi`): what a+ * profile resolves to, in `librechat.yaml` shape. `yaml` is librechat.yaml as the caller's tenant+ * sees it, `layers` the documents that merge over it (Base, then the profile) in merge order, and+ * `resolved` the result. Each tree is limited to the sections the caller can read, with secrets+ * redacted as reads redact them.+ */+export type AdminResolvedConfigResponse = {+ principalType: PrincipalType;+ principalId: string;+ yaml: Partial<TCustomConfig>;+ layers: AdminConfigLayer[];+ resolved: Partial<TCustomConfig>;+};++/**+ * 200 from `GET /api/admin/config/effective?userId=` (`resolvedApi`): what one user's requests+ * resolve to, over every profile that applies to them (Base, their role, their groups, their own),+ * in merge order. `principals` lists the principals the user resolves to, with or without a+ * profile.+ */+export type AdminEffectiveConfigResponse = {+ userId: string;+ principals: Array<{ principalType: PrincipalType; principalId: string }>;+ yaml: Partial<TCustomConfig>;+ layers: AdminConfigLayer[];+ resolved: Partial<TCustomConfig>;+};++/**+ * Why an endpoint the catalog lists is not served:+ * - `not_listed`: `ENDPOINTS` names the endpoints to serve, without this one;+ * - `missing_credentials`: no credential for a built-in endpoint in the environment (`envVars`);+ * - `missing_api_key`, `missing_base_url`, `missing_models`: a custom endpoint without an+ * `apiKey` (or one the merge dropped), a `baseURL`, or `models.default` or `models.fetch`.+ */+export type AdminCatalogEndpointReason =+ | 'not_listed'+ | 'missing_credentials'+ | 'missing_api_key'+ | 'missing_base_url'+ | 'missing_models';++export type AdminCatalogEndpoint = {+ /** Whether the scope's users are served the endpoint (`GET /api/endpoints` lists it). */+ enabled: boolean;+ custom: boolean;+ reason?: AdminCatalogEndpointReason;+ /**+ * Env names the endpoint takes its credentials or base URL from: a built-in endpoint's (from+ * the environment), or the `${NAME}` references of a custom endpoint's `apiKey` and `baseURL`.+ * Whether each is set is `GET /env-status`'s to say.+ */+ envVars: string[];+ /** The entry `GET /api/endpoints` serves the scope's users, when enabled. */+ config?: TConfig;+};++/** One endpoint's models for a scope; never fetched with any user's stored key. */+export type AdminCatalogModels = {+ /** What the scope's users are offered, as `GET /api/models` lists it for them. */+ served: string[];+ /**+ * The list the scope's config sets: `models` of a built-in endpoint, the models of the Azure+ * groups, or a custom endpoint's `models.default`. Absent when the config sets none.+ */+ configured?: string[];+ /**+ * What the endpoint offers without a configured list: a built-in endpoint's `*_MODELS` env+ * list, the provider's model list or the built-in defaults, or what a custom endpoint with+ * `models.fetch` fetches with the server's key. Absent for a custom endpoint that fetches+ * nothing (no `fetch`, or a key or URL each user provides).+ */+ defaults?: string[];+};++/** A librechat.yaml or profile MCP server the scope's users can reach. */+export type AdminCatalogMcpServer = {+ name: string;+ title?: string;+ transport: 'stdio' | 'sse' | 'streamable-http' | 'websocket';+ /** `yaml` when librechat.yaml defines it, `override` when a profile adds it. */+ source: 'yaml' | 'override';+ /** Runs as a local process (`stdio`), which profiles cannot change or hide. */+ processBacked: boolean;+};++/** A tool agents can use, as `GET /api/agents/tools` lists it. */+export type AdminCatalogTool = {+ pluginKey: string;+ name: string;+ description?: string;+ icon?: string;+ /** The server holds every credential the tool needs. */+ authenticated?: boolean;+ toolkit?: boolean;+};++/**+ * 200 from `GET /api/admin/config/catalog?principalType=&principalId=` (`catalogApi`): what a+ * scope serves, resolved as its users get it (Base by default). A part is present only for+ * callers who can read its section: `endpoints` and `models` for `endpoints`, `mcpServers` for+ * `mcpServers`, `tools` for `filteredTools` or `includedTools`.+ */+export type AdminConfigCatalogResponse = {+ principalType: PrincipalType;+ principalId: string;+ endpoints?: Record<string, AdminCatalogEndpoint>;+ models?: Record<string, AdminCatalogModels>;+ /** The tools every scope offers: tool filtering is deployment-only. */+ tools?: AdminCatalogTool[];+ mcpServers?: AdminCatalogMcpServer[];+};++/**+ * Where an env name `GET /env-status` reports is used: referenced in librechat.yaml (`yaml`), a+ * default reference librechat.yaml loading fills in (`default`, such as `${SEARXNG_INSTANCE_URL}`),+ * read by a built-in endpoint (`endpoint`), listed in `CONFIG_OVERRIDE_ENV_ALLOWLIST`+ * (`allowlist`), or referenced in a stored profile (`override`).+ */+export type AdminConfigEnvSource = 'yaml' | 'default' | 'endpoint' | 'allowlist' | 'override';++export type AdminConfigEnvStatus = {+ /** The variable holds a non-blank value on this server; the value itself is never returned. */+ set: boolean;+ /** The value is `user_provided`: each user enters their own. */+ userProvided?: true;+ sources: AdminConfigEnvSource[];+};++/** 200 from `GET /api/admin/config/env-status` (`envStatus`). */+export type AdminConfigEnvStatusResponse = {+ vars: Record<string, AdminConfigEnvStatus>;+};+/* ── Admin config contract (GET /api/admin/config/meta) ─────────────── *//**@@ -455,6 +672,29 @@ export type AdminConfigChangeErrorResponse = {* reference librechat.yaml uses beside a new destination keeps it, so for allowlisted names* (`envAllowlist`) the rule stops a destination change that leaves the reference out, not one* that restates it. Header maps are not covered.+ * - `resolvedApi`: `GET /resolved/:principalType/:principalId` returns what a profile resolves to+ * over librechat.yaml and the Base document (`AdminResolvedConfigResponse`), and+ * `GET /effective?userId=` what one user resolves to over every profile that applies to them+ * (`AdminEffectiveConfigResponse`; also needs `read:users` and `read:groups`, and answers 404+ * `USER_NOT_FOUND` for a user outside the caller's tenant). Both are in librechat.yaml shape,+ * merged exactly as requests merge them (the parity of `resolveConfigLayers` with the served+ * merge), with each document's `ignored` parts (`AdminConfigLayerIgnored`), read from the stored+ * documents rather than the override cache, limited to the sections the caller can read and+ * redacted as reads redact. A profile with no document resolves to Base; one whose principal+ * does not exist in the caller's tenant answers 404 `PRINCIPAL_NOT_FOUND`.+ * - `catalogApi`: `GET /catalog?principalType=&principalId=` returns the endpoints (served or not,+ * with a `reason` and the env names they read), models (`served`, `configured`, `defaults`),+ * MCP servers and agent tools a scope (Base by default) offers, as its users get them+ * (`AdminConfigCatalogResponse`). Models are never loaded with a user's stored key, header+ * templates that name a user resolve to nothing, a scope's model lists are reused for+ * `limits.catalogModelsTtlMs` while its endpoint config is unchanged, and no User-Agent is+ * needed. Each part is present only for callers who can read its section.+ * - `envStatus`: `GET /env-status` reports, for each env name librechat.yaml references, fills in+ * by default, or a built-in endpoint reads, and each name in `CONFIG_OVERRIDE_ENV_ALLOWLIST`,+ * whether it is set on the server and where it is used (`AdminConfigEnvStatusResponse`), never+ * its value. Names stored profiles reference are added for broad `manage:configs` holders+ * outside strict tenant isolation. A caller without broad read access sees only the names used+ * in sections it can read; infrastructure secrets (`CREDS_KEY`, ...) are never listed.* - `reloadRoute`: `POST /reload` reloads librechat.yaml on every instance without a config* write. It is for an admin without a tenant who holds broad `manage:configs` (otherwise 403* `FORBIDDEN`), since it reaches every tenant. The answering instance drops its cached@@ -493,6 +733,9 @@ export type AdminConfigFeatureFlag =| 'yamlSecretPreview'| 'envAllowlist'| 'secretRebinding'+ | 'resolvedApi'+ | 'catalogApi'+ | 'envStatus'| 'reloadRoute';export type AdminConfigFeatures = Record<AdminConfigFeatureFlag, boolean>;@@ -584,6 +827,12 @@ export type AdminConfigMeta = {* resolved config from before a write.*/overrideCacheTtlMs: number;+ /**+ * How long `GET /catalog` reuses a scope's model lists while its endpoint config is+ * unchanged (`catalogApi`): librechat.yaml's `endpoints.catalogModelsTtlMs`, two minutes by+ * default; `0` when every read resolves them.+ */+ catalogModelsTtlMs: number;};rules: AdminConfigRules;};diff --git a/packages/data-schemas/src/types/app.ts b/packages/data-schemas/src/types/app.tsindex c783e865e8..e74870d1d3 100644--- a/packages/data-schemas/src/types/app.ts+++ b/packages/data-schemas/src/types/app.ts@@ -141,6 +141,8 @@ export interface AppConfig {endpoints?: {/** Admin exemption list of host:port pairs that bypass the SSRF private-IP block */allowedAddresses?: string[];+ /** How long the admin config catalog reuses a scope's model lists, in milliseconds */+ catalogModelsTtlMs?: number;/** OpenAI endpoint configuration */openAI?: Partial<TEndpoint>;/** Google endpoint configuration */