🧾 feat: Admin Config Write Report, Structured Issues and Deployment-Only Paths (#17395)

* 🧾 feat: Admin Config Write Report, Structured Issues and Deployment-Only Paths

Admin config writes dropped what the API never stores (base-only sections, interface
permissions, dedicated sections) with a 200 and no word of it, stored values nothing reads
(boot-time and operator-only settings, overrides of MCP servers librechat.yaml runs as local
processes, tombstones inside arrays), answered most 4xx without a stable code, returned
validation issues without the bound or option that failed, and refused every admin write
once the terms-acceptance modal was on for an admin who had not accepted it, including the
write that turns it off.

PUT, PATCH /fields, POST /fields/tombstone and DELETE /fields now answer with `applied` and
`skipped` (with a reason per location); a whole `interface` PATCH keeps its UI fields;
base-only paths are skipped on every route. A new DEPLOYMENT_ONLY_CONFIG_PATHS list (rate
limits, CloudFront, permission leases, OpenAPI, skill deletion, the tool filters, the agents
and MCP boot settings, `cache`) is skipped on write, kept at librechat.yaml's value by the merge
and published in GET /meta. Writes and tombstones inside a librechat.yaml stdio MCP server
answer 400 PROCESS_MCP_SERVER_OVERRIDE, and a whole-section value leaves those servers out.
GET of a document lists what the merge leaves out of it (`ignored`, `ignoredBasis`).
Validation issues carry allowlisted `params`; each refused allowedAddresses entry is one issue
with a `reason`; agent recursion limits must be whole numbers of at least 1, and the runtime
ignores any other value. The config handlers' 4xx carry a `code`, the capability middleware adds
AUTH_REQUIRED/FORBIDDEN, and the admin config router opts out of the terms gate. PATCH checks a
section manager on every section it names, skipped entries included, as /changes does. New meta
flags: writeReport, issueParams, adminTermsExempt.

* 🧪 test: Expect Issue Params in the Whole-Document Override Validation Scenario

Validation issues now carry `params` (here the expected and received types), so the scenario that
asserts the exact issue list for a rejected PUT expects them too.

* 🧪 test: Cover Merged Read Codes, Tenant-Scoped Read Reports and Deployment-Only Resolution
This commit is contained in:
Danny Avila 2026-10-24 10:01:13 +02:00 • committed by GitHub
parent ba78cf5f5f
commit babf6f908b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
29 changed files with 3336 additions and 503 deletions

View file

@ -2,6 +2,7 @@ const express = require('express');
const {
rejectUnsafeConfigKeys,
createAdminConfigHandlers,
allowBeforeTermsAcceptance,
createAdminConfigReadHandlers,
createAdminConfigCatalogHandlers,
} = require('@librechat/api');
@ -82,7 +83,8 @@ const catalogHandlers = createAdminConfigCatalogHandlers({
overrideEnvAllowlist: process.env.CONFIG_OVERRIDE_ENV_ALLOWLIST,
});
router.use(requireJwtAuth, requireAdminAccess, rejectUnsafeConfigKeys);
/** Config reads and writes stay open to an admin who has not accepted the terms. */
router.use(allowBeforeTermsAcceptance, requireJwtAuth, requireAdminAccess, rejectUnsafeConfigKeys);
router.get('/', handlers.listConfigs);
router.get('/meta', handlers.getConfigMeta);

View file

@ -4,12 +4,21 @@ const mongoSanitize = require('express-mongo-sanitize');
const { createRequestSanitizer } = require('@librechat/api');
let hasAdminAccess;
/** Whether the deployment asks for terms acceptance, which the signed-in admin has not given. */
let mockTermsRequired = false;
/** Authenticates, then runs the real terms gate, as `requireJwtAuth` chains it. */
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();
req.user = { id: 'user-1', _id: 'user-1', role: 'ADMIN', termsAccepted: !mockTermsRequired };
const { createTermsAcceptanceGate } = require('@librechat/api');
const gate = createTermsAcceptanceGate({
getAppConfig: async () => ({
interfaceConfig: { termsOfService: { modalAcceptance: mockTermsRequired } },
}),
});
return gate(req, res, next);
});
const mockRequireCapability = jest.fn(() => (_req, res, next) => {
if (!hasAdminAccess) {
@ -87,6 +96,7 @@ describe('admin config routes', () => {
beforeEach(() => {
hasAdminAccess = true;
mockTermsRequired = false;
mockDb.listAllConfigs.mockResolvedValue([]);
mockDb.findConfigByPrincipal.mockResolvedValue(null);
mockDb.writeConfigDocument.mockImplementation(async (principalType, principalId, draft) => ({
@ -161,6 +171,35 @@ describe('admin config routes', () => {
});
});
it('takes config writes from an admin who has not accepted the terms, unlike other routes', async () => {
mockTermsRequired = true;
const gated = express();
gated.use(express.json());
gated.post('/api/agents/chat', mockRequireJwtAuth, (_req, res) => res.json({ ok: true }));
const chat = await request(gated)
.post('/api/agents/chat')
.set('authorization', 'Bearer admin')
.send({})
.expect(403);
expect(chat.body.code).toBe('terms_not_accepted');
const response = await request(app)
.patch('/api/admin/config/role/__base__/fields')
.set('authorization', 'Bearer admin')
.send({
entries: [{ fieldPath: 'interface.termsOfService.modalAcceptance', value: false }],
})
.expect(200);
expect(response.body.applied).toEqual([
{
path: 'interface.termsOfService.modalAcceptance',
segments: ['interface', 'termsOfService', 'modalAcceptance'],
},
]);
expect(mockDb.writeConfigDocument).toHaveBeenCalledTimes(1);
});
it('serves the config contract behind the same auth', async () => {
await request(app).get('/api/admin/config/meta').expect(401);

View file

@ -122,7 +122,12 @@ test.describe('Principal config override validation', () => {
expect(res.status()).toBe(400);
const body = (await res.json()) as {
code: string;
issues: Array<{ path: string; segments: string[]; code: string }>;
issues: Array<{
path: string;
segments: string[];
code: string;
params?: Record<string, unknown>;
}>;
};
expect(body.code).toBe('CONFIG_OVERRIDE_INVALID');
expect(body.issues).toEqual([
@ -130,6 +135,7 @@ test.describe('Principal config override validation', () => {
path: 'interface.contextCost',
segments: ['interface', 'contextCost'],
code: 'invalid_type',
params: { expected: 'boolean', received: 'string' },
},
]);

View file

@ -473,6 +473,7 @@ describe('GET /catalog', () => {
it('answers 403 without config read access, 400 for a half-named principal, 404 for a missing one', async () => {
const forbidden = await catalog({}, { hasAnyConfigReadAccess: async () => false });
expect(forbidden.res.statusCode).toBe(403);
expect(forbidden.res.body?.code).toBe('FORBIDDEN');
expect((await catalog({ principalType: ROLE })).res.statusCode).toBe(400);
expect((await catalog({ principalType: 'tenant', principalId: 'x' })).res.statusCode).toBe(400);
const missing = await catalog({ principalType: ROLE, principalId: 'ghost' });
@ -561,5 +562,6 @@ describe('GET /env-status', () => {
it('answers 403 without config read access', async () => {
const { res } = await envStatus({ hasAnyConfigReadAccess: async () => false });
expect(res.statusCode).toBe(403);
expect(res.body?.code).toBe('FORBIDDEN');
});
});

View file

@ -36,17 +36,19 @@ import type { CapabilityUser } from '~/middleware/capabilities';
import type { GetAppConfigOptions } from '~/app/service';
import type { ManifestTool } from '~/tools/available';
import type { ServerRequest } from '~/types/http';
import {
canReadSection,
getCapabilityUser,
validatePrincipalType,
forbiddenResponse,
authRequiredResponse,
principalNotFoundResponse,
} from './config';
import {
parseEnvAllowlist,
collectEnvReferenceSections,
collectDefaultEnvReferenceSections,
} from '~/app/allowlist';
import {
canReadSection,
getCapabilityUser,
validatePrincipalType,
principalNotFoundResponse,
} from './config';
import { resolveServedCustomEndpoints } from '~/endpoints/custom/config';
import { listAvailableTools } from '~/tools/available';
import { getSafeErrorMetadata } from '~/utils/errors';
@ -493,10 +495,10 @@ export function createAdminConfigCatalogHandlers(deps: AdminConfigCatalogDeps):
}
const user = getCapabilityUser(req);
if (!user) {
return res.status(401).json({ error: 'Authentication required' });
return authRequiredResponse(res);
}
if (!(await hasAnyConfigReadAccess(user))) {
return res.status(403).json({ error: 'Insufficient permissions' });
return forbiddenResponse(res);
}
const isBase = isBaseConfigPrincipal({ principalType, principalId });
const [readable, exists] = await Promise.all([
@ -576,10 +578,10 @@ export function createAdminConfigCatalogHandlers(deps: AdminConfigCatalogDeps):
try {
const user = getCapabilityUser(req);
if (!user) {
return res.status(401).json({ error: 'Authentication required' });
return authRequiredResponse(res);
}
if (!(await hasAnyConfigReadAccess(user))) {
return res.status(403).json({ error: 'Insufficient permissions' });
return forbiddenResponse(res);
}
const [baseConfig, overrides] = await Promise.all([
getAppConfig({ tenantId: user.tenantId, baseOnly: true }),

View file

@ -285,6 +285,7 @@ describe('POST …/changes: one atomic write', () => {
path: 'mcpServers.new.title',
segments: ['mcpServers', 'new', 'title'],
code: 'invalid_type',
params: { expected: 'string', received: 'number' },
},
]);
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
@ -1279,32 +1280,52 @@ describe('POST …/changes: entries librechat.yaml owns', () => {
path: 'endpoints.custom.2.baseURL',
segments: ['endpoints', 'custom', '2', 'baseURL'],
code: 'invalid_type',
params: { expected: 'string', received: 'number' },
},
]);
});
it('reports writes to a YAML stdio server as applied but ignored at runtime', async () => {
it('refuses a write inside a YAML stdio server, and leaves one out of a whole-section value', async () => {
const params = nextParams();
const { status, body } = await send(
const refused = await send(
{
ops: [
{ op: 'set', fieldPath: 'mcpServers.yaml-stdio.title', value: 'Local' },
{ op: 'set', fieldPath: 'mcpServers.yaml-http.title', value: 'Remote' },
{ op: 'set', fieldPath: 'mcpServers.yaml-stdio.title', value: 'Local' },
],
},
params,
);
expect(refused.status).toBe(400);
expect(refused.body).toMatchObject({ code: 'PROCESS_MCP_SERVER_OVERRIDE', opIndex: 1 });
expect(await storedDocument(params.principalId)).toBeNull();
const { status, body } = await send(
{
ops: [
{
op: 'set',
fieldPath: 'mcpServers',
value: { 'yaml-stdio': { title: 'Local' }, 'yaml-http': { title: 'Remote' } },
},
],
},
params,
);
expect(status).toBe(200);
expect(body.applied).toHaveLength(2);
expect(body.ignored).toEqual([
expect(body.applied).toEqual([{ opIndex: 0, op: 'set', segments: ['mcpServers'] }]);
expect(body.skipped).toEqual([
{
opIndex: 0,
op: 'set',
segments: ['mcpServers', 'yaml-stdio', 'title'],
segments: ['mcpServers', 'yaml-stdio'],
reason: 'process_mcp_server',
},
]);
expect(body.ignored).toEqual([]);
expect((await storedDocument(params.principalId))!.overrides).toEqual({
mcpServers: { 'yaml-http': { title: 'Remote' } },
});
});
it('reports the YAML stdio servers a whole-section tombstone leaves in place as ignored', async () => {
@ -1364,7 +1385,7 @@ describe('POST …/changes: entries librechat.yaml owns', () => {
expect((await storedDocument(params.principalId))!.tombstones).toEqual(['endpoints.agents']);
});
it('reports a rename under a YAML stdio server as ignored, but not an unset there', async () => {
it('refuses a rename under a YAML stdio server, but not an unset there', async () => {
const params = nextParams();
await seedDocument(
params.principalId,
@ -1379,7 +1400,7 @@ describe('POST …/changes: entries librechat.yaml owns', () => {
[],
);
const { status, body } = await send(
const rename = await send(
{
ops: [
{
@ -1388,24 +1409,22 @@ describe('POST …/changes: entries librechat.yaml owns', () => {
from: 'OLD',
to: 'NEW',
},
{ op: 'unset', fieldPath: 'mcpServers.yaml-stdio.title' },
],
},
params,
);
expect(rename.status).toBe(400);
expect(rename.body).toMatchObject({ code: 'PROCESS_MCP_SERVER_OVERRIDE', opIndex: 0 });
const { status, body } = await send(
{ ops: [{ op: 'unset', fieldPath: 'mcpServers.yaml-stdio.title' }] },
params,
);
expect(status).toBe(200);
expect(body.applied.map((ref) => ref.opIndex)).toEqual([0, 1]);
expect(body.ignored).toEqual([
{
opIndex: 0,
op: 'rename',
segments: ['mcpServers', 'yaml-stdio', 'customUserVars'],
reason: 'process_mcp_server',
},
]);
expect(body.applied.map((ref) => ref.opIndex)).toEqual([0]);
expect(body.ignored).toEqual([]);
expect((await storedDocument(params.principalId))!.overrides).toEqual({
mcpServers: { 'yaml-stdio': { customUserVars: { NEW: { title: 'T', description: 'D' } } } },
mcpServers: { 'yaml-stdio': { customUserVars: { OLD: { title: 'T', description: 'D' } } } },
});
});
@ -1897,7 +1916,12 @@ describe('POST …/changes: no-ops, dry runs and preconditions', () => {
);
expect(rewritten.status).toBe(400);
expect(rewritten.body.issues).toEqual([
{ path: 'balance.startBalance', segments: ['balance', 'startBalance'], code: 'invalid_type' },
{
path: 'balance.startBalance',
segments: ['balance', 'startBalance'],
code: 'invalid_type',
params: { expected: 'number', received: 'string' },
},
]);
});

View file

@ -286,6 +286,7 @@ describe('admin config writes refuse keys that cannot be config', () => {
path: `endpoints.bedrock.inferenceProfiles.${PROFILE}`,
segments: ['endpoints', 'bedrock', 'inferenceProfiles', PROFILE],
code: 'invalid_type',
params: { expected: 'string', received: 'number' },
},
]);
expect(await readRaw(role)).toBeNull();

View file

@ -473,6 +473,7 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(400);
expect(res.body).toEqual({
error: 'Process-backed MCP servers can only be configured in librechat.yaml',
code: 'PROCESS_MCP_CONFIG',
});
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@ -494,6 +495,7 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(400);
expect(res.body).toEqual({
error: 'Langfuse request headers can only be configured in librechat.yaml',
code: 'LANGFUSE_HEADERS_CONFIG',
});
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@ -517,6 +519,7 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(400);
expect(res.body).toEqual({
error: 'Langfuse request headers can only be configured in librechat.yaml',
code: 'LANGFUSE_HEADERS_CONFIG',
});
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@ -624,6 +627,9 @@ describe('createAdminConfigHandlers', () => {
expect(res.body).toEqual({
message: 'No actionable override sections provided',
revision: null,
config: null,
applied: [],
skipped: [{ path: 'langfuse', segments: ['langfuse'], reason: 'dedicated_section' }],
});
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@ -671,7 +677,7 @@ describe('createAdminConfigHandlers', () => {
await handlers.upsertConfigOverrides(req, res);
expect(res.statusCode).toBe(403);
expect(res.body).toEqual({ error: 'Insufficient permissions' });
expect(res.body).toEqual({ error: 'Insufficient permissions', code: 'FORBIDDEN' });
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@ -984,7 +990,19 @@ describe('createAdminConfigHandlers', () => {
await handlers.deleteConfigField(req, res);
expect(res.statusCode).toBe(200);
expect(res.body).toEqual({ message: 'No actionable field path provided', revision: null });
expect(res.body).toEqual({
message: 'No actionable field path provided',
revision: null,
config: null,
applied: [],
skipped: [
{
path: 'langfuse.enabled',
segments: ['langfuse', 'enabled'],
reason: 'dedicated_section',
},
],
});
expect(deps.unsetConfigField).not.toHaveBeenCalled();
});
@ -1128,7 +1146,19 @@ describe('createAdminConfigHandlers', () => {
await handlers.tombstoneConfigField(req, res);
expect(res.statusCode).toBe(200);
expect(res.body).toEqual({ message: 'No actionable field path provided', revision: null });
expect(res.body).toEqual({
message: 'No actionable field path provided',
revision: null,
config: null,
applied: [],
skipped: [
{
path: 'langfuse.enabled',
segments: ['langfuse', 'enabled'],
reason: 'dedicated_section',
},
],
});
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@ -1297,6 +1327,7 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(400);
expect(res.body).toEqual({
error: 'Process-backed MCP servers can only be configured in librechat.yaml',
code: 'PROCESS_MCP_CONFIG',
});
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@ -1317,6 +1348,7 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(400);
expect(res.body).toEqual({
error: 'Langfuse request headers can only be configured in librechat.yaml',
code: 'LANGFUSE_HEADERS_CONFIG',
});
}
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
@ -1373,7 +1405,19 @@ describe('createAdminConfigHandlers', () => {
await handlers.patchConfigField(req, res);
expect(res.statusCode).toBe(200);
expect(res.body).toEqual({ message: 'No actionable field entries provided', revision: null });
expect(res.body).toEqual({
message: 'No actionable field entries provided',
revision: null,
config: null,
applied: [],
skipped: [
{
path: 'langfuse.enabled',
segments: ['langfuse', 'enabled'],
reason: 'dedicated_section',
},
],
});
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@ -2764,7 +2808,7 @@ describe('createAdminConfigHandlers', () => {
const req = mockReq({
params: { principalType: 'role', principalId: 'admin' },
body: {
overrides: { registration: { oauthStateTtlMs: 5 }, interface: { modelSelect: false } },
overrides: { githubCompare: { timeoutMs: 0 }, interface: { modelSelect: false } },
},
});
const res = mockRes();
@ -2777,9 +2821,10 @@ describe('createAdminConfigHandlers', () => {
code: 'CONFIG_OVERRIDE_INVALID',
issues: [
{
path: 'registration.oauthStateTtlMs',
segments: ['registration', 'oauthStateTtlMs'],
path: 'githubCompare.timeoutMs',
segments: ['githubCompare', 'timeoutMs'],
code: 'too_small',
params: { minimum: 1, inclusive: true, exact: false, type: 'number' },
},
],
});
@ -2787,18 +2832,19 @@ describe('createAdminConfigHandlers', () => {
});
it('validates a whole-document write on the base its retained tombstones leave', async () => {
const base = {
config: {
cloudfront: { domain: 'https://cdn.example.com', imageSigning: 'cookies' },
},
};
const body = { overrides: { cloudfront: { requireSignedAccess: true } } };
/** A reset refill needs a whole interval; only a stored tombstone of the mode lifts that. */
const base = { config: { balance: { refillMode: 'reset' } } };
const body = { overrides: { balance: { refillIntervalValue: 1.5 } } };
const params = { principalType: 'role', principalId: 'admin' };
const kept = createHandlers({ getAppConfig: jest.fn().mockResolvedValue(base) });
const keptRes = mockRes();
await kept.handlers.upsertConfigOverrides(mockReq({ params, body }), keptRes);
expect(keptRes.statusCode).toBe(201);
expect(keptRes.statusCode).toBe(400);
expect(keptRes.body?.issues).toEqual([
expect.objectContaining({ path: 'balance.refillIntervalValue', code: 'custom' }),
]);
expect(kept.deps.writeConfigDocument).not.toHaveBeenCalled();
const tombstoned = createHandlers({
getAppConfig: jest.fn().mockResolvedValue(base),
@ -2806,16 +2852,13 @@ describe('createAdminConfigHandlers', () => {
_id: 'c1',
configVersion: 1,
overrides: {},
tombstones: ['cloudfront.imageSigning'],
tombstones: ['balance.refillMode'],
}),
});
const tombstonedRes = mockRes();
await tombstoned.handlers.upsertConfigOverrides(mockReq({ params, body }), tombstonedRes);
expect(tombstonedRes.statusCode).toBe(400);
expect(tombstonedRes.body?.issues).toEqual([
expect.objectContaining({ path: 'cloudfront.requireSignedAccess' }),
]);
expect(tombstoned.deps.writeConfigDocument).not.toHaveBeenCalled();
expect(tombstonedRes.statusCode).toBe(200);
expect(tombstoned.deps.writeConfigDocument).toHaveBeenCalledTimes(1);
});
it('accepts a partial section whose provided fields are valid', async () => {
@ -2824,7 +2867,7 @@ describe('createAdminConfigHandlers', () => {
params: { principalType: 'role', principalId: 'admin' },
body: {
overrides: {
registration: { oauthStateTtlMs: 120_000 },
registration: { allowedDomains: ['example.com'] },
mcpServers: { github: { timeout: 5000 } },
endpoints: { custom: [{ name: 'groq', apiKey: 'sk-test' }] },
},
@ -2954,7 +2997,7 @@ describe('createAdminConfigHandlers', () => {
body: {
entries: [
{ fieldPath: 'interface.customWelcome', value: 'hi' },
{ fieldPath: 'registration.oauthStateTtlMs', value: 'soon' },
{ fieldPath: 'githubCompare.timeoutMs', value: 'soon' },
],
},
});
@ -2964,7 +3007,12 @@ describe('createAdminConfigHandlers', () => {
expect(res.statusCode).toBe(400);
expect(res.body?.issues).toEqual([
expect.objectContaining({ path: 'registration.oauthStateTtlMs' }),
{
path: 'githubCompare.timeoutMs',
segments: ['githubCompare', 'timeoutMs'],
code: 'invalid_type',
params: { expected: 'number', received: 'string' },
},
]);
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});
@ -4203,6 +4251,15 @@ describe('createAdminConfigHandlers', () => {
expect(res.body).toEqual({
message: 'No actionable field entries provided',
revision: storedRevision,
config: expect.objectContaining({ revision: storedRevision }),
applied: [],
skipped: [
{
path: 'interface.prompts',
segments: ['interface', 'prompts'],
reason: 'interface_permission',
},
],
});
expect(deps.writeConfigDocument).not.toHaveBeenCalled();
});

View file

@ -571,6 +571,48 @@ describe('validation on the Base floor (W2-3)', () => {
expect(res.statusCode).toBe(200);
expect(res.body?.ignored).toEqual(dropped);
}
/** A read judges the stored profile over the same Base the writes judged it on. */
const read = await call(handlers.getConfig, { params: group });
expect(read.statusCode).toBe(200);
expect(read.body?.ignoredBasis).toBe('base');
expect(read.body?.ignored).toEqual(dropped);
});
it("keeps the stdio servers that tenant's librechat.yaml runs out of PUT and tombstones", async () => {
const getAppConfig = yamlByTenant({
mcpServers: { local: { type: 'stdio', command: 'node', args: ['server.js'] } },
} as never);
const handlers = createHandlers({}, { getAppConfig });
const group = await tenantProfile(handlers, 'group');
const replaced = await call(handlers.upsertConfigOverrides, {
params: group,
body: {
overrides: {
interface: { customWelcome: 'hi' },
mcpServers: { local: { title: 'Local' } },
},
},
});
const tombstoned = await call(handlers.tombstoneConfigField, {
params: group,
body: { fieldPath: 'mcpServers.local' },
});
expect(replaced.statusCode).toBe(200);
expect(replaced.body?.skipped).toEqual([
{
path: 'mcpServers.local',
segments: ['mcpServers', 'local'],
reason: 'process_mcp_server',
},
]);
expect(tombstoned.statusCode).toBe(400);
expect(tombstoned.body?.code).toBe('PROCESS_MCP_SERVER_OVERRIDE');
const kept = await stored(group.principalType, group.principalId);
expect(kept?.overrides).toEqual({ interface: { customWelcome: 'hi' } });
expect(kept?.tombstones ?? []).toEqual([]);
});
});

View file

@ -0,0 +1,761 @@
import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import type { AdminConfigReadResponse } from '@librechat/data-schemas';
import type { Response } from 'express';
import type { ServerRequest } from '~/types/http';
process.env.CREDS_KEY =
process.env.CREDS_KEY ?? '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
process.env.CREDS_IV = process.env.CREDS_IV ?? '0123456789abcdef0123456789abcdef';
type DataSchemas = typeof import('@librechat/data-schemas');
type Methods = ReturnType<DataSchemas['createMethods']>;
type AdminConfigHandlers = ReturnType<typeof import('./config').createAdminConfigHandlers>;
type AdminConfigDeps = Parameters<typeof import('./config').createAdminConfigHandlers>[0];
type Handler = (req: ServerRequest, res: Response) => Promise<Response>;
type Location = { path: string; segments: string[]; reason?: string; kind?: string };
interface MockRes {
statusCode: number;
body: undefined | Record<string, unknown>;
status: jest.Mock;
json: jest.Mock;
}
let mongoServer: MongoMemoryServer;
let methods: Methods;
let createAdminConfigHandlers: typeof import('./config').createAdminConfigHandlers;
/** librechat.yaml: a stdio server, a remote one, and fields only librechat.yaml sets. */
const YAML = {
mcpServers: {
local: { type: 'stdio', command: 'node', args: ['server.js'] },
remote: { type: 'streamable-http', url: 'https://mcp.example.com/mcp' },
},
endpoints: {
agents: {
pullRequests: { provider: 'github' },
eventDriven: { deadLetterRetentionDays: 7 },
},
},
memory: { agent: { id: 'agent_1' } },
};
function mockReq(overrides: Record<string, unknown> = {}): ServerRequest {
return {
user: { id: 'u1', role: 'ADMIN', _id: { toString: () => 'u1' } },
params: {},
body: {},
query: {},
...overrides,
} as Partial<ServerRequest> as ServerRequest;
}
function mockRes(): Response & MockRes {
const res: MockRes = {
statusCode: 200,
body: undefined,
status: jest.fn((code: number) => {
res.statusCode = code;
return res;
}),
json: jest.fn((data: MockRes['body']) => {
res.body = data;
return res;
}),
};
return res as Partial<Response> as Response & MockRes;
}
function createHandlers(overrides: Partial<AdminConfigDeps> = {}): AdminConfigHandlers {
return createAdminConfigHandlers({
listAllConfigs: methods.listAllConfigs,
findConfigByPrincipal: methods.findConfigByPrincipal,
writeConfigDocument: methods.writeConfigDocument,
unsetConfigField: methods.unsetConfigField,
deleteConfig: methods.deleteConfig,
toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
hasConfigCapability: async () => true,
hasAnyConfigReadAccess: async () => true,
hasCapability: async () => true,
getAppConfig: async () => ({ config: structuredClone(YAML) }) as never,
...overrides,
});
}
let counter = 0;
function nextParams(): { principalType: string; principalId: string } {
counter += 1;
return { principalType: 'role', principalId: `report-${counter}` };
}
async function call(handler: Handler, request: Record<string, unknown>): Promise<MockRes> {
const res = mockRes();
await handler(mockReq(request), res);
return res;
}
/** Stores a document as an older server or another writer left it, with no write-time checks. */
async function seed(
params: { principalType: string; principalId: string },
overrides: Record<string, unknown>,
tombstones: string[] = [],
): Promise<void> {
await methods.writeConfigDocument(
params.principalType as never,
params.principalId,
{ principalModel: 'Role' as never, priority: 10, overrides, tombstones, isActive: true },
'absent',
);
}
async function stored(params: { principalType: string; principalId: string }) {
return methods.findConfigByPrincipal(params.principalType as never, params.principalId, {
includeInactive: true,
});
}
/** `kind:path:reason`, sorted, for comparing report lists whatever their order. */
function describeAll(list: unknown): string[] {
return ((list as Location[] | undefined) ?? [])
.map(({ path, reason, kind }) => [kind, path, reason].filter(Boolean).join(':'))
.sort();
}
const LIFECYCLE_TIMEOUT_MS = 180_000;
beforeAll(async () => {
const [dataSchemas, handlersModule, server] = await Promise.all([
import('@librechat/data-schemas'),
import('./config'),
MongoMemoryServer.create(),
]);
mongoServer = server;
({ createAdminConfigHandlers } = handlersModule);
jest.spyOn(dataSchemas.logger, 'error').mockReturnValue(dataSchemas.logger);
jest.spyOn(dataSchemas.logger, 'warn').mockReturnValue(dataSchemas.logger);
jest.spyOn(dataSchemas.logger, 'info').mockReturnValue(dataSchemas.logger);
await mongoose.connect(mongoServer.getUri());
dataSchemas.createModels(mongoose);
await mongoose.models.Config.init();
methods = dataSchemas.createMethods(mongoose);
}, LIFECYCLE_TIMEOUT_MS);
afterAll(async () => {
await mongoose.disconnect();
await mongoServer?.stop();
}, LIFECYCLE_TIMEOUT_MS);
describe('write report', () => {
it('PATCH stores what it can and reports each part it skipped, at its own location', async () => {
const params = nextParams();
const res = await call(createHandlers().patchConfigField, {
params,
body: {
entries: [
{ fieldPath: 'interface', value: { prompts: false, modelSelect: true } },
{
fieldPath: 'endpoints.agents',
value: { pullRequests: { provider: 'gitlab' }, recursionLimit: 20 },
},
{ fieldPath: 'rateLimits.fileUploads.ipMax', value: 1 },
{ fieldPath: 'filters.x', value: 1 },
],
},
});
expect(res.statusCode).toBe(200);
expect(res.body?.applied).toEqual([
{ path: 'interface', segments: ['interface'] },
{ path: 'endpoints.agents', segments: ['endpoints', 'agents'] },
]);
expect(describeAll(res.body?.skipped)).toEqual([
'endpoints.agents.pullRequests.provider:base_only_path',
'filters.x:base_only_section',
'interface.prompts:interface_permission',
'rateLimits.fileUploads.ipMax:deployment_only_path',
]);
expect((await stored(params))?.overrides).toEqual({
interface: { modelSelect: true },
endpoints: { agents: { recursionLimit: 20 } },
});
});
it('PATCH resets a path whose whole value is skipped, as a written value replaces it', async () => {
const params = nextParams();
await seed(params, { interface: { customWelcome: 'stored' }, memory: { disabled: true } });
const res = await call(createHandlers().patchConfigField, {
params,
body: { entries: [{ fieldPath: 'interface', value: { prompts: false } }] },
});
expect(res.statusCode).toBe(200);
expect(res.body?.applied).toEqual([{ path: 'interface', segments: ['interface'] }]);
expect(describeAll(res.body?.skipped)).toEqual(['interface.prompts:interface_permission']);
expect((await stored(params))?.overrides).toEqual({ memory: { disabled: true } });
});
it('PATCH applies a reset where the request puts it, as a written value would land', async () => {
const later = nextParams();
const handlers = createHandlers();
const resetLast = await call(handlers.patchConfigField, {
params: later,
body: {
entries: [
{ fieldPath: 'interface.modelSelect', value: true },
{ fieldPath: 'interface', value: { prompts: false } },
{ fieldPath: 'memory.disabled', value: true },
],
},
});
expect(resetLast.statusCode).toBe(200);
expect((await stored(later))?.overrides).toEqual({ memory: { disabled: true } });
const earlier = nextParams();
const resetFirst = await call(handlers.patchConfigField, {
params: earlier,
body: {
entries: [
{ fieldPath: 'interface', value: { prompts: false } },
{ fieldPath: 'interface.modelSelect', value: true },
],
},
});
expect(resetFirst.statusCode).toBe(200);
expect((await stored(earlier))?.overrides).toEqual({ interface: { modelSelect: true } });
});
it('PATCH answers a section manager whose every entry is skipped as a write, not a 403', async () => {
const params = nextParams();
await seed(params, {
endpoints: { agents: { recursionLimit: 5 } },
memory: { disabled: true },
});
const sectionManager = createHandlers({
hasConfigCapability: async (_user, section) => section === 'endpoints',
hasCapability: async () => false,
});
const res = await call(sectionManager.patchConfigField, {
params,
body: {
entries: [
{ fieldPath: 'endpoints.agents.eventDriven', value: { deadLetterRetentionDays: 3 } },
{ fieldPath: 'endpoints.agents.pullRequests.provider', value: 'gitlab' },
],
},
});
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
message: 'No actionable field entries provided',
applied: [],
config: { overrides: { endpoints: { agents: { recursionLimit: 5 } } } },
});
expect(res.body?.config).not.toHaveProperty('overrides.memory');
expect(describeAll(res.body?.skipped)).toEqual([
'endpoints.agents.eventDriven:deployment_only_path',
'endpoints.agents.pullRequests.provider:base_only_path',
]);
for (const entries of [
[{ fieldPath: 'rateLimits.fileUploads.ipMax', value: 1 }],
[
{ fieldPath: 'endpoints.agents.recursionLimit', value: 9 },
{ fieldPath: 'rateLimits.fileUploads.ipMax', value: 1 },
],
]) {
const denied = await call(sectionManager.patchConfigField, { params, body: { entries } });
expect([denied.statusCode, denied.body?.code, denied.body?.section]).toEqual([
403,
'FORBIDDEN_SECTION',
'rateLimits',
]);
}
expect((await stored(params))?.overrides).toEqual({
endpoints: { agents: { recursionLimit: 5 } },
memory: { disabled: true },
});
});
it('PUT leaves out every field only librechat.yaml sets, Base included', async () => {
const base = { principalType: 'role', principalId: '__base__' };
const res = await call(createHandlers().upsertConfigOverrides, {
params: base,
body: {
overrides: {
cloudfront: { domain: 'https://cdn.example.com' },
permissions: { leaseTtlMs: 1000 },
endpoints: {
agents: {
toolApproval: { hooks: [{ module: './hooks.js' }] },
pullRequests: { host: 'ghe.example.com' },
disableBuilder: true,
},
},
registration: { openidDiscovery: { startupAttempts: 2 }, allowedDomains: ['a.com'] },
interface: { modelSelect: false, agents: { use: false } },
},
},
});
expect(res.statusCode).toBe(201);
expect(res.body?.applied).toEqual([
{ path: 'endpoints', segments: ['endpoints'] },
{ path: 'registration', segments: ['registration'] },
{ path: 'interface', segments: ['interface'] },
]);
expect(describeAll(res.body?.skipped)).toEqual([
'cloudfront:deployment_only_path',
'endpoints.agents.pullRequests.host:base_only_path',
'endpoints.agents.toolApproval.hooks:deployment_only_path',
'interface.agents.use:interface_permission',
'permissions:deployment_only_path',
'registration.openidDiscovery:deployment_only_path',
]);
expect((await stored(base))?.overrides).toEqual({
endpoints: { agents: { disableBuilder: true } },
registration: { allowedDomains: ['a.com'] },
interface: { modelSelect: false },
});
await methods.deleteConfig('role' as never, '__base__');
});
it('a tombstone of a field only librechat.yaml sets is skipped; deleting a stored one is cleanup', async () => {
const params = nextParams();
await seed(params, { rateLimits: { fileUploads: { ipMax: 1 } }, memory: { disabled: true } });
const handlers = createHandlers();
for (const fieldPath of ['rateLimits', 'endpoints.agents.pullRequests.provider', 'openapi']) {
const res = await call(handlers.tombstoneConfigField, { params, body: { fieldPath } });
expect(res.statusCode).toBe(200);
expect(res.body).toMatchObject({
message: 'No actionable field path provided',
applied: [],
config: expect.objectContaining({ overrides: expect.any(Object) }),
});
expect(describeAll(res.body?.skipped)).toEqual([
`${fieldPath}:${fieldPath === 'endpoints.agents.pullRequests.provider' ? 'base_only_path' : 'deployment_only_path'}`,
]);
}
expect((await stored(params))?.tombstones).toEqual([]);
const cleanup = await call(handlers.deleteConfigField, {
params,
query: { fieldPath: 'rateLimits' },
});
expect(cleanup.statusCode).toBe(200);
expect(cleanup.body?.applied).toEqual([{ path: 'rateLimits', segments: ['rateLimits'] }]);
expect(cleanup.body?.skipped).toEqual([]);
expect((await stored(params))?.overrides).toEqual({ memory: { disabled: true } });
});
it('refuses a tombstone at an array element, which would hide nothing', async () => {
const params = nextParams();
const res = await call(createHandlers().tombstoneConfigField, {
params,
body: { fieldPath: 'endpoints.custom.0' },
});
expect(res.statusCode).toBe(400);
expect(res.body).toMatchObject({ code: 'CONFIG_PATH_INVALID', reason: 'inside_array' });
expect(await stored(params)).toBeNull();
});
it('reports a tombstone as applied', async () => {
const params = nextParams();
const handlers = createHandlers();
const tombstone = await call(handlers.tombstoneConfigField, {
params,
body: { fieldPath: 'memory.agent' },
});
expect(tombstone.statusCode).toBe(200);
expect(tombstone.body?.applied).toEqual([
{ path: 'memory.agent', segments: ['memory', 'agent'] },
]);
expect(tombstone.body?.skipped).toEqual([]);
});
it.each([
[0, 'too_small', { minimum: 1, inclusive: true, exact: false, type: 'number' }],
[2.5, 'invalid_type', { expected: 'integer', received: 'float' }],
])('refuses a recursionLimit of %s with its bound', async (value, code, params) => {
const res = await call(createHandlers().patchConfigField, {
params: nextParams(),
body: { entries: [{ fieldPath: 'endpoints.agents.recursionLimit', value }] },
});
expect(res.statusCode).toBe(400);
expect(res.body?.issues).toEqual([
{
path: 'endpoints.agents.recursionLimit',
segments: ['endpoints', 'agents', 'recursionLimit'],
code,
params,
},
]);
});
});
describe('MCP servers librechat.yaml runs as local processes', () => {
it('refuses a field write or tombstone inside one, and keeps the process-field refusal', async () => {
const params = nextParams();
const handlers = createHandlers();
const title = await call(handlers.patchConfigField, {
params,
body: { entries: [{ fieldPath: 'mcpServers.local.title', value: 'Local' }] },
});
expect(title.statusCode).toBe(400);
expect(title.body).toEqual({
error:
'An MCP server librechat.yaml runs as a local process can only be configured in librechat.yaml',
code: 'PROCESS_MCP_SERVER_OVERRIDE',
});
const args = await call(handlers.patchConfigField, {
params,
body: { entries: [{ fieldPath: 'mcpServers.local.args', value: ['x'] }] },
});
expect(args.statusCode).toBe(400);
expect(args.body?.code).toBe('PROCESS_MCP_CONFIG');
for (const fieldPath of ['mcpServers.local', 'mcpServers.local.timeout']) {
const tombstone = await call(handlers.tombstoneConfigField, { params, body: { fieldPath } });
expect(tombstone.statusCode).toBe(400);
expect(tombstone.body?.code).toBe('PROCESS_MCP_SERVER_OVERRIDE');
}
expect(await stored(params)).toBeNull();
const remote = await call(handlers.patchConfigField, {
params,
body: { entries: [{ fieldPath: 'mcpServers.remote.title', value: 'Remote' }] },
});
expect(remote.statusCode).toBe(200);
});
it('a whole-document or whole-section write leaves one out, so a stored no-op round-trips', async () => {
const params = nextParams();
await seed(params, {
mcpServers: { local: { title: 'Local' }, remote: { title: 'Remote' } },
});
const handlers = createHandlers();
const read = await call(handlers.getConfig, { params });
expect(describeAll(read.body?.ignored)).toEqual([
'override:mcpServers.local:process_mcp_server',
]);
const put = await call(handlers.upsertConfigOverrides, {
params,
body: { overrides: (read.body?.config as { overrides: object }).overrides },
});
expect(put.statusCode).toBe(200);
expect(describeAll(put.body?.skipped)).toEqual(['mcpServers.local:process_mcp_server']);
expect((await stored(params))?.overrides).toEqual({
mcpServers: { remote: { title: 'Remote' } },
});
const section = await call(handlers.patchConfigField, {
params,
body: { entries: [{ fieldPath: 'mcpServers', value: { local: { title: 'L' } } }] },
});
expect(section.statusCode).toBe(200);
expect(describeAll(section.body?.skipped)).toEqual(['mcpServers.local:process_mcp_server']);
expect((await stored(params))?.overrides).toEqual({});
});
it('still lets a field delete clean up what an older server stored there', async () => {
const params = nextParams();
await seed(params, { mcpServers: { local: { title: 'Local' } } });
const res = await call(createHandlers().deleteConfigField, {
params,
query: { fieldPath: 'mcpServers.local.title' },
});
expect(res.statusCode).toBe(200);
expect((await stored(params))?.overrides).toEqual({});
});
});
describe('GET reports what the merge leaves out of a stored document', () => {
it('lists each stored part by location, reason and kind, judged over the Base floor', async () => {
const params = nextParams();
await seed(
params,
{
paths: { uploads: '/tmp' },
rateLimits: { fileUploads: { ipMax: 1 } },
interface: { prompts: false, modelSelect: true },
githubCompare: { timeoutMs: 40_000 },
endpoints: { agents: { pullRequests: { provider: 'gitlab' } } },
},
['filters', 'endpoints.agents'],
);
const res = await call(createHandlers().getConfig, { params });
expect(res.statusCode).toBe(200);
expect(res.body?.ignoredBasis).toBe('base');
expect(describeAll(res.body?.ignored)).toEqual([
'override:endpoints.agents.pullRequests.provider:base_only_path',
'override:githubCompare.timeoutMs:invalid',
'override:interface.prompts:interface_permission',
'override:paths:unknown_section',
'override:rateLimits:deployment_only_path',
'tombstone:endpoints.agents.eventDriven:deployment_only_path',
'tombstone:endpoints.agents.pullRequests.provider:base_only_path',
'tombstone:filters:base_only_section',
]);
});
it('judges a profile on the active Base, and Base on librechat.yaml alone', async () => {
const base = { principalType: 'role', principalId: '__base__' };
await seed(base, { memory: { agent: { provider: 'openAI', model: 'gpt-4o' } } }, [
'memory.agent.id',
]);
const params = nextParams();
await seed(params, { memory: { agent: { model: 'gpt-4.1' } } });
const handlers = createHandlers();
const profile = await call(handlers.getConfig, { params });
expect(profile.body?.ignored).toEqual([]);
const baseRead = await call(handlers.getConfig, { params: base });
expect(baseRead.body?.ignoredBasis).toBe('yaml');
expect(baseRead.body?.ignored).toEqual([]);
await methods.deleteConfig('role' as never, '__base__');
const withoutBase = await call(handlers.getConfig, { params });
expect(describeAll(withoutBase.body?.ignored)).toEqual(['override:memory.agent.model:invalid']);
});
it('shows a section-scoped reader only the sections it can read', async () => {
const params = nextParams();
await seed(params, { rateLimits: { fileUploads: { ipMax: 1 } }, filters: { x: 1 } });
const res = await call(
createHandlers({
getReadableConfigSections: async () => ({ broad: false, sections: new Set(['filters']) }),
}).getConfig,
{ params },
);
expect(describeAll(res.body?.ignored)).toEqual(['override:filters:base_only_section']);
});
it('still answers with the document when the Base document cannot be read', async () => {
const params = nextParams();
await seed(params, { rateLimits: { fileUploads: { ipMax: 1 } } });
const res = await call(
createHandlers({
findConfigByPrincipal: async (principalType, principalId, options) => {
if (principalId === '__base__') {
throw new Error('base unavailable');
}
return methods.findConfigByPrincipal(principalType, principalId, options);
},
}).getConfig,
{ params },
);
expect(res.statusCode).toBe(200);
expect((res.body?.config as { overrides: object }).overrides).toEqual({
rateLimits: { fileUploads: { ipMax: 1 } },
});
expect(res.body).not.toHaveProperty('ignored');
});
it('leaves the report out, rather than claiming nothing is ignored, when it cannot judge', async () => {
const params = nextParams();
await seed(params, { rateLimits: { fileUploads: { ipMax: 1 } } });
const res = await call(
createHandlers({
getAppConfig: async () => {
throw new Error('yaml unavailable');
},
}).getConfig,
{ params },
);
expect(res.statusCode).toBe(200);
expect(res.body).not.toHaveProperty('ignored');
const noBase = await call(createHandlers({ getAppConfig: undefined }).getConfig, { params });
expect(noBase.statusCode).toBe(200);
expect(noBase.body).not.toHaveProperty('ignored');
expect(noBase.body).not.toHaveProperty('ignoredBasis');
/** The read contract types this answer: a document whose report is left out. */
const unjudged: AdminConfigReadResponse = {
config: noBase.body?.config as AdminConfigReadResponse['config'],
};
expect(noBase.body).toEqual(unjudged);
});
});
describe('every 4xx a config handler answers carries a stable code', () => {
const params = { principalType: 'role', principalId: 'codes' };
const cases: Array<[string, keyof AdminConfigHandlers, Record<string, unknown>, string]> = [
[
'bad principal type',
'getConfig',
{ params: { ...params, principalType: 'x' } },
'INVALID_PRINCIPAL_TYPE',
],
['missing document', 'getConfig', { params }, 'CONFIG_NOT_FOUND'],
[
'overrides not an object',
'upsertConfigOverrides',
{ params, body: { overrides: [] } },
'INVALID_OVERRIDES',
],
[
'bad priority',
'upsertConfigOverrides',
{ params, body: { overrides: {}, priority: -1 } },
'INVALID_PRIORITY',
],
[
'bad revision',
'upsertConfigOverrides',
{ params, body: { overrides: {}, expectedRevision: 'x' } },
'INVALID_EXPECTED_REVISION',
],
[
'process server config',
'upsertConfigOverrides',
{ params, body: { overrides: { mcpServers: { s: { command: 'x' } } } } },
'PROCESS_MCP_CONFIG',
],
['no entries', 'patchConfigField', { params, body: { entries: [] } }, 'ENTRIES_REQUIRED'],
[
'too many entries',
'patchConfigField',
{
params,
body: {
entries: Array.from({ length: 101 }, (_, i) => ({
fieldPath: `interface.x${i}`,
value: 1,
})),
},
},
'PATCH_TOO_LARGE',
],
[
'unsafe path',
'patchConfigField',
{ params, body: { entries: [{ fieldPath: 'a..b', value: 1 }] } },
'INVALID_FIELD_PATH',
],
[
'unknown section',
'patchConfigField',
{ params, body: { entries: [{ fieldPath: 'paths.uploads', value: 1 }] } },
'UNKNOWN_SECTION',
],
[
'duplicate path',
'patchConfigField',
{
params,
body: {
entries: [
{ fieldPath: 'interface.a', value: 1 },
{ fieldPath: 'interface.a', value: 2 },
],
},
},
'DUPLICATE_FIELD_PATH',
],
[
'langfuse headers',
'patchConfigField',
{ params, body: { entries: [{ fieldPath: 'langfuse.headers', value: {} }] } },
'LANGFUSE_HEADERS_CONFIG',
],
[
'secret preview',
'patchConfigField',
{ params, body: { entries: [{ fieldPath: 'langfuse.secretKeyPreview', value: 'x' }] } },
'SECRET_PATH',
],
[
'invalid value',
'patchConfigField',
{ params, body: { entries: [{ fieldPath: 'githubCompare.timeoutMs', value: 0 }] } },
'CONFIG_OVERRIDE_INVALID',
],
[
'tombstone without a path',
'tombstoneConfigField',
{ params, body: {} },
'INVALID_FIELD_PATH',
],
['delete without a path', 'deleteConfigField', { params, query: {} }, 'INVALID_FIELD_PATH'],
[
'delete of a missing document',
'deleteConfigField',
{ params, query: { fieldPath: 'memory.disabled' } },
'CONFIG_NOT_FOUND',
],
['toggle without isActive', 'toggleConfig', { params, body: {} }, 'INVALID_IS_ACTIVE'],
[
'toggle of a missing document',
'toggleConfig',
{ params, body: { isActive: false } },
'CONFIG_NOT_FOUND',
],
['delete of a missing profile', 'deleteConfigOverrides', { params }, 'CONFIG_NOT_FOUND'],
['no ops', 'applyConfigChanges', { params, body: { ops: [] } }, 'OPS_REQUIRED'],
];
it.each(cases)('%s', async (_label, handler, request, code) => {
const res = await call(createHandlers()[handler], request);
expect(res.statusCode).toBeGreaterThanOrEqual(400);
expect(res.statusCode).toBeLessThan(500);
expect(res.body).toMatchObject({ code, error: expect.any(String) });
});
it('answers 401 and 403 with codes on every route', async () => {
const denied = createHandlers({
hasConfigCapability: async () => false,
hasAnyConfigReadAccess: async () => false,
hasCapability: async () => false,
});
const routes: Array<[keyof AdminConfigHandlers, Record<string, unknown>]> = [
['listConfigs', {}],
['getConfigMeta', {}],
['getBaseConfig', {}],
['getConfig', { params }],
['upsertConfigOverrides', { params, body: { overrides: { memory: {} } } }],
[
'patchConfigField',
{ params, body: { entries: [{ fieldPath: 'memory.disabled', value: true }] } },
],
['tombstoneConfigField', { params, body: { fieldPath: 'memory.disabled' } }],
['deleteConfigField', { params, query: { fieldPath: 'memory.disabled' } }],
['applyConfigChanges', { params, body: { ops: [{ op: 'unset', fieldPath: 'memory' }] } }],
['deleteConfigOverrides', { params }],
['toggleConfig', { params, body: { isActive: true } }],
['updateConfigPriority', { params, body: { priority: 1 } }],
['reloadConfig', {}],
];
for (const [handler, request] of routes) {
const forbidden = await call(denied[handler], request);
expect([handler, forbidden.statusCode, forbidden.body?.code]).toEqual([
handler,
403,
expect.stringMatching(/^FORBIDDEN/),
]);
const anonymous = await call(denied[handler], { ...request, user: undefined });
expect([handler, anonymous.statusCode, anonymous.body?.code]).toEqual([
handler,
401,
'AUTH_REQUIRED',
]);
}
});
});

View file

@ -651,7 +651,10 @@ describe('segment addressing on the field routes', () => {
expect(both.statusCode).toBe(400);
expect(duplicate.statusCode).toBe(400);
expect(duplicate.body).toEqual({ error: 'Duplicate field path segments' });
expect(duplicate.body).toEqual({
error: 'Duplicate field path segments',
code: 'DUPLICATE_FIELD_PATH',
});
expect(await raw().countDocuments({ principalId: params.principalId })).toBe(0);
});

File diff suppressed because it is too large Load diff

View file

@ -29,6 +29,7 @@ import {
BASE_ONLY_CONFIG_PATHS,
BASE_ONLY_CONFIG_SECTIONS,
PROCESS_MCP_SERVER_FIELDS,
DEPLOYMENT_ONLY_CONFIG_PATHS,
INTERFACE_PERMISSION_FIELDS,
mapModelToAzureConfig,
BASE_PRINCIPAL_CONFIG_SECTIONS,
@ -59,6 +60,7 @@ import {
encryptConfigSecretFields,
resolveRuntimeConfigSecrets,
} from './secrets';
import { allowBeforeTermsAcceptance, createTermsAcceptanceGate } from '~/middleware/terms';
import { createRequestSanitizer, rejectUnsafeConfigKeys } from '~/middleware/sanitize';
import { resolvePreAuthAppConfig, resolvePreLoginAppConfig } from '~/app/resolve';
import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';
@ -271,7 +273,7 @@ describe('GET /api/admin/config/meta', () => {
const forbidden = mockRes();
await createHandlers({ hasAnyConfigReadAccess }).getConfigMeta(mockReq(), forbidden);
expect(forbidden.statusCode).toBe(403);
expect(forbidden.body).toEqual({ error: 'Insufficient permissions' });
expect(forbidden.body).toEqual({ error: 'Insufficient permissions', code: 'FORBIDDEN' });
expect(hasAnyConfigReadAccess).toHaveBeenCalledWith(expect.objectContaining({ id: 'u1' }));
});
@ -300,6 +302,7 @@ describe('GET /api/admin/config/meta', () => {
expect(meta.metaVersion).toBe(1);
expect(Object.keys(meta.versions)).toEqual(['librechat', 'dataProvider', 'configSchema']);
expect(Object.keys(meta.features).sort()).toEqual([
'adminTermsExempt',
'awaitedInvalidation',
'azureGroupSecrets',
'catalogApi',
@ -309,6 +312,7 @@ describe('GET /api/admin/config/meta', () => {
'envAllowlist',
'envStatus',
'expectedRevision',
'issueParams',
'preAuthBaseOverrides',
'principalCheck',
'priorityRoute',
@ -321,6 +325,7 @@ describe('GET /api/admin/config/meta', () => {
'secretRebinding',
'sectionAllowlist',
'webSearchStoredKeys',
'writeReport',
'yamlMcpHide',
'yamlSecretPreview',
]);
@ -338,6 +343,7 @@ describe('GET /api/admin/config/meta', () => {
'baseOnlyPaths',
'baseOnlySections',
'basePrincipalSections',
'deploymentOnlyPaths',
'interface',
'overrideKeyMap',
'processMcpFields',
@ -374,6 +380,9 @@ describe('GET /api/admin/config/meta', () => {
catalogApi: true,
envStatus: true,
reloadRoute: true,
writeReport: true,
issueParams: true,
adminTermsExempt: true,
});
});
@ -408,6 +417,7 @@ describe('meta rules equal the rules the server applies', () => {
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.deploymentOnlyPaths).toEqual({ ...DEPLOYMENT_ONLY_CONFIG_PATHS });
expect(meta.rules.processMcpFields).toEqual([...PROCESS_MCP_SERVER_FIELDS]);
expect(meta.rules.interface).toEqual({
permissionFields: [...INTERFACE_PERMISSION_FIELDS],
@ -508,7 +518,28 @@ describe('meta rules equal the rules the server applies', () => {
const writeConfigDocument = jest.fn();
for (const section of meta.rules.baseOnlySections) {
const res = await patch([{ fieldPath: `${section}.x`, value: 1 }], { writeConfigDocument });
expect(res.body).toEqual({ message: 'No actionable field entries provided', revision: null });
expect(res.body).toEqual({
message: 'No actionable field entries provided',
revision: null,
config: null,
applied: [],
skipped: [{ path: `${section}.x`, segments: [section, 'x'], reason: 'base_only_section' }],
});
}
expect(writeConfigDocument).not.toHaveBeenCalled();
});
it('skips writes to every listed deployment-only path, and the merge keeps the YAML value', async () => {
const writeConfigDocument = jest.fn();
for (const path of Object.keys(meta.rules.deploymentOnlyPaths)) {
const res = await patch([{ fieldPath: path, value: 1 }], { writeConfigDocument });
expect(res.body?.skipped).toEqual([
{ path, segments: path.split('.'), reason: 'deployment_only_path' },
]);
const merged = mergeConfigOverrides({ config: {} } as AppConfig, [
storedConfig(setIn({}, path.split('.'), 1)),
]);
expect([path, getIn(merged, path)]).toEqual([path, undefined]);
}
expect(writeConfigDocument).not.toHaveBeenCalled();
});
@ -1806,6 +1837,130 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
audited[2].outcome === 'failure'
);
},
async writeReport() {
const base = {
config: {
mcpServers: { local: { type: 'stdio', command: 'node', args: ['server.js'] } },
},
} as Partial<AppConfig> as AppConfig;
const getAppConfig = jest.fn().mockResolvedValue(base);
const writeConfigDocument = jest.fn(
async (_type: string, _id: string, draft: ConfigDraft): Promise<ConfigRecord> =>
storedConfig(draft.overrides ?? {}, draft.tombstones),
);
const written = await patch(
[
{ fieldPath: 'interface', value: { prompts: false, modelSelect: true } },
{
fieldPath: 'endpoints.agents',
value: { eventDriven: { deadLetterRetentionDays: 1 }, recursionLimit: 20 },
},
{ fieldPath: 'rateLimits.fileUploads.ipMax', value: 1 },
],
{ getAppConfig, writeConfigDocument },
);
const stdio = await patch([{ fieldPath: 'mcpServers.local.title', value: 'Local' }], {
getAppConfig,
writeConfigDocument,
});
const stored = storedConfig(
{ rateLimits: { fileUploads: { ipMax: 1 } }, mcpServers: { local: { title: 'Local' } } },
['filters'],
);
const read = mockRes();
await createHandlers({
getAppConfig,
findConfigByPrincipal: jest.fn(async (_type: PrincipalType, id: string) =>
id === 'r1' ? stored : null,
),
}).getConfig(mockReq({ params: { principalType: 'role', principalId: 'r1' } }), read);
const invalid = await write('patchConfigField', {
params: { principalType: 'nobody', principalId: 'r1' },
body: { entries: [] },
});
const summarize = (list: unknown) =>
(list as Array<{ path: string; reason?: string; kind?: string }>)
.map(({ path, reason, kind }) => [kind, path, reason].filter(Boolean).join(':'))
.sort();
return (
written.statusCode === 200 &&
JSON.stringify(summarize(written.body?.applied)) ===
JSON.stringify(['endpoints.agents', 'interface']) &&
JSON.stringify(summarize(written.body?.skipped)) ===
JSON.stringify([
'endpoints.agents.eventDriven:deployment_only_path',
'interface.prompts:interface_permission',
'rateLimits.fileUploads.ipMax:deployment_only_path',
]) &&
JSON.stringify(writeConfigDocument.mock.calls[0]?.[2].overrides) ===
JSON.stringify({
interface: { modelSelect: true },
endpoints: { agents: { recursionLimit: 20 } },
}) &&
stdio.statusCode === 400 &&
stdio.body?.code === 'PROCESS_MCP_SERVER_OVERRIDE' &&
writeConfigDocument.mock.calls.length === 1 &&
read.body?.ignoredBasis === 'base' &&
JSON.stringify(summarize(read.body?.ignored)) ===
JSON.stringify([
'override:mcpServers.local:process_mcp_server',
'override:rateLimits:deployment_only_path',
'tombstone:filters:base_only_section',
]) &&
invalid.statusCode === 400 &&
invalid.body?.code === 'INVALID_PRINCIPAL_TYPE'
);
},
async issueParams() {
const res = await patch([
{ fieldPath: 'endpoints.agents.recursionLimit', value: 0 },
{ fieldPath: 'endpoints.allowedAddresses', value: ['localhost'] },
]);
const issues = [...((res.body?.issues as Array<{ path: string }>) ?? [])].sort((a, b) =>
a.path.localeCompare(b.path),
);
return (
res.statusCode === 400 &&
JSON.stringify(issues) ===
JSON.stringify([
{
path: 'endpoints.agents.recursionLimit',
segments: ['endpoints', 'agents', 'recursionLimit'],
code: 'too_small',
params: { minimum: 1, inclusive: true, exact: false, type: 'number' },
},
{
path: 'endpoints.allowedAddresses.0',
segments: ['endpoints', 'allowedAddresses', '0'],
code: 'custom',
params: { reason: 'missing_port' },
},
])
);
},
async adminTermsExempt() {
const gate = createTermsAcceptanceGate({
getAppConfig: jest.fn().mockResolvedValue({
interfaceConfig: { termsOfService: { modalAcceptance: true } },
}),
});
const passes = async (optedOut: boolean): Promise<boolean> => {
const req = {
method: 'PATCH',
baseUrl: '/api/admin/config',
path: '/role/r1/fields',
user: { id: 'u1', role: 'ADMIN', termsAccepted: false },
} as unknown as Request;
if (optedOut) {
allowBeforeTermsAcceptance(req, mockRes(), jest.fn());
}
const next = jest.fn();
const res = mockRes();
await gate(req, res, next);
return next.mock.calls.length === 1 && res.body === undefined;
};
return (await passes(true)) && !(await passes(false));
},
};
describe('meta feature flags', () => {

View file

@ -5,6 +5,7 @@ import {
PERMISSION_SUB_KEYS,
BASE_ONLY_CONFIG_PATHS,
DATA_PROVIDER_VERSION,
DEPLOYMENT_ONLY_CONFIG_PATHS,
BASE_ONLY_CONFIG_SECTIONS,
PROCESS_MCP_SERVER_FIELDS,
INTERFACE_PERMISSION_FIELDS,
@ -52,6 +53,9 @@ export const ADMIN_CONFIG_FEATURES: Readonly<AdminConfigFeatures> = {
catalogApi: true,
envStatus: true,
reloadRoute: true,
writeReport: true,
issueParams: true,
adminTermsExempt: true,
};
/**
@ -73,6 +77,7 @@ export function buildAdminConfigMeta(limits: AdminConfigMeta['limits']): AdminCo
baseOnlySections: [...BASE_ONLY_CONFIG_SECTIONS],
basePrincipalSections: [...BASE_PRINCIPAL_CONFIG_SECTIONS],
baseOnlyPaths: [...BASE_ONLY_CONFIG_PATHS],
deploymentOnlyPaths: { ...DEPLOYMENT_ONLY_CONFIG_PATHS },
...getConfigMergeRules(),
...getConfigSecretRules(),
processMcpFields: [...PROCESS_MCP_SERVER_FIELDS],

View file

@ -361,6 +361,7 @@ describe('GET /resolved/:principalType/:principalId', () => {
hasAnyConfigReadAccess: async () => false,
});
expect(forbidden.statusCode).toBe(403);
expect(forbidden.body?.code).toBe('FORBIDDEN');
const invalid = await getResolved('tenant', 'x');
expect(invalid.statusCode).toBe(400);
});
@ -439,6 +440,7 @@ describe('GET /effective?userId=', () => {
hasCapability: async (_user, capability: SystemCapability) => capability === 'read:users',
});
expect(withoutGroups.statusCode).toBe(403);
expect(withoutGroups.body?.code).toBe('FORBIDDEN');
const withoutConfigs = await getEffective(userId, {
hasAnyConfigReadAccess: async () => false,
});

View file

@ -28,6 +28,8 @@ import {
collectConfigSections,
validatePrincipalType,
redactConfigForResponse,
forbiddenResponse,
authRequiredResponse,
principalNotFoundResponse,
filterSectionsByReadAccess,
filterConfigDocForReadAccess,
@ -188,10 +190,10 @@ export function createAdminConfigReadHandlers(deps: AdminConfigReadDeps): {
}
const user = getCapabilityUser(req);
if (!user) {
return res.status(401).json({ error: 'Authentication required' });
return authRequiredResponse(res);
}
if (!(await hasAnyConfigReadAccess(user))) {
return res.status(403).json({ error: 'Insufficient permissions' });
return forbiddenResponse(res);
}
if (!resolveConfigLayers) {
return res.status(501).json({ error: 'Resolved config is not available' });
@ -245,7 +247,7 @@ export function createAdminConfigReadHandlers(deps: AdminConfigReadDeps): {
}
const user = getCapabilityUser(req);
if (!user) {
return res.status(401).json({ error: 'Authentication required' });
return authRequiredResponse(res);
}
const [canReadConfigs, canReadUsers, canReadGroups] = await Promise.all([
hasAnyConfigReadAccess(user),
@ -253,7 +255,7 @@ export function createAdminConfigReadHandlers(deps: AdminConfigReadDeps): {
hasCapability(user, SystemCapabilities.READ_GROUPS),
]);
if (!canReadConfigs || !canReadUsers || !canReadGroups) {
return res.status(403).json({ error: 'Insufficient permissions' });
return forbiddenResponse(res);
}
if (
!resolveConfigLayers ||

View file

@ -3980,7 +3980,7 @@ describe('a document an MCP removal creates', () => {
expect(tombstoned.statusCode).toBe(404);
expect(tombstoned.body).toMatchObject({ code: 'PRINCIPAL_NOT_FOUND' });
expect(unset.statusCode).toBe(404);
expect(unset.body).toEqual({ error: 'Config not found' });
expect(unset.body).toEqual({ error: 'Config not found', code: 'CONFIG_NOT_FOUND' });
expect(await mongoose.models.Config.findOne({ principalId })).toBeNull();
},
);

View file

@ -1,3 +1,4 @@
import { logger } from '@librechat/data-schemas';
import type { TAgentsEndpoint } from 'librechat-data-provider';
import {
resolveStreamLimits,
@ -60,6 +61,36 @@ describe('resolveRecursionLimit', () => {
expect(resolveRecursionLimit(config, { recursion_limit: 30 })).toBe(30);
});
it.each([0, -5, 2.5])('treats a yaml recursionLimit of %s as unset', (recursionLimit) => {
const config = { recursionLimit } as TAgentsEndpoint;
expect(resolveRecursionLimit(config, {})).toBe(50);
expect(resolveRecursionLimit(config, { recursion_limit: 20 })).toBe(20);
});
it.each([0.5, 2.5, -1])('ignores a maxRecursionLimit of %s', (maxRecursionLimit) => {
const config = { recursionLimit: 100, maxRecursionLimit } as TAgentsEndpoint;
expect(resolveRecursionLimit(config, {})).toBe(100);
expect(resolveRecursionLimit(config, { recursion_limit: 200 })).toBe(200);
});
it('ignores a fractional agent.recursion_limit', () => {
const config = { recursionLimit: 100 } as TAgentsEndpoint;
expect(resolveRecursionLimit(config, { recursion_limit: 2.5 })).toBe(100);
});
it('warns once per unusable config value', () => {
const warn = jest.spyOn(logger, 'warn').mockImplementation(() => logger);
const config = { recursionLimit: 0.25, maxRecursionLimit: 0.75 } as TAgentsEndpoint;
resolveRecursionLimit(config, {});
resolveRecursionLimit(config, {});
expect(warn).toHaveBeenCalledTimes(2);
expect(warn.mock.calls.map(([message]) => String(message))).toEqual([
expect.stringContaining('endpoints.agents.recursionLimit: 0.25'),
expect.stringContaining('endpoints.agents.maxRecursionLimit: 0.75'),
]);
warn.mockRestore();
});
it('does not cap when agent.recursion_limit equals maxRecursionLimit', () => {
const config = { recursionLimit: 50, maxRecursionLimit: 150 } as TAgentsEndpoint;
expect(resolveRecursionLimit(config, { recursion_limit: 150 })).toBe(150);

View file

@ -1,3 +1,4 @@
import { logger } from '@librechat/data-schemas';
import {
DEFAULT_AGENT_MODEL_RESPONSE_BODY_TIMEOUT_MS,
DEFAULT_AGENT_MODEL_RESPONSE_HEADERS_TIMEOUT_MS,
@ -32,28 +33,58 @@ export function resolveModelTransportTimeouts(
*/
const SUBAGENT_RECURSION_MULTIPLIER = 3;
/** Whether a recursion limit can bound a run: a whole number of steps, at least one. */
function isStepLimit(value: unknown): value is number {
return typeof value === 'number' && Number.isInteger(value) && value >= 1;
}
/** Config fields already warned about, by field and value, so a bad value warns once. */
const warnedLimits = new Set<string>();
/**
* An `endpoints.agents` recursion field as a step limit, or `undefined` when unset or unusable:
* 0, a negative or a fractional value would make every run fail at once, so it is treated as
* unset (with one warning), as the schema now refuses it.
*/
function readConfigStepLimit(
agentsEConfig: Partial<TAgentsEndpoint> | undefined,
field: 'recursionLimit' | 'maxRecursionLimit',
): number | undefined {
const value = agentsEConfig?.[field];
if (value == null || isStepLimit(value)) {
return value ?? undefined;
}
const key = `${field}:${String(value)}`;
if (!warnedLimits.has(key)) {
warnedLimits.add(key);
logger.warn(
`[resolveRecursionLimit] Ignoring endpoints.agents.${field}: ${String(value)} is not a whole number of at least 1`,
);
}
return undefined;
}
/**
* Resolves the effective recursion limit for an agent run via a 3-step cascade:
* 1. YAML endpoint config default (falls back to 50)
* 2. Per-agent DB override (if set and positive)
* 3. Global max cap from YAML (if set and positive)
* 2. Per-agent DB override (if set to a whole number of at least 1)
* 3. Global max cap from YAML (if set to a whole number of at least 1)
*
* A config value that is not a whole number of at least 1 counts as unset.
*/
export function resolveRecursionLimit(
agentsEConfig: Partial<TAgentsEndpoint> | undefined,
agent: { recursion_limit?: number } | undefined,
): number {
let limit = agentsEConfig?.recursionLimit ?? DEFAULT_RECURSION_LIMIT;
let limit = readConfigStepLimit(agentsEConfig, 'recursionLimit') ?? DEFAULT_RECURSION_LIMIT;
if (typeof agent?.recursion_limit === 'number' && agent.recursion_limit > 0) {
if (isStepLimit(agent?.recursion_limit)) {
limit = agent.recursion_limit;
}
if (
typeof agentsEConfig?.maxRecursionLimit === 'number' &&
agentsEConfig.maxRecursionLimit > 0 &&
limit > agentsEConfig.maxRecursionLimit
) {
limit = agentsEConfig.maxRecursionLimit;
const maxLimit = readConfigStepLimit(agentsEConfig, 'maxRecursionLimit');
if (maxLimit != null && limit > maxLimit) {
limit = maxLimit;
}
return limit;

View file

@ -231,7 +231,7 @@ describe('generateCapabilityCheck', () => {
expect(mockNext).not.toHaveBeenCalled();
expect(statusMock).toHaveBeenCalledWith(403);
expect(jsonMock).toHaveBeenCalledWith({ message: 'Forbidden' });
expect(jsonMock).toHaveBeenCalledWith({ message: 'Forbidden', code: 'FORBIDDEN' });
});
it('returns 401 when no user is present', async () => {
@ -242,7 +242,10 @@ describe('generateCapabilityCheck', () => {
expect(mockNext).not.toHaveBeenCalled();
expect(statusMock).toHaveBeenCalledWith(401);
expect(jsonMock).toHaveBeenCalledWith({ message: 'Authentication required' });
expect(jsonMock).toHaveBeenCalledWith({
message: 'Authentication required',
code: 'AUTH_REQUIRED',
});
});
it('returns 500 on unexpected error', async () => {

View file

@ -279,13 +279,13 @@ export function generateCapabilityCheck(deps: CapabilityDeps): {
return async (req: ServerRequest, res: Response, next: NextFunction) => {
try {
if (!req.user) {
res.status(401).json({ message: 'Authentication required' });
res.status(401).json({ message: 'Authentication required', code: 'AUTH_REQUIRED' });
return;
}
const id = req.user.id ?? req.user._id?.toString();
if (!id) {
res.status(401).json({ message: 'Authentication required' });
res.status(401).json({ message: 'Authentication required', code: 'AUTH_REQUIRED' });
return;
}
@ -305,7 +305,7 @@ export function generateCapabilityCheck(deps: CapabilityDeps): {
`missing-capability:${id}:${capability}`,
`[requireCapability] Forbidden: user ${id} missing capability '${capability}'`,
);
res.status(403).json({ message: 'Forbidden' });
res.status(403).json({ message: 'Forbidden', code: 'FORBIDDEN' });
} catch (err) {
logger.error(`[requireCapability] Error checking capability: ${capability}`, err);
res.status(500).json({ message: 'Internal Server Error' });

View file

@ -1,7 +1,12 @@
import { TERMS_NOT_ACCEPTED_CODE } from 'librechat-data-provider';
import type { NextFunction, Request, Response } from 'express';
import type { AppConfig } from '@librechat/data-schemas';
import { afterTermsGate, createTermsAcceptanceGate, createTermsBlockCheck } from './terms';
import {
afterTermsGate,
createTermsBlockCheck,
createTermsAcceptanceGate,
allowBeforeTermsAcceptance,
} from './terms';
const configWith = (modalAcceptance?: boolean): AppConfig =>
({ interfaceConfig: { termsOfService: { modalAcceptance } } }) as unknown as AppConfig;
@ -166,6 +171,46 @@ describe('createTermsAcceptanceGate', () => {
});
});
describe('allowBeforeTermsAcceptance', () => {
it('lets a router that opts out take writes from a user who has not accepted', async () => {
const req = createRequest('PATCH', '/api/admin/config/role/USER/fields', {
id: 'admin-1',
role: 'ADMIN',
termsAccepted: false,
});
const marked = jest.fn();
allowBeforeTermsAcceptance(req, createResponse(), marked as NextFunction);
expect(marked).toHaveBeenCalledWith();
const { getAppConfig, ...result } = await run(req);
expect(outcome(result)).toBe('allowed');
expect(getAppConfig).not.toHaveBeenCalled();
});
it('holds only inside the router that opted out, not one the request reaches after it', async () => {
const req = createRequest('POST', '/admin/config/role/USER/fields', {
id: 'admin-1',
role: 'ADMIN',
termsAccepted: false,
});
req.baseUrl = '/api/admin/config';
allowBeforeTermsAcceptance(req, createResponse(), jest.fn() as NextFunction);
req.baseUrl = '/api';
expect(outcome(await run(req))).toBe('blocked');
req.baseUrl = '/api/admin/config';
expect(outcome(await run(req))).toBe('allowed');
});
it('keeps every request it did not mark gated, on the same path and any other', async () => {
const user = { id: 'admin-1', role: 'ADMIN', termsAccepted: false };
const sameRoute = createRequest('PATCH', '/api/admin/config/role/USER/fields', user);
const chat = createRequest('POST', '/api/agents/chat/agents', user);
expect(outcome(await run(sameRoute))).toBe('blocked');
expect(outcome(await run(chat))).toBe('blocked');
});
});
describe('createTermsBlockCheck', () => {
const check = (config: AppConfig | undefined) =>
createTermsBlockCheck({ getAppConfig: jest.fn().mockResolvedValue(config) });

View file

@ -28,6 +28,31 @@ const EXEMPT_POSTS = new Set([
'/api/agents/chat/abort',
]);
/**
* Requests whose router opted out of the gate (`allowBeforeTermsAcceptance`), with the mount path
* of that router, so the opt-out holds only while the request is inside it.
*/
const routeOptOuts = new WeakMap<Request, string>();
/**
* The gate's explicit opt-out, mounted ahead of authentication on a router whose requests the
* gate must let through: the admin config API, so an admin who has not accepted the terms can
* still read the config and turn off the setting that asks for them. It marks the request object
* itself, which no client input reaches, rather than matching a path, and only for the router it
* is mounted on: a request that leaves that router unhandled and reaches another is gated there.
* Every other route (end-user routes, and admin routes that start work such as skill sync runs or
* code pairings) stays gated, and the router's own authentication and capability checks still run.
*/
export function allowBeforeTermsAcceptance(req: Request, _res: Response, next: NextFunction): void {
routeOptOuts.set(req, req.baseUrl ?? '');
next();
}
/** Whether the request is inside the router that opted it out of the gate. */
function isOptedOut(req: Request): boolean {
return routeOptOuts.has(req) && routeOptOuts.get(req) === (req.baseUrl ?? '');
}
function isExempt(method: string, pathname: string): boolean {
if (method === 'POST') {
return EXEMPT_POSTS.has(pathname);
@ -59,7 +84,8 @@ export function createTermsBlockCheck(deps: TermsAcceptanceGateDependencies) {
/**
* Enforces `interface.termsOfService.modalAcceptance` on the server: an authenticated user who has
* not accepted the terms may read but not write, so a client that skips the modal cannot start
* chats, uploads or any other processing. Runs after authentication and reads `termsAccepted` from
* chats, uploads or any other processing. A router that mounts `allowBeforeTermsAcceptance`
* opts its requests out. Runs after authentication and reads `termsAccepted` from
* the user document already on the request; the config is resolved only for a user who has not
* accepted and is attempting a write.
*/
@ -70,7 +96,7 @@ export function createTermsAcceptanceGate(
const isBlocked = createTermsBlockCheck(deps);
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
const user = req.user as TermsUser | undefined;
if (SAFE_METHODS.has(req.method) || isExempt(req.method, getPathname(req))) {
if (SAFE_METHODS.has(req.method) || isOptedOut(req) || isExempt(req.method, getPathname(req))) {
next();
return;
}

View file

@ -3,6 +3,10 @@ import type { TEndpointsConfig } from './types';
import {
allowedAddressesSchema,
agentsEndpointSchema,
BASE_ONLY_CONFIG_PATHS,
BASE_ONLY_CONFIG_SECTIONS,
DEPLOYMENT_ONLY_CONFIG_PATHS,
getAllowedAddressEntryIssue,
DEFAULT_RETAINED_ANSWER_TOKENS,
DEFAULT_HISTORY_CACHE_MAX_BYTES,
DEFAULT_MAX_RETAINED_TOOL_COUNT_CHARS,
@ -2093,6 +2097,70 @@ describe('allowedAddressesSchema', () => {
});
});
describe('one issue per refused entry', () => {
it.each([
['', 'empty'],
[' ', 'empty'],
['http://localhost:11434', 'format'],
['10.0.0.0/24', 'format'],
['10.0.0.5 ', 'format'],
['localhost', 'missing_port'],
['10.0.0.5', 'missing_port'],
['localhost:0', 'missing_port'],
['8.8.8.8:53', 'public_ip'],
['[2001:4860:4860::8888]:443', 'public_ip'],
])('reports "%s" once, as %s', (entry, reason) => {
expect(getAllowedAddressEntryIssue(entry)).toBe(reason);
const result = allowedAddressesSchema.safeParse([entry]);
expect(result.success).toBe(false);
if (result.success) {
return;
}
expect(result.error.issues).toHaveLength(1);
expect(result.error.issues[0]).toMatchObject({
code: 'custom',
path: [0],
params: { reason },
});
});
it.each([['localhost:11434'], ['10.0.0.5:11434'], ['[::1]:8080'], ['ollama.internal:443']])(
'accepts "%s" without an issue',
(entry) => {
expect(getAllowedAddressEntryIssue(entry)).toBeNull();
},
);
it('keeps the message of the rule an entry fails', () => {
const messages = ['', 'http://x', 'localhost', '8.8.8.8:53'].map((entry) => {
const result = allowedAddressesSchema.safeParse([entry]);
return result.success ? undefined : result.error.issues[0]?.message;
});
expect(messages).toEqual([
'allowedAddresses entries must be non-empty',
'allowedAddresses entries must be host:port pairs — no URLs, paths, CIDR ranges, or whitespace',
'allowedAddresses entries must include a port, for example localhost:11434 or [::1]:11434',
'allowedAddresses is scoped to private IP space — public IP literals are not permitted (use hostname:port if it resolves to a private IP)',
]);
});
it('reports a bare host in a config section once', () => {
const result = configSchema.safeParse({
version: '1.0',
endpoints: { allowedAddresses: ['localhost'] },
});
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.issues).toEqual([
expect.objectContaining({
path: ['endpoints', 'allowedAddresses', 0],
params: { reason: 'missing_port' },
}),
]);
}
});
});
describe('integration with configSchema', () => {
it('accepts the field on endpoints', () => {
const result = configSchema.safeParse({
@ -3129,3 +3197,69 @@ describe('GitHub comparison configuration', () => {
).toBe(false);
});
});
describe('agent recursion limits', () => {
it.each(['recursionLimit', 'maxRecursionLimit'])(
'%s takes a whole number of at least 1',
(field) => {
for (const value of [1, 50, 500]) {
expect(agentsEndpointSchema.safeParse({ [field]: value }).success).toBe(true);
}
for (const value of [0, -5, 2.5, 0.5]) {
expect(agentsEndpointSchema.safeParse({ [field]: value }).success).toBe(false);
}
expect(agentsEndpointSchema.parse({})[field as 'recursionLimit']).toBeUndefined();
},
);
});
describe('DEPLOYMENT_ONLY_CONFIG_PATHS', () => {
type Node = { _def: { typeName?: string; innerType?: Node; schema?: Node }; shape?: unknown };
/** The object schema beneath optional, default and refinement wrappers. */
function unwrap(node: Node): Node {
let current = node;
while (current._def.innerType ?? current._def.schema) {
current = (current._def.innerType ?? current._def.schema) as Node;
}
return current;
}
function hasSchemaPath(path: string): boolean {
let node: Node | undefined = configSchema as unknown as Node;
for (const segment of path.split('.')) {
const shape: Record<string, Node> | undefined = node
? (unwrap(node).shape as Record<string, Node> | undefined)
: undefined;
node = shape?.[segment];
if (!node) {
return false;
}
}
return true;
}
it('names fields configSchema defines', () => {
const paths = Object.keys(DEPLOYMENT_ONLY_CONFIG_PATHS);
expect(paths.length).toBeGreaterThan(0);
expect(paths.filter((path) => !hasSchemaPath(path))).toEqual([]);
});
it('declares the tool filters deployment-only', () => {
expect(DEPLOYMENT_ONLY_CONFIG_PATHS).toMatchObject({
includedTools: 'operator',
filteredTools: 'operator',
'endpoints.agents.toolApproval.hooks': 'operator',
cache: 'unused',
});
});
it('overlaps neither the base-only sections nor the base-only paths', () => {
const baseOnly = new Set<string>([...BASE_ONLY_CONFIG_SECTIONS, ...BASE_ONLY_CONFIG_PATHS]);
for (const path of Object.keys(DEPLOYMENT_ONLY_CONFIG_PATHS)) {
const segments = path.split('.');
const prefixes = segments.map((_, index) => segments.slice(0, index + 1).join('.'));
expect(prefixes.filter((prefix) => baseOnly.has(prefix))).toEqual([]);
}
});
});

View file

@ -138,6 +138,45 @@ export const BASE_ONLY_CONFIG_PATHS = [
* `endpoints.catalogModelsTtlMs` sets it: the two minutes a provider's model list is cached for. */
export const DEFAULT_CATALOG_MODELS_TTL_MS = 120_000;
/**
* Why a deployment-only path is set in librechat.yaml only:
* - `startup`: read once when the server starts, so a stored value would never apply.
* - `operator`: an operator boundary (signed access, rate limits, permission leases, code
* modules, which tools load), read from librechat.yaml itself.
* - `unused`: nothing reads it any more.
*/
export type DeploymentOnlyConfigReason = 'startup' | 'operator' | 'unused';
/**
* Paths of overridable sections that only librechat.yaml sets, as YAML key paths. No config
* document, Base included, stores them: admin writes skip them, and the merge keeps
* librechat.yaml's value. Unlike `BASE_ONLY_CONFIG_PATHS`, their readers never took a value from
* the merged config (apart from the tool filters, which only gated `ask_user_question` there), so
* a stored override had no effect rather than a dangerous one.
*/
export const DEPLOYMENT_ONLY_CONFIG_PATHS: Readonly<Record<string, DeploymentOnlyConfigReason>> = {
rateLimits: 'operator',
cloudfront: 'operator',
permissions: 'operator',
openapi: 'operator',
skillDeletion: 'startup',
includedTools: 'operator',
filteredTools: 'operator',
'registration.openidDiscovery': 'startup',
'registration.oauthStateTtlMs': 'startup',
'endpoints.agents.subagentActivity': 'startup',
'endpoints.agents.eventDriven': 'startup',
'endpoints.agents.backgroundTasks.shutdownInterruptGraceMs': 'startup',
'endpoints.agents.backgroundTasks.completionResultBatchSize': 'startup',
'endpoints.agents.backgroundTasks.completionReceiptBatching': 'startup',
'endpoints.agents.toolApproval.hooks': 'operator',
'mcpSettings.catalogRecovery.maxStateEntries': 'startup',
'mcpSettings.catalogRecovery.maxDetachedDiscoveries': 'startup',
'mcpSettings.catalogRecovery.authorizationFenceRetryIntervalMs': 'startup',
'mcpSettings.catalogRecovery.authorizationFenceRetryBatchSize': 'startup',
cache: 'unused',
};
export const defaultRetrievalModels = [
'gpt-4o',
'o1-preview-2024-09-12',
@ -314,36 +353,60 @@ function parseAllowedAddressEntry(entry: string): { address: string; port: strin
return { address, port };
}
const allowedAddressEntrySchema = z
.string()
.refine((entry) => entry.length > 0 && entry.trim().length > 0, {
message: 'allowedAddresses entries must be non-empty',
})
.refine((entry) => !entry.includes('://') && !entry.includes('/') && !/\s/.test(entry), {
message:
'allowedAddresses entries must be host:port pairs — no URLs, paths, CIDR ranges, or whitespace',
})
.refine((entry) => parseAllowedAddressEntry(entry) != null, {
message:
'allowedAddresses entries must include a port, for example localhost:11434 or [::1]:11434',
})
.refine(
(entry) => {
const parsed = parseAllowedAddressEntry(entry);
if (!parsed) return false;
const stripped = parsed.address;
const isIPv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.test(stripped);
const isIPv6 = !isIPv4 && stripped.includes(':');
if (!isIPv4 && !isIPv6) {
return true; // hostname — checked at runtime via DNS
}
return isIPv4 ? isPrivateIPv4Literal(stripped) : isPrivateIPv6Literal(stripped);
},
{
message:
'allowedAddresses is scoped to private IP space — public IP literals are not permitted (use hostname:port if it resolves to a private IP)',
},
);
/**
* Why an `allowedAddresses` entry is refused, as the `reason` param of its validation issue:
* - `empty`: the entry is empty or only whitespace.
* - `format`: a URL, path, CIDR range or whitespace instead of a `host:port` pair.
* - `missing_port`: no valid port (`localhost`, `10.0.0.5`).
* - `public_ip`: an IP literal outside private, loopback and link-local space.
*/
export type AllowedAddressIssue = 'empty' | 'format' | 'missing_port' | 'public_ip';
const ALLOWED_ADDRESS_ISSUE_MESSAGES: Readonly<Record<AllowedAddressIssue, string>> = {
empty: 'allowedAddresses entries must be non-empty',
format:
'allowedAddresses entries must be host:port pairs — no URLs, paths, CIDR ranges, or whitespace',
missing_port:
'allowedAddresses entries must include a port, for example localhost:11434 or [::1]:11434',
public_ip:
'allowedAddresses is scoped to private IP space — public IP literals are not permitted (use hostname:port if it resolves to a private IP)',
};
/**
* The first rule an `allowedAddresses` entry fails, checked in the order above, or `null` for an
* entry the schema accepts. A hostname passes: its resolved IP is checked at runtime.
*/
export function getAllowedAddressEntryIssue(entry: string): AllowedAddressIssue | null {
if (entry.trim().length === 0) {
return 'empty';
}
if (entry.includes('://') || entry.includes('/') || /\s/.test(entry)) {
return 'format';
}
const parsed = parseAllowedAddressEntry(entry);
if (!parsed) {
return 'missing_port';
}
const { address } = parsed;
const isIPv4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.test(address);
if (!isIPv4 && !address.includes(':')) {
return null;
}
const isPrivate = isIPv4 ? isPrivateIPv4Literal(address) : isPrivateIPv6Literal(address);
return isPrivate ? null : 'public_ip';
}
/** One issue per refused entry, with its message and `params.reason`. */
const allowedAddressEntrySchema = z.string().superRefine((entry, ctx) => {
const reason = getAllowedAddressEntryIssue(entry);
if (reason) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: ALLOWED_ADDRESS_ISSUE_MESSAGES[reason],
params: { reason },
});
}
});
export const allowedAddressesSchema = z.array(allowedAddressEntrySchema).optional();
@ -1615,7 +1678,8 @@ export const agentsEndpointSchema = baseEndpointSchema
message: 'Use 0 to disable, or at least 1000 ms',
})
.default(DEFAULT_STREAM_KEEPALIVE_INTERVAL_MS),
recursionLimit: z.number().optional(),
/** Graph steps an agent run may take; a run with fewer than 1 cannot take a step. */
recursionLimit: z.number().int().min(1).optional(),
disableBuilder: z.boolean().optional().default(false),
/** Optional workspace guidance acquisition budget, separate from command execution. */
repositoryInstructions: z
@ -1655,7 +1719,8 @@ export const agentsEndpointSchema = baseEndpointSchema
.default({}),
})
.optional(),
maxRecursionLimit: z.number().optional(),
/** Cap on any agent's `recursion_limit` and on `recursionLimit`. */
maxRecursionLimit: z.number().int().min(1).optional(),
/** Max cumulative bytes a single streamed tool call's arguments may reach before the run
* aborts. Defaults to 64 KiB in the agents SDK; `0` disables the guard. */
maxToolCallArgBytes: z.number().optional(),

View file

@ -391,6 +391,23 @@ describe('resolveConfigLayers', () => {
]);
});
it('keeps deployment-only fields at their librechat.yaml value, for writes and tombstones', () => {
const configs = [
role({ cache: false, rateLimits: { fileUploads: { ipMax: 1 } } }),
group({ interface: { customWelcome: 'Hi group' } }, ['cache']),
];
const resolution = resolveConfigLayers(appConfig, configs);
expect(resolution.merged).toEqual(mergeConfigOverrides(appConfig, configs));
expect(resolution.resolved.cache).toBe(true);
expect(resolution.resolved).not.toHaveProperty('rateLimits');
expect(resolution.resolved.interface?.customWelcome).toBe('Hi group');
expect(reasons(ignoredOf(resolution, 0))).toEqual([
['rateLimits', 'deployment_only_path'],
['cache', 'deployment_only_path'],
]);
expect(ignoredOf(resolution, 1)).toEqual([toIgnoredTombstone('cache', 'deployment_only_path')]);
});
it('keeps Azure groups as written and reports groups the Azure clients never read', () => {
const configs = PARITY_CASES.find(([name]) => name.startsWith('Azure groups'))![1]();
const resolution = resolveConfigLayers(appConfig, configs);

View file

@ -1,7 +1,9 @@
import { z } from 'zod';
import {
PermissionTypes,
SearchProviders,
INTERFACE_PERMISSION_FIELDS,
DEPLOYMENT_ONLY_CONFIG_PATHS,
} from 'librechat-data-provider';
import type { TCustomConfig, TWebSearchConfigInput } from 'librechat-data-provider';
import type { AppConfig, IConfig } from '~/types';
@ -21,6 +23,8 @@ import {
getConfigOverrideIssues,
combineFoldedConfigItems,
getIndexedMergeKeyIssues,
getConfigIssueParams,
getIgnoredConfigOverrides,
} from './resolution';
import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
import { toConfigOverrideState } from './mutations';
@ -1269,6 +1273,7 @@ describe('mergeConfigOverrides: invalid stored overrides', () => {
path: 'endpoints.custom.1.baseURL',
segments: ['endpoints', 'custom', '1', 'baseURL'],
code: 'invalid_type',
params: { expected: 'string', received: 'number' },
},
]);
@ -1376,7 +1381,7 @@ describe('mergeConfigOverrides: invalid stored overrides', () => {
});
it('keeps a lower layer that relies on a higher layer for a required field', () => {
const merged = mergeConfigOverrides({} as AppConfig, [
const layers = [
fakeConfig(
{
cloudfront: {
@ -1388,14 +1393,17 @@ describe('mergeConfigOverrides: invalid stored overrides', () => {
10,
),
fakeConfig({ cloudfront: { domain: 'https://cdn.example.com' } }, 20, undefined, 'other'),
]) as unknown as { cloudfront: Record<string, unknown> };
];
expect(merged.cloudfront).toEqual({
expect(resolveRawConfig({}, layers).cloudfront).toEqual({
imageSigning: 'cookies',
cookieDomain: '.example.com',
requireSignedAccess: true,
domain: 'https://cdn.example.com',
});
/** `cloudfront` is deployment-only: the served config keeps librechat.yaml's (none here). */
const merged = mergeConfigOverrides({} as AppConfig, layers) as { cloudfront?: unknown };
expect(merged.cloudfront).toBeUndefined();
});
it('lets a lower-priority valid override survive a higher-priority invalid one', () => {
@ -2046,6 +2054,7 @@ describe('endpoints.custom: names the runtime folds together', () => {
path: 'endpoints.custom.0.models',
segments: ['endpoints', 'custom', '0', 'models'],
code: 'invalid_type',
params: { expected: 'object', received: 'number' },
},
]);
expect(
@ -3423,6 +3432,7 @@ describe('getConfigChangeIssues', () => {
path: 'endpoints.bedrock.inferenceProfiles.eu.a.b',
segments: ['endpoints', 'bedrock', 'inferenceProfiles', 'eu.a.b'],
code: 'invalid_type',
params: { expected: 'string', received: 'number' },
},
]);
});
@ -3515,3 +3525,327 @@ describe('isAcceptedOverrideSection', () => {
}
});
});
describe('issue params', () => {
const firstIssue = (schema: z.ZodTypeAny, value: unknown) => {
const result = schema.safeParse(value);
if (result.success) {
throw new Error('expected a failure');
}
return result.error.issues[0];
};
it('carries the schema side of each failure, never the submitted value', () => {
const issues = getConfigOverrideIssues({
interface: { contextCost: 'no' },
fileStrategy: 'sentinel-fs',
githubCompare: { timeoutMs: 40_000 },
endpoints: { agents: { recursionLimit: 0 }, allowedAddresses: ['localhost'] },
});
const byPath = Object.fromEntries(issues.map(({ path, params }) => [path, params]));
expect(byPath['interface.contextCost']).toEqual({ expected: 'boolean', received: 'string' });
expect(byPath.fileStrategy).toEqual({
options: expect.arrayContaining(['local', 's3']),
});
expect(byPath['githubCompare.timeoutMs']).toEqual({
maximum: 30_000,
inclusive: true,
exact: false,
type: 'number',
});
expect(byPath['endpoints.agents.recursionLimit']).toEqual({
minimum: 1,
inclusive: true,
exact: false,
type: 'number',
});
expect(byPath['endpoints.allowedAddresses.0']).toEqual({ reason: 'missing_port' });
});
it('names the integer expectation of a fractional step limit', () => {
expect(getConfigOverrideIssues({ endpoints: { agents: { maxRecursionLimit: 2.5 } } })).toEqual([
{
path: 'endpoints.agents.maxRecursionLimit',
segments: ['endpoints', 'agents', 'maxRecursionLimit'],
code: 'invalid_type',
params: { expected: 'integer', received: 'float' },
},
]);
});
it('keeps record keys with dots as one segment beside the params', () => {
const [issue] = getConfigOverrideIssues({
endpoints: { bedrock: { inferenceProfiles: { 'us.a.b': 5 } } },
});
expect(issue.segments).toEqual(['endpoints', 'bedrock', 'inferenceProfiles', 'us.a.b']);
expect(issue.params).toEqual({ expected: 'string', received: 'number' });
});
it('leaves params off an issue attributed above the node that failed', () => {
const issues = getConfigOverrideIssues({ modelSpecs: { list: [{ name: 'only-name' }] } });
expect(issues.length).toBeGreaterThan(0);
for (const issue of issues) {
expect(issue.segments).toEqual(['modelSpecs', 'list', '0']);
expect(issue.params).toBeUndefined();
}
});
it('maps each zod issue code through its allowlist', () => {
expect(getConfigIssueParams(firstIssue(z.literal('a'), 'sentinel'))).toEqual({
expected: 'a',
});
expect(getConfigIssueParams(firstIssue(z.string().url(), 'sentinel'))).toEqual({
validation: 'url',
});
expect(getConfigIssueParams(firstIssue(z.string().startsWith('x'), 'sentinel'))).toEqual({
validation: 'startsWith',
});
expect(getConfigIssueParams(firstIssue(z.number().multipleOf(5), 7))).toEqual({
multipleOf: 5,
});
expect(getConfigIssueParams(firstIssue(z.array(z.string()).min(2), ['a']))).toEqual({
minimum: 2,
inclusive: true,
exact: false,
type: 'array',
});
expect(
getConfigIssueParams(firstIssue(z.date().min(new Date(1000)), new Date(5))),
).toMatchObject({ minimum: 1000, type: 'date' });
const union = z.discriminatedUnion('type', [
z.object({ type: z.literal('a') }),
z.object({ type: z.literal('b') }),
]);
expect(getConfigIssueParams(firstIssue(union, { type: 'sentinel' }))).toEqual({
options: ['a', 'b'],
});
expect(
getConfigIssueParams(
firstIssue(
z.string().refine(() => false, { params: { reason: 'not_allowed' } }),
'x',
),
),
).toEqual({ reason: 'not_allowed' });
expect(
getConfigIssueParams(
firstIssue(
z.string().refine(() => false, { params: { reason: 'echoes sentinel value' } }),
'x',
),
),
).toBeUndefined();
expect(
getConfigIssueParams(
firstIssue(
z.string().refine(() => false),
'x',
),
),
).toBeUndefined();
});
it('drops a bigint bound, so the issue still serializes', () => {
const params = getConfigIssueParams(firstIssue(z.bigint().min(BigInt(5)), BigInt(1)));
expect(params).toEqual({ inclusive: true, exact: false, type: 'bigint' });
expect(() => JSON.stringify(params)).not.toThrow();
});
it('never returns a sentinel written into any failing field', () => {
const sentinel = 'sentinel_0f3a9c';
const issues = getConfigOverrideIssues({
interface: { contextCost: sentinel, customWelcome: 5 },
fileStrategy: sentinel,
endpoints: {
allowedAddresses: [sentinel, `http://${sentinel}`, `${sentinel}:0`],
agents: { recursionLimit: sentinel, titleMethod: sentinel },
custom: [{ name: sentinel, baseURL: 5, titleMethod: sentinel }],
},
memory: { agent: { id: 5, provider: sentinel } },
webSearch: { searchProvider: sentinel },
githubCompare: { enabled: sentinel, timeoutMs: sentinel },
[`${sentinel}.section`]: 1,
});
expect(issues.length).toBeGreaterThan(5);
expect(issues.some((issue) => issue.params)).toBe(true);
const leaked = issues.filter(({ code, params }) =>
JSON.stringify({ code, params }).includes(sentinel),
);
expect(leaked).toEqual([]);
});
});
describe('deployment-only paths in the merge', () => {
const yamlValue = (path: string) => `yaml:${path}`;
function at(target: Record<string, unknown>, path: string): unknown {
return path
.split('.')
.reduce<unknown>((node, key) => (node as Record<string, unknown> | undefined)?.[key], target);
}
function put(target: Record<string, unknown>, path: string, value: unknown) {
const keys = path.split('.');
let node = target;
for (const key of keys.slice(0, -1)) {
node[key] = (node[key] as Record<string, unknown> | undefined) ?? {};
node = node[key] as Record<string, unknown>;
}
node[keys[keys.length - 1]] = value;
}
it('keeps librechat.yaml’s value at every deployment-only path, whatever a layer stores', () => {
const base: Record<string, unknown> = { config: {} };
const overrides: Record<string, unknown> = {};
for (const path of Object.keys(DEPLOYMENT_ONLY_CONFIG_PATHS)) {
put(base, path, yamlValue(path));
put(overrides, path, `override:${path}`);
}
const merged = mergeConfigOverrides(base as unknown as AppConfig, [
fakeConfig(overrides, 0, undefined, BASE_CONFIG_PRINCIPAL_ID),
fakeConfig(overrides, 10, undefined, 'editor'),
]) as unknown as Record<string, unknown>;
for (const path of Object.keys(DEPLOYMENT_ONLY_CONFIG_PATHS)) {
expect([path, at(merged, path)]).toEqual([path, yamlValue(path)]);
}
});
it('puts librechat.yaml’s value back below a tombstone of the parent, and hides the rest', () => {
const base = {
config: {},
endpoints: { agents: { eventDriven: { idlePolling: true }, recursionLimit: 20 } },
} as unknown as AppConfig;
const merged = mergeConfigOverrides(base, [fakeConfig({}, 10, ['endpoints.agents'])]) as {
endpoints?: { agents?: Record<string, unknown> };
};
expect(merged.endpoints?.agents).toEqual({ eventDriven: { idlePolling: true } });
});
it('keeps the tool filters librechat.yaml sets, so a profile cannot gate tools', () => {
const base = { config: {}, filteredTools: ['dalle'] } as unknown as AppConfig;
const merged = mergeConfigOverrides(base, [
fakeConfig({ filteredTools: ['ask_user_question'], includedTools: ['calculator'] }, 10),
]);
expect(merged.filteredTools).toEqual(['dalle']);
expect(merged.includedTools).toBeUndefined();
});
});
describe('getIgnoredConfigOverrides', () => {
const yaml = {
endpoints: {
agents: { pullRequests: { provider: 'github' }, eventDriven: { deadLetterRetentionDays: 7 } },
},
mcpServers: {
local: { type: 'stdio', command: 'node', args: ['server.js'] },
remote: { type: 'streamable-http', url: 'https://mcp.example.com' },
},
memory: { agent: { id: 'agent_1' } },
} as unknown as Partial<TCustomConfig>;
const reasons = (entries: ReturnType<typeof getIgnoredConfigOverrides>) =>
entries.map(({ path, reason, kind }) => `${kind}:${path}:${reason}`).sort();
it('lists every stored part the merge leaves out, by location and reason', () => {
const layer = fakeConfig(
{
paths: { uploads: '/tmp' },
filters: { x: 1 },
langfuse: { publicKey: 'pk' },
interface: {
prompts: false,
mcpServers: { use: false, placeholder: 'p' },
modelSelect: true,
},
mcpServers: { local: { title: 'Local' }, remote: { title: 'Remote' } },
endpoints: {
agents: {
pullRequests: { provider: 'gitlab' },
eventDriven: { deadLetterRetentionDays: 30 },
},
},
rateLimits: { fileUploads: { ipMax: 1 } },
githubCompare: { timeoutMs: 40_000 },
},
10,
['config', 'filters', 'langfuse.publicKey', 'mcpServers.local', 'cloudfront'],
'editor',
);
expect(reasons(getIgnoredConfigOverrides(yaml, layer))).toEqual(
[
'override:paths:unknown_section',
'tombstone:config:unknown_section',
'override:filters:base_only_section',
'tombstone:filters:base_only_section',
'override:langfuse:dedicated_section',
'tombstone:langfuse.publicKey:dedicated_section',
'override:interface.prompts:interface_permission',
'override:interface.mcpServers.use:interface_permission',
'override:mcpServers.local:process_mcp_server',
'tombstone:mcpServers.local:process_mcp_server',
'override:endpoints.agents.pullRequests.provider:base_only_path',
'override:endpoints.agents.eventDriven:deployment_only_path',
'override:rateLimits:deployment_only_path',
'tombstone:cloudfront:deployment_only_path',
'override:githubCompare.timeoutMs:invalid',
].sort(),
);
});
it('reports what librechat.yaml keeps below a tombstone, and each stdio server a section tombstone leaves', () => {
const layer = fakeConfig({}, 10, ['endpoints.agents', 'mcpServers'], 'editor');
expect(reasons(getIgnoredConfigOverrides(yaml, layer))).toEqual(
[
'tombstone:endpoints.agents.pullRequests.provider:base_only_path',
'tombstone:endpoints.agents.eventDriven:deployment_only_path',
'tombstone:mcpServers.local:process_mcp_server',
].sort(),
);
});
it('reports the defaults the merge puts back below a tombstone when given the resolved base', () => {
const resolved = {
config: yaml,
mcpSettings: { catalogRecovery: { maxStateEntries: 10_000, discoveryTimeoutMs: 3_000 } },
} as unknown as AppConfig;
const layer = fakeConfig({}, 10, ['mcpSettings'], 'editor');
expect(reasons(getIgnoredConfigOverrides(yaml, layer))).toEqual([]);
expect(reasons(getIgnoredConfigOverrides(yaml, layer, [], resolved))).toEqual([
'tombstone:mcpSettings.catalogRecovery.maxStateEntries:deployment_only_path',
]);
});
it('keeps dedicated sections for Base and reports nothing for a document the merge applies whole', () => {
const base = fakeConfig(
{ langfuse: { publicKey: 'pk' }, interface: { modelSelect: false } },
0,
undefined,
BASE_CONFIG_PRINCIPAL_ID,
);
expect(getIgnoredConfigOverrides(yaml, base)).toEqual([]);
});
it('judges values on the layers below, as the merge does', () => {
const memorySwitch = fakeConfig(
{ memory: { agent: { provider: 'openAI', model: 'gpt-4o' } } },
0,
['memory.agent.id'],
BASE_CONFIG_PRINCIPAL_ID,
);
const layer = fakeConfig({ memory: { agent: { model: 'gpt-4.1' } } }, 10, undefined, 'editor');
expect(reasons(getIgnoredConfigOverrides(yaml, layer))).toEqual([
'override:memory.agent.model:invalid',
]);
expect(getIgnoredConfigOverrides(yaml, layer, [memorySwitch])).toEqual([]);
});
it('does not log the merge warnings it reports', () => {
const warn = jest.spyOn(logger, 'warn');
getIgnoredConfigOverrides(
yaml,
fakeConfig({ paths: {}, githubCompare: { timeoutMs: 40_000 } }, 10, ['config'], 'editor'),
);
expect(warn).not.toHaveBeenCalled();
warn.mockRestore();
});
});

View file

@ -2,6 +2,7 @@ import {
BASE_PRINCIPAL_CONFIG_SECTIONS,
BASE_ONLY_CONFIG_SECTIONS,
BASE_ONLY_CONFIG_PATHS,
DEPLOYMENT_ONLY_CONFIG_PATHS,
INTERFACE_PERMISSION_FIELDS,
RUNTIME_CONFIG_INTERFACE_FIELDS,
PERMISSION_SUB_KEYS,
@ -13,8 +14,11 @@ import {
import type { TCustomConfig } from 'librechat-data-provider';
import type {
AdminConfigLayerIgnoreReason,
AdminConfigIgnoredOverride,
AdminConfigIgnoreReason,
AdminConfigLayerIgnored,
AdminConfigMergeRules,
ConfigIssueParams,
TWebSearchKeys,
AppConfig,
Config,
@ -28,9 +32,9 @@ import {
resolveAzureGroups,
} from './azure';
import { isBaseConfigPrincipal, sortByConfigPrecedence } from './precedence';
import { parseFieldPath, isDotFreePath, isSegmentPrefix } from './paths';
import { setConfigFields, toConfigOverrideState } from './mutations';
import { webSearchPairedFields, unbindWebSearchKeys } from './web';
import { parseFieldPath, isDotFreePath } from './paths';
import logger from '~/config/winston';
type AnyObject = { [key: string]: unknown };
@ -53,6 +57,40 @@ const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
const BASE_ONLY_OVERRIDE_SECTIONS = new Set<string>(['filters', ...BASE_ONLY_CONFIG_SECTIONS]);
const BASE_PRINCIPAL_OVERRIDE_SECTIONS = new Set<string>(BASE_PRINCIPAL_CONFIG_SECTIONS);
/** A field only librechat.yaml sets, as YAML key segments, and why the merge keeps its value. */
export interface YamlHeldPath {
segments: readonly string[];
reason: Extract<AdminConfigIgnoreReason, 'base_only_path' | 'deployment_only_path'>;
}
/**
* Every field the merge sets back to librechat.yaml's value whatever a layer stores or
* tombstones there: `BASE_ONLY_CONFIG_PATHS`, which per-request code reads from the merged
* config, and `DEPLOYMENT_ONLY_CONFIG_PATHS`, read at startup or from librechat.yaml itself.
*/
export const YAML_HELD_PATHS: readonly YamlHeldPath[] = [
...BASE_ONLY_CONFIG_PATHS.map(
(path): YamlHeldPath => ({ segments: path.split('.'), reason: 'base_only_path' }),
),
...Object.keys(DEPLOYMENT_ONLY_CONFIG_PATHS).map(
(path): YamlHeldPath => ({ segments: path.split('.'), reason: 'deployment_only_path' }),
),
];
/** Told about each stored override or tombstone of `layer` that a fold leaves out. */
type IgnoredSink = (layer: ConfigOverrideLayer, entry: AdminConfigIgnoredOverride) => void;
/** {@link IgnoredSink} bound to the layer being folded. */
type LayerIgnoredSink = (entry: AdminConfigIgnoredOverride) => void;
function toIgnored(
segments: readonly string[],
reason: AdminConfigIgnoreReason,
kind: AdminConfigIgnoredOverride['kind'],
): AdminConfigIgnoredOverride {
return { path: segments.join('.'), segments: [...segments], reason, kind };
}
/** Where the resolved Azure config sits in an AppConfig. */
const AZURE_CONFIG_PATH = `endpoints.${EModelEndpoint.azureOpenAI}`;
@ -344,7 +382,7 @@ export function combineFoldedConfigItems(arrayPath: string, items: unknown[]): u
}
/** `combineFoldedConfigItems` over every folded array of a stored overrides document. */
function combineStoredFoldedItems(overrides: unknown, principal: string): unknown {
function combineStoredFoldedItems(overrides: unknown, principal: string, quiet = false): unknown {
let result = overrides;
for (const arrayPath of Object.keys(MERGE_KEY_FOLDS)) {
const segments = arrayPath.split('.');
@ -356,9 +394,11 @@ function combineStoredFoldedItems(overrides: unknown, principal: string): unknow
if (combined === items) {
continue;
}
logger.warn(
`[mergeConfigOverrides] Combining "${arrayPath}" items that name one entry in different spellings for ${principal}; a write of this list must name each entry once`,
);
if (!quiet) {
logger.warn(
`[mergeConfigOverrides] Combining "${arrayPath}" items that name one entry in different spellings for ${principal}; a write of this list must name each entry once`,
);
}
result = setPath(result, segments, combined);
}
return result;
@ -496,6 +536,12 @@ export type ConfigOverrideIssue = {
* because they can echo the submitted values.
*/
code: string;
/**
* What the schema expected, for a zod issue attributed to the exact node that failed
* (`getConfigIssueParams`); absent when the issue is reported on an ancestor the override
* supplies, where the bound would describe a node the override did not write.
*/
params?: ConfigIssueParams;
};
type IssuePath = Array<string | number>;
@ -518,8 +564,100 @@ export function isAcceptedOverrideSection(key: string): boolean {
return hasOwn(configSchema.shape, key);
}
function toIssue(segments: string[], code: string): ConfigOverrideIssue {
return { path: segments.join('.'), segments, code };
function toIssue(
segments: string[],
code: string,
params?: ConfigIssueParams,
): ConfigOverrideIssue {
return params
? { path: segments.join('.'), segments, code, params }
: { path: segments.join('.'), segments, code };
}
type IssuePrimitive = string | number | boolean | null;
const CUSTOM_REASON = /^[a-z][a-z0-9_]*$/;
function isIssuePrimitive(value: unknown): value is IssuePrimitive {
return (
value === null ||
typeof value === 'string' ||
typeof value === 'boolean' ||
(typeof value === 'number' && Number.isFinite(value))
);
}
/** A numeric bound as JSON can carry it: a date as epoch milliseconds, never a bigint. */
function toIssueNumber(value: unknown): number | undefined {
if (value instanceof Date) {
const time = value.getTime();
return Number.isFinite(time) ? time : undefined;
}
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
}
/** The bound fields of a `too_small` or `too_big` issue, always with `inclusive`, `exact`, `type`. */
function getBoundParams(
bound: 'minimum' | 'maximum',
value: unknown,
issue: { inclusive: boolean; exact?: boolean; type: string },
): ConfigIssueParams {
const number = toIssueNumber(value);
return {
...(number !== undefined && { [bound]: number }),
inclusive: issue.inclusive,
exact: issue.exact ?? false,
type: issue.type,
};
}
/**
* The parts of a zod issue that describe the schema rather than the submitted value, by an
* allowlist per issue code: expected types and literals, accepted options, numeric bounds, the
* failed string check, a multiple, and a refinement's stable `reason`. A value the client sent
* is never copied (no `received` literal or enum value, no message), so the result is safe to
* return. `undefined` when the issue carries none of these.
*/
export function getConfigIssueParams(issue: SchemaIssue): ConfigIssueParams | undefined {
let params: ConfigIssueParams | undefined;
switch (issue.code) {
case 'invalid_type':
params = { expected: String(issue.expected), received: String(issue.received) };
break;
case 'invalid_literal':
params = isIssuePrimitive(issue.expected) ? { expected: issue.expected } : undefined;
break;
case 'invalid_enum_value':
case 'invalid_union_discriminator':
params = { options: (issue.options as unknown[]).filter(isIssuePrimitive) };
break;
case 'too_small':
params = getBoundParams('minimum', issue.minimum, issue);
break;
case 'too_big':
params = getBoundParams('maximum', issue.maximum, issue);
break;
case 'invalid_string': {
const { validation } = issue;
params = {
validation: typeof validation === 'string' ? validation : Object.keys(validation)[0],
};
break;
}
case 'not_multiple_of': {
const multipleOf = toIssueNumber(issue.multipleOf);
params = multipleOf !== undefined ? { multipleOf } : undefined;
break;
}
case 'custom': {
const reason: unknown = issue.params?.reason;
params = typeof reason === 'string' && CUSTOM_REASON.test(reason) ? { reason } : undefined;
break;
}
default:
params = undefined;
}
return params && Object.keys(params).length > 0 ? params : undefined;
}
/**
@ -977,7 +1115,11 @@ export function getConfigOverrideIssues(
const result = shape[section as keyof typeof shape].safeParse(merged[section]);
const shapeIssues = findShapeIssues(schema, merged[section], []);
const schemaIssues = result.success ? [] : expandUnionIssues(result.error.issues);
for (const issue of [...shapeIssues, ...schemaIssues]) {
const located: Array<{ issue: ShapeIssue | SchemaIssue; params: boolean }> = [
...shapeIssues.map((issue) => ({ issue, params: false })),
...schemaIssues.map((issue) => ({ issue, params: true })),
];
for (const { issue, params } of located) {
if (issue.code === 'unrecognized_keys') {
continue;
}
@ -994,7 +1136,14 @@ export function getConfigOverrideIssues(
continue;
}
seen.add(path);
issues.push(toIssue(segments, issue.code));
const exact = params && segments.length === issuePath.length;
issues.push(
toIssue(
segments,
issue.code,
exact ? getConfigIssueParams(issue as SchemaIssue) : undefined,
),
);
}
}
return issues;
@ -1215,10 +1364,11 @@ function omitPath(target: unknown, segments: string[]): unknown {
function stripInvalidOverrides(
config: ConfigOverrideLayer,
base: Partial<TCustomConfig>,
sink?: LayerIgnoredSink,
onStripped?: (issue: ConfigOverrideIssue) => void,
): AnyObject {
const principal = `${config.principalType}/${config.principalId}`;
let stripped: unknown = combineStoredFoldedItems(config.overrides, principal);
let stripped: unknown = combineStoredFoldedItems(config.overrides, principal, sink != null);
/**
* Removing a field can make a related field it supplies fail, so check again while
* removals make progress. If they stop, only the sections that still fail are dropped.
@ -1229,16 +1379,26 @@ function stripInvalidOverrides(
return stripped as AnyObject;
}
if (issues.some((issue) => issue.segments.length === 0)) {
logger.warn(`[mergeConfigOverrides] Ignoring malformed overrides document for ${principal}`);
if (sink) {
sink(toIgnored([], 'invalid', 'override'));
} else {
logger.warn(
`[mergeConfigOverrides] Ignoring malformed overrides document for ${principal}`,
);
}
onStripped?.(toIssue([], issues.find((issue) => issue.segments.length === 0)?.code ?? ''));
return {};
}
const before = stripped;
for (let index = issues.length - 1; index >= 0; index--) {
const { path, segments, code } = issues[index];
logger.warn(
`[mergeConfigOverrides] Ignoring invalid override "${path}" for ${principal} (${code})`,
);
if (sink) {
sink(toIgnored(segments, 'invalid', 'override'));
} else {
logger.warn(
`[mergeConfigOverrides] Ignoring invalid override "${path}" for ${principal} (${code})`,
);
}
stripped = omitPath(stripped, segments);
onStripped?.(issues[index]);
}
@ -1252,9 +1412,13 @@ function stripInvalidOverrides(
failing.set(issue.segments[0], issue.code);
}
}
logger.warn(
`[mergeConfigOverrides] Ignoring still-invalid sections ${[...failing.keys()].join(', ')} for ${principal}`,
);
if (sink) {
failing.forEach((_code, section) => sink(toIgnored([section], 'invalid', 'override')));
} else {
logger.warn(
`[mergeConfigOverrides] Ignoring still-invalid sections ${[...failing.keys()].join(', ')} for ${principal}`,
);
}
for (const [section, code] of failing) {
onStripped?.(toIssue([section], code));
}
@ -1263,7 +1427,15 @@ function stripInvalidOverrides(
);
}
function filterMCPServerOverrides(value: unknown, current: unknown): AnyObject {
/**
* A layer's `mcpServers` without the servers `current` (the merged MCP config below it) runs as
* a local process, or that the override would turn into one; `onDropped` is told each name.
*/
function filterMCPServerOverrides(
value: unknown,
current: unknown,
onDropped?: (serverName: string) => void,
): AnyObject {
if (value == null || typeof value !== 'object' || Array.isArray(value)) {
return {};
}
@ -1283,6 +1455,8 @@ function filterMCPServerOverrides(value: unknown, current: unknown): AnyObject {
) {
if (!isProcessMCPServerConfig(currentServer)) {
filtered[serverName] = serverOverride;
} else {
onDropped?.(serverName);
}
continue;
}
@ -1294,6 +1468,8 @@ function filterMCPServerOverrides(value: unknown, current: unknown): AnyObject {
const resolved = deepMerge(baseServer, serverOverride as AnyObject);
if (!isProcessMCPServerConfig(resolved)) {
filtered[serverName] = serverOverride;
} else {
onDropped?.(serverName);
}
}
@ -1457,7 +1633,10 @@ function describePrincipal(config: ConfigOverrideLayer): string {
* checked (or by another writer) and would reach runtime state no override may set, so it is
* dropped here, which neutralizes it without a migration. One warning per document.
*/
function withAcceptedSections(config: ConfigOverrideLayer): ConfigOverrideLayer {
function withAcceptedSections(
config: ConfigOverrideLayer,
sink?: LayerIgnoredSink,
): ConfigOverrideLayer {
const ignored = new Set<string>();
let overrides = config.overrides;
if (isPlainObject(overrides)) {
@ -1467,6 +1646,7 @@ function withAcceptedSections(config: ConfigOverrideLayer): ConfigOverrideLayer
accepted[key] = value;
} else {
ignored.add(key);
sink?.(toIgnored([key], 'unknown_section', 'override'));
}
}
overrides = accepted as Partial<TCustomConfig>;
@ -1482,12 +1662,16 @@ function withAcceptedSections(config: ConfigOverrideLayer): ConfigOverrideLayer
return true;
}
ignored.add(section);
sink?.(toIgnored(path.split('.'), 'unknown_section', 'tombstone'));
return false;
});
}
if (ignored.size === 0) {
return config;
}
if (sink) {
return { ...config, overrides, tombstones };
}
logger.warn(
`[mergeConfigOverrides] Ignoring unknown config sections ${[...ignored].join(', ')} for ${describePrincipal(config)}`,
);
@ -1506,6 +1690,7 @@ function withAcceptedSections(config: ConfigOverrideLayer): ConfigOverrideLayer
function resolveLayerAzureGroups(
endpoints: unknown,
config: ConfigOverrideLayer,
sink?: LayerIgnoredSink,
): AnyObject | null {
if (!isPlainObject(endpoints)) {
return null;
@ -1516,9 +1701,13 @@ function resolveLayerAzureGroups(
}
const resolved = resolveAzureGroups(azure.groups);
if (!resolved.isValid) {
logger.warn(
`[mergeConfigOverrides] Ignoring ${AZURE_CONFIG_PATH}.groups for ${describePrincipal(config)}: ${resolved.errors.join('; ')}`,
);
if (sink) {
sink(toIgnored(AZURE_GROUPS_PATH.split('.'), 'invalid', 'override'));
} else {
logger.warn(
`[mergeConfigOverrides] Ignoring ${AZURE_CONFIG_PATH}.groups for ${describePrincipal(config)}: ${resolved.errors.join('; ')}`,
);
}
return null;
}
const next: AnyObject = { ...azure };
@ -1602,7 +1791,7 @@ interface FoldTracker {
layers: LayerTrack[];
}
function toIgnored(
function toLayerIgnored(
segments: readonly string[],
reason: AdminConfigLayerIgnoreReason,
extra?: Pick<AdminConfigLayerIgnored, 'code' | 'tombstone'>,
@ -1643,13 +1832,13 @@ function startLayerTrack(
if (isPlainObject(layer.overrides)) {
for (const key of Object.keys(layer.overrides)) {
if (!isAcceptedOverrideSection(key)) {
ignored.push(toIgnored([key], 'unknown_section'));
ignored.push(toLayerIgnored([key], 'unknown_section'));
}
}
}
for (const path of Array.isArray(layer.tombstones) ? layer.tombstones : []) {
if (typeof path === 'string' && !isAcceptedOverrideSection(path.split('.')[0])) {
ignored.push(toIgnored(path.split('.'), 'unknown_section', { tombstone: true }));
ignored.push(toLayerIgnored(path.split('.'), 'unknown_section', { tombstone: true }));
}
}
}
@ -1678,6 +1867,52 @@ function getInterfacePermissionRemovals(value: AnyObject): string[][] {
return removed;
}
/**
* Reports what a tombstone leaves in place: a field only librechat.yaml sets, at or below the
* tombstone (the whole tombstone) or below it where the base config has a value the merge puts
* back (`isHeldValueSet`), and the MCP servers librechat.yaml runs as local processes (`merged`
* is the config below the layer).
*/
function reportTombstoneHeld(
path: string,
merged: AnyObject,
isHeldValueSet: (held: YamlHeldPath) => boolean,
sink: LayerIgnoredSink,
): void {
const segments = path.split('.');
for (const held of YAML_HELD_PATHS) {
if (isSegmentPrefix(held.segments, segments)) {
sink(toIgnored(segments, held.reason, 'tombstone'));
} else if (isSegmentPrefix(segments, held.segments) && isHeldValueSet(held)) {
sink(toIgnored(held.segments, held.reason, 'tombstone'));
}
}
const servers = merged.mcpConfig;
if (segments[0] !== 'mcpServers' || !isPlainObject(servers)) {
return;
}
const names = segments.length > 1 ? [segments[1]] : Object.keys(servers);
for (const name of names) {
if (isProcessMCPServerConfig(servers[name])) {
const location = segments.length > 1 ? segments : ['mcpServers', name];
sink(toIgnored(location, 'process_mcp_server', 'tombstone'));
}
}
}
/** What a fold reports beside its result (`foldConfigLayers`). */
interface FoldObservers {
/** Told about each stored override or tombstone a layer's fold leaves out. */
sink?: IgnoredSink;
/**
* For the `sink`: whether the merge puts back a held field below a tombstone; by default,
* whether the initial raw config (librechat.yaml) sets it.
*/
isHeldValueSet?: (held: YamlHeldPath) => boolean;
/** Keeps the YAML-shaped result and each layer's unapplied parts. */
tracker?: FoldTracker;
}
/**
* Folds override layers, in merge precedence order (`compareConfigPrecedence`), into
* `merged`, the served config, and `raw`, the YAML-shaped config each layer is validated on
@ -1686,23 +1921,30 @@ function getInterfacePermissionRemovals(value: AnyObject): string[][] {
* `groups` resolve into the fields the Azure clients read (`resolveLayerAzureGroups`).
* `webSearchWriters` names the layer behind each paired web search field, by its position in
* that order. `afterLayer` runs after each layer lands, and the next layer folds onto what it
* returns. With a `tracker`, the fold also keeps the YAML-shaped result the served config
* corresponds to, and what of each layer it did not apply (`resolveConfigLayers`).
* returns. With a `sink`, the fold tells it what of each stored layer it leaves out
* (`getIgnoredConfigOverrides`); with a `tracker`, it also keeps the YAML-shaped result the served
* config corresponds to, and what of each layer it did not apply (`resolveConfigLayers`).
*/
function foldConfigLayers<T extends AnyObject>(
initial: T,
initialRaw: Partial<TCustomConfig>,
configs: readonly ConfigOverrideLayer[],
afterLayer?: (step: FoldStep<T>) => T,
tracker?: FoldTracker,
{
sink,
tracker,
isHeldValueSet = (held) => getPath(initialRaw, [...held.segments]) !== undefined,
}: FoldObservers = {},
): { merged: T; raw: Partial<TCustomConfig>; webSearchWriters: WebSearchWriters } {
const sorted = sortByConfigPrecedence(configs);
let merged = initial;
let raw = initialRaw;
const webSearchWriters: WebSearchWriters = new Map();
for (let order = 0; order < sorted.length; order++) {
const config = withAcceptedSections(sorted[order]);
const track = tracker && startLayerTrack(tracker, sorted[order], config);
const source = sorted[order];
const layerSink: LayerIgnoredSink | undefined = sink && ((entry) => sink(source, entry));
const config = withAcceptedSections(source, layerSink);
const track = tracker && startLayerTrack(tracker, source, config);
const below = merged;
let contributed: AnyObject = {};
const removed: string[] = [];
@ -1713,33 +1955,37 @@ function foldConfigLayers<T extends AnyObject>(
if (typeof path !== 'string') {
continue;
}
if (
!isBaseOnlyOverridePath(path) &&
(isBasePrincipal || !BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(path.split('.')[0]))
) {
for (const removedPath of getTombstoneRemovals(path)) {
const mappedPath = remapOverridePath(removedPath);
removed.push(mappedPath);
merged = deleteConfigPath(merged, mappedPath);
raw = deletePath(raw as AnyObject, removedPath) as Partial<TCustomConfig>;
if (tracker) {
tracker.resolved = deleteConfigPath(tracker.resolved, mappedPath);
}
}
if (path === AZURE_GROUPS_PATH) {
merged = withoutAzureGroups(merged);
}
track?.tombstoned.push(path);
recordWebSearchTombstone(webSearchWriters, path, removal);
} else if (track) {
track.ignored.push(
toIgnored(
path.split('.'),
isBaseOnlyOverridePath(path) ? 'base_only_section' : 'base_principal_section',
{ tombstone: true },
),
if (isBaseOnlyOverridePath(path)) {
layerSink?.(toIgnored(path.split('.'), 'base_only_section', 'tombstone'));
track?.ignored.push(
toLayerIgnored(path.split('.'), 'base_only_section', { tombstone: true }),
);
continue;
}
if (!isBasePrincipal && BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(path.split('.')[0])) {
layerSink?.(toIgnored(path.split('.'), 'dedicated_section', 'tombstone'));
track?.ignored.push(
toLayerIgnored(path.split('.'), 'base_principal_section', { tombstone: true }),
);
continue;
}
if (layerSink) {
reportTombstoneHeld(path, merged, isHeldValueSet, layerSink);
}
for (const removedPath of getTombstoneRemovals(path)) {
const mappedPath = remapOverridePath(removedPath);
removed.push(mappedPath);
merged = deleteConfigPath(merged, mappedPath);
raw = deletePath(raw as AnyObject, removedPath) as Partial<TCustomConfig>;
if (tracker) {
tracker.resolved = deleteConfigPath(tracker.resolved, mappedPath);
}
}
if (path === AZURE_GROUPS_PATH) {
merged = withoutAzureGroups(merged);
}
track?.tombstoned.push(path);
recordWebSearchTombstone(webSearchWriters, path, removal);
}
}
@ -1751,35 +1997,39 @@ function foldConfigLayers<T extends AnyObject>(
const valid = stripInvalidOverrides(
config,
raw,
layerSink,
track &&
((issue) =>
track.ignored.push(
toIgnored(issue.segments, 'invalid_override', { code: issue.code }),
toLayerIgnored(issue.segments, 'invalid_override', { code: issue.code }),
)),
);
for (const [key, value] of Object.entries(valid)) {
if (
BASE_ONLY_OVERRIDE_SECTIONS.has(key) ||
(!isBasePrincipal && BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(key))
) {
track?.ignored.push(
toIgnored(
[key],
BASE_ONLY_OVERRIDE_SECTIONS.has(key) ? 'base_only_section' : 'base_principal_section',
),
);
if (BASE_ONLY_OVERRIDE_SECTIONS.has(key)) {
layerSink?.(toIgnored([key], 'base_only_section', 'override'));
track?.ignored.push(toLayerIgnored([key], 'base_only_section'));
continue;
}
if (!isBasePrincipal && BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(key)) {
layerSink?.(toIgnored([key], 'dedicated_section', 'override'));
track?.ignored.push(toLayerIgnored([key], 'base_principal_section'));
continue;
}
applied[key] = value;
const mappedKey = OVERRIDE_KEY_MAP[key as keyof typeof OVERRIDE_KEY_MAP] ?? key;
if (mappedKey === 'mcpConfig') {
remapped[mappedKey] = filterMCPServerOverrides(value, merged[mappedKey]);
remapped[mappedKey] = filterMCPServerOverrides(
value,
merged[mappedKey],
layerSink &&
((name) => layerSink(toIgnored([key, name], 'process_mcp_server', 'override'))),
);
/** A server the filter removed must not complete a later layer's partial of it. */
applied[key] = remapped[mappedKey];
if (track && isPlainObject(value)) {
for (const name of Object.keys(value)) {
if (!hasOwn(remapped[mappedKey] as AnyObject, name)) {
track.ignored.push(toIgnored([key, name], 'process_mcp_server'));
track.ignored.push(toLayerIgnored([key, name], 'process_mcp_server'));
}
}
}
@ -1804,6 +2054,8 @@ function foldConfigLayers<T extends AnyObject>(
for (const [sub, subVal] of Object.entries(fieldVal as AnyObject)) {
if (!PERMISSION_SUB_KEYS.has(sub)) {
uiOnly[sub] = subVal;
} else {
layerSink?.(toIgnored([key, field, sub], 'interface_permission', 'override'));
}
}
if (Object.keys(uiOnly).length > 0) {
@ -1813,22 +2065,26 @@ function foldConfigLayers<T extends AnyObject>(
// Dual-purpose field: the boolean form is a runtime disable, not a
// permission toggle, so preserve it (e.g. schedules: false).
filtered[field] = fieldVal;
} else {
// other boolean permission fields (e.g. runCode: false) are fully stripped
layerSink?.(toIgnored([key, field], 'interface_permission', 'override'));
}
// other boolean permission fields (e.g. runCode: false) are fully stripped
}
if (Object.keys(filtered).length > 0) {
remapped[mappedKey] = filtered;
}
for (const segments of track ? getInterfacePermissionRemovals(value as AnyObject) : []) {
track?.ignored.push(toIgnored(segments, 'interface_permission'));
track?.ignored.push(toLayerIgnored(segments, 'interface_permission'));
}
} else if (key === 'endpoints') {
const resolved = resolveLayerAzureGroups(value, config);
const resolved = resolveLayerAzureGroups(value, config, layerSink);
remapped[mappedKey] = resolved ?? value;
replacesAzureGroups = resolved != null;
writtenEndpoints = value;
if (track && resolved == null && hasAzureGroups(value)) {
track.ignored.push(toIgnored(AZURE_GROUPS_PATH.split('.'), 'azure_groups_unresolved'));
track.ignored.push(
toLayerIgnored(AZURE_GROUPS_PATH.split('.'), 'azure_groups_unresolved'),
);
}
} else {
remapped[mappedKey] = value;
@ -1843,6 +2099,13 @@ function foldConfigLayers<T extends AnyObject>(
}
}
}
if (layerSink) {
for (const held of YAML_HELD_PATHS) {
if (getPath(applied, [...held.segments]) !== undefined) {
layerSink(toIgnored(held.segments, held.reason, 'override'));
}
}
}
merged = deepMerge(merged, remapped);
raw = deepMerge(raw as AnyObject, applied) as Partial<TCustomConfig>;
recordWebSearchWrites(webSearchWriters, applied.webSearch, {
@ -1938,7 +2201,7 @@ function replayAzureServed(tracker: FoldTracker, before: AppConfig, after: AppCo
? getWriters(tracker, segments)
: getWriters(tracker, [...segments, field]);
for (const track of writers) {
track.ignored.push(toIgnored([...segments, field], 'azure_unserved'));
track.ignored.push(toLayerIgnored([...segments, field], 'azure_unserved'));
}
}
}
@ -1967,35 +2230,37 @@ function replayRuntimeStops(tracker: FoldTracker, baseConfig: AppConfig): void {
);
const segments = ['interface', key];
for (const track of getWriters(tracker, ['interfaceConfig', key])) {
track.ignored.push(toIgnored(segments, 'runtime_stop'));
track.ignored.push(toLayerIgnored(segments, 'runtime_stop'));
}
for (const track of getTombstoners(tracker, segments.join('.'), true)) {
track.ignored.push(toIgnored(segments, 'runtime_stop', { tombstone: true }));
track.ignored.push(toLayerIgnored(segments, 'runtime_stop', { tombstone: true }));
}
}
}
/**
* Replays on the YAML-shaped result what {@link preserveBaseOnlyPaths} did to the served config:
* each base-only field keeps the value `librechat.yaml` gives it. A layer is told when it wrote
* one, tombstoned one or anything below it, or tombstoned anything above one `librechat.yaml`
* sets, as write responses tell it (`base_only_path`).
* each field only librechat.yaml sets (`YAML_HELD_PATHS`: base-only and deployment-only) keeps
* the value `librechat.yaml` gives it. A layer is told when it wrote one, tombstoned one or
* anything below it, or tombstoned anything above one `librechat.yaml` sets, as write responses
* tell it (`base_only_path`, `deployment_only_path`).
*/
function replayBaseOnlyPaths(tracker: FoldTracker, baseYaml: Partial<TCustomConfig>): void {
for (const path of BASE_ONLY_CONFIG_PATHS) {
const segments = path.split('.');
const value = getPath(baseYaml, segments);
const writers = getWriters(tracker, segments);
for (const { segments, reason } of YAML_HELD_PATHS) {
const path = segments.join('.');
const appSegments = remapOverridePath(path).split('.');
const value = getPath(baseYaml, [...segments]);
const writers = getWriters(tracker, appSegments);
const tombstoners = getTombstoners(tracker, path, value !== undefined);
if (writers.length === 0 && tombstoners.length === 0) {
continue;
}
setResolved(tracker, segments, value);
setResolved(tracker, appSegments, value);
for (const track of writers) {
track.ignored.push(toIgnored(segments, 'base_only_path'));
track.ignored.push(toLayerIgnored(segments, reason));
}
for (const track of tombstoners) {
track.ignored.push(toIgnored(segments, 'base_only_path', { tombstone: true }));
track.ignored.push(toLayerIgnored(segments, reason, { tombstone: true }));
}
}
}
@ -2038,7 +2303,7 @@ function mergeLayers(
},
});
}),
tracker,
{ tracker },
);
const served = withServedAzureModels(folded.merged, configs);
if (tracker) {
@ -2058,7 +2323,7 @@ function mergeLayers(
setResolved(tracker, ['webSearch', apiKey], bound.webSearch?.[apiKey]);
tracker.layers
.find((track) => track.accepted === layer)
?.ignored.push(toIgnored(['webSearch', apiKey], 'secret_rebinding'));
?.ignored.push(toLayerIgnored(['webSearch', apiKey], 'secret_rebinding'));
}
replayRuntimeStops(tracker, baseConfig);
replayBaseOnlyPaths(tracker, baseConfig.config ?? {});
@ -2138,6 +2403,45 @@ export function resolveRawConfig(
return foldConfigLayers({ mcpConfig: baseYaml.mcpServers ?? null }, baseYaml, configs).raw;
}
/**
* What the merge leaves out of `layer`'s stored overrides and tombstones, each at its own
* location: the parts no merge applies (unknown, base-only and dedicated sections, interface
* permissions, MCP servers librechat.yaml runs as processes), the values it sets back to
* librechat.yaml's (base-only and deployment-only fields), and the values that fail validation
* where it applies them. Judged exactly as the merge folds the layer over `baseYaml`
* (librechat.yaml) and the layers in `below` (those that merge first, such as the active Base),
* through the same steps. A field below a tombstone counts as put back when librechat.yaml sets
* it or `resolved`, the AppConfig librechat.yaml resolves to, holds it (defaults included). Each location is listed once per reason and kind; nothing about a value
* is returned.
*/
export function getIgnoredConfigOverrides(
baseYaml: Partial<TCustomConfig>,
layer: ConfigOverrideLayer,
below: readonly ConfigOverrideLayer[] = [],
resolved?: AppConfig,
): AdminConfigIgnoredOverride[] {
const found = new Map<string, AdminConfigIgnoredOverride>();
foldConfigLayers(
{ mcpConfig: baseYaml.mcpServers ?? null },
baseYaml,
[...below, layer],
undefined,
{
sink: (source, entry) => {
const key = JSON.stringify([entry.kind, entry.reason, entry.segments]);
if (source === layer && !found.has(key)) {
found.set(key, entry);
}
},
isHeldValueSet: (held) =>
getPath(baseYaml, [...held.segments]) !== undefined ||
(resolved != null &&
getPath(resolved, remapOverridePath(held.segments.join('.')).split('.')) !== undefined),
},
);
return [...found.values()];
}
function getPath(target: unknown, segments: string[]): unknown {
let current = target;
for (const segment of segments) {
@ -2148,13 +2452,14 @@ function getPath(target: unknown, segments: string[]): unknown {
}
/**
* Puts back the base value of every `BASE_ONLY_CONFIG_PATHS` field, whatever an override set or a
* tombstone removed on the way, so every reader of the merged config sees the operator's value.
* Puts back the base value of every field only librechat.yaml sets (`YAML_HELD_PATHS`: the
* base-only and deployment-only paths), whatever an override set or a tombstone removed on the
* way, so every reader of the merged config sees the operator's value.
*/
function preserveBaseOnlyPaths<T extends AppConfig>(baseConfig: AppConfig, merged: T): T {
let result: unknown = merged;
for (const path of BASE_ONLY_CONFIG_PATHS) {
const segments = path.split('.');
for (const held of YAML_HELD_PATHS) {
const segments = remapOverridePath(held.segments.join('.')).split('.');
const value = getPath(baseConfig, segments);
if (getPath(result, segments) !== value) result = setPath(result, segments, value);
}

View file

@ -2,6 +2,7 @@ import type {
PrincipalType,
PrincipalModel,
TCustomConfig,
DeploymentOnlyConfigReason,
TConfig,
} from 'librechat-data-provider';
@ -47,10 +48,169 @@ export type AdminConfigResponse = {
config: AdminConfig;
};
/** A write the server had nothing to apply for; `revision` is the stored document's, if any. */
/** A location in a config document: its dotted `path`, and the same location key by key. */
export type AdminConfigLocation = {
path: string;
/** Unambiguous where a record key itself holds a dot (`gpt-4.1`). */
segments: string[];
};
/**
* What a write did with each location it addressed (`writeReport`): stored or removed
* (`applied`), or left alone because the generic config API never stores it there (`skipped`,
* with the reason). A skipped part of a written value is listed at its own location, and the
* rest of the value is stored.
*/
export type AdminConfigWriteReport = {
applied: AdminConfigLocation[];
skipped: Array<AdminConfigLocation & { reason: AdminConfigSkipReason }>;
};
/**
* 200 or 201 from PUT, PATCH `/fields`, POST `/fields/tombstone` and DELETE `/fields`: the
* written document as a read shows it, the write report, and the credentials the document's
* layer drops at merge (`secretRebinding`).
*/
export type AdminConfigWriteResponse = AdminConfigResponse &
AdminConfigWriteReport & {
ignored?: AdminConfigIgnoredSecret[];
};
/**
* A write the server had nothing to apply for; `revision` is the stored document's, if any.
* With `writeReport`, a write whose every location was skipped also carries the report and the
* stored document (`null` when the principal has none).
*/
export type AdminConfigNoopResponse = {
message: string;
revision: string | null;
} & Partial<AdminConfigWriteReport & { config: AdminConfig | null }>;
/**
* A stored override, or tombstone, that the runtime merge leaves out (`writeReport`), at its own
* location. `kind` says which of the document's parts holds it: removing the override (DELETE
* `/fields` at `path`) or the tombstone clears it.
*/
export type AdminConfigIgnoredOverride = AdminConfigLocation & {
reason: AdminConfigIgnoreReason;
kind: 'override' | 'tombstone';
};
/**
* GET `/:principalType/:principalId`. `ignored` lists what the document stores that the merge
* does not apply, judged as the merge applies the document: over librechat.yaml for Base
* (`ignoredBasis: 'yaml'`), and over librechat.yaml and the active Base document for any other
* principal (`ignoredBasis: 'base'`), whose users can hold other profiles in between that change
* the result. Limited to the sections the caller can read. Both are left out together, rather
* than claiming nothing is ignored, when the server cannot judge the document: librechat.yaml
* (the base config) or, for a principal other than Base, the Base document cannot be read, or
* building the report fails. A missing `ignored` means unknown, not empty.
*/
export type AdminConfigReadResponse = AdminConfigResponse & {
ignored?: Array<AdminConfigIgnoredOverride | AdminConfigIgnoredSecret>;
ignoredBasis?: 'yaml' | 'base';
};
/**
* Bounds and options a zod issue names, copied from the schema and never from the submitted
* value, so they are safe to return (`issueParams`). Present only where the issue is attributed
* to the exact node that failed.
*/
export type ConfigIssueParams = {
/** `invalid_type`: the type the schema expects. `invalid_literal`: the literal it expects. */
expected?: string | number | boolean | null;
/** `invalid_type`: the type that was found: a type name, never the value. */
received?: string;
/** `invalid_enum_value`, `invalid_union_discriminator`: the values the schema accepts. */
options?: Array<string | number | boolean | null>;
/** `too_small`: the bound, when it is a number (a date bound in epoch milliseconds). */
minimum?: number;
/** `too_big`: the bound, when it is a number (a date bound in epoch milliseconds). */
maximum?: number;
/** `too_small`, `too_big`: whether the bound itself is allowed. */
inclusive?: boolean;
/** `too_small`, `too_big`: whether the length or size must equal the bound. */
exact?: boolean;
/** `too_small`, `too_big`: what is bounded (`number`, `string`, `array`, `set`, `date`). */
type?: string;
/** `invalid_string`: the check that failed (`url`, `email`, `regex`, `startsWith`, ...). */
validation?: string;
/** `not_multiple_of`: the step the value must be a multiple of. */
multipleOf?: number;
/** `custom`: the stable reason a refinement names (`missing_port`), never its message. */
reason?: string;
};
/** One validation issue as the admin API returns it: a location, a stable code, safe params. */
export type AdminConfigIssue = AdminConfigLocation & {
code: string;
params?: ConfigIssueParams;
};
/**
* 400 `CONFIG_OVERRIDE_INVALID`: the written document fails validation. Messages are never
* returned, because schema messages can echo the submitted values.
*/
export type AdminConfigInvalidResponse = {
error: string;
code: 'CONFIG_OVERRIDE_INVALID';
issues: AdminConfigIssue[];
/** `POST …/changes` only: the batch's skipped report. */
skipped?: AdminConfigChangesResponse['skipped'];
};
/**
* The stable `code` the admin config API's own 4xx responses carry (`writeReport`), beside a
* human-readable `error`: every handler response, the unsafe-key check, and the capability
* middleware, which answers `AUTH_REQUIRED` and `FORBIDDEN` with a `message` instead of
* `error`. Shared layers in front of them answer without a `code`: the session check (401
* `{ message }` for a missing, invalid or expired token; read it as `AUTH_REQUIRED`), body
* parsing (400 for malformed JSON, 413 for an oversized body) and an unmatched route (404
* `Endpoint not found`).
*/
export type AdminConfigErrorCode =
| 'AUTH_REQUIRED'
| 'FORBIDDEN'
| 'FORBIDDEN_SECTION'
| 'INVALID_PRINCIPAL_TYPE'
| 'INVALID_OVERRIDES'
| 'INVALID_FIELD_PATH'
| 'DUPLICATE_FIELD_PATH'
| 'ENTRIES_REQUIRED'
| 'PATCH_TOO_LARGE'
| 'OPS_REQUIRED'
| 'TOO_MANY_OPS'
| 'INVALID_CHANGE'
| 'INVALID_DRY_RUN'
| 'INVALID_PRIORITY'
| 'INVALID_IS_ACTIVE'
| 'INVALID_EXPECTED_REVISION'
| 'PROCESS_MCP_CONFIG'
| 'PROCESS_MCP_SERVER_OVERRIDE'
| 'LANGFUSE_HEADERS_CONFIG'
| 'SECRET_PATH'
| 'UNKNOWN_SECTION'
| 'CONFIG_UNSAFE_KEY'
| 'CONFIG_PATH_INVALID'
| 'CONFIG_ENTRY_INVALID'
| 'CONFIG_RENAME_INVALID'
| 'CONFIG_OVERRIDE_INVALID'
| 'CONFIG_SECRET_REENTRY_REQUIRED'
| 'MCP_API_KEY_REENTRY_REQUIRED'
| 'MCP_OAUTH_SECRET_REENTRY_REQUIRED'
| 'CONFIG_NOT_FOUND'
| 'PRINCIPAL_NOT_FOUND'
| 'CONFIG_VERSION_CONFLICT'
| 'CONFIG_KEY_NOT_STORABLE'
| 'INVALID_PRINCIPAL'
| 'INVALID_USER_ID'
| 'USER_NOT_FOUND'
| 'CONFIG_RELOAD_INVALID';
/** A 4xx of the admin config API. Route-specific fields (`section`, `opIndex`, `reason`, ...) ride beside. */
export type AdminConfigErrorResponse = {
error: string;
code: AdminConfigErrorCode;
};
/** 409: the stored document is not at the `expectedRevision` the write named. */
@ -187,30 +347,58 @@ export type AdminConfigChangesRequest = AdminConfigWritePrecondition & {
};
/**
* Why a change, or part of a `set` value, was not stored. The rest of the batch still applies.
* Why a write, a change, or part of a written value, was not stored. The rest of the request
* still applies, and it answers 200 (owner decision: skip and report, never 400).
* - `base_only_section`: a section only `librechat.yaml` configures (`filters`, …).
* - `base_only_path`: a field of an overridable section only `librechat.yaml` sets
* (`endpoints.agents.pullRequests.provider`, …).
* (`endpoints.agents.pullRequests.provider`, …, `rules.baseOnlyPaths`), Base included.
* - `deployment_only_path`: a field only `librechat.yaml` sets because it is read at startup or
* is an operator boundary (`rateLimits`, `cloudfront`, the tool filters, …,
* `rules.deploymentOnlyPaths`), Base included.
* - `dedicated_section`: a section with its own admin API (`langfuse`).
* - `interface_permission`: an interface field that is a role permission.
* - `process_mcp_server`: a whole-document (PUT) or whole-section (`mcpServers`) write's entry
* for an MCP server `librechat.yaml` runs as a local process, whose configuration overrides
* never change. A write to a path inside such a server is refused instead (400
* `PROCESS_MCP_SERVER_OVERRIDE`).
*
* Removing a stored value (DELETE `/fields`, an `unset` change) is cleanup and is never skipped
* for `base_only_path`, `deployment_only_path` or `process_mcp_server`.
*/
export type AdminConfigSkipReason =
| 'base_only_section'
| 'base_only_path'
| 'deployment_only_path'
| 'dedicated_section'
| 'interface_permission';
| 'interface_permission'
| 'process_mcp_server';
/**
* Why a stored change, or part of one (at its own `segments`), has no effect at runtime.
* - `process_mcp_server`: a `set`, `tombstone` or `rename` addresses an MCP server
* `librechat.yaml` runs as a local process, whose configuration overrides never change, or a
* whole-section `mcpServers` tombstone leaves that server in place. An `unset` there is not
* reported: it asks for the YAML value, which is what runs.
* - `base_only_path`: a `tombstone` above a base-only field `librechat.yaml` sets
* (`endpoints.agents.pullRequests.provider`, …) leaves that field in place and hides only the
* rest.
* Why a stored override, tombstone, change or part of one (at its own `segments`) has no effect
* at runtime. `POST …/changes` reports `process_mcp_server`, `base_only_path` and
* `deployment_only_path` for the changes it applies; GET `/:principalType/:principalId` reports
* every reason for what the document stores.
* - `process_mcp_server`: an override or tombstone of an MCP server `librechat.yaml` runs as a
* local process, whose configuration overrides never change, or each such server a
* whole-section `mcpServers` tombstone leaves in place.
* - `base_only_path`, `deployment_only_path`: a value stored at such a field (the merge keeps
* `librechat.yaml`'s), or a field of either kind `librechat.yaml` sets below a tombstone, which
* the merge puts back so the tombstone hides only the rest.
* - `invalid`: a value that fails validation where the merge applies it, so the value beneath
* stays (stored before validation existed, or valid only over other layers).
* - `unknown_section`: a top-level key `configSchema` does not define (`sectionAllowlist`).
* - `base_only_section`, `dedicated_section`, `interface_permission`: as in
* {@link AdminConfigSkipReason}, for a value or tombstone already stored.
*/
export type AdminConfigIgnoreReason = 'process_mcp_server' | 'base_only_path';
export type AdminConfigIgnoreReason =
| 'process_mcp_server'
| 'base_only_path'
| 'deployment_only_path'
| 'invalid'
| 'unknown_section'
| 'base_only_section'
| 'dedicated_section'
| 'interface_permission';
/**
* A credential the runtime merge leaves out of a document's layer, or a destination it sets back,
@ -283,7 +471,7 @@ export type AdminConfigChangeErrorResponse = {
code: string;
opIndex?: number;
reason?: string;
issues?: Array<{ path: string; segments: string[]; code: string }>;
issues?: AdminConfigIssue[];
skipped?: AdminConfigChangesResponse['skipped'];
};
@ -299,6 +487,8 @@ export type AdminConfigChangeErrorResponse = {
* - `base_principal_section`: a section only the Base document holds (`langfuse`), in another.
* - `base_only_path`: a field only `librechat.yaml` sets (`rules.baseOnlyPaths`); it keeps the
* `librechat.yaml` value.
* - `deployment_only_path`: a field only `librechat.yaml` sets, read at startup or from
* `librechat.yaml` itself (`rules.deploymentOnlyPaths`); it keeps the `librechat.yaml` value.
* - `process_mcp_server`: an MCP server `librechat.yaml` runs as a local process.
* - `interface_permission`: an interface field that is a role permission.
* - `runtime_stop`: an interface feature `librechat.yaml` turns off, which stays off.
@ -320,6 +510,7 @@ export type AdminConfigLayerIgnoreReason =
| 'base_only_section'
| 'base_principal_section'
| 'base_only_path'
| 'deployment_only_path'
| 'process_mcp_server'
| 'interface_permission'
| 'runtime_stop'
@ -335,8 +526,9 @@ export type AdminConfigLayerIgnoreReason =
* Part of a layer the merge does not apply as written. `segments` locate it in librechat.yaml
* keys: in the document's overrides (array items by index), or for a credential or destination
* the merge drops or sets back, as write responses name it (a custom endpoint by its name). A
* tombstone above a `base_only_path` field or a `runtime_stop` feature names that field, which
* the merge keeps while it removes the rest (write responses name a base-only field the same way).
* tombstone above a `base_only_path` or `deployment_only_path` field or a `runtime_stop` feature
* names that field, which the merge keeps while it removes the rest (write responses name such a
* field the same way).
*/
export type AdminConfigLayerIgnored = {
path: string;
@ -712,6 +904,36 @@ export type AdminConfigEnvStatusResponse = {
* restarts. Every reload that runs is audited as `config.reloaded` with `metadata.broadcast`, a
* failed one with outcome `failure` and its `code`. A committed config write still reloads the
* file too, on the next read.
* - `writeReport`: PUT, PATCH `/fields`, POST `/fields/tombstone` and DELETE `/fields` answer with
* `applied` and `skipped` beside `config` (`AdminConfigWriteResponse`), and a write whose every
* location is skipped answers 200 with `message`, `revision`, the stored `config` (or `null`)
* and the report. Skipped (`AdminConfigSkipReason`), Base included: base-only and dedicated
* sections, interface permissions (a whole `interface` value keeps its other fields), base-only
* and deployment-only fields (`rules.baseOnlyPaths`, `rules.deploymentOnlyPaths`; a write above
* one stores the rest of its value, a removal of one is cleanup and applies), and in a PUT or a
* whole `mcpServers` value the servers librechat.yaml runs as local processes. A value cut out
* whole resets its path, in request order among a PATCH's entries. A write, rename
* or tombstone inside such a server answers 400 `PROCESS_MCP_SERVER_OVERRIDE` on PATCH, POST
* `/fields/tombstone` and `/changes` (with `opIndex`); DELETE `/fields` and `unset` stay
* allowed. POST `/fields/tombstone` at an array element or inside one answers 400
* `CONFIG_PATH_INVALID` (`inside_array`), as `/changes` does. The merge keeps librechat.yaml's
* value at every deployment-only field. GET `/:principalType/:principalId` adds `ignored` and
* `ignoredBasis` (`AdminConfigReadResponse`): every stored override or tombstone the merge
* leaves out, with its `kind` and reason, and the credentials it drops (`secret_rebinding`);
* both are left out when the server cannot judge the document. The config API's own 4xx
* responses carry a stable `code` (`AdminConfigErrorCode`); the capability middleware adds
* `AUTH_REQUIRED` and `FORBIDDEN` beside its `message`. The session check's 401 (an invalid
* or expired token) and an unmatched route's 404 carry none.
* - `issueParams`: `CONFIG_OVERRIDE_INVALID` issues carry `params` (`ConfigIssueParams`) where
* the issue is attributed to the exact node that failed: the expected type or literal, the
* accepted options, numeric bounds with `inclusive`, `exact` and `type`, the failed string
* check, the multiple, or a refinement's stable `reason`; never a submitted value or a
* message. Each refused `allowedAddresses` entry is one `custom` issue with `reason` `empty`,
* `format`, `missing_port` or `public_ip`.
* - `adminTermsExempt`: the admin config API (`/api/admin/config`, its reads and writes and
* `POST /reload`) stays open to an admin who has not accepted the terms of service
* (`interface.termsOfService.modalAcceptance`), so they can turn the setting off. Every other
* route, admin routes that start work included, still answers 403 `terms_not_accepted`.
*/
export type AdminConfigFeatureFlag =
| 'dottedKeys'
@ -736,7 +958,10 @@ export type AdminConfigFeatureFlag =
| 'resolvedApi'
| 'catalogApi'
| 'envStatus'
| 'reloadRoute';
| 'reloadRoute'
| 'writeReport'
| 'issueParams'
| 'adminTermsExempt';
export type AdminConfigFeatures = Record<AdminConfigFeatureFlag, boolean>;
@ -786,6 +1011,12 @@ export type AdminConfigRules = AdminConfigMergeRules & {
basePrincipalSections: string[];
/** Fields inside overridable sections that only `librechat.yaml` sets. */
baseOnlyPaths: string[];
/**
* Fields only `librechat.yaml` sets because they are read at startup (`startup`), are an
* operator boundary (`operator`) or are no longer read (`unused`). Writes skip them
* (`deployment_only_path`), Base included, and the merge keeps `librechat.yaml`'s value.
*/
deploymentOnlyPaths: Record<string, DeploymentOnlyConfigReason>;
secretFields: AdminConfigSecretFieldRule[];
arraySecretFields: AdminConfigArraySecretFieldRule[];
/** Secrets of record entries, kept and encrypted per entry like array secrets. */