Skip to content

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

🔑 feat: Keep Dotted Record Keys in Admin Config Writes and Publish the Config Contract (#17322)

Danny Avila2591a15c10af
diff --git a/api/server/experimental.js b/api/server/experimental.js
index 45029cc141..cad00b256c 100644
--- a/api/server/experimental.js
+++ b/api/server/experimental.js
@@ -58,6 +58,7 @@ const {
createCodeApiUploadRegistry,
cacheConfig,
createClusteredFileSweep,
+ createRequestSanitizer,
} = require('@librechat/api');
const { connectDb, indexSync } = require('~/db');
const initializeOAuthReconnectManager = require('./services/initializeOAuthReconnectManager');
@@ -614,7 +615,7 @@ if (cluster.isMaster) {
next();
});
- app.use(mongoSanitize());
+ app.use(createRequestSanitizer(mongoSanitize));
app.use(cors());
app.use(cookieParser());
diff --git a/api/server/index.js b/api/server/index.js
index 8f0aef132d..5b8c0bc680 100644
--- a/api/server/index.js
+++ b/api/server/index.js
@@ -69,6 +69,7 @@ const {
waitForKeyvRedisClient,
warnOnUnreachableDeliveryPaths,
createCodeApiUploadRegistry,
+ createRequestSanitizer,
} = require('@librechat/api');
const { connectDb, indexSync } = require('~/db');
const {
@@ -385,7 +386,7 @@ const startServer = async () => {
next();
});
- app.use(mongoSanitize());
+ app.use(createRequestSanitizer(mongoSanitize));
app.use(cors());
app.use(cookieParser());
diff --git a/api/server/routes/admin/config.js b/api/server/routes/admin/config.js
index eafcbffdaf..51aae02cc5 100644
--- a/api/server/routes/admin/config.js
+++ b/api/server/routes/admin/config.js
@@ -1,5 +1,5 @@
const express = require('express');
-const { createAdminConfigHandlers } = require('@librechat/api');
+const { createAdminConfigHandlers, rejectUnsafeConfigKeys } = require('@librechat/api');
const { SystemCapabilities } = require('@librechat/data-schemas');
const {
hasCapability,
@@ -8,7 +8,11 @@ const {
hasAnyConfigReadAccess,
getReadableConfigSections,
} = require('~/server/middleware/roles/capabilities');
-const { getAppConfig, invalidateConfigCaches } = require('~/server/services/Config');
+const {
+ getAppConfig,
+ overrideCacheTtl,
+ invalidateConfigCaches,
+} = require('~/server/services/Config');
const { requireJwtAuth } = require('~/server/middleware');
const db = require('~/models');
@@ -33,11 +37,13 @@ const handlers = createAdminConfigHandlers({
invalidateConfigCaches,
recordAuditEntry: db.recordAuditEntry,
auditFailClosed: process.env.AUDIT_LOG_FAIL_CLOSED === 'true',
+ overrideCacheTtlMs: overrideCacheTtl,
});
-router.use(requireJwtAuth, requireAdminAccess);
+router.use(requireJwtAuth, requireAdminAccess, rejectUnsafeConfigKeys);
router.get('/', handlers.listConfigs);
+router.get('/meta', handlers.getConfigMeta);
router.get('/base', handlers.getBaseConfig);
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.js
new file mode 100644
index 0000000000..7ecaa644e3
--- /dev/null
+++ b/api/server/routes/admin/config.test.js
@@ -0,0 +1,169 @@
+const express = require('express');
+const request = require('supertest');
+const mongoSanitize = require('express-mongo-sanitize');
+const { createRequestSanitizer } = require('@librechat/api');
+
+let hasAdminAccess;
+const mockRequireJwtAuth = jest.fn((req, res, next) => {
+ if (req.headers.authorization !== 'Bearer admin') {
+ return res.status(401).json({ message: 'Unauthorized' });
+ }
+ req.user = { id: 'user-1', _id: 'user-1', role: 'ADMIN' };
+ next();
+});
+const mockRequireCapability = jest.fn(() => (_req, res, next) => {
+ if (!hasAdminAccess) {
+ return res.status(403).json({ message: 'Forbidden' });
+ }
+ next();
+});
+const mockDb = {
+ listAllConfigs: jest.fn(),
+ findConfigByPrincipal: jest.fn(),
+ upsertConfig: jest.fn(),
+ patchConfigFields: jest.fn(),
+ tombstoneConfigField: jest.fn(),
+ unsetConfigField: jest.fn(),
+ deleteConfig: jest.fn(),
+ toggleConfigActiveTracked: jest.fn(),
+ recordAuditEntry: jest.fn(),
+};
+
+jest.mock('~/server/middleware', () => ({ requireJwtAuth: mockRequireJwtAuth }));
+
+jest.mock('~/server/middleware/roles/capabilities', () => ({
+ requireCapability: mockRequireCapability,
+ hasCapability: jest.fn(async () => true),
+ hasConfigCapability: jest.fn(async () => true),
+ hasAnyConfigReadAccess: jest.fn(async () => true),
+ getReadableConfigSections: jest.fn(async () => ({ broad: true, sections: new Set() })),
+}));
+
+jest.mock('~/server/services/Config', () => ({
+ getAppConfig: jest.fn(async () => ({ config: {} })),
+ overrideCacheTtl: 15_000,
+ invalidateConfigCaches: jest.fn(async () => undefined),
+}));
+
+jest.mock('~/models', () => mockDb);
+
+/** The app-level order of `api/server/index.js`: body parsing, writable query, sanitizer, router. */
+function createApp() {
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ Object.defineProperty(req, 'query', {
+ ...Object.getOwnPropertyDescriptor(req, 'query'),
+ value: req.query,
+ writable: true,
+ });
+ next();
+ });
+ app.use(createRequestSanitizer(mongoSanitize));
+ app.use('/api/admin/config', require('./config'));
+ return app;
+}
+
+const PROFILE = 'us.anthropic.claude-sonnet-4-6';
+const ARN =
+ 'arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.anthropic.claude-sonnet-4-6';
+
+describe('admin config routes', () => {
+ let app;
+
+ beforeAll(() => {
+ app = createApp();
+ });
+
+ beforeEach(() => {
+ hasAdminAccess = true;
+ mockDb.findConfigByPrincipal.mockResolvedValue(null);
+ mockDb.patchConfigFields.mockImplementation(async (principalType, principalId, _m, fields) => ({
+ principalType,
+ principalId,
+ priority: 10,
+ isActive: true,
+ configVersion: 1,
+ overrides: {
+ endpoints: {
+ bedrock: { inferenceProfiles: fields['endpoints.bedrock.inferenceProfiles'] },
+ },
+ },
+ }));
+ });
+
+ const unsafeBody = {
+ entries: [{ fieldPath: 'endpoints.bedrock.inferenceProfiles', value: { $where: 'sleep(1)' } }],
+ };
+
+ it('answers 401 before the key guard for an unauthenticated `$` key', async () => {
+ const response = await request(app)
+ .patch('/api/admin/config/role/USER/fields')
+ .send(unsafeBody)
+ .expect(401);
+
+ expect(response.body).toEqual({ message: 'Unauthorized' });
+ expect(mockDb.patchConfigFields).not.toHaveBeenCalled();
+ });
+
+ it('answers 403 before the key guard without admin access', async () => {
+ hasAdminAccess = false;
+
+ await request(app)
+ .patch('/api/admin/config/role/USER/fields')
+ .set('authorization', 'Bearer admin')
+ .send(unsafeBody)
+ .expect(403);
+
+ expect(mockDb.patchConfigFields).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['a `$` operator key', unsafeBody],
+ ['a `__proto__` key', JSON.parse('{"overrides":{"registration":{"__proto__":{"x":1}}}}')],
+ ])('answers 400 CONFIG_UNSAFE_KEY for %s after auth', async (_label, body) => {
+ const response = await request(app)
+ .put('/api/admin/config/role/USER')
+ .set('authorization', 'Bearer admin')
+ .send(body)
+ .expect(400);
+
+ expect(response.body.code).toBe('CONFIG_UNSAFE_KEY');
+ expect(JSON.stringify(response.body)).not.toMatch(/\$where|__proto__/);
+ expect(mockDb.upsertConfig).not.toHaveBeenCalled();
+ });
+
+ it('delivers dotted record keys to the write method intact', async () => {
+ const response = await request(app)
+ .patch('/api/admin/config/role/USER/fields')
+ .set('authorization', 'Bearer admin')
+ .send({
+ entries: [{ fieldPath: 'endpoints.bedrock.inferenceProfiles', value: { [PROFILE]: ARN } }],
+ })
+ .expect(200);
+
+ expect(mockDb.patchConfigFields).toHaveBeenCalledWith(
+ 'role',
+ 'USER',
+ expect.anything(),
+ { 'endpoints.bedrock.inferenceProfiles': { [PROFILE]: ARN } },
+ expect.any(Number),
+ );
+ expect(response.body.config.overrides.endpoints.bedrock.inferenceProfiles).toEqual({
+ [PROFILE]: ARN,
+ });
+ });
+
+ it('serves the config contract behind the same auth', async () => {
+ await request(app).get('/api/admin/config/meta').expect(401);
+
+ const response = await request(app)
+ .get('/api/admin/config/meta')
+ .set('authorization', 'Bearer admin')
+ .expect(200);
+
+ expect(response.body.metaVersion).toBe(1);
+ expect(response.body.features.dottedKeys).toBe(true);
+ expect(response.body.limits).toEqual({ maxPatchEntries: 100, overrideCacheTtlMs: 15_000 });
+ });
+});
diff --git a/api/server/services/Config/app.js b/api/server/services/Config/app.js
index c0859093ca..7a70db520d 100644
--- a/api/server/services/Config/app.js
+++ b/api/server/services/Config/app.js
@@ -45,7 +45,7 @@ const loadBaseConfig = async (mode) => {
return AppService({ config, paths, systemTools });
};
-const { getAppConfig, clearAppConfigCache, clearOverrideCache } = createAppConfigService({
+const appConfigService = createAppConfigService({
loadBaseConfig,
setCachedTools,
getCache: getLogStores,
@@ -67,6 +67,8 @@ const { getAppConfig, clearAppConfigCache, clearOverrideCache } = createAppConfi
});
},
});
+const { getAppConfig, clearAppConfigCache, clearOverrideCache, overrideCacheTtl } =
+ appConfigService;
// Config owns the reader; models never import this module to obtain it.
db.initializeMessageBudget(getAppConfig);
@@ -99,6 +101,7 @@ async function invalidateConfigCaches(tenantId) {
module.exports = {
getAppConfig,
+ overrideCacheTtl,
invalidateConfigCaches,
getCodeEnvironmentRegistry,
invalidateCodeEnvironmentConfigCache,
diff --git a/e2e/specs/mock/scenarios/config-override-validation.spec.ts b/e2e/specs/mock/scenarios/config-override-validation.spec.ts
index 07be48b676..9f8110733b 100644
--- a/e2e/specs/mock/scenarios/config-override-validation.spec.ts
+++ b/e2e/specs/mock/scenarios/config-override-validation.spec.ts
@@ -122,10 +122,16 @@ test.describe('Principal config override validation', () => {
expect(res.status()).toBe(400);
const body = (await res.json()) as {
code: string;
- issues: Array<{ path: string; code: string }>;
+ issues: Array<{ path: string; segments: string[]; code: string }>;
};
expect(body.code).toBe('CONFIG_OVERRIDE_INVALID');
- expect(body.issues).toEqual([{ path: 'interface.contextCost', code: 'invalid_type' }]);
+ expect(body.issues).toEqual([
+ {
+ path: 'interface.contextCost',
+ segments: ['interface', 'contextCost'],
+ code: 'invalid_type',
+ },
+ ]);
expect(await storedOverrides(request, admin, target.userId)).toBeNull();
const iface = await readInterface(request, target);
diff --git a/packages/api/src/admin/config.dotted.integration.spec.ts b/packages/api/src/admin/config.dotted.integration.spec.ts
new file mode 100644
index 0000000000..57377ddbd4
--- /dev/null
+++ b/packages/api/src/admin/config.dotted.integration.spec.ts
@@ -0,0 +1,395 @@
+import express from 'express';
+import mongoose from 'mongoose';
+import request from 'supertest';
+import mongoSanitize from 'express-mongo-sanitize';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import type { AppConfig, IConfig } from '@librechat/data-schemas';
+import type { Request, Response, NextFunction } 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 Doc = Record<string, unknown>;
+type Handler = (req: ServerRequest, res: Response) => Promise<Response>;
+
+let mongoServer: MongoMemoryServer;
+let app: express.Express;
+let logger: DataSchemas['logger'];
+let decryptV3: DataSchemas['decryptV3'];
+let mergeConfigOverrides: DataSchemas['mergeConfigOverrides'];
+
+const PROFILE = 'us.anthropic.claude-sonnet-4-6';
+const ARN =
+ 'arn:aws:bedrock:us-east-1:123456789012:inference-profile/us.anthropic.claude-sonnet-4-6';
+const DOCX = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
+const API_KEY = 'sk-gateway-literal-0123456789';
+
+/**
+ * The request path of `api/server/index.js` and `routes/admin/config.js`: app-level sanitizer,
+ * authentication, the unsafe-key guard, then the real handlers over the real config methods.
+ */
+beforeAll(async () => {
+ jest.resetModules();
+ const dataSchemas = await import('@librechat/data-schemas');
+ ({ decryptV3, mergeConfigOverrides, logger } = dataSchemas);
+ jest.spyOn(dataSchemas.logger, 'warn').mockReturnValue(dataSchemas.logger);
+ jest.spyOn(dataSchemas.logger, 'info').mockReturnValue(dataSchemas.logger);
+ const { createAdminConfigHandlers } = await import('./config');
+ const { createRequestSanitizer, rejectUnsafeConfigKeys } = await import('~/middleware/sanitize');
+
+ mongoServer = await MongoMemoryServer.create();
+ await mongoose.connect(mongoServer.getUri());
+ dataSchemas.createModels(mongoose);
+ const methods = dataSchemas.createMethods(mongoose);
+ const handlers = createAdminConfigHandlers({
+ listAllConfigs: methods.listAllConfigs,
+ findConfigByPrincipal: methods.findConfigByPrincipal,
+ upsertConfig: methods.upsertConfig,
+ patchConfigFields: methods.patchConfigFields,
+ tombstoneConfigField: methods.tombstoneConfigField,
+ unsetConfigField: methods.unsetConfigField,
+ deleteConfig: methods.deleteConfig,
+ toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
+ hasConfigCapability: async () => true,
+ hasAnyConfigReadAccess: async () => true,
+ hasCapability: async () => true,
+ getAppConfig: async () => ({ config: {} }) as AppConfig,
+ });
+
+ const route = (handler: Handler) => async (req: Request, res: Response) => {
+ await handler(req as ServerRequest, res);
+ };
+ const router = express.Router();
+ router.use((req: Request, _res: Response, next: NextFunction) => {
+ (req as ServerRequest).user = { id: 'u1', role: 'ADMIN' } as ServerRequest['user'];
+ next();
+ }, rejectUnsafeConfigKeys);
+ router.get('/:principalType/:principalId', route(handlers.getConfig));
+ router.put('/:principalType/:principalId', route(handlers.upsertConfigOverrides));
+ router.patch('/:principalType/:principalId/fields', route(handlers.patchConfigField));
+ router.delete('/:principalType/:principalId/fields', route(handlers.deleteConfigField));
+
+ app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ Object.defineProperty(req, 'query', {
+ ...Object.getOwnPropertyDescriptor(req, 'query'),
+ value: req.query,
+ writable: true,
+ });
+ next();
+ });
+ app.use(createRequestSanitizer(mongoSanitize));
+ app.use('/api/admin/config', router);
+});
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer.stop();
+});
+
+let principalCounter = 0;
+function nextRole(): string {
+ principalCounter += 1;
+ return `DOTTED_${principalCounter}`;
+}
+
+/** The stored document as the driver returns it, without schema hydration. */
+async function readRaw(principalId: string): Promise<{ overrides: Doc } | null> {
+ return mongoose.models.Config.collection.findOne<{ overrides: Doc }>({ principalId });
+}
+
+function getIn(target: unknown, segments: string[]): unknown {
+ return segments.reduce<unknown>(
+ (node, segment) =>
+ node != null && typeof node === 'object' ? (node as Doc)[segment] : undefined,
+ target,
+ );
+}
+
+function patchFields(role: string, entries: Array<{ fieldPath: string; value: unknown }>) {
+ return request(app).patch(`/api/admin/config/role/${role}/fields`).send({ entries });
+}
+
+function putOverrides(role: string, overrides: unknown) {
+ return request(app).put(`/api/admin/config/role/${role}`).send({ overrides });
+}
+
+async function getOverrides(role: string): Promise<Doc> {
+ const response = await request(app).get(`/api/admin/config/role/${role}`).expect(200);
+ return response.body.config.overrides as Doc;
+}
+
+function merge(stored: Doc): AppConfig {
+ const config = { principalType: 'role', principalId: 'r', priority: 10, isActive: true };
+ return mergeConfigOverrides({ config: {} } as AppConfig, [
+ { ...config, overrides: stored } as Partial<IConfig> as IConfig,
+ ]);
+}
+
+describe('admin config writes keep dotted record keys (real sanitizer, handlers and Mongo)', () => {
+ it('round-trips Bedrock inference profiles through PATCH, storage, GET and merge', async () => {
+ const role = nextRole();
+ const profiles = { [PROFILE]: ARN, 'eu.amazon.nova-pro-v1:0': 'arn:aws:bedrock:eu:1:x' };
+ await patchFields(role, [
+ { fieldPath: 'endpoints.bedrock.inferenceProfiles', value: profiles },
+ ]).expect(200);
+
+ const raw = await readRaw(role);
+ expect(getIn(raw?.overrides, ['endpoints', 'bedrock', 'inferenceProfiles'])).toEqual(profiles);
+ const read = await getOverrides(role);
+ expect(getIn(read, ['endpoints', 'bedrock', 'inferenceProfiles'])).toEqual(profiles);
+ expect(getIn(merge(read), ['endpoints', 'bedrock', 'inferenceProfiles'])).toEqual(profiles);
+ });
+
+ it('round-trips Azure group model names through PUT, storage and GET', async () => {
+ const role = nextRole();
+ const models = { 'gpt-4.1': true, 'gpt-4.1-mini': { deploymentName: 'mini' } };
+ await putOverrides(role, {
+ endpoints: {
+ azureOpenAI: {
+ groups: [{ group: 'eastus', apiKey: '${AZURE_API_KEY}', instanceName: 'east', models }],
+ },
+ },
+ }).expect(201);
+
+ const path = ['endpoints', 'azureOpenAI', 'groups', '0', 'models'];
+ expect(getIn((await readRaw(role))?.overrides, path)).toEqual(models);
+ expect(getIn(await getOverrides(role), path)).toEqual(models);
+ });
+
+ it('round-trips MIME-type delivery overrides and dotted header names', async () => {
+ const role = nextRole();
+ await patchFields(role, [
+ { fieldPath: 'fileConfig.defaultLLMDeliveryPath.overrides', value: { [DOCX]: 'text' } },
+ {
+ fieldPath: 'mcpServers.docs',
+ value: {
+ type: 'streamable-http',
+ url: 'https://mcp.example.com',
+ headers: { 'X-Org.Id': 'o' },
+ },
+ },
+ ]).expect(200);
+
+ const read = await getOverrides(role);
+ expect(getIn(read, ['fileConfig', 'defaultLLMDeliveryPath', 'overrides'])).toEqual({
+ [DOCX]: 'text',
+ });
+ expect(getIn(read, ['mcpServers', 'docs', 'headers'])).toEqual({ 'X-Org.Id': 'o' });
+ });
+
+ it('still encrypts a secret that sits beside dotted record keys', async () => {
+ const role = nextRole();
+ const response = await patchFields(role, [
+ {
+ fieldPath: 'endpoints.custom',
+ value: [
+ {
+ name: 'gateway',
+ apiKey: API_KEY,
+ baseURL: 'https://gateway.example.com/v1',
+ models: { default: ['gpt-4.1'] },
+ headers: { 'x-portkey.config': 'cfg' },
+ },
+ ],
+ },
+ ]).expect(200);
+ expect(JSON.stringify(response.body)).not.toContain(API_KEY);
+
+ const [stored] = getIn((await readRaw(role))?.overrides, ['endpoints', 'custom']) as Doc[];
+ expect(stored.headers).toEqual({ 'x-portkey.config': 'cfg' });
+ expect(stored.apiKey).toMatch(/^v3:/);
+ expect(decryptV3(stored.apiKey as string)).toBe(API_KEY);
+ });
+
+ it('removes a dotted record whole through its own field path', async () => {
+ const role = nextRole();
+ await patchFields(role, [
+ { fieldPath: 'endpoints.bedrock.inferenceProfiles', value: { [PROFILE]: ARN } },
+ { fieldPath: 'endpoints.bedrock.models', value: ['anthropic.claude-sonnet-4-6'] },
+ ]).expect(200);
+
+ await request(app)
+ .delete(`/api/admin/config/role/${role}/fields`)
+ .query({ fieldPath: 'endpoints.bedrock.inferenceProfiles' })
+ .expect(200);
+ expect(getIn((await readRaw(role))?.overrides, ['endpoints', 'bedrock'])).toEqual({
+ models: ['anthropic.claude-sonnet-4-6'],
+ });
+ });
+});
+
+describe('admin config writes refuse keys that cannot be config', () => {
+ it.each([
+ [
+ 'a `$` operator in a PATCH value',
+ { entries: [{ fieldPath: 'endpoints.bedrock.inferenceProfiles', value: { $gt: '' } }] },
+ ],
+ ['a `$` key in a PUT section', { overrides: { registration: { $set: { enabled: false } } } }],
+ [
+ 'a `__proto__` key',
+ JSON.parse('{"overrides":{"registration":{"__proto__":{"admin":true}}}}'),
+ ],
+ ])('answers 400 CONFIG_UNSAFE_KEY for %s and stores nothing', async (_label, body) => {
+ const role = nextRole();
+ const method = 'entries' in body ? 'patch' : 'put';
+ const path = `/api/admin/config/role/${role}${method === 'patch' ? '/fields' : ''}`;
+ const response = await request(app)[method](path).send(body).expect(400);
+
+ expect(response.body.code).toBe('CONFIG_UNSAFE_KEY');
+ expect(await readRaw(role)).toBeNull();
+ });
+
+ it.each([
+ ['a dotted section name', { 'webSearch.serperApiKey': 'sk-serper-plaintext-0123' }],
+ ['a dotted base-only section', { 'filters.x': { allow: true } }],
+ ['a dotted key in a fixed-shape object', { registration: { 'allowedDomains.0': 'x.com' } }],
+ ])('answers 400 dotted_key for %s instead of storing an inert key', async (_label, overrides) => {
+ const role = nextRole();
+ const response = await putOverrides(role, overrides).expect(400);
+
+ expect(response.body.code).toBe('CONFIG_OVERRIDE_INVALID');
+ expect(response.body.issues).toEqual([expect.objectContaining({ code: 'dotted_key' })]);
+ expect(await readRaw(role)).toBeNull();
+ });
+
+ it('answers 400 dotted_key for a fixed-shape dotted key in a PATCH value', async () => {
+ const role = nextRole();
+ const response = await patchFields(role, [
+ { fieldPath: 'webSearch', value: { 'serperApiKey.x': 'sk-serper-plaintext-0123' } },
+ ]).expect(400);
+
+ expect(response.body.issues).toEqual([
+ {
+ path: 'webSearch.serperApiKey.x',
+ segments: ['webSearch', 'serperApiKey.x'],
+ code: 'dotted_key',
+ },
+ ]);
+ expect(await readRaw(role)).toBeNull();
+ });
+
+ it('names an invalid dotted record key by its segments', async () => {
+ const role = nextRole();
+ const response = await patchFields(role, [
+ { fieldPath: 'endpoints.bedrock.inferenceProfiles', value: { [PROFILE]: 123 } },
+ ]).expect(400);
+
+ expect(response.body.issues).toEqual([
+ {
+ path: `endpoints.bedrock.inferenceProfiles.${PROFILE}`,
+ segments: ['endpoints', 'bedrock', 'inferenceProfiles', PROFILE],
+ code: 'invalid_type',
+ },
+ ]);
+ expect(await readRaw(role)).toBeNull();
+ });
+});
+
+/** The first key holding a dot anywhere inside a stored value. */
+function findDottedKey(value: unknown): string | undefined {
+ if (value == null || typeof value !== 'object') {
+ return undefined;
+ }
+ for (const [key, child] of Object.entries(value)) {
+ const found = key.includes('.') ? key : findDottedKey(child);
+ if (found) {
+ return found;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Turns the in-memory MongoDB into an engine that refuses dotted field names inside stored
+ * documents, the way MongoDB before 3.6 did, instead of storing them. `$set` paths stay dotted;
+ * only keys inside the values are judged.
+ */
+function refuseDottedFieldNames(): () => void {
+ const collection = mongoose.models.Config.collection;
+ const findOneAndUpdate = collection.findOneAndUpdate.bind(collection);
+ collection.findOneAndUpdate = (async (filter: Doc, update: { $set?: Doc }, options: Doc) => {
+ const key = Object.values(update.$set ?? {})
+ .map(findDottedKey)
+ .find((found) => found != null);
+ if (key) {
+ throw new mongoose.mongo.MongoServerError({
+ ok: 0,
+ code: 57,
+ errmsg: `The dotted field '${key}' in 'overrides' is not valid for storage.`,
+ });
+ }
+ return findOneAndUpdate(filter, update, options);
+ }) as unknown as typeof collection.findOneAndUpdate;
+ return () => {
+ Reflect.deleteProperty(collection, 'findOneAndUpdate');
+ };
+}
+
+describe('admin config writes on an engine that cannot store dotted keys', () => {
+ let restore: () => void;
+
+ beforeAll(() => {
+ restore = refuseDottedFieldNames();
+ });
+
+ afterAll(() => {
+ restore();
+ });
+
+ let warn: jest.SpyInstance;
+
+ beforeEach(() => {
+ warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ });
+
+ it.each([
+ [
+ 'PATCH',
+ (role: string) =>
+ patchFields(role, [
+ { fieldPath: 'endpoints.bedrock.inferenceProfiles', value: { [PROFILE]: ARN } },
+ ]),
+ ],
+ [
+ 'PUT',
+ (role: string) =>
+ putOverrides(role, {
+ endpoints: {
+ azureOpenAI: {
+ groups: [
+ { group: 'eastus', apiKey: '${AZURE_API_KEY}', models: { 'gpt-4.1': true } },
+ ],
+ },
+ },
+ }),
+ ],
+ ])('answers %s with 422 CONFIG_KEY_NOT_STORABLE, not an uncoded 500', async (_label, write) => {
+ const role = nextRole();
+ const response = await write(role).expect(422);
+
+ expect(response.body).toEqual({
+ error: 'The database cannot store a key name in this config',
+ code: 'CONFIG_KEY_NOT_STORABLE',
+ });
+ const logged = JSON.stringify(warn.mock.calls);
+ expect(logged).toContain('rejected a key name');
+ expect(logged).not.toMatch(/us\.anthropic|gpt-4\.1/);
+ expect(await readRaw(role)).toBeNull();
+ });
+
+ it('still stores writes without dotted keys', async () => {
+ const role = nextRole();
+ await patchFields(role, [
+ { fieldPath: 'endpoints.bedrock.models', value: ['anthropic.claude-sonnet-4-6'] },
+ ]).expect(200);
+
+ expect(getIn((await readRaw(role))?.overrides, ['endpoints', 'bedrock'])).toEqual({
+ models: ['anthropic.claude-sonnet-4-6'],
+ });
+ });
+});
diff --git a/packages/api/src/admin/config.handler.spec.ts b/packages/api/src/admin/config.handler.spec.ts
index b19aa8edd1..30072d6e49 100644
--- a/packages/api/src/admin/config.handler.spec.ts
+++ b/packages/api/src/admin/config.handler.spec.ts
@@ -575,7 +575,6 @@ describe('createAdminConfigHandlers', () => {
enabled: false,
publicKey: 'pk-role',
},
- 'langfuse.secretKey': 'sk-role',
},
},
});
@@ -588,6 +587,53 @@ describe('createAdminConfigHandlers', () => {
expect(deps.upsertConfig).not.toHaveBeenCalled();
});
+ it('rejects a dotted section name instead of reading it as a path', async () => {
+ const { handlers, deps } = createHandlers();
+ const req = mockReq({
+ params: { principalType: 'role', principalId: '__base__' },
+ body: {
+ overrides: {
+ langfuse: { enabled: false },
+ 'langfuse.secretKey': 'sk-role',
+ },
+ },
+ });
+ const res = mockRes();
+
+ await handlers.upsertConfigOverrides(req, res);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body).toEqual({
+ error: 'Invalid config override',
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [
+ { path: 'langfuse.secretKey', segments: ['langfuse.secretKey'], code: 'dotted_key' },
+ ],
+ });
+ expect(deps.upsertConfig).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['no config capability', false],
+ ['only assign:configs for the principal type', true],
+ ])('answers 403 before judging a dotted section name with %s', async (_label, canAssign) => {
+ const { handlers, deps } = createHandlers({
+ hasConfigCapability: jest.fn().mockResolvedValue(false),
+ hasCapability: jest.fn().mockResolvedValue(canAssign),
+ });
+ const req = mockReq({
+ params: { principalType: 'role', principalId: 'editor' },
+ body: { overrides: { 'webSearch.serperApiKey': 'sk-serper' } },
+ });
+ const res = mockRes();
+
+ await handlers.upsertConfigOverrides(req, res);
+
+ expect(res.statusCode).toBe(403);
+ expect(res.body).toEqual({ error: 'Insufficient permissions' });
+ expect(deps.upsertConfig).not.toHaveBeenCalled();
+ });
+
it('preserves stored Langfuse settings during a full base-config replacement', async () => {
const storedLangfuse = {
enabled: true,
@@ -2459,7 +2505,13 @@ describe('createAdminConfigHandlers', () => {
expect(res.body).toEqual({
error: 'Invalid config override',
code: 'CONFIG_OVERRIDE_INVALID',
- issues: [{ path: 'registration.oauthStateTtlMs', code: 'too_small' }],
+ issues: [
+ {
+ path: 'registration.oauthStateTtlMs',
+ segments: ['registration', 'oauthStateTtlMs'],
+ code: 'too_small',
+ },
+ ],
});
expect(deps.upsertConfig).not.toHaveBeenCalled();
});
@@ -2564,7 +2616,11 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(400);
expect(res.body?.issues).toEqual([
- { path: 'endpoints.custom', code: 'indexed_merge_key_write' },
+ {
+ path: 'endpoints.custom',
+ segments: ['endpoints', 'custom'],
+ code: 'indexed_merge_key_write',
+ },
]);
expect(deps.patchConfigFields).not.toHaveBeenCalled();
});
diff --git a/packages/api/src/admin/config.ts b/packages/api/src/admin/config.ts
index 6ff2567032..f56d301a59 100644
--- a/packages/api/src/admin/config.ts
+++ b/packages/api/src/admin/config.ts
@@ -1,7 +1,9 @@
import {
logger,
+ isFieldNameRejection,
getConfigFieldIssues,
applyConfigTombstones,
+ getDottedSectionIssues,
getConfigOverrideIssues,
BASE_CONFIG_PRINCIPAL_ID,
} from '@librechat/data-schemas';
@@ -42,8 +44,10 @@ import {
preserveConfigSecrets,
redactConfigSecrets,
} from './secrets';
+import { DEFAULT_OVERRIDE_CACHE_TTL } from '~/app/service';
import { getSafeErrorMetadata } from '~/utils/errors';
import { createAdminAuditEmitter } from './audit';
+import { buildAdminConfigMeta } from './meta';
const UNSAFE_SEGMENTS = /(?:^|\.)(__[\w]*|constructor|prototype)(?:\.|$)/;
const MAX_PATCH_ENTRIES = 100;
@@ -259,6 +263,11 @@ export interface AdminConfigDeps {
/** When true, a failed audit write surfaces as a 5xx after the mutation has
* been persisted. Defaults to fail-open. */
auditFailClosed?: boolean;
+ /**
+ * The `overrideCacheTtl` the app config service runs with, which `GET /meta` reports.
+ * Defaults to the service's own default.
+ */
+ overrideCacheTtlMs?: number;
}
/** Audit target for a principal's override document. Records field paths and
@@ -438,12 +447,30 @@ function redactAppConfigForResponse(appConfig: AppConfig): AppConfig {
return safeConfig;
}
-/** Reports only the paths and stable codes: schema messages can echo the submitted values. */
+/**
+ * Reports only locations and stable codes: schema messages can echo the submitted values.
+ * `segments` names the location key by key, since `path` is ambiguous once a record key
+ * itself holds a dot.
+ */
function invalidOverrideResponse(res: Response, issues: ConfigOverrideIssue[]): Response {
return res.status(400).json({
error: 'Invalid config override',
code: 'CONFIG_OVERRIDE_INVALID',
- issues: issues.map(({ path, code }) => ({ path, code })),
+ issues: issues.map(({ path, segments, code }) => ({ path, segments, code })),
+ });
+}
+
+/**
+ * The database refused a key name in the written overrides, such as a dotted record key on an
+ * engine that cannot store one. Nothing was written; the key is not echoed.
+ */
+function unstorableKeyResponse(res: Response, operation: string): Response {
+ logger.warn(
+ `[adminConfig] ${operation}: the database rejected a key name in the overrides, such as a dotted record key this engine cannot store`,
+ );
+ return res.status(422).json({
+ error: 'The database cannot store a key name in this config',
+ code: 'CONFIG_KEY_NOT_STORABLE',
});
}
@@ -464,6 +491,7 @@ function preservePatchedConfigSecretFields(
export function createAdminConfigHandlers(deps: AdminConfigDeps): {
listConfigs: (req: ServerRequest, res: Response) => Promise<Response>;
+ getConfigMeta: (req: ServerRequest, res: Response) => Promise<Response>;
getBaseConfig: (req: ServerRequest, res: Response) => Promise<Response>;
getConfig: (req: ServerRequest, res: Response) => Promise<Response>;
upsertConfigOverrides: (req: ServerRequest, res: Response) => Promise<Response>;
@@ -498,6 +526,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
invalidateConfigCaches,
recordAuditEntry,
auditFailClosed,
+ overrideCacheTtlMs = DEFAULT_OVERRIDE_CACHE_TTL,
} = deps;
const emitAudit = createAdminAuditEmitter({
@@ -506,6 +535,8 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
logPrefix: '[adminConfig]',
});
+ const meta = buildAdminConfigMeta({ maxPatchEntries: MAX_PATCH_ENTRIES, overrideCacheTtlMs });
+
/** The deployment's `librechat.yaml` config, which overrides are validated on top of. */
async function getBaseYamlConfig(tenantId?: string): Promise<Partial<TCustomConfig>> {
if (!getAppConfig) {
@@ -542,6 +573,29 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
}
+ /**
+ * GET /meta — The contract this server applies to config writes: feature flags, limits,
+ * versions and the rules a client mirrors. An older server answers 404, which a client reads
+ * as every feature off.
+ */
+ async function getConfigMeta(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' });
+ }
+
+ return res.status(200).json(meta);
+ } catch (error) {
+ logger.error('[adminConfig] getConfigMeta error:', getSafeErrorMetadata(error));
+ return res.status(500).json({ error: 'Failed to get config meta' });
+ }
+ }
+
/**
* GET /base — Return the raw AppConfig (YAML + DB base merged).
* This is the full config structure admins can edit, NOT the startup payload.
@@ -676,6 +730,17 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return res.status(403).json({ error: 'Insufficient permissions' });
}
+ /**
+ * Checked before any section rule or secret encryption reads a dotted key as a path. A
+ * dotted key is a section write, which only broad manage may make.
+ */
+ const dottedSectionIssues = getDottedSectionIssues(rawOverrides);
+ if (dottedSectionIssues.length > 0) {
+ return hasBroadManage
+ ? invalidOverrideResponse(res, dottedSectionIssues)
+ : res.status(403).json({ error: 'Insufficient permissions' });
+ }
+
const filteredOverrides = {
...(overrides as Record<string, unknown>),
} as Partial<TCustomConfig>;
@@ -838,6 +903,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
config: config ? redactConfigForResponse(config) : config,
});
} catch (error) {
+ if (isFieldNameRejection(error)) {
+ return unstorableKeyResponse(res, 'upsertConfigOverrides');
+ }
logger.error('[adminConfig] upsertConfigOverrides error:', getSafeErrorMetadata(error));
return res.status(500).json({ error: 'Failed to upsert config' });
}
@@ -845,6 +913,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
/**
* PATCH /:principalType/:principalId/fields — Set individual fields via dot-paths.
+ *
+ * A `fieldPath` (here, and for tombstones and unsets) is split on dots, so it cannot address
+ * a record key that holds one, such as a Bedrock inference profile or a `gpt-4.1` model
+ * entry: write that record whole at its own path (`endpoints.bedrock.inferenceProfiles`).
*/
async function patchConfigField(req: ServerRequest, res: Response): Promise<Response> {
try {
@@ -1013,6 +1085,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
return res.status(200).json({ config: config ? redactConfigForResponse(config) : config });
} catch (error) {
+ if (isFieldNameRejection(error)) {
+ return unstorableKeyResponse(res, 'patchConfigField');
+ }
logger.error('[adminConfig] patchConfigField error:', getSafeErrorMetadata(error));
return res.status(500).json({ error: 'Failed to patch config fields' });
}
@@ -1409,6 +1484,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
return {
listConfigs,
+ getConfigMeta,
getBaseConfig,
getConfig,
upsertConfigOverrides,
diff --git a/packages/api/src/admin/meta.spec.ts b/packages/api/src/admin/meta.spec.ts
new file mode 100644
index 0000000000..0f134f16e7
--- /dev/null
+++ b/packages/api/src/admin/meta.spec.ts
@@ -0,0 +1,349 @@
+import { join } from 'path';
+import { readFileSync } from 'fs';
+import mongoSanitize from 'express-mongo-sanitize';
+import { mergeConfigOverrides, getConfigOverrideIssues } from '@librechat/data-schemas';
+import {
+ Constants,
+ configSchema,
+ PERMISSION_SUB_KEYS,
+ BASE_ONLY_CONFIG_PATHS,
+ BASE_ONLY_CONFIG_SECTIONS,
+ PROCESS_MCP_SERVER_FIELDS,
+ INTERFACE_PERMISSION_FIELDS,
+ BASE_PRINCIPAL_CONFIG_SECTIONS,
+ RUNTIME_CONFIG_INTERFACE_FIELDS,
+} from 'librechat-data-provider';
+import type {
+ AdminConfigFeatureFlag,
+ AdminConfigMeta,
+ AppConfig,
+ IConfig,
+} from '@librechat/data-schemas';
+import type { Request, Response } from 'express';
+import type { ServerRequest } from '~/types/http';
+import type { AdminConfigDeps } from './config';
+import { createRequestSanitizer, rejectUnsafeConfigKeys } from '~/middleware/sanitize';
+import { createAdminConfigHandlers } from './config';
+import { redactConfigSecrets } from './secrets';
+import { ADMIN_CONFIG_FEATURES } from './meta';
+
+type Doc = Record<string, unknown>;
+type ResponseBody = { config?: { overrides: Doc }; [key: string]: unknown };
+type MockRes = Response & { statusCode: number; body: ResponseBody | undefined };
+type MockReqInit = Omit<Partial<ServerRequest>, 'body'> & { body?: object };
+type PatchEntry = { fieldPath: string; value: unknown };
+
+function mockRes(): MockRes {
+ const res = { statusCode: 200, body: undefined } as MockRes;
+ res.status = jest.fn((code: number) => {
+ res.statusCode = code;
+ return res;
+ });
+ res.json = jest.fn((data: ResponseBody) => {
+ res.body = data;
+ return res;
+ });
+ return res;
+}
+
+function mockReq(init: MockReqInit = {}): ServerRequest {
+ return {
+ user: { id: 'u1', role: 'ADMIN', _id: { toString: () => 'u1' } },
+ params: {},
+ body: {},
+ query: {},
+ ...init,
+ } as Partial<ServerRequest> as ServerRequest;
+}
+
+function createHandlers(overrides: Partial<AdminConfigDeps> = {}) {
+ return createAdminConfigHandlers({
+ listAllConfigs: jest.fn().mockResolvedValue([]),
+ findConfigByPrincipal: jest.fn().mockResolvedValue(null),
+ upsertConfig: jest.fn().mockResolvedValue(null),
+ patchConfigFields: jest.fn().mockResolvedValue(null),
+ tombstoneConfigField: jest.fn().mockResolvedValue(null),
+ unsetConfigField: jest.fn().mockResolvedValue(null),
+ deleteConfig: jest.fn().mockResolvedValue(null),
+ toggleConfigActiveTracked: jest.fn().mockResolvedValue(null),
+ hasConfigCapability: jest.fn().mockResolvedValue(true),
+ hasAnyConfigReadAccess: jest.fn().mockResolvedValue(true),
+ hasCapability: jest.fn().mockResolvedValue(true),
+ getAppConfig: jest.fn().mockResolvedValue({ config: {} }),
+ ...overrides,
+ });
+}
+
+async function getMeta(): Promise<{ status: number; meta: AdminConfigMeta }> {
+ const res = mockRes();
+ await createHandlers().getConfigMeta(mockReq(), res);
+ return { status: res.statusCode, meta: res.body as AdminConfigMeta };
+}
+
+async function patch(
+ entries: PatchEntry[],
+ overrides: Partial<AdminConfigDeps> = {},
+): Promise<MockRes> {
+ const res = mockRes();
+ await createHandlers(overrides).patchConfigField(
+ mockReq({ params: { principalType: 'role', principalId: 'r1' }, body: { entries } }),
+ res,
+ );
+ return res;
+}
+
+function storedConfig(overrides: Doc): IConfig {
+ return {
+ principalType: 'role',
+ principalId: 'r1',
+ priority: 10,
+ overrides,
+ isActive: true,
+ } as Partial<IConfig> as IConfig;
+}
+
+function setIn(target: Doc, segments: string[], value: unknown): Doc {
+ const [head, ...rest] = segments;
+ const child = target[head];
+ const parent = child != null && typeof child === 'object' ? (child as Doc) : {};
+ return { ...target, [head]: rest.length === 0 ? value : setIn(parent, rest, value) };
+}
+
+function getIn(target: object, path: string): unknown {
+ return path
+ .split('.')
+ .reduce<unknown>(
+ (node, segment) =>
+ node != null && typeof node === 'object' ? (node as Doc)[segment] : undefined,
+ target,
+ );
+}
+
+describe('GET /api/admin/config/meta', () => {
+ it('answers 401 without a user and 403 without any config read access', async () => {
+ const anonymous = mockRes();
+ await createHandlers().getConfigMeta(mockReq({ user: undefined }), anonymous);
+ expect(anonymous.statusCode).toBe(401);
+
+ const hasAnyConfigReadAccess = jest.fn().mockResolvedValue(false);
+ const forbidden = mockRes();
+ await createHandlers({ hasAnyConfigReadAccess }).getConfigMeta(mockReq(), forbidden);
+ expect(forbidden.statusCode).toBe(403);
+ expect(forbidden.body).toEqual({ error: 'Insufficient permissions' });
+ expect(hasAnyConfigReadAccess).toHaveBeenCalledWith(expect.objectContaining({ id: 'u1' }));
+ });
+
+ it('answers 500 without echoing the failure when the access check throws', async () => {
+ const res = mockRes();
+ const hasAnyConfigReadAccess = jest.fn().mockRejectedValue(new Error('db down: secret'));
+ await createHandlers({ hasAnyConfigReadAccess }).getConfigMeta(mockReq(), res);
+ expect(res.statusCode).toBe(500);
+ expect(res.body).toEqual({ error: 'Failed to get config meta' });
+ });
+
+ it('keeps its response keys stable', async () => {
+ const { status, meta } = await getMeta();
+ expect(status).toBe(200);
+ expect(Object.keys(meta)).toEqual(['metaVersion', 'versions', 'features', 'limits', 'rules']);
+ expect(meta.metaVersion).toBe(1);
+ expect(Object.keys(meta.versions)).toEqual(['librechat', 'dataProvider', 'configSchema']);
+ expect(Object.keys(meta.features).sort()).toEqual([
+ 'dottedKeys',
+ 'readFilteredWriteResponses',
+ 'sectionAllowlist',
+ ]);
+ expect(meta.limits).toEqual({ maxPatchEntries: 100, overrideCacheTtlMs: 60_000 });
+ expect(Object.keys(meta.rules).sort()).toEqual([
+ 'acceptedSections',
+ 'arrayMergeKeys',
+ 'arraySecretFields',
+ 'atomicMergePaths',
+ 'baseOnlyPaths',
+ 'baseOnlySections',
+ 'basePrincipalSections',
+ 'interface',
+ 'overrideKeyMap',
+ 'processMcpFields',
+ 'refusedMaps',
+ 'secretFields',
+ 'titleResolution',
+ ]);
+ });
+
+ it('reports the override cache TTL the app config service runs with', async () => {
+ const res = mockRes();
+ await createHandlers({ overrideCacheTtlMs: 15_000 }).getConfigMeta(mockReq(), res);
+ expect((res.body as AdminConfigMeta).limits.overrideCacheTtlMs).toBe(15_000);
+ });
+
+ it('reports the versions this server was built with', async () => {
+ const { meta } = await getMeta();
+ const dataProvider = JSON.parse(
+ readFileSync(join(__dirname, '../../../data-provider/package.json'), 'utf8'),
+ ) as { version: string };
+ expect(meta.versions).toEqual({
+ librechat: Constants.VERSION,
+ dataProvider: dataProvider.version,
+ configSchema: Constants.CONFIG_VERSION,
+ });
+ expect(meta.versions.dataProvider).not.toContain('__');
+ });
+});
+
+describe('meta rules equal the rules the server applies', () => {
+ let meta: AdminConfigMeta;
+ beforeAll(async () => {
+ ({ meta } = await getMeta());
+ });
+
+ it('lists the sections and paths of the live constants', () => {
+ expect(meta.rules.acceptedSections).toEqual(Object.keys(configSchema.shape));
+ expect(meta.rules.baseOnlySections).toEqual([...BASE_ONLY_CONFIG_SECTIONS]);
+ expect(meta.rules.basePrincipalSections).toEqual([...BASE_PRINCIPAL_CONFIG_SECTIONS]);
+ expect(meta.rules.baseOnlyPaths).toEqual([...BASE_ONLY_CONFIG_PATHS]);
+ expect(meta.rules.processMcpFields).toEqual([...PROCESS_MCP_SERVER_FIELDS]);
+ expect(meta.rules.interface).toEqual({
+ permissionFields: [...INTERFACE_PERMISSION_FIELDS],
+ runtimeFields: [...RUNTIME_CONFIG_INTERFACE_FIELDS],
+ permissionSubKeys: [...PERMISSION_SUB_KEYS],
+ });
+ expect(meta.rules.titleResolution).toBe('block');
+ });
+
+ it('lists exactly the secret fields reads withhold, with their preview companions', () => {
+ expect(meta.rules.secretFields.length).toBeGreaterThan(0);
+ const placeholder = '${SOME_KEY}';
+ const stalePreview = 'sk-live-...cdef';
+ const write = (value: string): Doc =>
+ meta.rules.secretFields.reduce<Doc>(
+ (doc, { path, previewPath }) =>
+ setIn(setIn(doc, path.split('.'), value), previewPath.split('.'), stalePreview),
+ {},
+ );
+
+ const literals = redactConfigSecrets(write('sk-live-0123456789abcdef'));
+ const placeholders = redactConfigSecrets(write(placeholder));
+ for (const { path, previewPath, allowEnvPlaceholder } of meta.rules.secretFields) {
+ expect(getIn(literals, path)).toBeUndefined();
+ expect(getIn(literals, previewPath)).toBe('*'.repeat(stalePreview.length));
+ expect(getIn(placeholders, path)).toBe(allowEnvPlaceholder ? placeholder : undefined);
+ }
+ });
+
+ it('lists the array secret reads withhold on custom endpoints', () => {
+ expect(meta.rules.arraySecretFields).toEqual([
+ {
+ arrayPath: 'endpoints.custom',
+ secretKey: 'apiKey',
+ previewKey: 'apiKeyPreview',
+ identityKey: 'name',
+ },
+ ]);
+ const [{ arrayPath, secretKey, identityKey }] = meta.rules.arraySecretFields;
+ const doc = setIn({}, arrayPath.split('.'), [{ [identityKey]: 'gw', [secretKey]: 'sk-live' }]);
+ expect(getIn(redactConfigSecrets(doc), arrayPath)).toEqual([{ [identityKey]: 'gw' }]);
+ });
+
+ it('refuses writes to every listed map and process MCP field', async () => {
+ for (const path of meta.rules.refusedMaps) {
+ expect((await patch([{ fieldPath: path, value: { 'X-Token': 't' } }])).statusCode).toBe(400);
+ }
+ for (const field of meta.rules.processMcpFields) {
+ const res = await patch([{ fieldPath: `mcpServers.s1.${field}`, value: 'x' }]);
+ expect(res.statusCode).toBe(400);
+ }
+ });
+
+ it('drops writes to base-only sections', async () => {
+ const patchConfigFields = jest.fn();
+ for (const section of meta.rules.baseOnlySections) {
+ const res = await patch([{ fieldPath: `${section}.x`, value: 1 }], { patchConfigFields });
+ expect(res.body).toEqual({ message: 'No actionable field entries provided' });
+ }
+ expect(patchConfigFields).not.toHaveBeenCalled();
+ });
+
+ it('requires the listed merge key on items of every merged array', () => {
+ for (const [arrayPath, key] of Object.entries(meta.rules.arrayMergeKeys)) {
+ const segments = arrayPath.split('.');
+ const missing = getConfigOverrideIssues(setIn({}, segments, [{ other: 1 }]));
+ expect(missing).toContainEqual(expect.objectContaining({ code: 'missing_merge_key' }));
+ const keyed = getConfigOverrideIssues(setIn({}, segments, [{ [key]: 'a' }]));
+ expect(keyed).not.toContainEqual(expect.objectContaining({ code: 'missing_merge_key' }));
+ }
+ });
+
+ it('replaces every listed atomic path whole, under the mapped resolved key', () => {
+ const theme = (name: string, modes: Doc) => ({ version: 1, name, modes });
+ for (const atomicPath of meta.rules.atomicMergePaths) {
+ const [section, ...rest] = atomicPath.split('.');
+ const resolved = [meta.rules.overrideKeyMap[section] ?? section, ...rest];
+ const base = setIn({}, resolved, theme('base', { light: { colors: { a: '0 0 0' } } }));
+ const override = theme('override', { dark: { colors: { b: '1 1 1' } } });
+ const merged = mergeConfigOverrides(Object.assign({ config: {} } as AppConfig, base), [
+ storedConfig(setIn({}, atomicPath.split('.'), override)),
+ ]);
+ expect(getIn(merged, resolved.join('.'))).toEqual(override);
+ }
+ });
+});
+
+/**
+ * Each flag is checked against the behaviour itself: a flag left `false` once its change lands,
+ * or set `true` without it, fails here.
+ */
+const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
+ async dottedKeys() {
+ const body = {
+ overrides: { endpoints: { bedrock: { inferenceProfiles: { 'us.a.b': 'x' } } } },
+ };
+ const req = {
+ path: '/api/admin/config/role/r1',
+ headers: {},
+ query: {},
+ body: structuredClone(body),
+ } as Request;
+ const next = jest.fn();
+ createRequestSanitizer(mongoSanitize)(req, mockRes(), next);
+ const keepsDots =
+ next.mock.calls.length === 1 && JSON.stringify(req.body) === JSON.stringify(body);
+
+ const unsafe = mockRes();
+ rejectUnsafeConfigKeys({ body: { overrides: { $where: 1 } } } as Request, unsafe, jest.fn());
+
+ const flagsFixedShape = getConfigOverrideIssues({ registration: { 'a.b': 1 } }).some(
+ (issue) => issue.code === 'dotted_key',
+ );
+ return keepsDots && unsafe.statusCode === 400 && flagsFixedShape;
+ },
+ async sectionAllowlist() {
+ return getConfigOverrideIssues({ paths: { uploads: '/tmp' } }).length > 0;
+ },
+ async readFilteredWriteResponses() {
+ const res = await patch([{ fieldPath: 'endpoints.openAI.titleModel', value: 'gpt-4o-mini' }], {
+ hasConfigCapability: jest.fn(
+ async (_user, section, verb = 'manage') => verb === 'manage' && section === 'endpoints',
+ ),
+ getReadableConfigSections: jest.fn().mockResolvedValue({ broad: false, sections: new Set() }),
+ patchConfigFields: jest.fn().mockResolvedValue(
+ storedConfig({
+ endpoints: { openAI: { titleModel: 'gpt-4o-mini' } },
+ memory: { disabled: true },
+ }),
+ ),
+ });
+ const overrides = res.body?.config?.overrides;
+ return res.statusCode === 200 && overrides != null && !('memory' in overrides);
+ },
+};
+
+describe('meta feature flags', () => {
+ it.each(Object.keys(FEATURE_PROBES) as AdminConfigFeatureFlag[])(
+ '%s matches what the server does',
+ async (flag) => {
+ const { meta } = await getMeta();
+ expect(meta.features[flag]).toBe(ADMIN_CONFIG_FEATURES[flag]);
+ expect(meta.features[flag]).toBe(await FEATURE_PROBES[flag]());
+ },
+ );
+});
diff --git a/packages/api/src/admin/meta.ts b/packages/api/src/admin/meta.ts
new file mode 100644
index 0000000000..3838255959
--- /dev/null
+++ b/packages/api/src/admin/meta.ts
@@ -0,0 +1,58 @@
+import { getConfigMergeRules } from '@librechat/data-schemas';
+import {
+ Constants,
+ configSchema,
+ PERMISSION_SUB_KEYS,
+ BASE_ONLY_CONFIG_PATHS,
+ DATA_PROVIDER_VERSION,
+ BASE_ONLY_CONFIG_SECTIONS,
+ PROCESS_MCP_SERVER_FIELDS,
+ INTERFACE_PERMISSION_FIELDS,
+ BASE_PRINCIPAL_CONFIG_SECTIONS,
+ RUNTIME_CONFIG_INTERFACE_FIELDS,
+} from 'librechat-data-provider';
+import type { AdminConfigFeatures, AdminConfigMeta } from '@librechat/data-schemas';
+import { getConfigSecretRules } from './secrets';
+
+/**
+ * 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
+ * claim what the server does not do, nor stay off once it does.
+ */
+export const ADMIN_CONFIG_FEATURES: Readonly<AdminConfigFeatures> = {
+ dottedKeys: true,
+ sectionAllowlist: false,
+ readFilteredWriteResponses: false,
+};
+
+/**
+ * The contract `GET /api/admin/config/meta` reports, built from the constants the server
+ * enforces rather than restated, so the rules a client mirrors cannot drift from them.
+ */
+export function buildAdminConfigMeta(limits: AdminConfigMeta['limits']): AdminConfigMeta {
+ return {
+ metaVersion: 1,
+ versions: {
+ librechat: String(Constants.VERSION),
+ dataProvider: DATA_PROVIDER_VERSION,
+ configSchema: String(Constants.CONFIG_VERSION),
+ },
+ features: { ...ADMIN_CONFIG_FEATURES },
+ limits: { ...limits },
+ rules: {
+ acceptedSections: Object.keys(configSchema.shape),
+ baseOnlySections: [...BASE_ONLY_CONFIG_SECTIONS],
+ basePrincipalSections: [...BASE_PRINCIPAL_CONFIG_SECTIONS],
+ baseOnlyPaths: [...BASE_ONLY_CONFIG_PATHS],
+ ...getConfigMergeRules(),
+ ...getConfigSecretRules(),
+ processMcpFields: [...PROCESS_MCP_SERVER_FIELDS],
+ interface: {
+ permissionFields: [...INTERFACE_PERMISSION_FIELDS],
+ runtimeFields: [...RUNTIME_CONFIG_INTERFACE_FIELDS],
+ permissionSubKeys: [...PERMISSION_SUB_KEYS],
+ },
+ titleResolution: 'block',
+ },
+ };
+}
diff --git a/packages/api/src/admin/secrets.ts b/packages/api/src/admin/secrets.ts
index 547600c52e..84d6505bc4 100644
--- a/packages/api/src/admin/secrets.ts
+++ b/packages/api/src/admin/secrets.ts
@@ -1,6 +1,7 @@
import isPlainObject from 'lodash/isPlainObject';
import { encryptV3, decryptV3, logger } from '@librechat/data-schemas';
import { envVarRegex, extractEnvVariable } from 'librechat-data-provider';
+import type { AdminConfigRules } from '@librechat/data-schemas';
import { isUserProvided } from '~/utils/common';
const ENCRYPTED_PREFIX = 'v3:';
@@ -143,6 +144,29 @@ export function getConfigSecretSections(): readonly string[] {
return SECRET_SECTIONS;
}
+/** The secret registries as plain data, for admin clients that render secret inputs. */
+export function getConfigSecretRules(): Pick<
+ AdminConfigRules,
+ 'secretFields' | 'arraySecretFields' | 'refusedMaps'
+> {
+ return {
+ secretFields: CONFIG_SECRET_FIELDS.map(({ path, previewPath, allowEnvPlaceholder }) => ({
+ path,
+ previewPath,
+ allowEnvPlaceholder: allowEnvPlaceholder === true,
+ })),
+ arraySecretFields: ARRAY_SECRET_FIELDS.map(
+ ({ arrayPath, secretKey, previewKey, identityKey }) => ({
+ arrayPath,
+ secretKey,
+ previewKey,
+ identityKey,
+ }),
+ ),
+ refusedMaps: [...CONFIG_SECRET_MAP_FIELDS],
+ };
+}
+
function normalizeSecretString(value: unknown): string | undefined {
return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined;
}
diff --git a/packages/api/src/app/service.spec.ts b/packages/api/src/app/service.spec.ts
index aeb553311f..a27bcd3ba4 100644
--- a/packages/api/src/app/service.spec.ts
+++ b/packages/api/src/app/service.spec.ts
@@ -4,6 +4,7 @@ import type { AppConfig } from '@librechat/data-schemas';
import {
createAppConfigService,
createMessageBudgetReader,
+ DEFAULT_OVERRIDE_CACHE_TTL,
_resetOverrideStrictCache,
getAppConfigOptionsFromUser,
} from './service';
@@ -1410,6 +1411,44 @@ describe('createAppConfigService', () => {
await expect(clearOverrideCache()).resolves.toBeUndefined();
});
});
+
+ describe('overrideCacheTtl', () => {
+ const overrideDeps = (overrides = {}) =>
+ createDeps({
+ getApplicableConfigs: jest
+ .fn()
+ .mockResolvedValue([{ priority: 10, overrides: { x: 1 }, isActive: true }]),
+ ...overrides,
+ });
+
+ it('reports the TTL it caches merged configs for', async () => {
+ const deps = overrideDeps({ overrideCacheTtl: 15_000 });
+ const service = createAppConfigService(deps);
+
+ await service.getAppConfig({ role: 'ADMIN' });
+
+ expect(service.overrideCacheTtl).toBe(15_000);
+ expect(deps._cache.set).toHaveBeenCalledWith(
+ expect.stringContaining('ADMIN'),
+ expect.anything(),
+ 15_000,
+ );
+ });
+
+ it('reports the default TTL when none is configured', async () => {
+ const deps = overrideDeps();
+ const service = createAppConfigService(deps);
+
+ await service.getAppConfig({ role: 'ADMIN' });
+
+ expect(service.overrideCacheTtl).toBe(DEFAULT_OVERRIDE_CACHE_TTL);
+ expect(deps._cache.set).toHaveBeenCalledWith(
+ expect.stringContaining('ADMIN'),
+ expect.anything(),
+ DEFAULT_OVERRIDE_CACHE_TTL,
+ );
+ });
+ });
});
describe('getAppConfigOptionsFromUser', () => {
diff --git a/packages/api/src/app/service.ts b/packages/api/src/app/service.ts
index 1e6304fb13..cfb4cf85be 100644
--- a/packages/api/src/app/service.ts
+++ b/packages/api/src/app/service.ts
@@ -351,6 +351,8 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {
getAppConfig: (options?: GetAppConfigOptions) => Promise<AppConfig>;
clearAppConfigCache: () => Promise<void>;
clearOverrideCache: (tenantId?: string) => Promise<void>;
+ /** The TTL in ms this service caches per-principal merged configs for. */
+ overrideCacheTtl: number;
} {
const {
loadBaseConfig,
@@ -658,6 +660,7 @@ export function createAppConfigService(deps: AppConfigServiceDeps): {
getAppConfig,
clearAppConfigCache,
clearOverrideCache,
+ overrideCacheTtl,
};
}
diff --git a/packages/api/src/middleware/index.ts b/packages/api/src/middleware/index.ts
index 82b706028f..9bbb1127f8 100644
--- a/packages/api/src/middleware/index.ts
+++ b/packages/api/src/middleware/index.ts
@@ -7,6 +7,7 @@ export * from './origin';
export * from './balance';
export * from './ban';
export * from './json';
+export * from './sanitize';
export * from './capabilities';
export * from './auth';
export {
diff --git a/packages/api/src/middleware/sanitize.spec.ts b/packages/api/src/middleware/sanitize.spec.ts
new file mode 100644
index 0000000000..a55c20a3f2
--- /dev/null
+++ b/packages/api/src/middleware/sanitize.spec.ts
@@ -0,0 +1,115 @@
+import express from 'express';
+import request from 'supertest';
+import mongoSanitize from 'express-mongo-sanitize';
+import type { Request, Response, NextFunction } from 'express';
+import { createRequestSanitizer, rejectUnsafeConfigKeys } from './sanitize';
+
+type Echo = { body: unknown; query: unknown; headers: Record<string, unknown> };
+
+/** The app-level order in `api/server/index.js`: JSON body, writable query, then the sanitizer. */
+function createApp(...guards: Array<(req: Request, res: Response, next: NextFunction) => void>) {
+ const app = express();
+ app.use(express.json());
+ app.use((req, _res, next) => {
+ Object.defineProperty(req, 'query', {
+ ...Object.getOwnPropertyDescriptor(req, 'query'),
+ value: req.query,
+ writable: true,
+ });
+ next();
+ });
+ app.use(createRequestSanitizer(mongoSanitize));
+ app.use(...guards, (req: Request, res: Response) => {
+ res.json({ body: req.body, query: req.query, headers: req.headers });
+ });
+ return app;
+}
+
+async function send(app: express.Express, path: string, body: unknown, query = '') {
+ const response = await request(app)
+ .patch(`${path}${query}`)
+ .set('x-test.dotted', 'h')
+ .set('$x-test', 'h')
+ .send(body as object);
+ return { status: response.status, echo: response.body as Echo };
+}
+
+const DOTTED_BODY = {
+ entries: [
+ {
+ fieldPath: 'endpoints.bedrock.inferenceProfiles',
+ value: { 'us.anthropic.claude-sonnet-4-6': 'arn:aws:bedrock:us-east-1:1:x' },
+ },
+ ],
+};
+
+describe('createRequestSanitizer', () => {
+ const app = createApp();
+
+ it.each([
+ '/api/admin/config/role/__base__/fields',
+ '/API/Admin/Config/role/__base__/fields',
+ '/api/admin/config',
+ ])('keeps dotted body keys on %s', async (path) => {
+ const { status, echo } = await send(app, path, DOTTED_BODY);
+ expect(status).toBe(200);
+ expect(echo.body).toEqual(DOTTED_BODY);
+ });
+
+ it('keeps query and headers strict on the admin config path', async () => {
+ const { echo } = await send(
+ app,
+ '/api/admin/config/role/x/fields',
+ DOTTED_BODY,
+ '?a.b=1&$where=1&ok=1',
+ );
+ expect(echo.query).toEqual({ ok: '1' });
+ expect(echo.headers).not.toHaveProperty('x-test.dotted');
+ expect(echo.headers).not.toHaveProperty('$x-test');
+ });
+
+ it.each([
+ '/api/admin/configs',
+ '/api/admin/configuration',
+ '/api/admin/roles',
+ '/api/agents',
+ '/api/admin/%63onfig/role/x/fields',
+ ])('still strips dotted and $ keys from the body on %s', async (path) => {
+ const { echo } = await send(app, path, {
+ entries: [{ fieldPath: 'x', value: { 'a.b': 1, $where: 'x', kept: 1 } }],
+ });
+ expect(echo.body).toEqual({ entries: [{ fieldPath: 'x', value: { kept: 1 } }] });
+ });
+});
+
+describe('rejectUnsafeConfigKeys', () => {
+ const app = createApp(rejectUnsafeConfigKeys);
+
+ it.each([
+ ['a $ operator', '{"entries":[{"fieldPath":"x","value":{"$where":"1"}}]}'],
+ ['a nested $ key in an array', '{"overrides":{"a":[{"b":[{"$set":1}]}]}}'],
+ ['a __proto__ key', '{"overrides":{"registration":{"__proto__":{"polluted":true}}}}'],
+ ['a constructor key', '{"overrides":{"constructor":{"prototype":{}}}}'],
+ ])('answers 400 CONFIG_UNSAFE_KEY for %s without echoing it', async (_label, raw) => {
+ const response = await request(app)
+ .patch('/api/admin/config/role/x/fields')
+ .set('content-type', 'application/json')
+ .send(raw);
+ expect(response.status).toBe(400);
+ expect(response.body).toEqual({
+ error: 'Config keys cannot start with "$" or name an object prototype',
+ code: 'CONFIG_UNSAFE_KEY',
+ });
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
+ });
+
+ it('passes dotted keys, `$` inside values, and bodies without objects through', async () => {
+ const body = { entries: [{ fieldPath: 'a.b', value: { 'gpt-4.1': '$5 per run', n: [1] } }] };
+ const { status, echo } = await send(app, '/api/admin/config/role/x/fields', body);
+ expect(status).toBe(200);
+ expect(echo.body).toEqual(body);
+
+ const empty = await request(app).delete('/api/admin/config/role/x/fields?fieldPath=a');
+ expect(empty.status).toBe(200);
+ });
+});
diff --git a/packages/api/src/middleware/sanitize.ts b/packages/api/src/middleware/sanitize.ts
new file mode 100644
index 0000000000..71a090d6c8
--- /dev/null
+++ b/packages/api/src/middleware/sanitize.ts
@@ -0,0 +1,76 @@
+import type { Request, Response, NextFunction, RequestHandler } from 'express';
+
+/** The parts of `express-mongo-sanitize` the request sanitizer uses; the caller supplies it. */
+export interface MongoSanitizer {
+ (): RequestHandler;
+ sanitize: <T extends Record<string, unknown> | unknown[]>(target: T) => T;
+}
+
+/**
+ * Admin config writes carry config keys verbatim, and record keys legitimately hold dots (model
+ * names such as `gpt-4.1`, Bedrock inference profiles, MIME types). Matched case-insensitively
+ * on the raw path, as Express routes it, so an encoded path Express would not route to the
+ * admin config router stays strict.
+ */
+const ADMIN_CONFIG_PATH = /^\/api\/admin\/config(?:\/|$)/i;
+
+/**
+ * App-level request sanitizer: strict `express-mongo-sanitize` everywhere, except that admin
+ * config bodies keep their keys. Their `$`-prefixed and prototype keys are rejected after auth
+ * by {@link rejectUnsafeConfigKeys} instead, so an unauthenticated caller still gets a 401.
+ */
+export function createRequestSanitizer(mongoSanitize: MongoSanitizer): RequestHandler {
+ const strict = mongoSanitize();
+ return function sanitizeRequest(req: Request, res: Response, next: NextFunction): void {
+ if (!ADMIN_CONFIG_PATH.test(req.path)) {
+ strict(req, res, next);
+ return;
+ }
+ req.headers = mongoSanitize.sanitize(req.headers);
+ req.query = mongoSanitize.sanitize(req.query);
+ next();
+ };
+}
+
+const PROTOTYPE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
+
+function isUnsafeKey(key: string): boolean {
+ return key.startsWith('$') || PROTOTYPE_KEYS.has(key);
+}
+
+/** Whether any key in `value`, at any depth, is a `$` operator or names an object prototype. */
+function hasUnsafeConfigKey(value: unknown): boolean {
+ const pending: unknown[] = [value];
+ while (pending.length > 0) {
+ const node = pending.pop();
+ if (Array.isArray(node)) {
+ for (const item of node) {
+ pending.push(item);
+ }
+ } else if (node != null && typeof node === 'object') {
+ for (const [key, child] of Object.entries(node)) {
+ if (isUnsafeKey(key)) {
+ return true;
+ }
+ pending.push(child);
+ }
+ }
+ }
+ return false;
+}
+
+/**
+ * Admin config route guard, mounted after authentication: answers 400 `CONFIG_UNSAFE_KEY` for a
+ * body key the database would read as an operator (`$set`, `$where`) or that names an object
+ * prototype, instead of silently dropping it. The key is not echoed back.
+ */
+export function rejectUnsafeConfigKeys(req: Request, res: Response, next: NextFunction): void {
+ if (!hasUnsafeConfigKey(req.body)) {
+ next();
+ return;
+ }
+ res.status(400).json({
+ error: 'Config keys cannot start with "$" or name an object prototype',
+ code: 'CONFIG_UNSAFE_KEY',
+ });
+}
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index 352869f1f2..b5c3935689 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -5317,6 +5317,12 @@ export enum Constants {
TOOL_CALL_LIMIT_FINISH_REASON = 'tool_call_limit',
}
+/**
+ * This package's own version, swapped in from `packages/data-provider/package.json` at build
+ * time like `Constants.VERSION`, so a server can report which schema package it validates with.
+ */
+export const DATA_PROVIDER_VERSION: string = '__DATA_PROVIDER_VERSION__';
+
/**
* Normalizes a server name into the character set tool keys are built from.
* Tool keys embed this output, so any candidate list matched against a key must
diff --git a/packages/data-provider/src/mcp.ts b/packages/data-provider/src/mcp.ts
index faf5c52a0b..01c09d730a 100644
--- a/packages/data-provider/src/mcp.ts
+++ b/packages/data-provider/src/mcp.ts
@@ -378,7 +378,14 @@ const ProxyUrlSchema = z
},
);
-const PROCESS_MCP_SERVER_FIELDS = new Set(['command', 'args', 'env', 'cwd', 'stderr']);
+/** Fields that make an MCP server process-backed (spawned by the server); only `librechat.yaml` may set them. */
+export const PROCESS_MCP_SERVER_FIELDS: ReadonlySet<string> = new Set([
+ 'command',
+ 'args',
+ 'env',
+ 'cwd',
+ 'stderr',
+]);
export function isProcessMCPServerField(field: string): boolean {
return PROCESS_MCP_SERVER_FIELDS.has(field);
diff --git a/packages/data-provider/tsdown.config.mjs b/packages/data-provider/tsdown.config.mjs
index e2e9a7bea7..130fe0bedf 100644
--- a/packages/data-provider/tsdown.config.mjs
+++ b/packages/data-provider/tsdown.config.mjs
@@ -5,6 +5,7 @@ import { defineConfig } from 'tsdown';
const require = createRequire(import.meta.url);
const rootPkg = require('../../package.json');
+const pkg = require('./package.json');
export default defineConfig({
entry: ['src/index.ts', 'src/react-query/index.ts'],
@@ -32,6 +33,7 @@ export default defineConfig({
values: {
__IS_DEV__: process.env.NODE_ENV === 'development',
__LIBRECHAT_VERSION__: rootPkg.version,
+ __DATA_PROVIDER_VERSION__: pkg.version,
},
}),
],
diff --git a/packages/data-schemas/misc/documentdb/compat.documentdb.spec.ts b/packages/data-schemas/misc/documentdb/compat.documentdb.spec.ts
index 5f5940410b..9259c5084e 100644
--- a/packages/data-schemas/misc/documentdb/compat.documentdb.spec.ts
+++ b/packages/data-schemas/misc/documentdb/compat.documentdb.spec.ts
@@ -21,6 +21,7 @@ import { decrementTagCounts } from '~/methods/conversationTag';
import { tenantStorage } from '~/config/tenantContext';
import { supportsTransactions } from '~/utils/transactions';
import { createScheduleMethods } from '~/methods/schedule';
+import { createConfigMethods } from '~/methods/config';
import { createUserMethods } from '~/methods/user';
import { createFileMethods } from '~/methods/file';
import { createModels } from '~/models';
@@ -368,6 +369,82 @@ describeLive('Amazon DocumentDB live compatibility', () => {
});
});
+ /**
+ * Admin config overrides are Mixed subdocuments whose record keys can hold dots (Bedrock
+ * inference profiles, model names such as `gpt-4.1`, MIME types, header names). The admin
+ * config API stores them verbatim, so the engine must accept dotted field names inside
+ * embedded documents through both write shapes the config methods use: a `$set` of a dotted
+ * `overrides.<path>` whose value carries dotted keys, and a whole-object `$set` of `overrides`.
+ */
+ describe('admin config overrides with dotted record keys', () => {
+ const principalId = (label: string) => `compat_${label}_${runId}`;
+ const profiles = {
+ 'us.anthropic.claude-sonnet-4-6': 'arn:aws:bedrock:us-east-1:1:inference-profile/x',
+ 'eu.amazon.nova-pro-v1:0': 'arn:aws:bedrock:eu-west-1:1:inference-profile/y',
+ };
+ const models = { 'gpt-4.1': true, 'gpt-4.1-mini': { deploymentName: 'mini' } };
+ const mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
+
+ afterAll(async () => {
+ await mongoose.models.Config.deleteMany({ principalId: { $regex: runId } });
+ });
+
+ it('stores dotted keys under a dotted $set path and reads them back', async () => {
+ const methods = createConfigMethods(mongoose);
+ const id = principalId('patch');
+ await methods.patchConfigFields(
+ PrincipalType.ROLE,
+ id,
+ PrincipalModel.ROLE,
+ {
+ 'endpoints.bedrock.inferenceProfiles': profiles,
+ 'fileConfig.defaultLLMDeliveryPath.overrides': { [mime]: 'text' },
+ },
+ 10,
+ );
+ const stored = await methods.findConfigByPrincipal(PrincipalType.ROLE, id);
+ const overrides = stored?.overrides as Record<string, Record<string, unknown>>;
+ expect(overrides.endpoints.bedrock).toEqual({ inferenceProfiles: profiles });
+ expect(overrides.fileConfig).toEqual({
+ defaultLLMDeliveryPath: { overrides: { [mime]: 'text' } },
+ });
+ capabilities['dotted keys via $set path'] = 'supported';
+ });
+
+ it('stores dotted keys inside a whole-object $set, arrays included', async () => {
+ const methods = createConfigMethods(mongoose);
+ const id = principalId('upsert');
+ const overrides = {
+ endpoints: {
+ azureOpenAI: { groups: [{ group: 'eastus', apiKey: '${KEY}', models }] },
+ custom: [{ name: 'gw', headers: { 'x-portkey.config': 'cfg' } }],
+ },
+ };
+ await methods.upsertConfig(
+ PrincipalType.ROLE,
+ id,
+ PrincipalModel.ROLE,
+ overrides as never,
+ 10,
+ );
+ const [stored] = await methods.getApplicableConfigs([
+ { principalType: PrincipalType.ROLE, principalId: id },
+ ]);
+ expect(stored.overrides).toEqual(overrides);
+ capabilities['dotted keys via whole $set'] = 'supported';
+ });
+
+ it('records whether the engine stores a `$`-prefixed key inside a value', async () => {
+ const probe = getDb().collection(`dollar_key_probe_${runId}`);
+ capabilities['$-prefixed key in $set value'] = await probe
+ .updateOne({ probe: 1 }, { $set: { value: { $where: 'x' } } }, { upsert: true })
+ .then(() => 'stored (the admin API guard is the only $ check)')
+ .catch((error: Error) => `rejected (${error.message})`);
+ await probe.drop().catch(() => undefined);
+ expect(capabilities['$-prefixed key in $set value']).toBeDefined();
+ });
+ });
+
/**
* The scheduler's rewritten write shapes (classic operators, worker clock — the
* DocumentDB-portable replacements for its original pipeline/$$NOW CAS forms),
diff --git a/packages/data-schemas/misc/documentdb/documentdb-compat.md b/packages/data-schemas/misc/documentdb/documentdb-compat.md
index a86d38a212..8424dc444e 100644
--- a/packages/data-schemas/misc/documentdb/documentdb-compat.md
+++ b/packages/data-schemas/misc/documentdb/documentdb-compat.md
@@ -347,3 +347,39 @@ those namespaces before opening the transaction.
This sweep exists because every incompatibility found so far was invisible
until someone thought to look for its class; here the engine adjudicates
whatever each method emits, known class or not.
+
+## Dotted keys in admin config overrides (2026-10-20, DocumentDB pending)
+
+The admin config API keeps dotted record keys in write bodies: Bedrock
+inference profiles (`us.anthropic.claude-sonnet-4-6`), model names
+(`gpt-4.1`), MIME types and header names. They land in the `overrides` Mixed
+subdocument through two write shapes: `patchConfigFields` sets a dotted
+`overrides.<path>` whose value carries dotted keys, and `upsertConfig` sets
+the whole `overrides` object. Dots in path segments are never written as
+paths; only keys inside values hold them.
+
+`compat.documentdb.spec.ts` › "admin config overrides with dotted record keys"
+covers both shapes and records whether the engine stores a `$`-prefixed key
+inside a value. Local runs used the whole compat suite against a single-node
+replica set of each server (16 of 16 passing on every version):
+
+| Engine | Dotted keys, `$set` path | Dotted keys, whole `$set` | `$` key inside a value |
+| --------------------------- | ------------------------ | ------------------------- | ---------------------- |
+| MongoDB 4.4.29 (local) | supported | supported | rejected |
+| MongoDB 5.0.31 (local) | supported | supported | stored |
+| MongoDB 6.0.26 (local) | supported | supported | stored |
+| MongoDB 7.0.14 (local) | supported | supported | stored |
+| MongoDB 8.2.6 (local) | supported | supported | stored |
+| Amazon DocumentDB 5.0 | **not yet run** | **not yet run** | **not yet run** |
+| Azure Cosmos DB for MongoDB | **not yet run** | **not yet run** | **not yet run** |
+
+- MongoDB 5.0 and later store a `$` key inside a value, so the admin config
+ router's post-auth guard (`CONFIG_UNSAFE_KEY`) is the only `$` check there.
+- Before a release that advertises `dottedKeys`, run the block against a
+ DocumentDB 5.0 cluster (and Cosmos DB where it is supported):
+ `npx jest --config misc/documentdb/jest.documentdb.config.mjs -t 'dotted record keys'`.
+- If an engine rejects the writes, the request fails with 422
+ `CONFIG_KEY_NOT_STORABLE` (`isFieldNameRejection` recognizes the engine's
+ error) and nothing is stored; nothing is silently dropped. The fallback is
+ reversible key encoding at the data-schemas storage boundary (escape `.`, a
+ leading `$` and the escape character on write; decode on read).
diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.ts
index ba054547f2..173dbf0075 100644
--- a/packages/data-schemas/src/app/resolution.spec.ts
+++ b/packages/data-schemas/src/app/resolution.spec.ts
@@ -2,9 +2,11 @@ import { INTERFACE_PERMISSION_FIELDS, PermissionTypes } from 'librechat-data-pro
import type { TCustomConfig } from 'librechat-data-provider';
import type { AppConfig, IConfig } from '~/types';
import {
+ getConfigMergeRules,
mergeConfigOverrides,
getConfigFieldIssues,
applyConfigTombstones,
+ getDottedSectionIssues,
getConfigOverrideIssues,
} from './resolution';
import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
@@ -1049,6 +1051,28 @@ describe('mergeConfigOverrides: invalid stored overrides', () => {
});
});
+ it('ignores a stored dotted key at a fixed-shape position and merges dotted record keys', () => {
+ const profile = 'us.anthropic.claude-sonnet-4-6';
+ const arn = 'arn:aws:bedrock:us-east-1:1:inference-profile/x';
+ const merged = mergeConfigOverrides(base, [
+ fakeConfig(
+ {
+ 'registration.allowedDomains': ['dotted.com'],
+ registration: { 'oauthStateTtlMs.x': 1, allowedDomains: ['override.com'] },
+ endpoints: { bedrock: { inferenceProfiles: { [profile]: arn } } },
+ },
+ 10,
+ ),
+ ]) as unknown as Record<string, Record<string, unknown>>;
+
+ expect(merged['registration.allowedDomains']).toBeUndefined();
+ expect(merged.registration).toEqual({
+ oauthStateTtlMs: 600_000,
+ allowedDomains: ['override.com'],
+ });
+ expect(merged.endpoints.bedrock).toEqual({ inferenceProfiles: { [profile]: arn } });
+ });
+
it('drops only the invalid field of a merged array item', () => {
const merged = mergeConfigOverrides(base, [
fakeConfig(
@@ -1384,6 +1408,80 @@ describe('getConfigOverrideIssues', () => {
).toEqual([expect.objectContaining({ segments: ['mcpServers', 'team.prod', 'timeout'] })]);
});
+ it('reports a dotted key where the schema has a fixed shape', () => {
+ const issues = getConfigOverrideIssues({
+ 'webSearch.serperApiKey': 'x',
+ registration: { 'socialLogins.0': 'github' },
+ interface: { theme: { 'modes.light': { colors: {} } } },
+ endpoints: {
+ azureOpenAI: {
+ groups: [{ group: 'g', apiKey: 'k', models: { 'gpt-4.1': true }, 'models.x': {} }],
+ },
+ },
+ });
+ expect(issues.filter((issue) => issue.code === 'dotted_key')).toEqual([
+ { path: 'webSearch.serperApiKey', segments: ['webSearch.serperApiKey'], code: 'dotted_key' },
+ {
+ path: 'registration.socialLogins.0',
+ segments: ['registration', 'socialLogins.0'],
+ code: 'dotted_key',
+ },
+ {
+ path: 'interface.theme.modes.light',
+ segments: ['interface', 'theme', 'modes.light'],
+ code: 'dotted_key',
+ },
+ {
+ path: 'endpoints.azureOpenAI.groups.0.models.x',
+ segments: ['endpoints', 'azureOpenAI', 'groups', '0', 'models.x'],
+ code: 'dotted_key',
+ },
+ ]);
+ });
+
+ it('keeps dotted keys where the schema has a record', () => {
+ expect(
+ getConfigOverrideIssues({
+ endpoints: {
+ bedrock: {
+ inferenceProfiles: {
+ 'us.anthropic.claude-sonnet-4-6': 'arn:aws:bedrock:us-east-1:1:inference-profile/x',
+ },
+ },
+ azureOpenAI: {
+ groups: [
+ {
+ group: 'eastus',
+ apiKey: '${AZURE_KEY}',
+ instanceName: 'east',
+ models: { 'gpt-4.1': true, 'gpt-4.1-mini': { deploymentName: 'mini' } },
+ addParams: { 'reasoning.effort': 'high' },
+ },
+ ],
+ },
+ custom: [
+ {
+ name: 'gateway',
+ apiKey: 'k',
+ baseURL: 'https://gw',
+ models: { default: ['gpt-4.1'] },
+ headers: { 'x-portkey.config': 'cfg' },
+ tokenConfig: { 'gpt-4.1': { prompt: 1, completion: 2, context: 1000 } },
+ },
+ ],
+ },
+ fileConfig: {
+ defaultLLMDeliveryPath: {
+ overrides: {
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'text',
+ },
+ },
+ },
+ mcpServers: { 'team.prod': { url: 'https://mcp.example.com', headers: { 'X-A.B': 'v' } } },
+ }),
+ ).toEqual([]);
+ });
+
it('accepts keys the schema does not define and stored secret shapes', () => {
expect(
getConfigOverrideIssues({ unknownSection: 5, registration: { enabled: false } }),
@@ -1413,6 +1511,29 @@ describe('getConfigOverrideIssues', () => {
});
});
+describe('getDottedSectionIssues', () => {
+ it('reports only top-level keys holding a dot', () => {
+ expect(getDottedSectionIssues({ 'filters.x': 1, registration: { 'a.b': 1 } })).toEqual([
+ { path: 'filters.x', segments: ['filters.x'], code: 'dotted_key' },
+ ]);
+ expect(getDottedSectionIssues(['stray'])).toEqual([]);
+ });
+});
+
+describe('getConfigMergeRules', () => {
+ it('names merge paths by their override (YAML) keys', () => {
+ expect(getConfigMergeRules()).toEqual({
+ arrayMergeKeys: { 'endpoints.custom': 'name' },
+ atomicMergePaths: ['interface.theme'],
+ overrideKeyMap: {
+ mcpServers: 'mcpConfig',
+ interface: 'interfaceConfig',
+ turnstile: 'turnstileConfig',
+ },
+ });
+ });
+});
+
describe('getConfigOverrideIssues: items addressed by id', () => {
it('attributes a refinement that names an array item by its id to that item', () => {
const environment = (id: string, extra: Record<string, unknown> = {}) => ({
diff --git a/packages/data-schemas/src/app/resolution.ts b/packages/data-schemas/src/app/resolution.ts
index 49b2226992..99c9c86ac9 100644
--- a/packages/data-schemas/src/app/resolution.ts
+++ b/packages/data-schemas/src/app/resolution.ts
@@ -9,7 +9,7 @@ import {
configSchema,
} from 'librechat-data-provider';
import type { TCustomConfig } from 'librechat-data-provider';
-import type { AppConfig, IConfig } from '~/types';
+import type { AdminConfigMergeRules, AppConfig, IConfig } from '~/types';
import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
import { getTombstonePathsToClear } from '~/methods/config';
import logger from '~/config/winston';
@@ -59,6 +59,31 @@ const OVERRIDE_KEY_MAP: Partial<Record<keyof TCustomConfig, keyof AppConfig>> =
turnstile: 'turnstileConfig',
};
+/** AppConfig key → the override (YAML) section merged into it, the inverse of `OVERRIDE_KEY_MAP`. */
+const OVERRIDE_SECTION_BY_APP_KEY = new Map<string, string>(
+ Object.entries(OVERRIDE_KEY_MAP).flatMap(([section, appKey]) =>
+ appKey ? [[appKey, section]] : [],
+ ),
+);
+
+function toOverridePath(appConfigPath: string): string {
+ const [first, ...rest] = appConfigPath.split('.');
+ return [OVERRIDE_SECTION_BY_APP_KEY.get(first) ?? first, ...rest].join('.');
+}
+
+/** The merge rules in override (YAML) key names, for clients that plan writes the way they merge. */
+export function getConfigMergeRules(): AdminConfigMergeRules {
+ return {
+ arrayMergeKeys: Object.fromEntries(
+ Object.entries(ARRAY_MERGE_KEYS).map(([path, key]) => [toOverridePath(path), key]),
+ ),
+ atomicMergePaths: [...ATOMIC_MERGE_PATHS].map(toOverridePath),
+ overrideKeyMap: Object.fromEntries(
+ [...OVERRIDE_SECTION_BY_APP_KEY].map(([appKey, section]) => [section, appKey]),
+ ),
+ };
+}
+
function isSafePath(path: string): boolean {
const segments = path.split('.');
if (
@@ -258,8 +283,9 @@ export type ConfigOverrideIssue = {
segments: string[];
/**
* A stable, machine-readable reason: a zod issue code (`invalid_type`, `custom`, ...),
- * `missing_merge_key`, `duplicate_merge_key`, `indexed_merge_key_write`, `union_dropped_key`, or `invalid_document`. Schema messages are not carried because
- * they can echo the submitted values.
+ * `missing_merge_key`, `duplicate_merge_key`, `indexed_merge_key_write`, `union_dropped_key`,
+ * `dotted_key`, or `invalid_document`. Schema messages are not carried because they can echo
+ * the submitted values.
*/
code: string;
};
@@ -425,25 +451,28 @@ function expandUnionIssues(issues: SchemaIssue[], depth = 0): SchemaIssue[] {
});
}
-/** The parts of a zod schema the stripped-key walk reads, without depending on zod. */
+/** The parts of a zod schema the shape walk reads, without depending on zod. */
type SchemaNode = {
_def: {
typeName?: string;
innerType?: SchemaNode;
schema?: SchemaNode;
+ getter?: () => SchemaNode;
type?: SchemaNode;
valueType?: SchemaNode;
+ left?: SchemaNode;
+ right?: SchemaNode;
options?: SchemaNode[] | Map<unknown, SchemaNode>;
};
shape?: Record<string, SchemaNode>;
safeParse: (value: unknown) => { success: boolean };
};
-/** The schema beneath optional, nullable, default and refinement wrappers. */
+/** The schema beneath optional, nullable, default, refinement and lazy wrappers. */
function unwrapSchema(schema: SchemaNode): SchemaNode {
let node = schema;
for (let depth = 0; depth < MAX_MERGE_DEPTH; depth++) {
- const inner = node._def.innerType ?? node._def.schema;
+ const inner = node._def.innerType ?? node._def.schema ?? node._def.getter?.();
if (!inner) {
break;
}
@@ -453,38 +482,104 @@ function unwrapSchema(schema: SchemaNode): SchemaNode {
}
/**
- * Keys a union dropped: an object parses with the first union option that accepts it, and
- * that option strips keys it does not define, so a key another option defines (and would
- * type-check) is kept raw in the stored override but never validated. Keys no option defines
- * are unknown keys and stay accepted.
+ * The combined fixed shape of an intersection of objects (`a.and(b)`), or `undefined` when a
+ * side is not an object, so nothing is judged on a shape the walk cannot see whole.
*/
-function findUnionDroppedKeys(
+function getIntersectionShape(node: SchemaNode, depth = 0): Record<string, SchemaNode> | undefined {
+ if (depth >= MAX_MERGE_DEPTH || !node._def.left || !node._def.right) {
+ return undefined;
+ }
+ const [left, right] = [node._def.left, node._def.right].map((side) => {
+ const inner = unwrapSchema(side);
+ return inner._def.typeName === 'ZodIntersection'
+ ? getIntersectionShape(inner, depth + 1)
+ : inner.shape;
+ });
+ return left && right ? { ...left, ...right } : undefined;
+}
+
+/** Whether a schema accepts arbitrary keys at this level (a record, or a union with one). */
+function isRecordSchema(schema: SchemaNode): boolean {
+ const node = unwrapSchema(schema);
+ const { typeName, options } = node._def;
+ if (typeName === 'ZodRecord') {
+ return true;
+ }
+ return (
+ (typeName === 'ZodUnion' || typeName === 'ZodDiscriminatedUnion') &&
+ options != null &&
+ [...options.values()].some(isRecordSchema)
+ );
+}
+
+type ShapeIssue = { code: 'union_dropped_key' | 'dotted_key'; path: IssuePath };
+
+function toDottedKeyIssues(value: AnyObject, path: IssuePath): ShapeIssue[] {
+ return Object.keys(value)
+ .filter((key) => key.includes('.'))
+ .map((key): ShapeIssue => ({ code: 'dotted_key', path: [...path, key] }));
+}
+
+/**
+ * The walk of an object with a fixed shape: a key holding a dot can only be a mistaken
+ * path (`{ 'webSearch.serperApiKey': ... }`), which the schema strips as unknown and the secret
+ * registry never sees, so it is reported instead of stored as an inert literal key.
+ */
+function findObjectShapeIssues(
+ shape: Record<string, SchemaNode>,
+ value: AnyObject,
+ path: IssuePath,
+ depth: number,
+): ShapeIssue[] {
+ return Object.keys(value).flatMap((key): ShapeIssue[] => {
+ if (key.includes('.')) {
+ return [{ code: 'dotted_key', path: [...path, key] }];
+ }
+ return hasOwn(shape, key)
+ ? findShapeIssues(shape[key], value[key], [...path, key], depth + 1)
+ : [];
+ });
+}
+
+/**
+ * What a schema walk finds that parsing does not report:
+ * - `union_dropped_key`: an object parses with the first union option that accepts it, and
+ * that option strips keys it does not define, so a key another option defines (and would
+ * type-check) is kept raw in the stored override but never validated.
+ * - `dotted_key`: a key holding a dot where the schema has a fixed shape. Dots are only
+ * meaningful in record keys (model names such as `gpt-4.1`, Bedrock inference profiles, MIME
+ * types, header names), which a record keeps as one segment.
+ *
+ * Keys no schema node defines are unknown keys and stay accepted.
+ */
+function findShapeIssues(
schema: SchemaNode,
value: unknown,
path: IssuePath,
depth = 0,
-): IssuePath[] {
+): ShapeIssue[] {
if (depth >= MAX_MERGE_DEPTH) {
return [];
}
const node = unwrapSchema(schema);
const { typeName } = node._def;
if (typeName === 'ZodObject' && node.shape && isPlainObject(value)) {
- const shape = node.shape;
- return Object.keys(value)
- .filter((key) => hasOwn(shape, key))
- .flatMap((key) => findUnionDroppedKeys(shape[key], value[key], [...path, key], depth + 1));
+ return findObjectShapeIssues(node.shape, value, path, depth);
+ }
+ if (typeName === 'ZodIntersection' && isPlainObject(value)) {
+ const shape = getIntersectionShape(node);
+ return shape ? findObjectShapeIssues(shape, value, path, depth) : [];
}
if (typeName === 'ZodArray' && node._def.type && Array.isArray(value)) {
const item = node._def.type;
return value.flatMap((entry, index) =>
- findUnionDroppedKeys(item, entry, [...path, index], depth + 1),
+ findShapeIssues(item, entry, [...path, index], depth + 1),
);
}
if (typeName === 'ZodRecord' && node._def.valueType && isPlainObject(value)) {
const entrySchema = node._def.valueType;
return Object.entries(value).flatMap(([key, entry]) =>
- findUnionDroppedKeys(entrySchema, entry, [...path, key], depth + 1),
+ findShapeIssues(entrySchema, entry, [...path, key], depth + 1),
);
}
if (
@@ -497,18 +592,32 @@ function findUnionDroppedKeys(
const options = [...node._def.options.values()];
const accepted = options.find((option) => option.safeParse(value).success);
if (!accepted) {
- return [];
+ /** A strict option fails on the dotted key itself, and parsing reports it only as unrecognized. */
+ return isRecordSchema(node) ? [] : toDottedKeyIssues(value, path);
}
const acceptedShape = unwrapSchema(accepted).shape;
const defined = new Set(
options.flatMap((option) => Object.keys(unwrapSchema(option).shape ?? {})),
);
- const dropped = acceptedShape
+ const dropped: ShapeIssue[] = acceptedShape
? Object.keys(value)
.filter((key) => !hasOwn(acceptedShape, key) && defined.has(key))
- .map((key) => [...path, key])
+ .map((key): ShapeIssue => ({ code: 'union_dropped_key', path: [...path, key] }))
: [];
- return [...dropped, ...findUnionDroppedKeys(accepted, value, path, depth + 1)];
+ return [...dropped, ...findShapeIssues(accepted, value, path, depth + 1)];
+}
+
+/**
+ * Top-level override keys are section names, never paths: a dotted one would be stored as an
+ * inert literal key, outside the secret registry and every per-section rule.
+ */
+export function getDottedSectionIssues(overrides: unknown): ConfigOverrideIssue[] {
+ if (!isPlainObject(overrides)) {
+ return [];
+ }
+ return Object.keys(overrides)
+ .filter((key) => key.includes('.'))
+ .map((key) => toIssue([key], 'dotted_key'));
}
/**
@@ -517,7 +626,9 @@ function findUnionDroppedKeys(
* to the override node that caused it. Unions, refinements, required fields and defaults
* are therefore judged on the merged result, not on the patch alone. An issue caused only
* by leaving something out (a required or related field another layer may supply) is not
- * reported, except inside an array the merge replaces, where nothing can supply it. Keys the schema does not define are accepted unchanged.
+ * reported, except inside an array the merge replaces, where nothing can supply it. Keys the
+ * schema does not define are accepted unchanged; a key holding a dot is a `dotted_key` issue
+ * unless it sits where the schema has a record.
*/
export function getConfigOverrideIssues(
overrides: unknown,
@@ -527,7 +638,7 @@ export function getConfigOverrideIssues(
return [toIssue([], 'invalid_document')];
}
const merged = deepMerge(base as AnyObject, overrides);
- const issues = getMergeKeyIssues(overrides);
+ const issues = [...getDottedSectionIssues(overrides), ...getMergeKeyIssues(overrides)];
const seen = new Set(issues.map((issue) => issue.path));
const shape = configSchema.shape;
for (const section of Object.keys(overrides)) {
@@ -536,12 +647,9 @@ export function getConfigOverrideIssues(
}
const schema = shape[section as keyof typeof shape] as unknown as SchemaNode;
const result = shape[section as keyof typeof shape].safeParse(merged[section]);
- const dropped = findUnionDroppedKeys(schema, merged[section], []).map((path) => ({
- code: 'union_dropped_key',
- path,
- }));
+ const shapeIssues = findShapeIssues(schema, merged[section], []);
const schemaIssues = result.success ? [] : expandUnionIssues(result.error.issues);
- for (const issue of [...dropped, ...schemaIssues]) {
+ for (const issue of [...shapeIssues, ...schemaIssues]) {
if (issue.code === 'unrecognized_keys') {
continue;
}
diff --git a/packages/data-schemas/src/types/admin.ts b/packages/data-schemas/src/types/admin.ts
index c0a3011436..51fd3adc66 100644
--- a/packages/data-schemas/src/types/admin.ts
+++ b/packages/data-schemas/src/types/admin.ts
@@ -39,6 +39,105 @@ export type AdminConfigDeleteResponse = {
success: boolean;
};
+/* ── Admin config contract (GET /api/admin/config/meta) ─────────────── */
+
+/**
+ * Admin config API behaviours a client gates on. A flag is `true` only when the running server
+ * has the behaviour; a server without the meta route (404) has none of them.
+ * - `dottedKeys`: keys containing dots survive writes where the schema has a record (model
+ * names such as `gpt-4.1`, Bedrock inference profiles, MIME types, header names); a dotted key
+ * at a fixed-shape position is a `dotted_key` issue, and `$`-prefixed or prototype keys are
+ * rejected with `CONFIG_UNSAFE_KEY`. Issues carry `segments`, which name a dotted record key
+ * unambiguously. A database engine that cannot store a dotted key answers 422
+ * `CONFIG_KEY_NOT_STORABLE` and stores nothing.
+ * - `sectionAllowlist`: writes to a top-level key `configSchema` does not define are rejected,
+ * and stored ones are ignored at merge.
+ * - `readFilteredWriteResponses`: write responses are filtered by the caller's read access.
+ */
+export type AdminConfigFeatureFlag =
+ | 'dottedKeys'
+ | 'sectionAllowlist'
+ | 'readFilteredWriteResponses';
+
+export type AdminConfigFeatures = Record<AdminConfigFeatureFlag, boolean>;
+
+/** A secret config field: encrypted at rest, omitted from reads, kept when a write omits it. */
+export type AdminConfigSecretFieldRule = {
+ path: string;
+ /** Masked-preview companion returned on reads; never writable. */
+ previewPath: string;
+ /** Whether a `${ENV_VAR}` reference is stored and returned as is instead of encrypted. */
+ allowEnvPlaceholder: boolean;
+};
+
+/** A secret held by every item of an array, matched across writes by `identityKey`. */
+export type AdminConfigArraySecretFieldRule = {
+ arrayPath: string;
+ secretKey: string;
+ previewKey: string;
+ identityKey: string;
+};
+
+/** How overrides merge, in override (`librechat.yaml`) key names. */
+export type AdminConfigMergeRules = {
+ /** Arrays merged item by item on a key field instead of replaced. */
+ arrayMergeKeys: Record<string, string>;
+ /** Objects an override replaces whole instead of merging into. */
+ atomicMergePaths: string[];
+ /** Override sections the resolved config (`GET /base`) holds under another name. */
+ overrideKeyMap: Record<string, string>;
+};
+
+export type AdminConfigRules = AdminConfigMergeRules & {
+ /** Top-level sections `configSchema` defines; enforced on writes when `sectionAllowlist`. */
+ acceptedSections: string[];
+ /** Sections only `librechat.yaml` sets; writes to them are dropped. */
+ baseOnlySections: string[];
+ /** Sections only the base (`__base__`) document may hold, through their dedicated APIs. */
+ basePrincipalSections: string[];
+ /** Fields inside overridable sections that only `librechat.yaml` sets. */
+ baseOnlyPaths: string[];
+ secretFields: AdminConfigSecretFieldRule[];
+ arraySecretFields: AdminConfigArraySecretFieldRule[];
+ /** Maps of credentials admin writes are refused for; reads mask their values. */
+ refusedMaps: string[];
+ /** MCP server fields that make a server process-backed; only `librechat.yaml` sets them. */
+ processMcpFields: string[];
+ interface: {
+ /** Interface fields that are role permissions; overrides drop them. */
+ permissionFields: string[];
+ /** Permission fields whose boolean form is a runtime toggle overrides keep. */
+ runtimeFields: string[];
+ /** Sub-keys of an object-form permission field that are permission bits. */
+ permissionSubKeys: string[];
+ };
+ /** Whether `endpoints.all` title settings apply as one block or per field. */
+ titleResolution: 'block' | 'field';
+};
+
+export type AdminConfigMeta = {
+ metaVersion: 1;
+ versions: {
+ /** LibreChat release. */
+ librechat: string;
+ /** `librechat-data-provider` the server validates with. */
+ dataProvider: string;
+ /** `librechat.yaml` schema version. */
+ configSchema: string;
+ };
+ features: AdminConfigFeatures;
+ limits: {
+ /** Most entries one `PATCH /fields` accepts. */
+ maxPatchEntries: number;
+ /**
+ * The app config service's `overrideCacheTtl`: how long another server instance may serve
+ * resolved config from before a write.
+ */
+ overrideCacheTtlMs: number;
+ };
+ rules: AdminConfigRules;
+};
+
/* ── Audit log taxonomy ─────────────────────────────────────────────── */
/**
diff --git a/packages/data-schemas/src/utils/fields.spec.ts b/packages/data-schemas/src/utils/fields.spec.ts
new file mode 100644
index 0000000000..eaabf5ccd4
--- /dev/null
+++ b/packages/data-schemas/src/utils/fields.spec.ts
@@ -0,0 +1,86 @@
+import mongoose from 'mongoose';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import type { Collection } from 'mongodb';
+import { isFieldNameRejection } from './fields';
+
+let mongoServer: MongoMemoryServer;
+let collection: Collection;
+
+beforeAll(async () => {
+ mongoServer = await MongoMemoryServer.create();
+ await mongoose.connect(mongoServer.getUri());
+ collection = mongoose.connection.db!.collection('field_name_probe');
+ await collection.createIndex({ key: 1 }, { unique: true });
+});
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer.stop();
+});
+
+async function rejectionOf(write: () => Promise<unknown>): Promise<unknown> {
+ return write().then(
+ () => {
+ throw new Error('expected the write to be rejected');
+ },
+ (error: unknown) => error,
+ );
+}
+
+/** What an engine that still refuses a field name sends back, in MongoDB's own wording. */
+function engineRejection(code: number, errmsg: string): Error {
+ return new mongoose.mongo.MongoServerError({ ok: 0, code, errmsg });
+}
+
+function bsonKeyError(document: Record<string, unknown>): unknown {
+ try {
+ mongoose.mongo.BSON.serialize(document, { checkKeys: true });
+ } catch (error) {
+ return error;
+ }
+ throw new Error('expected the key check to throw');
+}
+
+describe('isFieldNameRejection', () => {
+ it('recognizes the server refusing a field name in an update', async () => {
+ const error = await rejectionOf(() =>
+ collection.updateOne({ key: 'empty' }, { $set: { 'overrides.a..b': 1 } }, { upsert: true }),
+ );
+
+ expect(error).toBeInstanceOf(mongoose.mongo.MongoServerError);
+ expect(isFieldNameRejection(error)).toBe(true);
+ });
+
+ it.each([
+ [52, "The dollar ($) prefixed field '$where' in 'overrides.$where' is not valid for storage."],
+ [
+ 57,
+ "The dotted field 'us.anthropic.x' in 'overrides.us.anthropic.x' is not valid for storage.",
+ ],
+ [2, "The dotted field 'gpt-4.1' in 'overrides.models.gpt-4.1' is not valid for storage."],
+ [2, "Field names cannot contain '.'"],
+ ])('recognizes an engine refusing a field name with code %d: %s', (code, errmsg) => {
+ expect(isFieldNameRejection(engineRejection(code, errmsg))).toBe(true);
+ });
+
+ it("recognizes the driver's client-side key check", () => {
+ expect(isFieldNameRejection(bsonKeyError({ 'us.anthropic.x': 1 }))).toBe(true);
+ expect(isFieldNameRejection(bsonKeyError({ $where: 1 }))).toBe(true);
+ });
+
+ it('leaves other database failures alone', async () => {
+ await collection.insertOne({ key: 'taken' });
+ const duplicate = await rejectionOf(() => collection.insertOne({ key: 'taken' }));
+
+ expect(duplicate).toBeInstanceOf(mongoose.mongo.MongoServerError);
+ expect(isFieldNameRejection(duplicate)).toBe(false);
+ expect(isFieldNameRejection(engineRejection(2, 'Invalid $set: expected an object'))).toBe(
+ false,
+ );
+ expect(isFieldNameRejection(new Error('connection reset'))).toBe(false);
+ });
+
+ it.each([null, undefined, 'not valid for storage', 57])('is false for %p', (value) => {
+ expect(isFieldNameRejection(value)).toBe(false);
+ });
+});
diff --git a/packages/data-schemas/src/utils/fields.ts b/packages/data-schemas/src/utils/fields.ts
new file mode 100644
index 0000000000..b8dafbef9b
--- /dev/null
+++ b/packages/data-schemas/src/utils/fields.ts
@@ -0,0 +1,32 @@
+/**
+ * MongoDB's `DollarPrefixedFieldName`, `EmptyFieldName` and `DottedFieldName` server codes: a
+ * field name the engine will not store. Current MongoDB stores dotted names and, from 5.0,
+ * `$`-prefixed names inside values; older servers and MongoDB-compatible engines may still
+ * reject them with these codes.
+ */
+const FIELD_NAME_ERROR_CODES = new Set<number>([52, 56, 57]);
+
+/**
+ * The storage-validation wording MongoDB uses ("... is not valid for storage", "contains an
+ * empty field name") and the driver's client-side key check ("key a.b must not contain '.'"),
+ * for engines that answer with a generic code.
+ */
+const FIELD_NAME_ERROR_MESSAGE =
+ /not valid for storage|empty field name|field names? (?:cannot|can't|must not|may not)|must not (?:contain '\.'|start with '\$')/i;
+
+/**
+ * Whether a write failed because the database refused a field name in the document, such as a
+ * dotted record key on an engine that cannot store one. The request carried a key this
+ * deployment cannot hold, rather than hitting an outage, so the caller can answer with a
+ * stable code instead of a generic failure.
+ */
+export function isFieldNameRejection(error: unknown): boolean {
+ if (error == null || typeof error !== 'object') {
+ return false;
+ }
+ const { code, message } = error as { code?: unknown; message?: unknown };
+ if (typeof code === 'number' && FIELD_NAME_ERROR_CODES.has(code)) {
+ return true;
+ }
+ return typeof message === 'string' && FIELD_NAME_ERROR_MESSAGE.test(message);
+}
diff --git a/packages/data-schemas/src/utils/index.ts b/packages/data-schemas/src/utils/index.ts
index 828eb80429..921d73a95f 100644
--- a/packages/data-schemas/src/utils/index.ts
+++ b/packages/data-schemas/src/utils/index.ts
@@ -11,4 +11,5 @@ export * from './stripUIResourceMarkers';
export * from './fading';
export * from './eviction';
export { buildIndexWithRetry, createIndexesWithRetry, isIndexBuildInProgress } from './retry';
+export { isFieldNameRejection } from './fields';
export type { IndexBuildOptions } from './retry';