Skip to content

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

⚛️ feat: Atomic Admin Config Changes Endpoint (set, unset, tombstone, entry upsert/remove/rename) (#17328)

Danny Avila4e0d9145e08a
diff --git a/api/server/routes/__tests__/admin-config-reload.spec.js b/api/server/routes/__tests__/admin-config-reload.spec.js
index f14480f382..8b59bee242 100644
--- a/api/server/routes/__tests__/admin-config-reload.spec.js
+++ b/api/server/routes/__tests__/admin-config-reload.spec.js
@@ -92,6 +92,8 @@ async function served() {
}
describe('admin config writes and librechat.yaml', () => {
+ const batch = { ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'batch' }] };
+
/** Ordered: each write acts on the document the previous one left. */
const writes = [
['PUT a document', 201, (agent) => agent.put(principal).send({ overrides: {}, priority: 10 })],
@@ -114,6 +116,7 @@ describe('admin config writes and librechat.yaml', () => {
(agent) =>
agent.delete(`${principal}/fields`).query({ fieldPath: 'interface.customWelcome' }),
],
+ ['POST a change batch', 200, (agent) => agent.post(`${principal}/changes`).send(batch)],
[
'deactivate the document',
200,
@@ -154,4 +157,18 @@ describe('admin config writes and librechat.yaml', () => {
expect(write.status).toBe(201);
expect(await served()).toEqual([committed + 1, committed + 1]);
});
+
+ it('does not reload for a change batch that leaves the document as it is', async () => {
+ const committed = writes.length + 2;
+ const first = await request(app).post(`${principal}/changes`).send(batch);
+ expect(first.body.written).toBe(true);
+ expect(await served()).toEqual([committed, committed]);
+ writeYaml(committed + 1);
+
+ const repeat = await request(app).post(`${principal}/changes`).send(batch);
+
+ expect(repeat.status).toBe(200);
+ expect(repeat.body.written).toBe(false);
+ expect(await served()).toEqual([committed, committed]);
+ });
});
diff --git a/api/server/routes/admin/config.js b/api/server/routes/admin/config.js
index 398b752e83..652f79ffbc 100644
--- a/api/server/routes/admin/config.js
+++ b/api/server/routes/admin/config.js
@@ -49,6 +49,7 @@ router.put('/:principalType/:principalId', handlers.upsertConfigOverrides);
router.patch('/:principalType/:principalId/fields', handlers.patchConfigField);
router.post('/:principalType/:principalId/fields/tombstone', handlers.tombstoneConfigField);
router.delete('/:principalType/:principalId/fields', handlers.deleteConfigField);
+router.post('/:principalType/:principalId/changes', handlers.applyConfigChanges);
router.delete('/:principalType/:principalId', handlers.deleteConfigOverrides);
router.patch('/:principalType/:principalId/active', handlers.toggleConfig);
diff --git a/api/server/routes/admin/config.test.js b/api/server/routes/admin/config.test.js
index b01eab3d25..fe30dda433 100644
--- a/api/server/routes/admin/config.test.js
+++ b/api/server/routes/admin/config.test.js
@@ -159,6 +159,10 @@ describe('admin config routes', () => {
expect(response.body.metaVersion).toBe(1);
expect(response.body.features.dottedKeys).toBe(true);
- expect(response.body.limits).toEqual({ maxPatchEntries: 100, overrideCacheTtlMs: 15_000 });
+ expect(response.body.limits).toEqual({
+ maxPatchEntries: 100,
+ maxChangeOps: 1000,
+ overrideCacheTtlMs: 15_000,
+ });
});
});
diff --git a/packages/api/src/admin/binding.ts b/packages/api/src/admin/binding.ts
index 96133db111..f8ba0c5849 100644
--- a/packages/api/src/admin/binding.ts
+++ b/packages/api/src/admin/binding.ts
@@ -115,23 +115,38 @@ export function getPatchReentryIssues(
stored: StoredConfigState,
writes: readonly ConfigFieldWrite[],
next: StoredConfigState,
+): SecretReentryIssue[] {
+ if (!writes.some(({ segments }) => segments[0] === WEB_SEARCH)) {
+ return [];
+ }
+ return getBatchReentryIssues(stored, writes, next);
+}
+
+/**
+ * Re-entry issues for a batch of changes, judged on the document the batch
+ * would store. Its sets, unsets and tombstones apply in order, so only the
+ * planned document says which URL a stored key ends up beside; a key the batch
+ * sets counts as entered again.
+ * @param stored - The document before the batch.
+ * @param writes - The values the batch sets, in order.
+ * @param next - The overrides and tombstones the batch would store.
+ */
+export function getBatchReentryIssues(
+ stored: StoredConfigState,
+ writes: readonly ConfigFieldWrite[],
+ next: StoredConfigState,
): SecretReentryIssue[] {
const written = new Set<string>();
- let touched = false;
for (const { segments, value } of writes) {
if (segments[0] !== WEB_SEARCH) {
continue;
}
- touched = true;
if (segments.length === 1) {
Object.keys(getRecord(value) ?? {}).forEach((field) => written.add(field));
} else if (segments.length === 2) {
written.add(segments[1]);
}
}
- if (!touched) {
- return [];
- }
return toReentryIssues(
getWebSearchView(getWebSearch(stored?.overrides), stored?.tombstones),
getWebSearchView(getWebSearch(next?.overrides), next?.tombstones),
diff --git a/packages/api/src/admin/config.changes.integration.spec.ts b/packages/api/src/admin/config.changes.integration.spec.ts
new file mode 100644
index 0000000000..55b8e398b9
--- /dev/null
+++ b/packages/api/src/admin/config.changes.integration.spec.ts
@@ -0,0 +1,1740 @@
+import mongoose from 'mongoose';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import { PrincipalType, PrincipalModel } from 'librechat-data-provider';
+import type { AppConfig, ConfigDraft } 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 AdminConfigDeps = Parameters<typeof import('./config').createAdminConfigHandlers>[0];
+type Secrets = typeof import('./secrets');
+
+interface MockRes {
+ statusCode: number;
+ body: undefined | Record<string, unknown>;
+ status: jest.Mock;
+ json: jest.Mock;
+}
+
+interface ChangesBody {
+ config?: { overrides: Record<string, unknown>; tombstones: string[]; revision: string } | null;
+ revision: string | null;
+ written: boolean;
+ dryRun: boolean;
+ applied: Array<{ opIndex: number; op: string; segments: string[]; key?: string }>;
+ skipped: Array<{ opIndex: number; op: string; segments: string[]; reason: string }>;
+ ignored: Array<{ opIndex: number; op: string; segments: string[]; reason: string }>;
+ unchanged: Array<{ opIndex: number; op: string; segments: string[] }>;
+ error?: string;
+ code?: string;
+ reason?: string;
+ opIndex?: number;
+ issues?: Array<{ path: string; code: string }>;
+ currentRevision?: string | null;
+}
+
+let mongoServer: MongoMemoryServer;
+let methods: Methods;
+let decryptV3: DataSchemas['decryptV3'];
+let secrets: Secrets;
+let createAdminConfigHandlers: typeof import('./config').createAdminConfigHandlers;
+
+/** The deployment's librechat.yaml, which every write is validated on top of. */
+const YAML = {
+ endpoints: {
+ custom: [
+ {
+ name: 'yaml-endpoint',
+ apiKey: '${YAML_KEY}',
+ baseURL: 'https://yaml.example.com/v1',
+ models: { default: ['m'] },
+ },
+ ],
+ },
+ mcpServers: {
+ 'yaml-http': { type: 'streamable-http', url: 'https://mcp.example.com/mcp' },
+ 'yaml-stdio': { command: 'node', args: ['server.js'] },
+ },
+ memory: { agent: { id: 'agent_yaml' } },
+};
+
+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 createDeps(overrides: Partial<AdminConfigDeps> = {}): AdminConfigDeps {
+ return {
+ listAllConfigs: methods.listAllConfigs,
+ findConfigByPrincipal: methods.findConfigByPrincipal,
+ writeConfigDocument: jest.fn(methods.writeConfigDocument),
+ tombstoneConfigField: methods.tombstoneConfigField,
+ unsetConfigField: methods.unsetConfigField,
+ deleteConfig: methods.deleteConfig,
+ toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
+ hasConfigCapability: async () => true,
+ hasAnyConfigReadAccess: async () => true,
+ hasCapability: async () => true,
+ getAppConfig: async () => ({ config: YAML }) as unknown as AppConfig,
+ invalidateConfigCaches: jest.fn(async () => undefined),
+ recordAuditEntry: jest.fn(async () => undefined),
+ ...overrides,
+ };
+}
+
+const raw = () => mongoose.connection.db!.collection('configs');
+
+let counter = 0;
+function nextParams(): { principalType: string; principalId: string } {
+ counter += 1;
+ return { principalType: 'role', principalId: `changes-${counter}` };
+}
+
+async function send(
+ body: Record<string, unknown>,
+ params: { principalType: string; principalId: string },
+ deps: AdminConfigDeps = createDeps(),
+): Promise<{ status: number; body: ChangesBody; deps: AdminConfigDeps }> {
+ const handlers = createAdminConfigHandlers(deps);
+ const res = mockRes();
+ await handlers.applyConfigChanges(mockReq({ params, body }), res);
+ return { status: res.statusCode, body: res.body as unknown as ChangesBody, deps };
+}
+
+async function storedDocument(principalId: string) {
+ return raw().findOne({ principalId });
+}
+
+/** Stores a role document as is, past every API guard, as an older server or another writer might. */
+async function seedDocument(
+ principalId: string,
+ overrides: Record<string, unknown>,
+ tombstones: string[],
+): Promise<void> {
+ const draft: ConfigDraft = {
+ principalModel: PrincipalModel.ROLE,
+ priority: 10,
+ isActive: true,
+ overrides: overrides as ConfigDraft['overrides'],
+ tombstones,
+ };
+ await methods.writeConfigDocument(PrincipalType.ROLE, principalId, draft, 'absent');
+}
+
+async function patchFields(
+ entries: Array<{ fieldPath: string; value: unknown }>,
+ params: { principalType: string; principalId: string },
+): Promise<{ status: number; body: ChangesBody }> {
+ const handlers = createAdminConfigHandlers(createDeps());
+ const res = mockRes();
+ await handlers.patchConfigField(mockReq({ params, body: { entries } }), res);
+ return { status: res.statusCode, body: res.body as unknown as ChangesBody };
+}
+
+const endpoint = (name: string, extra: Record<string, unknown> = {}) => ({
+ name,
+ baseURL: `https://${name}.example.com/v1`,
+ models: { default: ['m'] },
+ ...extra,
+});
+
+/** Booting mongod and importing data-schemas and the handlers can be slow on a busy runner. */
+const LIFECYCLE_TIMEOUT_MS = 180_000;
+
+beforeAll(async () => {
+ const [dataSchemas, handlersModule, secretsModule, server] = await Promise.all([
+ import('@librechat/data-schemas'),
+ import('./config'),
+ import('./secrets'),
+ MongoMemoryServer.create(),
+ ]);
+ mongoServer = server;
+ secrets = secretsModule;
+ ({ decryptV3 } = dataSchemas);
+ ({ 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('POST …/changes: one atomic write', () => {
+ it('applies a mixed batch in order with one compare-and-swap write', async () => {
+ const params = nextParams();
+ await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' },
+ { op: 'set', fieldPath: 'balance.startBalance', value: 5 },
+ { op: 'set', fieldPath: 'mcpServers.mine', value: { type: 'sse', url: 'https://a/sse' } },
+ ],
+ },
+ params,
+ );
+ const before = await storedDocument(params.principalId);
+
+ const { status, body, deps } = await send(
+ {
+ ops: [
+ { op: 'unset', fieldPath: 'balance.startBalance' },
+ { op: 'tombstone', fieldPath: 'memory.agent' },
+ { op: 'rename', fieldPath: 'mcpServers', from: 'mine', to: 'renamed' },
+ { op: 'set', fieldPath: 'mcpServers.renamed.title', value: 'Mine' },
+ { op: 'upsertEntry', fieldPath: 'endpoints.custom', entry: endpoint('own') },
+ ],
+ expectedRevision: `${before!._id.toString()}:${before!.configVersion}`,
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(body.written).toBe(true);
+ expect(body.applied.map((ref) => ref.op)).toEqual([
+ 'unset',
+ 'tombstone',
+ 'rename',
+ 'set',
+ 'upsertEntry',
+ ]);
+ expect(body.applied[4].key).toBe('own');
+ expect(deps.writeConfigDocument).toHaveBeenCalledTimes(1);
+ expect(deps.invalidateConfigCaches).toHaveBeenCalledTimes(1);
+
+ const after = await storedDocument(params.principalId);
+ expect(after!.configVersion).toBe(before!.configVersion + 1);
+ expect(after!.overrides).toEqual({
+ interface: { customWelcome: 'hi' },
+ mcpServers: { renamed: { type: 'sse', url: 'https://a/sse', title: 'Mine' } },
+ endpoints: { custom: [endpoint('own')] },
+ });
+ expect(after!.tombstones).toEqual(['memory.agent']);
+ expect(body.revision).toBe(`${after!._id.toString()}:${after!.configVersion}`);
+ expect(body.config?.revision).toBe(body.revision);
+ });
+
+ it('writes nothing when any change is invalid: a rename plus an invalid title (audit mcp-01)', async () => {
+ const params = nextParams();
+ await send(
+ {
+ ops: [{ op: 'set', fieldPath: 'mcpServers.old', value: { type: 'sse', url: 'https://o' } }],
+ },
+ params,
+ );
+ const before = await storedDocument(params.principalId);
+
+ const { status, body, deps } = await send(
+ {
+ ops: [
+ { op: 'rename', fieldPath: 'mcpServers', from: 'old', to: 'new' },
+ { op: 'set', fieldPath: 'mcpServers.new.title', value: 123 },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(body.code).toBe('CONFIG_OVERRIDE_INVALID');
+ expect(body.issues).toEqual([
+ {
+ path: 'mcpServers.new.title',
+ segments: ['mcpServers', 'new', 'title'],
+ code: 'invalid_type',
+ },
+ ]);
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ expect(await storedDocument(params.principalId)).toEqual(before);
+ });
+
+ it('does not apply a reset when a set in the same batch is invalid (audit providers-03)', async () => {
+ const params = nextParams();
+ await send({ ops: [{ op: 'set', fieldPath: 'balance.startBalance', value: 5 }] }, params);
+ const before = await storedDocument(params.principalId);
+
+ const { status } = await send(
+ {
+ ops: [
+ { op: 'unset', fieldPath: 'balance.startBalance' },
+ { op: 'set', fieldPath: 'balance.refillAmount', value: 'lots' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(await storedDocument(params.principalId)).toEqual(before);
+ });
+
+ it('applies far more than the PATCH limit of 100 entries atomically', async () => {
+ const params = nextParams();
+ const ops = Array.from({ length: 250 }, (_, index) => ({
+ op: 'set',
+ segments: ['endpoints', 'bedrock', 'inferenceProfiles', `us.model-${index}.v1`],
+ value: `arn:aws:bedrock:us-east-1:1:inference-profile/${index}`,
+ }));
+
+ const refused = await send(
+ { ops: [...ops, { op: 'set', fieldPath: 'balance.startBalance', value: 'x' }] },
+ params,
+ );
+ expect(refused.status).toBe(400);
+ expect(await storedDocument(params.principalId)).toBeNull();
+
+ const { status, body } = await send({ ops }, params);
+ expect(status).toBe(200);
+ expect(body.applied).toHaveLength(250);
+ const stored = await methods.findConfigByPrincipal('role' as never, params.principalId);
+ expect(stored!.configVersion).toBe(1);
+ expect(
+ Object.keys(
+ (stored!.overrides as { endpoints: { bedrock: { inferenceProfiles: object } } }).endpoints
+ .bedrock.inferenceProfiles,
+ ),
+ ).toHaveLength(250);
+ });
+
+ it('judges the batch in its end state: tombstone the YAML agent id, set provider and model', async () => {
+ const params = nextParams();
+ const setsOnly = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'memory.agent.provider', value: 'openAI' },
+ { op: 'set', fieldPath: 'memory.agent.model', value: 'gpt-4o' },
+ ],
+ },
+ params,
+ );
+ expect(setsOnly.status).toBe(400);
+
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'tombstone', fieldPath: 'memory.agent.id' },
+ { op: 'set', fieldPath: 'memory.agent.provider', value: 'openAI' },
+ { op: 'set', fieldPath: 'memory.agent.model', value: 'gpt-4o' },
+ ],
+ },
+ params,
+ );
+ expect(status).toBe(200);
+ expect(body.config?.overrides).toEqual({
+ memory: { agent: { provider: 'openAI', model: 'gpt-4o' } },
+ });
+ expect(body.config?.tombstones).toEqual(['memory.agent.id']);
+ });
+});
+
+describe('POST …/changes: secrets', () => {
+ it('keeps a stored secret when a set of its object omits it', async () => {
+ const params = nextParams();
+ await send(
+ {
+ ops: [
+ {
+ op: 'set',
+ fieldPath: 'webSearch',
+ value: { serperApiKey: 'sk-serper-secret-value', searchProvider: 'serper' },
+ },
+ ],
+ },
+ params,
+ );
+ const stored = await storedDocument(params.principalId);
+ const ciphertext = stored!.overrides.webSearch.serperApiKey as string;
+ expect(ciphertext.startsWith('v3:')).toBe(true);
+
+ const { status, body } = await send(
+ {
+ ops: [
+ {
+ op: 'set',
+ fieldPath: 'webSearch',
+ value: {
+ searchProvider: 'serper',
+ serperApiKeyPreview: '...lue',
+ scraperTimeout: 9000,
+ },
+ },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ const after = await storedDocument(params.principalId);
+ expect(after!.overrides.webSearch.serperApiKey).toBe(ciphertext);
+ expect(decryptV3(after!.overrides.webSearch.serperApiKey)).toBe('sk-serper-secret-value');
+ expect(after!.overrides.webSearch.scraperTimeout).toBe(9000);
+ expect(JSON.stringify(body)).not.toContain('sk-serper-secret-value');
+ expect(JSON.stringify(body)).not.toContain(ciphertext);
+ });
+
+ it('encrypts an entry key, keeps it through a rename and an edit, and never needs it again', async () => {
+ const params = nextParams();
+ const created = await send(
+ {
+ ops: [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('old', { apiKey: 'sk-endpoint-secret-0001' }),
+ },
+ ],
+ },
+ params,
+ );
+ expect(created.status).toBe(200);
+ const stored = await storedDocument(params.principalId);
+ const [storedEntry] = stored!.overrides.endpoints.custom;
+ expect(storedEntry.apiKey.startsWith('v3:')).toBe(true);
+ expect(storedEntry.apiKeyPreview).toBe('...0001');
+
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'rename', fieldPath: 'endpoints.custom', from: 'old', to: 'new' },
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('new', { baseURL: 'https://new.example.com/v2' }),
+ },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ const [entry] = (await storedDocument(params.principalId))!.overrides.endpoints.custom;
+ expect(entry).toEqual({
+ ...endpoint('new', { baseURL: 'https://new.example.com/v2' }),
+ apiKey: storedEntry.apiKey,
+ apiKeyPreview: '...0001',
+ });
+ expect(secrets.resolveCustomEndpointSecrets(entry).apiKey).toBe('sk-endpoint-secret-0001');
+ const returned = (body.config?.overrides.endpoints as { custom: object[] }).custom[0];
+ expect(returned).not.toHaveProperty('apiKey');
+ expect(returned).toHaveProperty('apiKeyPreview', '...0001');
+ });
+
+ it('refuses submitted ciphertext and writes under a secret, naming the change', async () => {
+ const params = nextParams();
+
+ const encrypted = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' },
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('x', { apiKey: 'v3:00112233445566778899aabbccddeeff:abcd' }),
+ },
+ ],
+ },
+ params,
+ );
+ expect(encrypted.status).toBe(400);
+ expect(encrypted.body).toMatchObject({ code: 'SECRET_PATH', opIndex: 1 });
+
+ const inside = await send(
+ { ops: [{ op: 'set', fieldPath: 'webSearch.serperApiKey.nested', value: 'x' }] },
+ params,
+ );
+ expect(inside.body).toMatchObject({ code: 'SECRET_PATH', opIndex: 0 });
+
+ const preview = await send(
+ { ops: [{ op: 'unset', fieldPath: 'webSearch.serperApiKeyPreview' }] },
+ params,
+ );
+ expect(preview.body).toMatchObject({ code: 'SECRET_PATH', opIndex: 0 });
+ expect(await storedDocument(params.principalId)).toBeNull();
+ });
+
+ it('removes a secret and its preview together on unset and tombstone', async () => {
+ const params = nextParams();
+ await send(
+ { ops: [{ op: 'set', fieldPath: 'webSearch.serperApiKey', value: 'sk-serper-0123456789' }] },
+ params,
+ );
+ expect(Object.keys((await storedDocument(params.principalId))!.overrides.webSearch)).toEqual([
+ 'serperApiKey',
+ 'serperApiKeyPreview',
+ ]);
+
+ await send({ ops: [{ op: 'tombstone', fieldPath: 'webSearch.serperApiKey' }] }, params);
+
+ const stored = await storedDocument(params.principalId);
+ expect(stored!.overrides).toEqual({});
+ expect(stored!.tombstones).toEqual(['webSearch.serperApiKey', 'webSearch.serperApiKeyPreview']);
+ });
+});
+
+describe('POST …/changes: a stored web search key and the URL it is sent to', () => {
+ const URL_FIELD = 'webSearch.searxngInstanceUrl';
+ const KEY_FIELD = 'webSearch.searxngApiKey';
+ const REENTRY = {
+ path: URL_FIELD,
+ segments: ['webSearch', 'searxngInstanceUrl'],
+ code: 'secret_reentry_required',
+ secretPath: KEY_FIELD,
+ };
+
+ async function storeSearxng() {
+ const params = nextParams();
+ const { status } = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: URL_FIELD, value: 'https://search.example.com' },
+ { op: 'set', fieldPath: KEY_FIELD, value: 'searxng-secret-key' },
+ ],
+ },
+ params,
+ );
+ expect(status).toBe(200);
+ return { params, before: await storedDocument(params.principalId) };
+ }
+
+ it.each([
+ ['sets a new URL', [{ op: 'set', fieldPath: URL_FIELD, value: 'https://other.example.com' }]],
+ ['resets the URL to the inherited one', [{ op: 'unset', fieldPath: URL_FIELD }]],
+ ['tombstones the URL', [{ op: 'tombstone', fieldPath: URL_FIELD }]],
+ [
+ 'replaces webSearch without the key',
+ [
+ {
+ op: 'set',
+ fieldPath: 'webSearch',
+ value: { searxngInstanceUrl: 'https://other.example.com' },
+ },
+ ],
+ ],
+ ])('refuses a batch that %s beside the stored key, writing nothing', async (_label, ops) => {
+ const { params, before } = await storeSearxng();
+
+ for (const dryRun of [true, false]) {
+ const { status, body } = await send({ ops, dryRun }, params);
+ expect(status).toBe(400);
+ expect(body).toEqual({
+ error: expect.any(String),
+ code: 'CONFIG_SECRET_REENTRY_REQUIRED',
+ issues: [REENTRY],
+ });
+ }
+ expect(await storedDocument(params.principalId)).toEqual(before);
+ });
+
+ it('stores a new URL entered together with the key', async () => {
+ const { params } = await storeSearxng();
+
+ const { status } = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: URL_FIELD, value: 'https://other.example.com' },
+ { op: 'set', fieldPath: KEY_FIELD, value: 'other-secret-key' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ const after = await storedDocument(params.principalId);
+ expect(after!.overrides.webSearch.searxngInstanceUrl).toBe('https://other.example.com');
+ expect(decryptV3(after!.overrides.webSearch.searxngApiKey)).toBe('other-secret-key');
+ });
+});
+
+describe('POST …/changes: entries librechat.yaml owns', () => {
+ it('refuses to rename a YAML entry or to take its name', async () => {
+ const params = nextParams();
+ await send(
+ {
+ ops: [
+ { op: 'upsertEntry', fieldPath: 'endpoints.custom', entry: endpoint('own') },
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('yaml-endpoint', { baseURL: 'https://yaml.example.com/v1' }),
+ },
+ { op: 'set', fieldPath: 'mcpServers.yaml-http.title', value: 'HTTP' },
+ ],
+ },
+ params,
+ );
+ const before = await storedDocument(params.principalId);
+
+ for (const op of [
+ { op: 'rename', fieldPath: 'endpoints.custom', from: 'yaml-endpoint', to: 'other' },
+ { op: 'rename', fieldPath: 'endpoints.custom', from: 'own', to: 'yaml-endpoint' },
+ { op: 'rename', fieldPath: 'mcpServers', from: 'yaml-http', to: 'other' },
+ ]) {
+ const { status, body } = await send({ ops: [op] }, params);
+ expect(status).toBe(400);
+ expect(body).toMatchObject({
+ code: 'CONFIG_ENTRY_INVALID',
+ reason: 'inherited_entry',
+ opIndex: 0,
+ });
+ }
+ expect(await storedDocument(params.principalId)).toEqual(before);
+ });
+
+ it('lets removeEntry revert an own override of a YAML entry and report a missing one', async () => {
+ const params = nextParams();
+ await send(
+ {
+ ops: [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: { name: 'yaml-endpoint', models: { default: ['override'] } },
+ },
+ ],
+ },
+ params,
+ );
+
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'removeEntry', fieldPath: 'endpoints.custom', key: 'yaml-endpoint' },
+ { op: 'removeEntry', fieldPath: 'endpoints.custom', key: 'never-added' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(body.applied.map((ref) => ref.key)).toEqual(['yaml-endpoint']);
+ expect(body.unchanged.map((ref) => ref.opIndex)).toEqual([1]);
+ expect((await storedDocument(params.principalId))!.overrides).toEqual({});
+ });
+
+ it('removes an entry beside a legacy-invalid one, which it leaves for merge time as before', async () => {
+ const params = nextParams();
+ const legacy = endpoint('legacy', { baseURL: 42 });
+ await seedDocument(
+ params.principalId,
+ {
+ endpoints: {
+ custom: [
+ endpoint('first'),
+ legacy,
+ { baseURL: 'https://keyless.example.com' },
+ endpoint('last'),
+ ],
+ },
+ },
+ [],
+ );
+
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'removeEntry', fieldPath: 'endpoints.custom', key: 'first' },
+ { op: 'removeEntry', fieldPath: 'endpoints.custom', key: 'last' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(body.applied.map((ref) => ref.key)).toEqual(['first', 'last']);
+ expect((await storedDocument(params.principalId))!.overrides).toEqual({
+ endpoints: { custom: [legacy, { baseURL: 'https://keyless.example.com' }] },
+ });
+
+ const invalid = await send(
+ {
+ ops: [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('fresh', { baseURL: 7 }),
+ },
+ ],
+ },
+ params,
+ );
+ expect(invalid.status).toBe(400);
+ expect(invalid.body.issues).toEqual([
+ {
+ path: 'endpoints.custom.2.baseURL',
+ segments: ['endpoints', 'custom', '2', 'baseURL'],
+ code: 'invalid_type',
+ },
+ ]);
+ });
+
+ it('reports writes to a YAML stdio server as applied but ignored at runtime', async () => {
+ const params = nextParams();
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'mcpServers.yaml-stdio.title', value: 'Local' },
+ { op: 'set', fieldPath: 'mcpServers.yaml-http.title', value: 'Remote' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(body.applied).toHaveLength(2);
+ expect(body.ignored).toEqual([
+ {
+ opIndex: 0,
+ op: 'set',
+ segments: ['mcpServers', 'yaml-stdio', 'title'],
+ reason: 'process_mcp_server',
+ },
+ ]);
+ });
+
+ it('reports the YAML stdio servers a whole-section tombstone leaves in place as ignored', async () => {
+ const params = nextParams();
+ const { status, body } = await send(
+ { ops: [{ op: 'tombstone', fieldPath: 'mcpServers' }] },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(body.applied).toEqual([{ opIndex: 0, op: 'tombstone', segments: ['mcpServers'] }]);
+ expect(body.ignored).toEqual([
+ {
+ opIndex: 0,
+ op: 'tombstone',
+ segments: ['mcpServers', 'yaml-stdio'],
+ reason: 'process_mcp_server',
+ },
+ ]);
+ expect((await storedDocument(params.principalId))!.tombstones).toEqual(['mcpServers']);
+ });
+
+ it('reports the base-only fields librechat.yaml sets that a tombstone above them leaves in place', async () => {
+ const params = nextParams();
+ const pullRequests = { provider: 'github', host: 'ghe.example.com', enabled: true };
+ const yaml = { ...YAML, endpoints: { ...YAML.endpoints, agents: { pullRequests } } };
+ const deps = createDeps({
+ getAppConfig: async () => ({ config: yaml }) as unknown as AppConfig,
+ });
+
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'tombstone', fieldPath: 'endpoints.agents' },
+ { op: 'tombstone', fieldPath: 'endpoints.agents.pullRequests.provider' },
+ ],
+ },
+ params,
+ deps,
+ );
+
+ expect(status).toBe(200);
+ expect(body.applied).toEqual([
+ { opIndex: 0, op: 'tombstone', segments: ['endpoints', 'agents'] },
+ ]);
+ expect(body.ignored).toEqual(
+ ['provider', 'host'].map((field) => ({
+ opIndex: 0,
+ op: 'tombstone',
+ segments: ['endpoints', 'agents', 'pullRequests', field],
+ reason: 'base_only_path',
+ })),
+ );
+ expect(body.skipped.map(({ opIndex, reason }) => [opIndex, reason])).toEqual([
+ [1, 'base_only_path'],
+ ]);
+ 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 () => {
+ const params = nextParams();
+ await seedDocument(
+ params.principalId,
+ {
+ mcpServers: {
+ 'yaml-stdio': {
+ title: 'Local',
+ customUserVars: { OLD: { title: 'T', description: 'D' } },
+ },
+ },
+ },
+ [],
+ );
+
+ const { status, body } = await send(
+ {
+ ops: [
+ {
+ op: 'rename',
+ fieldPath: 'mcpServers.yaml-stdio.customUserVars',
+ from: 'OLD',
+ to: 'NEW',
+ },
+ { 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((await storedDocument(params.principalId))!.overrides).toEqual({
+ mcpServers: { 'yaml-stdio': { customUserVars: { NEW: { title: 'T', description: 'D' } } } },
+ });
+ });
+
+ it('refuses process-only MCP fields as PATCH does', async () => {
+ const { status, body } = await send(
+ { ops: [{ op: 'set', fieldPath: 'mcpServers.mine.command', value: 'rm' }] },
+ nextParams(),
+ );
+ expect(status).toBe(400);
+ expect(body).toMatchObject({ code: 'PROCESS_MCP_CONFIG', opIndex: 0 });
+ });
+});
+
+describe('POST …/changes: skipped, not refused (owner decision #2)', () => {
+ it('stores the rest of the batch and reports each skipped change or part with its reason', async () => {
+ const params = nextParams();
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'filters.blockedDomains', value: ['x.com'] },
+ { op: 'set', fieldPath: 'langfuse.publicKey', value: 'pk' },
+ { op: 'set', fieldPath: 'interface.prompts', value: false },
+ {
+ op: 'set',
+ fieldPath: 'interface',
+ value: {
+ modelSelect: false,
+ agents: { use: false, placeholder: 'keep' },
+ bookmarks: false,
+ },
+ },
+ {
+ op: 'set',
+ fieldPath: 'endpoints.agents',
+ value: { disableBuilder: true, pullRequests: { provider: 'github', enabled: true } },
+ },
+ { op: 'tombstone', fieldPath: 'endpoints.agents.pullRequests.host' },
+ { op: 'set', fieldPath: 'endpoints.agents.pullRequests.oauth', value: {} },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(
+ body.skipped.map(({ opIndex, segments, reason }) => [opIndex, segments.join('.'), reason]),
+ ).toEqual([
+ [0, 'filters.blockedDomains', 'base_only_section'],
+ [1, 'langfuse.publicKey', 'dedicated_section'],
+ [2, 'interface.prompts', 'interface_permission'],
+ [3, 'interface.agents.use', 'interface_permission'],
+ [3, 'interface.bookmarks', 'interface_permission'],
+ [4, 'endpoints.agents.pullRequests.provider', 'base_only_path'],
+ [5, 'endpoints.agents.pullRequests.host', 'base_only_path'],
+ [6, 'endpoints.agents.pullRequests.oauth', 'base_only_path'],
+ ]);
+ expect(body.applied.map((ref) => ref.opIndex)).toEqual([3, 4]);
+ const stored = await storedDocument(params.principalId);
+ expect(stored!.overrides).toEqual({
+ interface: { modelSelect: false, agents: { placeholder: 'keep' } },
+ endpoints: { agents: { disableBuilder: true, pullRequests: { enabled: true } } },
+ });
+ expect(stored!.tombstones).toEqual([]);
+ });
+
+ it('replaces what a whole-value set addresses with what is left of it, resetting it when nothing is', async () => {
+ const params = nextParams();
+ const seed = () =>
+ send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' },
+ { op: 'set', fieldPath: 'endpoints.agents.pullRequests.enabled', value: true },
+ ],
+ },
+ params,
+ );
+ const resetOps = [
+ { op: 'set', fieldPath: 'interface', value: { prompts: false } },
+ { op: 'set', fieldPath: 'endpoints.agents.pullRequests', value: { provider: 'github' } },
+ ];
+ await seed();
+
+ const partial = await send(
+ {
+ ops: [{ op: 'set', fieldPath: 'interface', value: { prompts: false, modelSelect: true } }],
+ },
+ params,
+ );
+ expect(partial.body.config?.overrides.interface).toEqual({ modelSelect: true });
+
+ await seed();
+ const { status, body } = await send({ ops: resetOps }, params);
+
+ expect(status).toBe(200);
+ expect(body.applied.map(({ opIndex, op }) => [opIndex, op])).toEqual([
+ [0, 'set'],
+ [1, 'set'],
+ ]);
+ expect(body.skipped.map(({ segments, reason }) => [segments.join('.'), reason])).toEqual([
+ ['interface.prompts', 'interface_permission'],
+ ['endpoints.agents.pullRequests.provider', 'base_only_path'],
+ ]);
+ expect((await storedDocument(params.principalId))!.overrides).toEqual({});
+
+ const again = await send({ ops: resetOps }, params);
+ expect(again.body.written).toBe(false);
+ expect(again.body.unchanged.map((ref) => ref.opIndex)).toEqual([0, 1]);
+ });
+
+ it('answers 200 without writing when every change is skipped', async () => {
+ const params = nextParams();
+ const { status, body, deps } = await send(
+ { ops: [{ op: 'set', fieldPath: 'filters.blockedDomains', value: [] }] },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(body).toMatchObject({ written: false, revision: null, config: null, applied: [] });
+ expect(body.skipped).toHaveLength(1);
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ expect(deps.recordAuditEntry).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST …/changes: no-ops, dry runs and preconditions', () => {
+ it('writes nothing for a batch that changes nothing, keeping the revision', async () => {
+ const params = nextParams();
+ const first = await send(
+ { ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ params,
+ );
+
+ const { status, body, deps } = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' },
+ { op: 'unset', fieldPath: 'balance' },
+ { op: 'removeEntry', fieldPath: 'endpoints.custom', key: 'none' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(body.written).toBe(false);
+ expect(body.unchanged.map((ref) => ref.opIndex)).toEqual([0, 1, 2]);
+ expect(body.revision).toBe(first.body.revision);
+ expect(deps.writeConfigDocument).not.toHaveBeenCalled();
+ expect(deps.invalidateConfigCaches).not.toHaveBeenCalled();
+ });
+
+ it('writes nothing when the changes cancel out, creating no document and keeping a revision', async () => {
+ const absent = nextParams();
+ const created = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' },
+ { op: 'unset', fieldPath: 'interface' },
+ ],
+ },
+ absent,
+ );
+
+ expect(created.status).toBe(200);
+ expect(created.body).toMatchObject({
+ written: false,
+ revision: null,
+ applied: [],
+ ignored: [],
+ });
+ expect(created.body.unchanged.map((ref) => ref.opIndex)).toEqual([0, 1]);
+ expect(await storedDocument(absent.principalId)).toBeNull();
+ expect(created.deps.writeConfigDocument).not.toHaveBeenCalled();
+ expect(created.deps.invalidateConfigCaches).not.toHaveBeenCalled();
+ expect(created.deps.recordAuditEntry).not.toHaveBeenCalled();
+
+ const params = nextParams();
+ const first = await send(
+ { ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ params,
+ );
+ const restored = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'interface', value: { customWelcome: 'bye' } },
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' },
+ ],
+ },
+ params,
+ );
+
+ expect(restored.status).toBe(200);
+ expect(restored.body.written).toBe(false);
+ expect(restored.body.revision).toBe(first.body.revision);
+ expect(restored.deps.writeConfigDocument).not.toHaveBeenCalled();
+ });
+
+ it('validates only what the batch leaves changed, not changes a later one undoes', async () => {
+ const params = nextParams();
+ const balance = { enabled: true, startBalance: 'legacy' };
+ await seedDocument(params.principalId, { balance }, []);
+
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'balance.startBalance', value: 1000 },
+ { op: 'set', fieldPath: 'balance', value: balance },
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(body.written).toBe(true);
+ expect((await storedDocument(params.principalId))!.overrides).toEqual({
+ balance,
+ interface: { customWelcome: 'hi' },
+ });
+
+ const rewritten = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'balance.startBalance', value: 1000 },
+ { op: 'set', fieldPath: 'balance', value: { ...balance, enabled: false } },
+ ],
+ },
+ params,
+ );
+ expect(rewritten.status).toBe(400);
+ expect(rewritten.body.issues).toEqual([
+ { path: 'balance.startBalance', segments: ['balance', 'startBalance'], code: 'invalid_type' },
+ ]);
+ });
+
+ it('finds an entry a later change moves by its key, not by where it was written', async () => {
+ const params = nextParams();
+ const legacy = endpoint('legacy', { baseURL: 42 });
+ await seedDocument(
+ params.principalId,
+ { endpoints: { custom: [endpoint('first'), endpoint('second'), legacy] } },
+ [],
+ );
+
+ const { status, body } = await send(
+ {
+ ops: [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('second', { models: { default: ['n'] } }),
+ },
+ { op: 'removeEntry', fieldPath: 'endpoints.custom', key: 'first' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(body.applied.map((ref) => ref.key)).toEqual(['second', 'first']);
+ expect((await storedDocument(params.principalId))!.overrides).toEqual({
+ endpoints: { custom: [endpoint('second', { models: { default: ['n'] } }), legacy] },
+ });
+ });
+
+ it('validates and reports on a dry run without writing', async () => {
+ const params = nextParams();
+ const valid = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' },
+ { op: 'set', fieldPath: 'filters.blockedDomains', value: [] },
+ ],
+ dryRun: true,
+ },
+ params,
+ );
+ expect(valid.status).toBe(200);
+ expect(valid.body).toMatchObject({ dryRun: true, written: false, revision: null });
+ expect(valid.body).not.toHaveProperty('config');
+ expect(valid.body.applied).toHaveLength(1);
+ expect(valid.body.skipped).toHaveLength(1);
+
+ const invalid = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'filters.blockedDomains', value: [] },
+ { op: 'set', fieldPath: 'balance.startBalance', value: 'x' },
+ ],
+ dryRun: true,
+ },
+ params,
+ );
+ expect(invalid.status).toBe(400);
+ expect(invalid.body).toMatchObject({
+ code: 'CONFIG_OVERRIDE_INVALID',
+ issues: [
+ {
+ path: 'balance.startBalance',
+ segments: ['balance', 'startBalance'],
+ code: 'invalid_type',
+ },
+ ],
+ skipped: [
+ {
+ opIndex: 0,
+ op: 'set',
+ segments: ['filters', 'blockedDomains'],
+ reason: 'base_only_section',
+ },
+ ],
+ });
+ expect(await storedDocument(params.principalId)).toBeNull();
+ });
+
+ it('answers 409 for a stale revision and for a create-only batch on an existing document', async () => {
+ const params = nextParams();
+ const created = await send(
+ { ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'one' }] },
+ params,
+ );
+ await send(
+ { ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'two' }] },
+ params,
+ );
+ const current = (await send({ ops: [{ op: 'unset', fieldPath: 'none' }] }, params)).body
+ .revision;
+
+ const stale = await send(
+ {
+ ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'three' }],
+ expectedRevision: created.body.revision,
+ },
+ params,
+ );
+ expect(stale.status).toBe(409);
+ expect(stale.body).toMatchObject({ code: 'CONFIG_VERSION_CONFLICT', currentRevision: current });
+
+ const createOnly = await send(
+ {
+ ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'three' }],
+ expectedRevision: 'absent',
+ },
+ params,
+ );
+ expect(createOnly.status).toBe(409);
+
+ const malformed = await send(
+ { ops: [{ op: 'unset', fieldPath: 'x' }], expectedRevision: 'nope' },
+ params,
+ );
+ expect(malformed.body.code).toBe('INVALID_EXPECTED_REVISION');
+ expect((await storedDocument(params.principalId))!.overrides.interface.customWelcome).toBe(
+ 'two',
+ );
+ });
+
+ it('absorbs concurrent batches without a revision so neither is lost', async () => {
+ const params = nextParams();
+ await send({ ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'x' }] }, params);
+
+ const results = await Promise.all(
+ ['a', 'b', 'c'].map((key) =>
+ send(
+ { ops: [{ op: 'set', segments: ['mcpServers', key], value: { url: `https://${key}` } }] },
+ params,
+ ),
+ ),
+ );
+
+ expect(results.map((result) => result.status)).toEqual([200, 200, 200]);
+ const stored = await storedDocument(params.principalId);
+ expect(Object.keys(stored!.overrides.mcpServers).sort()).toEqual(['a', 'b', 'c']);
+ expect(stored!.configVersion).toBe(4);
+ });
+
+ it('lets exactly one of two batches at the same revision win', async () => {
+ const params = nextParams();
+ const created = await send(
+ { ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'x' }] },
+ params,
+ );
+
+ const results = await Promise.all(
+ ['a', 'b'].map((value) =>
+ send(
+ {
+ ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value }],
+ expectedRevision: created.body.revision,
+ },
+ params,
+ ),
+ ),
+ );
+
+ expect(results.map((result) => result.status).sort()).toEqual([200, 409]);
+ });
+});
+
+describe('POST …/changes: request checks', () => {
+ it('refuses two changes that address the same path or entry', async () => {
+ const samePath = await send(
+ {
+ ops: [
+ { op: 'unset', fieldPath: 'interface.customWelcome' },
+ { op: 'set', segments: ['interface', 'customWelcome'], value: 'x' },
+ ],
+ },
+ nextParams(),
+ );
+ expect(samePath.body).toMatchObject({ code: 'DUPLICATE_FIELD_PATH', opIndex: 1 });
+
+ const sameEntry = await send(
+ {
+ ops: [
+ { op: 'upsertEntry', fieldPath: 'endpoints.custom', entry: endpoint('a') },
+ { op: 'removeEntry', fieldPath: 'endpoints.custom', key: 'a' },
+ ],
+ },
+ nextParams(),
+ );
+ expect(sameEntry.body).toMatchObject({ code: 'DUPLICATE_FIELD_PATH', opIndex: 1 });
+
+ const otherEntries = await send(
+ {
+ ops: [
+ { op: 'upsertEntry', fieldPath: 'endpoints.custom', entry: endpoint('a') },
+ { op: 'upsertEntry', fieldPath: 'endpoints.custom', entry: endpoint('b') },
+ { op: 'set', fieldPath: 'endpoints.custom', value: [endpoint('c')] },
+ ],
+ },
+ nextParams(),
+ );
+ expect(otherEntries.status).toBe(200);
+ expect(otherEntries.body.config?.overrides).toEqual({ endpoints: { custom: [endpoint('c')] } });
+ });
+
+ it('refuses malformed changes, naming the first one', async () => {
+ const cases: Array<[unknown, string, string?]> = [
+ [{ op: 'replace', fieldPath: 'a' }, 'INVALID_CHANGE'],
+ [null, 'INVALID_CHANGE'],
+ [{ op: 'set', fieldPath: 'interface.customWelcome' }, 'INVALID_CHANGE'],
+ [{ op: 'set', fieldPath: 'a..b', value: 1 }, 'INVALID_FIELD_PATH'],
+ [
+ { op: 'set', segments: ['interface', '$where'], value: 1 },
+ 'CONFIG_PATH_INVALID',
+ 'unsafe_segment',
+ ],
+ [
+ { op: 'tombstone', segments: ['endpoints', 'bedrock', 'inferenceProfiles', 'us.a'] },
+ 'CONFIG_PATH_INVALID',
+ 'dotted_segment',
+ ],
+ [
+ { op: 'upsertEntry', fieldPath: 'modelSpecs.list', entry: { name: 'x' } },
+ 'CONFIG_ENTRY_INVALID',
+ 'not_collection',
+ ],
+ [
+ { op: 'upsertEntry', fieldPath: 'endpoints.custom', entry: { baseURL: 'x' } },
+ 'CONFIG_ENTRY_INVALID',
+ 'invalid_entry',
+ ],
+ [
+ { op: 'removeEntry', fieldPath: 'endpoints.custom' },
+ 'CONFIG_ENTRY_INVALID',
+ 'invalid_entry',
+ ],
+ [
+ { op: 'rename', fieldPath: 'interface', from: 'a', to: 'b' },
+ 'CONFIG_ENTRY_INVALID',
+ 'not_collection',
+ ],
+ [
+ { op: 'rename', fieldPath: 'mcpServers', from: 'a', to: 'b.c' },
+ 'CONFIG_PATH_INVALID',
+ 'dotted_segment',
+ ],
+ [
+ { op: 'rename', fieldPath: 'mcpServers', from: 'a', to: '__proto__' },
+ 'CONFIG_PATH_INVALID',
+ 'unsafe_segment',
+ ],
+ [{ op: 'set', fieldPath: 'paths.uploads', value: '/tmp/x' }, 'UNKNOWN_SECTION'],
+ [{ op: 'set', fieldPath: 'config.version', value: '1.0.0' }, 'UNKNOWN_SECTION'],
+ [{ op: 'set', segments: ['availableTools'], value: {} }, 'UNKNOWN_SECTION'],
+ [{ op: 'tombstone', fieldPath: 'interfaceConfig.customWelcome' }, 'UNKNOWN_SECTION'],
+ [{ op: 'upsertEntry', fieldPath: 'mcpConfig', entry: { name: 'x' } }, 'UNKNOWN_SECTION'],
+ [{ op: 'rename', fieldPath: 'turnstileConfig', from: 'a', to: 'b' }, 'UNKNOWN_SECTION'],
+ [
+ { op: 'tombstone', fieldPath: 'endpoints.custom.0.baseURL' },
+ 'CONFIG_PATH_INVALID',
+ 'inside_array',
+ ],
+ [{ op: 'tombstone', fieldPath: 'endpoints.custom.0' }, 'CONFIG_PATH_INVALID', 'inside_array'],
+ [
+ { op: 'tombstone', fieldPath: 'modelSpecs.list.0.preset' },
+ 'CONFIG_PATH_INVALID',
+ 'inside_array',
+ ],
+ ];
+ for (const [op, code, reason] of cases) {
+ const { status, body } = await send(
+ { ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'ok' }, op] },
+ nextParams(),
+ );
+ expect({ op, status, code: body.code, reason: body.reason, opIndex: body.opIndex }).toEqual({
+ op,
+ status: 400,
+ code,
+ reason,
+ opIndex: 1,
+ });
+ }
+ });
+
+ it('lets unset remove what an older server stored outside configSchema, which nothing else may write', async () => {
+ const params = nextParams();
+ await seedDocument(
+ params.principalId,
+ { paths: { uploads: '/tmp/x' }, interface: { customWelcome: 'hi' } },
+ ['config.version'],
+ );
+
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'unset', fieldPath: 'paths' },
+ { op: 'unset', fieldPath: 'config' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(200);
+ expect(body.applied.map((ref) => ref.opIndex)).toEqual([0, 1]);
+ const stored = await storedDocument(params.principalId);
+ expect(stored!.overrides).toEqual({ interface: { customWelcome: 'hi' } });
+ expect(stored!.tombstones).toEqual([]);
+ });
+
+ it('hides a whole inherited array but refuses a tombstone inside one', async () => {
+ const params = nextParams();
+ const whole = await send({ ops: [{ op: 'tombstone', fieldPath: 'endpoints.custom' }] }, params);
+ expect(whole.status).toBe(200);
+ expect(whole.body.config?.tombstones).toEqual(['endpoints.custom']);
+
+ const inside = await send(
+ { ops: [{ op: 'tombstone', segments: ['mcpServers', 'yaml-stdio', 'args', '0'] }] },
+ params,
+ );
+ expect(inside.body).toMatchObject({
+ code: 'CONFIG_PATH_INVALID',
+ reason: 'inside_array',
+ opIndex: 0,
+ });
+ expect((await storedDocument(params.principalId))!.tombstones).toEqual(['endpoints.custom']);
+ });
+
+ it('refuses a record rename that reaches into a merged-by-key array by position', async () => {
+ const params = nextParams();
+ await send(
+ {
+ ops: [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('own', { headers: { 'X-Old': '1' } }),
+ },
+ ],
+ },
+ params,
+ );
+
+ const { status, body } = await send(
+ {
+ ops: [
+ { op: 'rename', fieldPath: 'endpoints.custom.0.headers', from: 'X-Old', to: 'X-New' },
+ ],
+ },
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(body.issues).toEqual([
+ {
+ path: 'endpoints.custom',
+ segments: ['endpoints', 'custom'],
+ code: 'indexed_merge_key_write',
+ },
+ ]);
+ });
+
+ it('refuses a tombstone with an index below a field configSchema does not define', async () => {
+ const params = nextParams();
+ const { status, body } = await send(
+ { ops: [{ op: 'tombstone', fieldPath: 'interface.futureList.0' }] },
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(body).toMatchObject({ code: 'CONFIG_PATH_INVALID', reason: 'inside_array', opIndex: 0 });
+ expect(await storedDocument(params.principalId)).toBeNull();
+
+ const whole = await send(
+ { ops: [{ op: 'tombstone', fieldPath: 'interface.futureList' }] },
+ params,
+ );
+ expect(whole.status).toBe(200);
+ });
+
+ it('refuses an unset that reaches into a merged-by-key array by position', async () => {
+ const params = nextParams();
+ await send(
+ {
+ ops: [
+ {
+ op: 'upsertEntry',
+ fieldPath: 'endpoints.custom',
+ entry: endpoint('own', { headers: { 'X-Old': '1' } }),
+ },
+ ],
+ },
+ params,
+ );
+ const before = await storedDocument(params.principalId);
+
+ const { status, body } = await send(
+ { ops: [{ op: 'unset', fieldPath: 'endpoints.custom.0.headers' }] },
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(body.issues).toEqual([
+ {
+ path: 'endpoints.custom',
+ segments: ['endpoints', 'custom'],
+ code: 'indexed_merge_key_write',
+ },
+ ]);
+ expect(await storedDocument(params.principalId)).toEqual(before);
+ });
+
+ it('refuses a change the stored document cannot take, writing nothing', async () => {
+ const params = nextParams();
+ await send({ ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' }] }, params);
+ const before = await storedDocument(params.principalId);
+
+ const scalar = await send(
+ { ops: [{ op: 'set', fieldPath: 'interface.customWelcome.nested', value: 1 }] },
+ params,
+ );
+ expect(scalar.body).toMatchObject({
+ code: 'CONFIG_PATH_INVALID',
+ reason: 'scalar_parent',
+ opIndex: 0,
+ });
+
+ const missing = await send(
+ { ops: [{ op: 'rename', fieldPath: 'mcpServers', from: 'ghost', to: 'other' }] },
+ params,
+ );
+ expect(missing.body).toMatchObject({
+ code: 'CONFIG_ENTRY_INVALID',
+ reason: 'entry_not_found',
+ opIndex: 0,
+ });
+ expect(await storedDocument(params.principalId)).toEqual(before);
+ });
+
+ it('bounds the batch size and checks the body fields', async () => {
+ const params = nextParams();
+ const tooMany = Array.from({ length: 1001 }, (_, index) => ({
+ op: 'unset',
+ fieldPath: `x.k${index}`,
+ }));
+ expect((await send({ ops: tooMany }, params)).body.code).toBe('TOO_MANY_OPS');
+ expect((await send({ ops: [] }, params)).body.code).toBe('OPS_REQUIRED');
+ expect((await send({}, params)).body.code).toBe('OPS_REQUIRED');
+ expect(
+ (await send({ ops: [{ op: 'unset', fieldPath: 'x' }], priority: -1 }, params)).body.code,
+ ).toBe('INVALID_PRIORITY');
+ expect(
+ (await send({ ops: [{ op: 'unset', fieldPath: 'x' }], dryRun: 'yes' }, params)).body.code,
+ ).toBe('INVALID_DRY_RUN');
+ expect(
+ (await send({ ops: [{ op: 'unset', fieldPath: 'x' }] }, { ...params, principalType: 'x' }))
+ .body.code,
+ ).toBe('INVALID_PRINCIPAL_TYPE');
+ });
+});
+
+describe('POST …/changes: access', () => {
+ const sectionManager = (sections: string[]) =>
+ createDeps({
+ hasConfigCapability: async (_user, section, verb) =>
+ section != null && sections.includes(section) && verb === 'manage',
+ getReadableConfigSections: async () => ({ broad: false, sections: new Set<string>() }),
+ });
+
+ it('requires manage on every section a batch touches, skipped changes included', async () => {
+ const params = nextParams();
+ const denied = await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' },
+ { op: 'set', fieldPath: 'filters.blockedDomains', value: [] },
+ ],
+ },
+ params,
+ sectionManager(['interface']),
+ );
+
+ expect(denied.status).toBe(403);
+ expect(denied.body).toMatchObject({ code: 'FORBIDDEN_SECTION', section: 'filters' });
+ expect(denied.deps.writeConfigDocument).not.toHaveBeenCalled();
+ });
+
+ it('returns only the sections a section manager can read or just wrote, and keeps the priority', async () => {
+ const params = nextParams();
+ await send(
+ {
+ ops: [{ op: 'set', fieldPath: 'balance.startBalance', value: 5 }],
+ priority: 30,
+ },
+ params,
+ );
+
+ const { status, body } = await send(
+ {
+ ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' }],
+ priority: 99,
+ },
+ params,
+ sectionManager(['interface']),
+ );
+
+ expect(status).toBe(200);
+ expect(body.config?.overrides).toEqual({ interface: { customWelcome: 'hi' } });
+ const stored = await storedDocument(params.principalId);
+ expect(stored!.priority).toBe(30);
+ expect(stored!.overrides.balance).toEqual({ startBalance: 5 });
+ });
+
+ it('lets only a broad manager change __base__ and the priority', async () => {
+ const base = { principalType: 'role', principalId: '__base__' };
+ const denied = await send(
+ { ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'hi' }] },
+ base,
+ sectionManager(['interface']),
+ );
+ expect(denied.status).toBe(403);
+
+ const params = nextParams();
+ await send({ ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'x' }] }, params);
+ const priorityOnly = await send(
+ { ops: [{ op: 'set', fieldPath: 'interface.customWelcome', value: 'x' }], priority: 42 },
+ params,
+ );
+ expect(priorityOnly.body.written).toBe(true);
+ expect((await storedDocument(params.principalId))!.priority).toBe(42);
+ });
+
+ it('creates a document holding only the priority a broad manager sets on an absent principal', async () => {
+ const absent = nextParams();
+ const noop = { ops: [{ op: 'unset', fieldPath: 'interface.missing' }], priority: 42 };
+
+ const dry = await send({ ...noop, dryRun: true }, absent);
+ expect(dry.body).toMatchObject({ written: false, dryRun: true, revision: null });
+ const scoped = await send(noop, absent, sectionManager(['interface']));
+ expect(scoped.body).toMatchObject({ written: false, revision: null });
+ expect(await storedDocument(absent.principalId)).toBeNull();
+
+ const recordAuditEntry = jest.fn(async () => undefined);
+ const created = await send(noop, absent, createDeps({ recordAuditEntry }));
+ expect(created.status).toBe(200);
+ expect(created.body).toMatchObject({
+ written: true,
+ applied: [],
+ unchanged: [{ opIndex: 0, op: 'unset', segments: ['interface', 'missing'] }],
+ });
+ expect(created.body.revision).toEqual(expect.any(String));
+ expect(await storedDocument(absent.principalId)).toMatchObject({
+ priority: 42,
+ overrides: {},
+ tombstones: [],
+ isActive: true,
+ });
+ expect(created.deps.invalidateConfigCaches).toHaveBeenCalledTimes(1);
+ expect(recordAuditEntry).toHaveBeenCalledTimes(1);
+ expect(recordAuditEntry.mock.calls[0]).toMatchObject([
+ { action: 'config.created', metadata: { operation: 'batch', changes: 0, priority: 42 } },
+ ]);
+
+ const repeated = await send(noop, absent);
+ expect(repeated.body).toMatchObject({ written: false, revision: created.body.revision });
+ expect(repeated.deps.writeConfigDocument).not.toHaveBeenCalled();
+ });
+
+ it('records one audit entry naming paths and entries, never values', async () => {
+ const params = nextParams();
+ const recordAuditEntry = jest.fn(async () => undefined);
+ await send(
+ {
+ ops: [
+ { op: 'set', fieldPath: 'webSearch.serperApiKey', value: 'sk-audit-secret-000' },
+ { op: 'upsertEntry', fieldPath: 'endpoints.custom', entry: endpoint('audited') },
+ { op: 'tombstone', fieldPath: 'memory.agent' },
+ { op: 'unset', fieldPath: 'balance.startBalance' },
+ ],
+ },
+ params,
+ createDeps({ recordAuditEntry }),
+ );
+
+ expect(recordAuditEntry).toHaveBeenCalledTimes(1);
+ const [entry] = recordAuditEntry.mock.calls[0] as unknown as [
+ { action: string; metadata: Record<string, unknown> },
+ ];
+ expect(entry.action).toBe('config.created');
+ expect(entry.metadata).toMatchObject({
+ operation: 'batch',
+ changes: 3,
+ set: 'webSearch.serperApiKey',
+ upsertEntry: 'endpoints.custom["audited"]',
+ tombstone: 'memory.agent',
+ });
+ expect(entry.metadata).not.toHaveProperty('unset');
+ expect(JSON.stringify(entry)).not.toContain('sk-audit-secret-000');
+ });
+});
+
+describe('PATCH /fields and POST …/changes: tombstones a write lifts', () => {
+ const AGENT_SWITCH = { fieldPath: 'memory.agent.id', value: 'agent_other' };
+
+ /** A role that hides the YAML agent id and configures its own provider and model instead. */
+ const seedOwnAgent = (params: { principalType: string; principalId: string }) =>
+ send(
+ {
+ ops: [
+ { op: 'tombstone', fieldPath: 'memory.agent.id' },
+ { op: 'set', fieldPath: 'memory.agent.provider', value: 'openAI' },
+ { op: 'set', fieldPath: 'memory.agent.model', value: 'gpt-4o' },
+ ],
+ },
+ params,
+ );
+
+ it('lets PATCH switch a union one field at a time, and /changes switch it in one batch', async () => {
+ const patched = nextParams();
+ await seedOwnAgent(patched);
+ expect((await patchFields([AGENT_SWITCH], patched)).status).toBe(200);
+
+ const batched = nextParams();
+ await seedOwnAgent(batched);
+ const alone = await send({ ops: [{ op: 'set', ...AGENT_SWITCH }] }, batched);
+ expect(alone.status).toBe(400);
+ expect(alone.body.issues).toEqual([
+ {
+ path: 'memory.agent.provider',
+ segments: ['memory', 'agent', 'provider'],
+ code: 'union_dropped_key',
+ },
+ {
+ path: 'memory.agent.model',
+ segments: ['memory', 'agent', 'model'],
+ code: 'union_dropped_key',
+ },
+ ]);
+
+ const switched = await send(
+ {
+ ops: [
+ { op: 'set', ...AGENT_SWITCH },
+ { op: 'unset', fieldPath: 'memory.agent.provider' },
+ { op: 'unset', fieldPath: 'memory.agent.model' },
+ ],
+ },
+ batched,
+ );
+ expect(switched.status).toBe(200);
+ const stored = await storedDocument(batched.principalId);
+ expect(stored!.overrides).toEqual({ memory: { agent: { id: 'agent_other' } } });
+ expect(stored!.tombstones).toEqual([]);
+ });
+
+ it('refuses a PATCH whose deeper write brings back a hidden value the stored fields conflict with', async () => {
+ const params = nextParams();
+ await seedDocument(
+ params.principalId,
+ { memory: { agent: { provider: 'openAI', model: 'gpt-4o' } } },
+ ['memory.agent'],
+ );
+ const before = await storedDocument(params.principalId);
+
+ const { status, body } = await patchFields(
+ [{ fieldPath: 'memory.agent.enabled', value: true }],
+ params,
+ );
+
+ expect(status).toBe(400);
+ expect(body.issues).toEqual([
+ {
+ path: 'memory.agent.provider',
+ segments: ['memory', 'agent', 'provider'],
+ code: 'union_dropped_key',
+ },
+ {
+ path: 'memory.agent.model',
+ segments: ['memory', 'agent', 'model'],
+ code: 'union_dropped_key',
+ },
+ ]);
+ expect(await storedDocument(params.principalId)).toEqual(before);
+ });
+});
diff --git a/packages/api/src/admin/config.handler.spec.ts b/packages/api/src/admin/config.handler.spec.ts
index cb949fa8c1..f42710d475 100644
--- a/packages/api/src/admin/config.handler.spec.ts
+++ b/packages/api/src/admin/config.handler.spec.ts
@@ -1803,6 +1803,13 @@ describe('createAdminConfigHandlers', () => {
body: { isActive: false },
},
},
+ {
+ name: 'applyConfigChanges',
+ reqOverrides: {
+ params: { principalType: 'role', principalId: 'admin' },
+ body: { ops: [{ op: 'set', fieldPath: 'interface.modelSelect', value: false }] },
+ },
+ },
];
describe('upsertConfigOverrides: scope-lifecycle auth (ASSIGN_CONFIGS)', () => {
diff --git a/packages/api/src/admin/config.ts b/packages/api/src/admin/config.ts
index 8f146afbc1..2095ee099c 100644
--- a/packages/api/src/admin/config.ts
+++ b/packages/api/src/admin/config.ts
@@ -1,6 +1,7 @@
import {
BASE_PRINCIPAL_CONFIG_SECTIONS,
BASE_ONLY_CONFIG_SECTIONS,
+ BASE_ONLY_CONFIG_PATHS,
PrincipalType,
PrincipalModel,
INTERFACE_PERMISSION_FIELDS,
@@ -12,11 +13,28 @@ import {
} from 'librechat-data-provider';
import {
logger,
+ getAtPath,
+ unsetAtPath,
+ isPlainRecord,
isDotFreePath,
+ isSegmentPrefix,
parseFieldPath,
setConfigFields,
+ applyConfigChange,
+ getConfigEntryKey,
unsetConfigPaths,
getConfigRevision,
+ isConfigEntryError,
+ isConfigRecordPath,
+ pruneEmptyAncestors,
+ isConfigArrayItemPath,
+ isAcceptedOverrideSection,
+ MAX_CONFIG_CHANGE_OPS,
+ getConfigChangeIssues,
+ getConfigArrayMergeKey,
+ getIndexedMergeKeyIssues,
+ getConfigBatchWrittenPaths,
+ isSameConfigValue,
isConfigRevision,
isConfigPathError,
isFieldNameRejection,
@@ -39,6 +57,7 @@ import {
import type {
AppConfig,
ConfigDraft,
+ ConfigChange,
ConfigRecord,
ConfigSection,
ConfigRevision,
@@ -48,6 +67,14 @@ import type {
ConfigPathInputs,
ConfigOverrideIssue,
ConfigPathErrorReason,
+ ConfigOverrideState,
+ ConfigEntryError,
+ AdminConfigChangeOp,
+ AdminConfigChangeRef,
+ AdminConfigSkipReason,
+ AdminConfigIgnoreReason,
+ AdminConfigChangesResponse,
+ AdminConfigChangeErrorResponse,
ConfigMutationOutcome,
} from '@librechat/data-schemas';
import type { TCustomConfig } from 'librechat-data-provider';
@@ -64,12 +91,14 @@ import {
getConfigSecretSections,
isConfigSecretAncestorPath,
isConfigSecretDescendantPath,
+ isConfigSecretKeyRename,
isConfigSecretPreservablePatch,
isConfigSecretRelatedSegments,
preserveConfigSecrets,
redactConfigSecrets,
} from './secrets';
import {
+ getBatchReentryIssues,
getPatchReentryIssues,
isWebSearchBindingPath,
getRemovalReentryIssues,
@@ -138,10 +167,6 @@ export function getTopLevelSection(fieldPath: string): string {
return fieldPath.split('.')[0];
}
-function isBaseOnlyFieldPath(fieldPath: string): boolean {
- return BASE_ONLY_OVERRIDE_SECTIONS.has(getTopLevelSection(fieldPath));
-}
-
function isProcessMCPServerFieldPath(fieldPath: string, value: unknown): boolean {
const [section, _serverName, field] = fieldPath.split('.');
if (section !== 'mcpServers' && section !== 'mcpConfig') {
@@ -327,6 +352,161 @@ function normalizeInterfaceFieldPatch(fieldPath: string, value: unknown): unknow
return normalizeRuntimeInterfaceValue(parts[1], value);
}
+/** Sets a key as data, so a submitted `__proto__` key never becomes a prototype. */
+function defineKey(target: Record<string, unknown>, key: string, value: unknown): void {
+ Object.defineProperty(target, key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true,
+ });
+}
+
+/**
+ * Drops the role-permission fields from a whole `interface` override: a composite permission
+ * field keeps its UI-only sub-keys, a runtime field keeps its boolean form, and runtime disables
+ * are normalized. Returns what is left (`undefined` when nothing is) and the dropped paths
+ * relative to `interface`.
+ */
+function filterInterfaceOverride(iface: Record<string, unknown>): {
+ value?: Record<string, unknown>;
+ stripped: string[][];
+} {
+ const value: Record<string, unknown> = {};
+ const stripped: string[][] = [];
+ for (const [field, rawValue] of Object.entries(iface)) {
+ const fieldValue = normalizeRuntimeInterfaceValue(field, rawValue);
+ if (!INTERFACE_PERMISSION_FIELDS.has(field)) {
+ defineKey(value, field, fieldValue);
+ continue;
+ }
+ if (isPlainRecord(fieldValue)) {
+ const uiOnly: Record<string, unknown> = {};
+ for (const [sub, subValue] of Object.entries(fieldValue)) {
+ if (PERMISSION_SUB_KEYS.has(sub)) {
+ stripped.push([field, sub]);
+ } else {
+ defineKey(uiOnly, sub, subValue);
+ }
+ }
+ if (Object.keys(uiOnly).length > 0) {
+ defineKey(value, field, uiOnly);
+ }
+ continue;
+ }
+ if (RUNTIME_CONFIG_INTERFACE_FIELDS.has(field)) {
+ defineKey(value, field, fieldValue);
+ continue;
+ }
+ stripped.push([field]);
+ }
+ return { value: Object.keys(value).length > 0 ? value : undefined, stripped };
+}
+
+/** A failure a field guard answers with 400: a message and a stable code. */
+interface FieldGuardError {
+ error: string;
+ code: 'PROCESS_MCP_CONFIG' | 'LANGFUSE_HEADERS_CONFIG' | 'SECRET_PATH';
+}
+
+/** Why a field write at `fieldPath` is refused outright, checked before anything is read. */
+function getFieldWriteError(fieldPath: string, value: unknown): FieldGuardError | null {
+ if (isProcessMCPServerFieldPath(fieldPath, value)) {
+ return { error: PROCESS_MCP_CONFIG_ERROR, code: 'PROCESS_MCP_CONFIG' };
+ }
+ if (isLangfuseHeadersFieldPath(fieldPath)) {
+ return { error: LANGFUSE_HEADERS_CONFIG_ERROR, code: 'LANGFUSE_HEADERS_CONFIG' };
+ }
+ if (isConfigSecretDescendantPath(fieldPath)) {
+ return {
+ error: `Cannot patch inside protected secret path: ${fieldPath}`,
+ code: 'SECRET_PATH',
+ };
+ }
+ const secretInputError = getConfigSecretInputError(fieldPath, value);
+ if (secretInputError) {
+ return { error: secretInputError, code: 'SECRET_PATH' };
+ }
+ if (Array.isArray(value) && isConfigSecretAncestorPath(fieldPath)) {
+ return {
+ error: `Cannot patch protected secret ancestor as an array: ${fieldPath}`,
+ code: 'SECRET_PATH',
+ };
+ }
+ return null;
+}
+
+/** Why a removal or tombstone at `fieldPath` is refused outright. */
+function getFieldRemovalError(fieldPath: string): FieldGuardError | null {
+ const secretInputError = getConfigSecretInputError(fieldPath, undefined);
+ return secretInputError ? { error: secretInputError, code: 'SECRET_PATH' } : null;
+}
+
+/**
+ * Why the generic config API leaves a path alone instead of changing it: a section only
+ * librechat.yaml configures, a section with its own admin API, or an interface permission. The
+ * request still succeeds (owner decision: skip and report, never 400).
+ */
+function getFieldSkipReason(fieldPath: string): AdminConfigSkipReason | null {
+ const section = getTopLevelSection(fieldPath);
+ if (BASE_ONLY_OVERRIDE_SECTIONS.has(section)) {
+ return 'base_only_section';
+ }
+ if (BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(section)) {
+ return 'dedicated_section';
+ }
+ return isInterfacePermissionPath(fieldPath) ? 'interface_permission' : null;
+}
+
+const SKIP_DESCRIPTIONS: Readonly<Record<AdminConfigSkipReason, string>> = {
+ base_only_section: 'base-only config field %s - configure it in librechat.yaml instead',
+ base_only_path: 'base-only config path %s - configure it in librechat.yaml instead',
+ dedicated_section: 'dedicated tenant-wide config field %s in the generic config API',
+ interface_permission: 'interface permission field %s — use role permissions instead',
+};
+
+/** Logs a skipped path; `action` is how the route words it (`Stripping`, `Ignoring tombstone for`). */
+function logSkippedField(action: string, fieldPath: string, reason: AdminConfigSkipReason): void {
+ logger.warn(
+ `[adminConfig] ${action} ${SKIP_DESCRIPTIONS[reason].replace('%s', JSON.stringify(fieldPath))}`,
+ );
+}
+
+/** Fields of overridable sections only librechat.yaml sets, as segments. */
+const BASE_ONLY_PATHS: ReadonlyArray<readonly string[]> = BASE_ONLY_CONFIG_PATHS.map((path) =>
+ path.split('.'),
+);
+
+/** Whether `segments` is a base-only field or lies inside one. */
+function isBaseOnlyPath(segments: readonly string[]): boolean {
+ return BASE_ONLY_PATHS.some((path) => isSegmentPrefix(path, segments));
+}
+
+/**
+ * Removes the base-only fields below `segments` from a value written there (`endpoints.agents`
+ * carrying `pullRequests.provider`), with the objects that leaves empty. Returns the value to
+ * store and the full paths it removed.
+ */
+function stripBaseOnlyPaths(
+ segments: readonly string[],
+ value: unknown,
+): { value: unknown; stripped: string[][] } {
+ let result = value;
+ const stripped: string[][] = [];
+ for (const path of BASE_ONLY_PATHS) {
+ if (path.length <= segments.length || !isSegmentPrefix(segments, path)) {
+ continue;
+ }
+ const relative = path.slice(segments.length);
+ if (!isPlainRecord(result) || getAtPath(result, relative) === undefined) {
+ continue;
+ }
+ result = pruneEmptyAncestors(unsetAtPath(result, relative), relative);
+ stripped.push([...path]);
+ }
+ return { value: result, stripped };
+}
+
/**
* Positional slot where config methods once took a Mongoose `ClientSession`; the portable
* config store does not join transactions.
@@ -537,10 +717,10 @@ function filterSectionsByReadAccess<T extends Record<string, unknown>>(
return result as T;
}
-function filterConfigDocForReadAccess(
- config: ConfigRecord,
+function filterConfigDocForReadAccess<T extends ConfigRecord>(
+ config: T,
readable: ReadableSections,
-): ConfigRecord {
+): T {
const canRead = (section: string): boolean => canReadSection(readable, section);
const filteredOverrides = filterSectionsByReadAccess(
(config.overrides ?? {}) as Record<string, unknown>,
@@ -625,13 +805,18 @@ function redactAppConfigForResponse(appConfig: AppConfig, yamlConfig?: AppConfig
/**
* Reports only locations and stable codes: schema messages can echo the submitted values.
* `segments` names the location key by key, since `path` is ambiguous once a record key
- * itself holds a dot.
+ * itself holds a dot. `report` adds what a route reports alongside them (a batch's `skipped`).
*/
-function invalidOverrideResponse(res: Response, issues: ConfigOverrideIssue[]): Response {
+function invalidOverrideResponse(
+ res: Response,
+ issues: ConfigOverrideIssue[],
+ report?: Pick<AdminConfigChangeErrorResponse, 'skipped'>,
+): Response {
return res.status(400).json({
error: 'Invalid config override',
code: 'CONFIG_OVERRIDE_INVALID',
issues: issues.map(({ path, segments, code }) => ({ path, segments, code })),
+ ...report,
});
}
@@ -708,6 +893,495 @@ function preservePatchedConfigSecretFields(
return result;
}
+// ── Change batches ───────────────────────────────────────────────────
+
+type ChangeOpKind = AdminConfigChangeOp['op'];
+
+const CHANGE_OPS: ReadonlySet<string> = new Set<ChangeOpKind>([
+ 'set',
+ 'unset',
+ 'tombstone',
+ 'upsertEntry',
+ 'removeEntry',
+ 'rename',
+]);
+
+/** Changes whose own path may not reach into a merged-by-key array entry by position. */
+const INDEXED_PATH_OPS: ReadonlySet<ChangeOpKind> = new Set<ChangeOpKind>([
+ 'set',
+ 'unset',
+ 'rename',
+]);
+
+/** Changes that leave an override in place, which the runtime merge may then drop. */
+const IGNORABLE_OPS: ReadonlySet<ChangeOpKind> = new Set<ChangeOpKind>([
+ 'set',
+ 'tombstone',
+ 'rename',
+]);
+
+type SkippedChange = AdminConfigChangeRef & { reason: AdminConfigSkipReason };
+type IgnoredChange = AdminConfigChangeRef & { reason: AdminConfigIgnoreReason };
+
+/** A 400 for one change of a batch; `opIndex` names it and nothing submitted is echoed. */
+interface ChangeFailure {
+ error: string;
+ code: string;
+ opIndex: number;
+ reason?: string;
+}
+
+/**
+ * A change of a batch, checked and prepared before the stored document is read: guards run,
+ * skipped parts are cut out, and submitted secrets are encrypted once. What depends on the
+ * stored document (secrets an object omits, entries to rename) is resolved while applying.
+ */
+interface PreparedChange {
+ index: number;
+ op: ChangeOpKind;
+ target: FieldTarget;
+ /** The entry key of `upsertEntry` and `removeEntry`; the old key of `rename`. */
+ key?: string;
+ /** The new key of `rename`. */
+ to?: string;
+ /** `set`: the value to store, after normalization and stripping. */
+ value?: unknown;
+ /** `set` on a dot-free path: `value` with secrets encrypted, plus any preview companion. */
+ fields?: Record<string, unknown>;
+ /** `upsertEntry`: the entry with secrets encrypted. */
+ entry?: Record<string, unknown>;
+ /**
+ * `unset` and `tombstone`: the paths removed together (a secret and its preview). `set`: the
+ * paths it resets instead, when nothing of its value is stored.
+ */
+ paths?: string[][];
+}
+
+type PreparedRead =
+ | {
+ ok: true;
+ /** Two changes with the same identity address the same location. */
+ identity: string;
+ section: string;
+ /** `null` when the whole change is skipped. */
+ change: PreparedChange | null;
+ skipped: SkippedChange[];
+ }
+ | { ok: false; failure: ChangeFailure };
+
+function changeFailure(
+ opIndex: number,
+ error: string,
+ code: string,
+ reason?: string,
+): PreparedRead {
+ return {
+ ok: false,
+ failure: reason ? { error, code, opIndex, reason } : { error, code, opIndex },
+ };
+}
+
+function toChangeRef(
+ change: Pick<PreparedChange, 'index' | 'op' | 'target' | 'key'>,
+): AdminConfigChangeRef {
+ const ref: AdminConfigChangeRef = {
+ opIndex: change.index,
+ op: change.op,
+ segments: [...change.target.segments],
+ };
+ if (change.key !== undefined && change.op !== 'rename') {
+ ref.key = change.key;
+ }
+ return ref;
+}
+
+function isEntryOp(op: ChangeOpKind): boolean {
+ return op === 'upsertEntry' || op === 'removeEntry' || op === 'rename';
+}
+
+function isNonEmptyString(value: unknown): value is string {
+ return typeof value === 'string' && value !== '';
+}
+
+/** The paths an `unset` of `target` removes together: a secret and its preview companion. */
+function getRemovalPaths(target: FieldTarget): string[][] {
+ return target.dotFree
+ ? getConfigSecretMutationPaths(target.fieldPath).map(parseFieldPath)
+ : [target.segments];
+}
+
+/**
+ * Prepares a `set`: refuses what PATCH refuses, skips what PATCH strips, filters a whole
+ * `interface` object and base-only fields out of the value (reporting each), and encrypts it.
+ * A set replaces what is stored at its path with what is left of its value, so one whose
+ * whole value is filtered out resets the path, as an `unset` does.
+ */
+function prepareSet(
+ raw: Record<string, unknown>,
+ base: Pick<PreparedChange, 'index' | 'op' | 'target'>,
+ skipReason: AdminConfigSkipReason | null,
+): PreparedRead | { ok: true; change: PreparedChange | null; skipped: SkippedChange[] } {
+ const { index, target } = base;
+ if (!Object.prototype.hasOwnProperty.call(raw, 'value') || raw.value === undefined) {
+ return changeFailure(index, 'A set change needs a value', 'INVALID_CHANGE');
+ }
+ const guardError = getFieldWriteError(target.fieldPath, raw.value);
+ if (guardError) {
+ return changeFailure(index, guardError.error, guardError.code);
+ }
+ const ref = toChangeRef(base);
+ if (skipReason) {
+ return { ok: true, change: null, skipped: [{ ...ref, reason: skipReason }] };
+ }
+ let value = normalizeInterfaceFieldPatch(target.fieldPath, raw.value);
+ const skipped: SkippedChange[] = [];
+ if (target.segments.length === 1 && target.segments[0] === 'interface' && isPlainRecord(value)) {
+ const filtered = filterInterfaceOverride(value);
+ for (const path of filtered.stripped) {
+ skipped.push({ ...ref, segments: ['interface', ...path], reason: 'interface_permission' });
+ }
+ if (filtered.stripped.length > 0 && !filtered.value) {
+ return { ok: true, change: { ...base, paths: getRemovalPaths(target) }, skipped };
+ }
+ value = filtered.value ?? value;
+ }
+ const stripped = stripBaseOnlyPaths(target.segments, value);
+ for (const segments of stripped.stripped) {
+ skipped.push({ ...ref, segments, reason: 'base_only_path' });
+ }
+ if (
+ stripped.stripped.length > 0 &&
+ isPlainRecord(stripped.value) &&
+ Object.keys(stripped.value).length === 0
+ ) {
+ return { ok: true, change: { ...base, paths: getRemovalPaths(target) }, skipped };
+ }
+ value = stripped.value;
+ const fields = target.dotFree
+ ? encryptConfigSecretFields({ [target.fieldPath]: value })
+ : undefined;
+ return { ok: true, change: { ...base, value, fields }, skipped };
+}
+
+/** Prepares an entry change: the path must hold a merged-by-key array (or, to rename, a record). */
+function prepareEntryChange(
+ raw: Record<string, unknown>,
+ base: Pick<PreparedChange, 'index' | 'op' | 'target'>,
+ skipReason: AdminConfigSkipReason | null,
+): PreparedRead | { ok: true; change: PreparedChange | null; skipped: SkippedChange[] } {
+ const { index, op, target } = base;
+ const keyField = getConfigArrayMergeKey(target.segments);
+ let change: PreparedChange;
+ if (op === 'rename') {
+ if (!isNonEmptyString(raw.from) || !isNonEmptyString(raw.to)) {
+ return changeFailure(
+ index,
+ 'A rename needs non-empty from and to',
+ 'CONFIG_ENTRY_INVALID',
+ 'invalid_entry',
+ );
+ }
+ if (!keyField) {
+ if (!isConfigRecordPath(target.segments)) {
+ return changeFailure(
+ index,
+ 'A rename addresses a collection merged by key or a record of named entries',
+ 'CONFIG_ENTRY_INVALID',
+ 'not_collection',
+ );
+ }
+ for (const name of [raw.from, raw.to]) {
+ const keyTarget = readFieldTarget(undefined, [...target.segments, name]);
+ if (!keyTarget.ok) {
+ return changeFailure(index, keyTarget.error, 'CONFIG_PATH_INVALID', keyTarget.reason);
+ }
+ }
+ if (isConfigSecretKeyRename(target.segments, raw.from, raw.to)) {
+ return changeFailure(index, 'A rename cannot move a registered secret', 'SECRET_PATH');
+ }
+ }
+ change = { ...base, key: raw.from, to: raw.to };
+ } else if (!keyField) {
+ return changeFailure(
+ index,
+ 'Entry changes address a collection merged by key, such as endpoints.custom',
+ 'CONFIG_ENTRY_INVALID',
+ 'not_collection',
+ );
+ } else if (op === 'removeEntry') {
+ if (!isNonEmptyString(raw.key)) {
+ return changeFailure(
+ index,
+ 'removeEntry needs a non-empty key',
+ 'CONFIG_ENTRY_INVALID',
+ 'invalid_entry',
+ );
+ }
+ change = { ...base, key: raw.key };
+ } else {
+ const key = getConfigEntryKey(raw.entry, keyField);
+ if (key === undefined) {
+ return changeFailure(
+ index,
+ `upsertEntry needs an entry object with a non-empty ${keyField}`,
+ 'CONFIG_ENTRY_INVALID',
+ 'invalid_entry',
+ );
+ }
+ const guardError = getFieldWriteError(target.fieldPath, [raw.entry]);
+ if (guardError) {
+ return changeFailure(index, guardError.error, guardError.code);
+ }
+ const [entry] = encryptConfigSecrets([raw.entry as Record<string, unknown>], target.fieldPath);
+ change = { ...base, key, entry };
+ }
+ if (skipReason) {
+ return { ok: true, change: null, skipped: [{ ...toChangeRef(change), reason: skipReason }] };
+ }
+ return { ok: true, change, skipped: [] };
+}
+
+/**
+ * What a change addresses, for refusing two changes of a batch that address the same thing: a
+ * path, or one entry of a collection (by its key; a rename by the key it starts from).
+ */
+function getChangeIdentity(
+ raw: Record<string, unknown>,
+ op: ChangeOpKind,
+ segments: readonly string[],
+): string {
+ if (!isEntryOp(op)) {
+ return JSON.stringify(['path', segments]);
+ }
+ if (op === 'rename') {
+ return JSON.stringify(['entry', segments, raw.from]);
+ }
+ if (op === 'removeEntry') {
+ return JSON.stringify(['entry', segments, raw.key]);
+ }
+ const keyField = getConfigArrayMergeKey(segments);
+ return JSON.stringify([
+ 'entry',
+ segments,
+ keyField ? getConfigEntryKey(raw.entry, keyField) : null,
+ ]);
+}
+
+/**
+ * Reads and checks one change of a batch without touching the stored document. A change
+ * refused outright fails the whole batch (400, by `opIndex`); one the API never stores
+ * (decision #2: base-only, deployment-owned, dedicated, interface permission) is reported as
+ * skipped and the rest of the batch still applies.
+ */
+function prepareChange(raw: unknown, index: number): PreparedRead {
+ if (!isPlainRecord(raw) || typeof raw.op !== 'string' || !CHANGE_OPS.has(raw.op)) {
+ return changeFailure(
+ index,
+ 'Each change needs an op: set, unset, tombstone, upsertEntry, removeEntry or rename',
+ 'INVALID_CHANGE',
+ );
+ }
+ const op = raw.op as ChangeOpKind;
+ const read = readFieldTarget(raw.fieldPath, raw.segments);
+ if (!read.ok) {
+ return changeFailure(
+ index,
+ read.error,
+ read.reason ? 'CONFIG_PATH_INVALID' : 'INVALID_FIELD_PATH',
+ read.reason,
+ );
+ }
+ const { target } = read;
+ const base = { index, op, target };
+ const section = target.segments[0];
+ /** Unsetting what an older server stored outside configSchema is cleanup, as DELETE allows. */
+ if (op !== 'unset' && !isAcceptedOverrideSection(section)) {
+ return changeFailure(index, 'Unknown config section', 'UNKNOWN_SECTION');
+ }
+ const sectionSkip = getFieldSkipReason(target.fieldPath);
+
+ let prepared:
+ | PreparedRead
+ | { ok: true; change: PreparedChange | null; skipped: SkippedChange[] };
+ if (op === 'set') {
+ prepared = prepareSet(
+ raw,
+ base,
+ sectionSkip ?? (isBaseOnlyPath(target.segments) ? 'base_only_path' : null),
+ );
+ } else if (isEntryOp(op)) {
+ prepared = prepareEntryChange(raw, base, sectionSkip);
+ } else {
+ if (op === 'tombstone' && !target.dotFree) {
+ return changeFailure(
+ index,
+ 'A tombstone cannot name a key that contains a dot',
+ 'CONFIG_PATH_INVALID',
+ 'dotted_segment',
+ );
+ }
+ if (op === 'tombstone' && isConfigArrayItemPath(target.segments)) {
+ return changeFailure(
+ index,
+ 'A tombstone can hide a whole array, not an element or a path inside one',
+ 'CONFIG_PATH_INVALID',
+ 'inside_array',
+ );
+ }
+ const removalError = target.dotFree ? getFieldRemovalError(target.fieldPath) : null;
+ if (removalError) {
+ return changeFailure(index, removalError.error, removalError.code);
+ }
+ /** Unsetting a stored base-only field is cleanup, so only a tombstone of one is skipped. */
+ const skipReason =
+ sectionSkip ??
+ (op === 'tombstone' && isBaseOnlyPath(target.segments) ? 'base_only_path' : null);
+ prepared = skipReason
+ ? { ok: true, change: null, skipped: [{ ...toChangeRef(base), reason: skipReason }] }
+ : { ok: true, change: { ...base, paths: getRemovalPaths(target) }, skipped: [] };
+ }
+ if (!prepared.ok) {
+ return prepared;
+ }
+ return {
+ ok: true,
+ identity: getChangeIdentity(raw, op, target.segments),
+ section,
+ change: prepared.change,
+ skipped: prepared.skipped,
+ };
+}
+
+/** The changes a prepared change applies, resolved against the document as it stands. */
+function expandChange(change: PreparedChange, overrides: unknown): ConfigChange[] {
+ const { segments } = change.target;
+ switch (change.op) {
+ case 'set': {
+ if (change.paths) {
+ return change.paths.map((path) => ({ op: 'unset', segments: path }));
+ }
+ if (!change.fields) {
+ return [{ op: 'set', segments, value: change.value }];
+ }
+ /** Secrets an object omits are kept from the document before this change. */
+ const fields = preservePatchedConfigSecretFields(change.fields, overrides);
+ return toOrderedWrites([{ target: change.target, value: change.value }], fields).map(
+ (write) => ({ op: 'set', segments: write.segments, value: write.value }),
+ );
+ }
+ case 'unset':
+ case 'tombstone':
+ return (change.paths ?? [segments]).map(
+ (path) => ({ op: change.op, segments: path }) as ConfigChange,
+ );
+ case 'upsertEntry': {
+ /** An entry that omits its secret keeps the one stored on the entry of the same key. */
+ const [entry] = preserveConfigSecrets(
+ [change.entry ?? {}],
+ overrides,
+ change.target.fieldPath,
+ );
+ return [{ op: 'upsertEntry', segments, entry }];
+ }
+ case 'removeEntry':
+ return [{ op: 'removeEntry', segments, key: change.key ?? '' }];
+ case 'rename':
+ return [{ op: 'rename', segments, from: change.key ?? '', to: change.to ?? '' }];
+ }
+}
+
+/** Whether `librechat.yaml` itself defines entry `name` of the collection a change addresses. */
+function isYamlEntry(base: unknown, change: PreparedChange, name: string): boolean {
+ const node = getAtPath(base, change.target.segments);
+ const keyField = getConfigArrayMergeKey(change.target.segments);
+ if (keyField) {
+ return (
+ Array.isArray(node) && node.some((item) => isPlainRecord(item) && item[keyField] === name)
+ );
+ }
+ return isPlainRecord(node) && Object.prototype.hasOwnProperty.call(node, name);
+}
+
+/**
+ * What `librechat.yaml` keeps whatever an override does: the MCP servers it runs as local
+ * processes, and the base-only fields it sets.
+ */
+interface YamlHeld {
+ processServers: ReadonlySet<string>;
+ baseOnlyPaths: ReadonlyArray<readonly string[]>;
+}
+
+function getYamlHeld(base: Partial<TCustomConfig>): YamlHeld {
+ const servers = (base as { mcpServers?: unknown }).mcpServers;
+ const processServers = isPlainRecord(servers)
+ ? Object.entries(servers)
+ .filter(([, serverConfig]) => isProcessMCPServerConfig(serverConfig))
+ .map(([name]) => name)
+ : [];
+ return {
+ processServers: new Set(processServers),
+ baseOnlyPaths: BASE_ONLY_PATHS.filter((path) => getAtPath(base, path) !== undefined),
+ };
+}
+
+type IgnoredPart = { segments: string[]; reason: AdminConfigIgnoreReason };
+
+/**
+ * The parts of an applied change under an MCP server librechat.yaml runs as a process, whose
+ * overrides the merge never applies: a write, rename or tombstone there, and each such server a
+ * tombstone of the whole section leaves in place. An `unset` there is not one: it asks for the
+ * YAML value, which is what runs. A rename of a server itself never names a YAML one, which the
+ * handler refuses.
+ */
+function getProcessServerParts(
+ change: PreparedChange,
+ processServers: ReadonlySet<string>,
+): IgnoredPart[] {
+ const [section, name] = change.target.segments;
+ if (section !== 'mcpServers' || processServers.size === 0 || !IGNORABLE_OPS.has(change.op)) {
+ return [];
+ }
+ const reason = 'process_mcp_server';
+ if (name !== undefined) {
+ return processServers.has(name) ? [{ segments: [...change.target.segments], reason }] : [];
+ }
+ if (change.op === 'tombstone') {
+ return [...processServers].map((server) => ({ segments: ['mcpServers', server], reason }));
+ }
+ if (!isPlainRecord(change.value)) {
+ return [];
+ }
+ return Object.keys(change.value)
+ .filter((server) => processServers.has(server))
+ .map((server) => ({ segments: ['mcpServers', server], reason }));
+}
+
+/**
+ * The parts of an applied change the runtime merge drops: those under a YAML stdio MCP server,
+ * and the base-only fields librechat.yaml sets below a tombstone (a tombstone of one itself is
+ * skipped), which the merge puts back so the tombstone hides only the rest.
+ */
+function getIgnoredParts(change: PreparedChange, held: YamlHeld): IgnoredPart[] {
+ const parts = getProcessServerParts(change, held.processServers);
+ if (change.op !== 'tombstone') {
+ return parts;
+ }
+ const { segments } = change.target;
+ const baseOnly = held.baseOnlyPaths
+ .filter((path) => path.length > segments.length && isSegmentPrefix(segments, path))
+ .map((path): IgnoredPart => ({ segments: [...path], reason: 'base_only_path' }));
+ return [...parts, ...baseOnly];
+}
+
+/** How an applied change is named in audit metadata: its path, plus the entry it addressed. */
+function describeChange(change: PreparedChange): string {
+ const path = describeFieldTarget(change.target);
+ if (change.op === 'rename') {
+ return `${path}[${JSON.stringify(change.key)}->${JSON.stringify(change.to)}]`;
+ }
+ return change.key !== undefined ? `${path}[${JSON.stringify(change.key)}]` : path;
+}
+
// ── Handler factory ──────────────────────────────────────────────────
export function createAdminConfigHandlers(deps: AdminConfigDeps): {
@@ -719,6 +1393,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
patchConfigField: (req: ServerRequest, res: Response) => Promise<Response>;
tombstoneConfigField: (req: ServerRequest, res: Response) => Promise<Response>;
deleteConfigField: (req: ServerRequest, res: Response) => Promise<Response>;
+ applyConfigChanges: (req: ServerRequest, res: Response) => Promise<Response>;
deleteConfigOverrides: (req: ServerRequest, res: Response) => Promise<Response>;
toggleConfig: (req: ServerRequest, res: Response) => Promise<Response>;
} {
@@ -755,7 +1430,11 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
logPrefix: '[adminConfig]',
});
- const meta = buildAdminConfigMeta({ maxPatchEntries: MAX_PATCH_ENTRIES, overrideCacheTtlMs });
+ const meta = buildAdminConfigMeta({
+ maxPatchEntries: MAX_PATCH_ENTRIES,
+ maxChangeOps: MAX_CONFIG_CHANGE_OPS,
+ overrideCacheTtlMs,
+ });
function readStoredConfig(
principalType: PrincipalType,
@@ -1116,40 +1795,13 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
}
const iface = (overrides as Record<string, unknown>).interface;
- if (iface != null && typeof iface === 'object' && !Array.isArray(iface)) {
- const filteredIface: Record<string, unknown> = {};
- for (const [field, rawVal] of Object.entries(iface as Record<string, unknown>)) {
- const val = normalizeRuntimeInterfaceValue(field, rawVal);
- if (!INTERFACE_PERMISSION_FIELDS.has(field)) {
- filteredIface[field] = val;
- } else if (val != null && typeof val === 'object' && !Array.isArray(val)) {
- // Composite permission field (e.g. mcpServers): strip permission
- // sub-keys but preserve UI-only sub-keys like placeholder/trustCheckbox.
- const uiOnly: Record<string, unknown> = {};
- for (const [sub, subVal] of Object.entries(val as Record<string, unknown>)) {
- if (!PERMISSION_SUB_KEYS.has(sub)) {
- uiOnly[sub] = subVal;
- } else {
- logger.warn(
- `[adminConfig] Stripping interface permission sub-field "${field}.${sub}" — use role permissions instead`,
- );
- }
- }
- if (Object.keys(uiOnly).length > 0) {
- filteredIface[field] = uiOnly;
- }
- } else if (RUNTIME_CONFIG_INTERFACE_FIELDS.has(field)) {
- // Dual-purpose field: the boolean form is a runtime disable, not a
- // permission toggle, so preserve it (e.g. schedules: false).
- filteredIface[field] = val;
- } else {
- logger.warn(
- `[adminConfig] Stripping interface permission field "${field}" — use role permissions instead`,
- );
- }
+ if (isPlainRecord(iface)) {
+ const { value, stripped } = filterInterfaceOverride(iface);
+ for (const path of stripped) {
+ logSkippedField('Stripping', ['interface', ...path].join('.'), 'interface_permission');
}
- if (Object.keys(filteredIface).length > 0) {
- (filteredOverrides as Record<string, unknown>).interface = filteredIface;
+ if (value) {
+ (filteredOverrides as Record<string, unknown>).interface = value;
} else {
delete (filteredOverrides as Record<string, unknown>).interface;
}
@@ -1342,27 +1994,10 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
if (!read.ok) {
return fieldTargetErrorResponse(res, read);
}
- const { fieldPath } = read.target;
const value = entry?.value;
- if (isProcessMCPServerFieldPath(fieldPath, value)) {
- return res.status(400).json({ error: PROCESS_MCP_CONFIG_ERROR });
- }
- if (isLangfuseHeadersFieldPath(fieldPath)) {
- return res.status(400).json({ error: LANGFUSE_HEADERS_CONFIG_ERROR });
- }
- if (isConfigSecretDescendantPath(fieldPath)) {
- return res
- .status(400)
- .json({ error: `Cannot patch inside protected secret path: ${fieldPath}` });
- }
- const secretInputError = getConfigSecretInputError(fieldPath, value);
- if (secretInputError) {
- return res.status(400).json({ error: secretInputError });
- }
- if (Array.isArray(value) && isConfigSecretAncestorPath(fieldPath)) {
- return res.status(400).json({
- error: `Cannot patch protected secret ancestor as an array: ${fieldPath}`,
- });
+ const guardError = getFieldWriteError(read.target.fieldPath, value);
+ if (guardError) {
+ return res.status(400).json({ error: guardError.error });
}
targets.push({ target: read.target, value });
}
@@ -1378,25 +2013,11 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
value: normalizeInterfaceFieldPatch(target.fieldPath, value),
}))
.filter(({ target: { fieldPath } }) => {
- if (isBaseOnlyFieldPath(fieldPath)) {
- logger.warn(
- `[adminConfig] Stripping base-only config field "${fieldPath}" - configure it in librechat.yaml instead`,
- );
- return false;
- }
- if (BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(getTopLevelSection(fieldPath))) {
- logger.warn(
- `[adminConfig] Stripping dedicated tenant-wide config field "${fieldPath}" from the generic config API`,
- );
- return false;
+ const skipReason = getFieldSkipReason(fieldPath);
+ if (skipReason) {
+ logSkippedField('Stripping', fieldPath, skipReason);
}
- if (isInterfacePermissionPath(fieldPath)) {
- logger.warn(
- `[adminConfig] Stripping interface permission field "${fieldPath}" — use role permissions instead`,
- );
- return false;
- }
- return true;
+ return skipReason == null;
});
const hasBroadManage = await hasConfigCapability(user, null, 'manage');
@@ -1585,9 +2206,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
});
}
const { fieldPath } = read.target;
- const secretInputError = getConfigSecretInputError(fieldPath, undefined);
- if (secretInputError) {
- return res.status(400).json({ error: secretInputError });
+ const removalError = getFieldRemovalError(fieldPath);
+ if (removalError) {
+ return res.status(400).json({ error: removalError.error });
}
const user = getCapabilityUser(req);
@@ -1612,35 +2233,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
});
}
- if (isBaseOnlyFieldPath(fieldPath)) {
- logger.warn(
- `[adminConfig] Ignoring tombstone for base-only config field "${fieldPath}" - configure it in librechat.yaml instead`,
- );
- return noopResponse(
- res,
- 'No actionable field path provided',
- principalType,
- principalId,
- expected.value,
- );
- }
-
- if (isInterfacePermissionPath(fieldPath)) {
- logger.warn(
- `[adminConfig] Ignoring tombstone for interface permission field "${fieldPath}" — use role permissions instead`,
- );
- return noopResponse(
- res,
- 'No actionable field path provided',
- principalType,
- principalId,
- expected.value,
- );
- }
- if (BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(section)) {
- logger.warn(
- `[adminConfig] Ignoring dedicated tenant-wide config tombstone "${fieldPath}" in the generic config API`,
- );
+ const skipReason = getFieldSkipReason(fieldPath);
+ if (skipReason) {
+ logSkippedField('Ignoring tombstone for', fieldPath, skipReason);
return noopResponse(
res,
'No actionable field path provided',
@@ -1734,9 +2329,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
const { target } = read;
const { fieldPath } = target;
- const secretInputError = getConfigSecretInputError(fieldPath, undefined);
- if (secretInputError) {
- return res.status(400).json({ error: secretInputError });
+ const removalError = getFieldRemovalError(fieldPath);
+ if (removalError) {
+ return res.status(400).json({ error: removalError.error });
}
const user = getCapabilityUser(req);
@@ -1761,36 +2356,9 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
});
}
- if (isBaseOnlyFieldPath(fieldPath)) {
- logger.warn(
- `[adminConfig] Ignoring delete for base-only config field "${fieldPath}" - configure it in librechat.yaml instead`,
- );
- return noopResponse(
- res,
- 'No actionable field path provided',
- principalType,
- principalId,
- expected.value,
- );
- }
-
- if (BASE_PRINCIPAL_OVERRIDE_SECTIONS.has(section)) {
- logger.warn(
- `[adminConfig] Ignoring dedicated tenant-wide config delete "${fieldPath}" in the generic config API`,
- );
- return noopResponse(
- res,
- 'No actionable field path provided',
- principalType,
- principalId,
- expected.value,
- );
- }
-
- if (isInterfacePermissionPath(fieldPath)) {
- logger.warn(
- `[adminConfig] Ignoring delete for interface permission field "${fieldPath}" — use role permissions instead`,
- );
+ const skipReason = getFieldSkipReason(fieldPath);
+ if (skipReason) {
+ logSkippedField('Ignoring delete for', fieldPath, skipReason);
return noopResponse(
res,
'No actionable field path provided',
@@ -1849,6 +2417,356 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
}
}
+ /**
+ * The document a write returns, as a read would show it to the caller: redacted, and limited
+ * to the sections they can read plus the ones they just managed (`manage:configs:<section>`
+ * does not imply reading other sections).
+ */
+ async function toReadableConfig(
+ user: CapabilityUser,
+ config: ConfigRecord,
+ access: { hasBroadManage: boolean; managedSections: readonly string[] },
+ ): Promise<ConfigResponse> {
+ const safeConfig = redactConfigForResponse(config);
+ if (access.hasBroadManage) {
+ return safeConfig;
+ }
+ const readable = await getReadableConfigSections(user, [
+ ...new Set(collectConfigSections(safeConfig)),
+ ] as ConfigSection[]);
+ const sections = new Set([...readable.sections, ...access.managedSections]);
+ return filterConfigDocForReadAccess(safeConfig, { broad: readable.broad, sections });
+ }
+
+ /**
+ * POST /:principalType/:principalId/changes — Apply a batch of changes atomically.
+ *
+ * Every change is checked before anything is read; then the stored document is read, the
+ * changes are applied in order as pure transforms (secrets an object omits are kept from the
+ * document as it stands before each change), the end state is validated on the deployment's
+ * librechat.yaml without the principal's tombstones, and the result is written with one
+ * compare-and-swap. Any failure leaves the document as it was.
+ */
+ async function applyChanges(req: ServerRequest, res: Response): Promise<Response> {
+ try {
+ const { principalType, principalId } = req.params as {
+ principalType: string;
+ principalId: string;
+ };
+
+ if (!validatePrincipalType(principalType)) {
+ return res.status(400).json({
+ error: `Invalid principalType: ${principalType}`,
+ code: 'INVALID_PRINCIPAL_TYPE',
+ });
+ }
+
+ const body = (req.body ?? {}) as {
+ ops?: unknown;
+ priority?: unknown;
+ dryRun?: unknown;
+ expectedRevision?: unknown;
+ };
+ const { ops, priority } = body;
+
+ if (
+ priority != null &&
+ (typeof priority !== 'number' || !Number.isFinite(priority) || priority < 0)
+ ) {
+ return res
+ .status(400)
+ .json({ error: 'priority must be a non-negative number', code: 'INVALID_PRIORITY' });
+ }
+
+ if (body.dryRun !== undefined && typeof body.dryRun !== 'boolean') {
+ return res.status(400).json({ error: 'dryRun must be a boolean', code: 'INVALID_DRY_RUN' });
+ }
+ const dryRun = body.dryRun === true;
+
+ const expected = readExpectedRevision(body.expectedRevision);
+ if (!expected.ok) {
+ return invalidExpectedRevisionResponse(res);
+ }
+
+ if (!Array.isArray(ops) || ops.length === 0) {
+ return res
+ .status(400)
+ .json({ error: 'ops array is required and must not be empty', code: 'OPS_REQUIRED' });
+ }
+
+ if (ops.length > MAX_CONFIG_CHANGE_OPS) {
+ return res.status(400).json({
+ error: `ops array exceeds maximum of ${MAX_CONFIG_CHANGE_OPS}`,
+ code: 'TOO_MANY_OPS',
+ });
+ }
+
+ const changes: PreparedChange[] = [];
+ const skipped: SkippedChange[] = [];
+ const identities = new Set<string>();
+ const sections = new Set<string>();
+ for (let index = 0; index < ops.length; index++) {
+ const prepared = prepareChange(ops[index], index);
+ if (!prepared.ok) {
+ return res.status(400).json(prepared.failure);
+ }
+ if (identities.has(prepared.identity)) {
+ return res.status(400).json({
+ error: 'Two changes address the same path or entry',
+ code: 'DUPLICATE_FIELD_PATH',
+ opIndex: index,
+ });
+ }
+ identities.add(prepared.identity);
+ sections.add(prepared.section);
+ skipped.push(...prepared.skipped);
+ if (prepared.change) {
+ changes.push(prepared.change);
+ }
+ }
+
+ const user = getCapabilityUser(req);
+ if (!user) {
+ return res.status(401).json({ error: 'Authentication required' });
+ }
+
+ const hasBroadManage = await hasConfigCapability(user, null, 'manage');
+
+ if (principalId === BASE_CONFIG_PRINCIPAL_ID && !hasBroadManage) {
+ return res.status(403).json({ error: 'Insufficient permissions', code: 'FORBIDDEN' });
+ }
+
+ const managedSections = [...sections];
+ if (!hasBroadManage) {
+ const allowed = await Promise.all(
+ managedSections.map((section) =>
+ hasConfigCapability(user, section as ConfigSection, 'manage'),
+ ),
+ );
+ const denied = managedSections.find((_, i) => !allowed[i]);
+ if (denied) {
+ return res.status(403).json({
+ error: `Insufficient permissions for config section: ${denied}`,
+ code: 'FORBIDDEN_SECTION',
+ section: denied,
+ });
+ }
+ }
+
+ if (priority != null && !hasBroadManage) {
+ logger.warn(
+ `[adminConfig] Ignoring caller-supplied priority on section-scoped changes to ${principalType}/${principalId}: only broad manage:configs may modify document priority`,
+ );
+ }
+ const requestedPriority = hasBroadManage ? (priority as number | undefined) : undefined;
+
+ const baseYaml = await getBaseYamlConfig(user.tenantId);
+ for (const change of changes) {
+ if (
+ change.op === 'rename' &&
+ (isYamlEntry(baseYaml, change, change.key ?? '') ||
+ isYamlEntry(baseYaml, change, change.to ?? ''))
+ ) {
+ return res.status(400).json({
+ error:
+ 'An entry librechat.yaml defines cannot be renamed, and no entry can take its name',
+ code: 'CONFIG_ENTRY_INVALID',
+ reason: 'inherited_entry',
+ opIndex: change.index,
+ });
+ }
+ }
+ const yamlHeld = getYamlHeld(baseYaml);
+
+ interface ChangesReport {
+ applied: AdminConfigChangeRef[];
+ unchanged: AdminConfigChangeRef[];
+ ignored: IgnoredChange[];
+ appliedChanges: PreparedChange[];
+ }
+ type ChangesStop =
+ | { kind: 'issues'; issues: ConfigOverrideIssue[] }
+ | { kind: 'reentry'; issues: SecretReentryIssue[] }
+ | { kind: 'change'; failure: ChangeFailure };
+ type ChangesResult = { report: ChangesReport; stop?: never } | { stop: ChangesStop };
+
+ const plan = (
+ stored: ConfigRecord | null,
+ ): { draft: ConfigDraft | null; result: ChangesResult } => {
+ const report: ChangesReport = {
+ applied: [],
+ unchanged: [],
+ ignored: [],
+ appliedChanges: [],
+ };
+ const appliedSteps: ConfigChange[] = [];
+ let state: ConfigOverrideState = toConfigOverrideState(stored);
+ for (const change of changes) {
+ const steps = expandChange(change, state.overrides);
+ let next = state;
+ try {
+ for (const step of steps) {
+ next = applyConfigChange(next, step);
+ }
+ } catch (error) {
+ if (!isConfigPathError(error) && !isConfigEntryError(error)) {
+ throw error;
+ }
+ const failure: ChangeFailure = {
+ error: 'Config change cannot be applied to the stored config',
+ code: (error as ConfigPathError | ConfigEntryError).code,
+ reason: (error as ConfigPathError | ConfigEntryError).reason,
+ opIndex: change.index,
+ };
+ return { draft: null, result: { stop: { kind: 'change', failure } } };
+ }
+ const ref = toChangeRef(change);
+ if (next === state) {
+ report.unchanged.push(ref);
+ continue;
+ }
+ appliedSteps.push(...steps);
+ report.applied.push(ref);
+ report.appliedChanges.push(change);
+ for (const part of getIgnoredParts(change, yamlHeld)) {
+ report.ignored.push({ ...ref, ...part });
+ }
+ state = next;
+ }
+
+ /** Entries of a merged-by-key array are named by key: a write, a removal or a record
+ * rename that reaches into one by position is refused, since the position can name
+ * another entry by the time the batch is applied. */
+ const indexed = getIndexedMergeKeyIssues(
+ changes
+ .filter((change) => INDEXED_PATH_OPS.has(change.op))
+ .map((change) => change.target.segments),
+ );
+ if (indexed.length > 0) {
+ return { draft: null, result: { stop: { kind: 'issues', issues: indexed } } };
+ }
+ /** Changes that cancel out (a set, then an unset of its parent) leave nothing to write. */
+ const storedState = toConfigOverrideState(stored);
+ const documentChanged =
+ report.applied.length > 0 &&
+ !(
+ isSameConfigValue(state.overrides, storedState.overrides) &&
+ isSameConfigValue(state.tombstones, storedState.tombstones)
+ );
+ if (!documentChanged && report.applied.length > 0) {
+ report.unchanged = [...report.applied, ...report.unchanged].sort(
+ (left, right) => left.opIndex - right.opIndex,
+ );
+ report.applied = [];
+ report.ignored = [];
+ report.appliedChanges = [];
+ }
+ /** As on PUT, a priority for a principal without a document creates one that holds it. */
+ const priorityChanged = requestedPriority != null && requestedPriority !== stored?.priority;
+ if (!documentChanged && !priorityChanged) {
+ return { draft: null, result: { report } };
+ }
+ if (documentChanged) {
+ const written = getConfigBatchWrittenPaths(appliedSteps, state, storedState);
+ const issues = getConfigChangeIssues(state, baseYaml, stored, written);
+ if (issues.length > 0) {
+ return { draft: null, result: { stop: { kind: 'issues', issues } } };
+ }
+ /** Judged on the values the request sent: a secret a set kept from the stored
+ * document was not entered again. */
+ const requested = report.appliedChanges.flatMap((change) =>
+ change.op === 'set' && !change.paths
+ ? [{ segments: change.target.segments, value: change.value }]
+ : [],
+ );
+ const reentry = getBatchReentryIssues(stored, requested, state);
+ if (reentry.length > 0) {
+ return { draft: null, result: { stop: { kind: 'reentry', issues: reentry } } };
+ }
+ }
+ if (dryRun) {
+ return { draft: null, result: { report } };
+ }
+ return {
+ draft: {
+ principalModel: principalModel(principalType),
+ priority: requestedPriority ?? stored?.priority ?? DEFAULT_CONFIG_PRIORITY,
+ overrides: state.overrides,
+ tombstones: state.tombstones,
+ isActive: stored?.isActive ?? true,
+ },
+ result: { report },
+ };
+ };
+
+ let outcome;
+ try {
+ outcome = await runConfigMutation<ChangesResult>(
+ {
+ read: () => readStoredConfig(principalType, principalId),
+ write: (draft, revision) =>
+ writeConfigDocument(principalType, principalId, draft, revision),
+ },
+ plan,
+ { expectedRevision: expected.value },
+ );
+ } catch (error) {
+ return await writeFailureResponse(res, error, principalType, principalId);
+ }
+
+ const result = outcome.result as ChangesResult;
+ if (result.stop?.kind === 'change') {
+ return res.status(400).json(result.stop.failure);
+ }
+ if (result.stop?.kind === 'reentry') {
+ return secretReentryResponse(res, result.stop.issues);
+ }
+ if (result.stop) {
+ return invalidOverrideResponse(res, result.stop.issues, { skipped });
+ }
+ const { report } = result;
+ const config = outcome.written ? outcome.record : outcome.current;
+
+ if (outcome.written) {
+ await invalidateCaches(user.tenantId, 'changes');
+ const paths = new Map<string, string[]>();
+ for (const change of report.appliedChanges) {
+ paths.set(change.op, [...(paths.get(change.op) ?? []), describeChange(change)]);
+ }
+ await emitAudit(req, {
+ action: outcome.previous == null ? 'config.created' : 'config.updated',
+ target: configTarget(principalType, principalId),
+ metadata: {
+ operation: 'batch',
+ changes: report.applied.length,
+ priority: outcome.record.priority,
+ ...Object.fromEntries([...paths].map(([op, described]) => [op, described.join(',')])),
+ },
+ });
+ }
+
+ return res.status(200).json({
+ ...(dryRun
+ ? {}
+ : {
+ config: config
+ ? await toReadableConfig(user, config, { hasBroadManage, managedSections })
+ : null,
+ }),
+ revision: config ? getConfigRevision(config) : null,
+ written: outcome.written,
+ dryRun,
+ applied: report.applied,
+ skipped,
+ ignored: report.ignored,
+ unchanged: report.unchanged,
+ } satisfies Omit<AdminConfigChangesResponse, 'config'> & { config?: ConfigResponse | null });
+ } catch (error) {
+ logger.error('[adminConfig] applyConfigChanges error:', getSafeErrorMetadata(error));
+ return res.status(500).json({ error: 'Failed to apply config changes' });
+ }
+ }
+
/**
* DELETE /:principalType/:principalId — Delete an entire config override.
*/
@@ -2012,6 +2930,7 @@ export function createAdminConfigHandlers(deps: AdminConfigDeps): {
patchConfigField,
tombstoneConfigField,
deleteConfigField,
+ applyConfigChanges: applyChanges,
deleteConfigOverrides,
toggleConfig,
};
diff --git a/packages/api/src/admin/meta.spec.ts b/packages/api/src/admin/meta.spec.ts
index 036cae7c60..6a1e0e332b 100644
--- a/packages/api/src/admin/meta.spec.ts
+++ b/packages/api/src/admin/meta.spec.ts
@@ -180,6 +180,7 @@ describe('GET /api/admin/config/meta', () => {
expect(Object.keys(meta.versions)).toEqual(['librechat', 'dataProvider', 'configSchema']);
expect(Object.keys(meta.features).sort()).toEqual([
'awaitedInvalidation',
+ 'changesBatch',
'dottedKeys',
'expectedRevision',
'prunesEmptyParents',
@@ -187,7 +188,11 @@ describe('GET /api/admin/config/meta', () => {
'sectionAllowlist',
'webSearchStoredKeys',
]);
- expect(meta.limits).toEqual({ maxPatchEntries: 100, overrideCacheTtlMs: 60_000 });
+ expect(meta.limits).toEqual({
+ maxPatchEntries: 100,
+ maxChangeOps: 1000,
+ overrideCacheTtlMs: 60_000,
+ });
expect(Object.keys(meta.rules).sort()).toEqual([
'acceptedSections',
'arrayMergeKeys',
@@ -531,6 +536,57 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
return held && res.statusCode === 200 && bypassed && dropsStaleMerge;
},
+ async changesBatch() {
+ const writeConfigDocument = jest.fn(
+ async (_type: string, _id: string, draft: ConfigDraft): Promise<ConfigRecord> => ({
+ ...storedConfig(draft.overrides ?? {}),
+ tombstones: draft.tombstones ?? [],
+ configVersion: 2,
+ }),
+ );
+ const deps = {
+ findConfigByPrincipal: jest
+ .fn()
+ .mockResolvedValue(storedConfig({ interface: { customWelcome: 'v1' } })),
+ writeConfigDocument,
+ };
+ const send = async (ops: unknown[]) => {
+ const res = mockRes();
+ await createHandlers(deps).applyConfigChanges(
+ mockReq({ params: { principalType: 'role', principalId: 'r1' }, body: { ops } }),
+ res,
+ );
+ return res;
+ };
+
+ const tooMany = await send(
+ Array.from({ length: 1001 }, (_, i) => ({
+ op: 'set',
+ fieldPath: `interface.customWelcome${i}`,
+ value: 'x',
+ })),
+ );
+ const refused = await send([
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'v2' },
+ { op: 'set', fieldPath: 'interface.modelSelect', value: 'yes' },
+ ]);
+ const writesAfterRefusal = writeConfigDocument.mock.calls.length;
+ const applied = await send([
+ { op: 'set', fieldPath: 'interface.customWelcome', value: 'v2' },
+ { op: 'tombstone', fieldPath: 'interface.privacyPolicy' },
+ ]);
+ const [, , draft] = writeConfigDocument.mock.calls[0] ?? [];
+ return (
+ tooMany.statusCode === 400 &&
+ tooMany.body?.code === 'TOO_MANY_OPS' &&
+ refused.statusCode === 400 &&
+ writesAfterRefusal === 0 &&
+ applied.statusCode === 200 &&
+ writeConfigDocument.mock.calls.length === 1 &&
+ getIn(draft?.overrides ?? {}, 'interface.customWelcome') === 'v2' &&
+ (draft?.tombstones ?? []).includes('interface.privacyPolicy')
+ );
+ },
};
describe('meta feature flags', () => {
diff --git a/packages/api/src/admin/meta.ts b/packages/api/src/admin/meta.ts
index 331054c3c2..f6fa4c0f02 100644
--- a/packages/api/src/admin/meta.ts
+++ b/packages/api/src/admin/meta.ts
@@ -27,6 +27,7 @@ export const ADMIN_CONFIG_FEATURES: Readonly<AdminConfigFeatures> = {
expectedRevision: true,
prunesEmptyParents: true,
awaitedInvalidation: true,
+ changesBatch: true,
};
/**
diff --git a/packages/api/src/admin/secrets.spec.ts b/packages/api/src/admin/secrets.spec.ts
index c0468c8a35..fda6a18207 100644
--- a/packages/api/src/admin/secrets.spec.ts
+++ b/packages/api/src/admin/secrets.spec.ts
@@ -15,6 +15,7 @@ let getSecretAncestorPatterns: typeof import('./secrets').getSecretAncestorPatte
let matchesSecretPattern: typeof import('./secrets').matchesSecretPattern;
let isConfigSecretRelatedSegments: typeof import('./secrets').isConfigSecretRelatedSegments;
let isConfigSecretDescendantPath: typeof import('./secrets').isConfigSecretDescendantPath;
+let isConfigSecretKeyRename: typeof import('./secrets').isConfigSecretKeyRename;
let preserveConfigSecrets: typeof import('./secrets').preserveConfigSecrets;
let redactConfigSecrets: typeof import('./secrets').redactConfigSecrets;
let resolveConfigSecret: typeof import('./secrets').resolveConfigSecret;
@@ -37,6 +38,7 @@ beforeAll(async () => {
matchesSecretPattern,
isConfigSecretRelatedSegments,
isConfigSecretDescendantPath,
+ isConfigSecretKeyRename,
preserveConfigSecrets,
redactConfigSecrets,
resolveConfigSecret,
@@ -1099,3 +1101,25 @@ describe('Custom endpoint config secrets', () => {
expect(resolveCustomEndpointSecrets(passthrough)).toBe(passthrough);
});
});
+
+describe('isConfigSecretKeyRename', () => {
+ it('refuses a rename that would move a value onto or off a literal secret location', () => {
+ expect(isConfigSecretKeyRename(['webSearch'], 'serperApiKey', 'other')).toBe(true);
+ expect(isConfigSecretKeyRename(['webSearch'], 'other', 'serperApiKeyPreview')).toBe(true);
+ expect(isConfigSecretKeyRename(['speech', 'tts'], 'openai', 'mine')).toBe(true);
+ expect(isConfigSecretKeyRename(['langfuse'], 'displaySecretKey', 'x')).toBe(true);
+ });
+
+ it('refuses a rename inside a secret value', () => {
+ expect(isConfigSecretKeyRename(['webSearch', 'serperApiKey'], 'a', 'b')).toBe(true);
+ });
+
+ it('allows renames that never touch a registered location', () => {
+ expect(isConfigSecretKeyRename(['mcpServers'], 'a', 'b')).toBe(false);
+ expect(isConfigSecretKeyRename(['mcpServers', 'a', 'headers'], 'X-Old', 'X-New')).toBe(false);
+ expect(isConfigSecretKeyRename(['webSearch'], 'firecrawlOptions', 'other')).toBe(false);
+ expect(
+ isConfigSecretKeyRename(['endpoints', 'bedrock', 'inferenceProfiles'], 'us.a', 'eu.a'),
+ ).toBe(false);
+ });
+});
diff --git a/packages/api/src/admin/secrets.ts b/packages/api/src/admin/secrets.ts
index 9e7404e7a8..b0768181ff 100644
--- a/packages/api/src/admin/secrets.ts
+++ b/packages/api/src/admin/secrets.ts
@@ -409,6 +409,32 @@ export function isConfigSecretRelatedSegments(segments: readonly string[]): bool
});
}
+/**
+ * Whether renaming key `from` to `to` of the record at `segments` would carry a value onto or
+ * off a registered secret location: the record lies at or inside one, or a location names
+ * `from` or `to` literally at the renamed position. A location with a wildcard there (an entry
+ * of a record of servers, say) moves with its entry and stays registered.
+ */
+export function isConfigSecretKeyRename(
+ segments: readonly string[],
+ from: string,
+ to: string,
+): boolean {
+ const matches = (location: readonly string[], length: number): boolean =>
+ segments
+ .slice(0, length)
+ .every((segment, index) => location[index] === ANY_SEGMENT || location[index] === segment);
+ return SECRET_LOCATIONS.some((location) => {
+ if (location.length <= segments.length) {
+ return matches(location, location.length);
+ }
+ const key = location[segments.length];
+ return (
+ matches(location, segments.length) && key !== ANY_SEGMENT && (key === from || key === to)
+ );
+ });
+}
+
export function getConfigSecretInputError(fieldPath: string, value: unknown): string | null {
if (PREVIEW_PATHS.has(fieldPath)) {
return `Cannot write protected secret preview path: ${fieldPath}`;
diff --git a/packages/data-schemas/misc/documentdb/documentdb-compat.md b/packages/data-schemas/misc/documentdb/documentdb-compat.md
index 63e25673cd..6047806ec2 100644
--- a/packages/data-schemas/misc/documentdb/documentdb-compat.md
+++ b/packages/data-schemas/misc/documentdb/documentdb-compat.md
@@ -394,6 +394,10 @@ rules turn out. Values are never rewritten.
- No dotted-path `$set`/`$unset` or `$pull`/`$addToSet` touches `overrides` or
`tombstones`; every mutation is a pure transform followed by one
compare-and-swap on `{_id, configVersion}`, which every engine supports.
+ The batch route (`POST /api/admin/config/:type/:id/changes`, `src/app/changes.ts`)
+ applies any mix of set, unset, tombstone and entry changes (upsert, remove, rename)
+ to the decoded document and stores the result with that same single write, so it
+ needs nothing from the engine beyond the contract.
- Pre-release check on a real cluster: run the conformance runner
(`misc/ferretdb/configStore.ferretdb.spec.ts`, any MongoDB-compatible URI in
`FERRETDB_URI`) against DocumentDB 5.0 and Cosmos. It passes 24/24 against
diff --git a/packages/data-schemas/src/app/changes.spec.ts b/packages/data-schemas/src/app/changes.spec.ts
new file mode 100644
index 0000000000..57321d6fe0
--- /dev/null
+++ b/packages/data-schemas/src/app/changes.spec.ts
@@ -0,0 +1,540 @@
+import type { ConfigOverrideState } from './mutations';
+import type { ConfigChange } from './changes';
+import {
+ applyConfigChange,
+ isConfigEntryError,
+ applyConfigChanges,
+ isSameConfigValue,
+ getConfigBatchWrittenPaths,
+ getConfigChangeWrittenPaths,
+} from './changes';
+import { setConfigFields, unsetConfigPaths, tombstoneConfigPaths } from './mutations';
+import { isConfigPathError, parseFieldPath } from './paths';
+
+function state(overrides: Record<string, unknown>, tombstones: string[] = []): ConfigOverrideState {
+ return { overrides, tombstones };
+}
+
+const at = (fieldPath: string): string[] => parseFieldPath(fieldPath);
+
+/** Freezes a value and everything in it, so a transform that mutates its input throws. */
+function deepFreeze<T>(value: T): T {
+ if (value != null && typeof value === 'object') {
+ for (const child of Object.values(value)) {
+ deepFreeze(child);
+ }
+ Object.freeze(value);
+ }
+ return value;
+}
+
+function errorOf(run: () => unknown): unknown {
+ try {
+ run();
+ } catch (error) {
+ return error;
+ }
+ throw new Error('expected an error');
+}
+
+const CUSTOM = ['endpoints', 'custom'];
+
+const endpoint = (name: string, extra: Record<string, unknown> = {}) => ({
+ name,
+ baseURL: `https://${name}.example.com/v1`,
+ models: { default: ['m'] },
+ ...extra,
+});
+
+describe('applyConfigChanges: parity with the single-kind transforms', () => {
+ it('gives the same document as the same changes applied one request at a time', () => {
+ const stored = deepFreeze(
+ state(
+ {
+ interface: { modelSelect: true, customWelcome: 'hi' },
+ balance: { enabled: true, startBalance: 5 },
+ mcpServers: { github: { title: 'GH', url: 'https://gh' } },
+ },
+ ['memory.agent', 'webSearch'],
+ ),
+ );
+ const changes: ConfigChange[] = [
+ { op: 'set', segments: at('interface.modelSelect'), value: false },
+ { op: 'unset', segments: at('balance.startBalance') },
+ { op: 'tombstone', segments: at('mcpServers.github') },
+ { op: 'set', segments: at('webSearch.serperApiKey'), value: '${SERPER}' },
+ { op: 'unset', segments: at('memory') },
+ ];
+
+ let sequential: ConfigOverrideState = stored;
+ sequential = setConfigFields(sequential, [
+ { segments: at('interface.modelSelect'), value: false },
+ ]);
+ sequential = unsetConfigPaths(sequential, [at('balance.startBalance')]);
+ sequential = tombstoneConfigPaths(sequential, [at('mcpServers.github')]);
+ sequential = setConfigFields(sequential, [
+ { segments: at('webSearch.serperApiKey'), value: '${SERPER}' },
+ ]);
+ sequential = unsetConfigPaths(sequential, [at('memory')]);
+
+ const { state: batched, changed } = applyConfigChanges(stored, changes);
+
+ expect(batched).toEqual(sequential);
+ expect(batched).toEqual({
+ overrides: {
+ interface: { modelSelect: false, customWelcome: 'hi' },
+ balance: { enabled: true },
+ webSearch: { serperApiKey: '${SERPER}' },
+ },
+ /** A nested write keeps a whole-section tombstone. */
+ tombstones: ['webSearch', 'mcpServers.github'],
+ });
+ expect(changed).toEqual([true, true, true, true, true]);
+ });
+
+ it('applies changes in array order, so the last change to a subtree decides', () => {
+ const resetThenSet = applyConfigChanges(state({ a: { x: 1, y: 2 } }), [
+ { op: 'unset', segments: at('a') },
+ { op: 'set', segments: at('a.y'), value: 3 },
+ ]);
+ expect(resetThenSet.state.overrides).toEqual({ a: { y: 3 } });
+
+ const setThenReset = applyConfigChanges(state({ a: { x: 1 } }), [
+ { op: 'set', segments: at('a.y'), value: 3 },
+ { op: 'unset', segments: at('a') },
+ ]);
+ expect(setThenReset.state.overrides).toEqual({});
+
+ const hideThenShow = applyConfigChanges(state({}), [
+ { op: 'tombstone', segments: at('memory.agent') },
+ { op: 'set', segments: at('memory.agent.provider'), value: 'openAI' },
+ ]);
+ expect(hideThenShow.state).toEqual({
+ overrides: { memory: { agent: { provider: 'openAI' } } },
+ tombstones: [],
+ });
+ });
+
+ it('never changes its input, and leaves it untouched when a later change fails', () => {
+ const stored = deepFreeze(state({ a: { list: [1, 2] } }, ['b.c']));
+
+ const error = errorOf(() =>
+ applyConfigChanges(stored, [
+ { op: 'set', segments: at('a.z'), value: 1 },
+ { op: 'unset', segments: at('a.list.0') },
+ ]),
+ );
+
+ expect(isConfigPathError(error)).toBe(true);
+ expect(stored).toEqual(state({ a: { list: [1, 2] } }, ['b.c']));
+ });
+});
+
+describe('applyConfigChange: set, unset, tombstone', () => {
+ it('clears the written path and its ancestors below the section, never a whole section', () => {
+ const next = applyConfigChange(
+ state({}, ['memory', 'memory.agent', 'memory.agent.provider', 'memory.agent.model']),
+ { op: 'set', segments: at('memory.agent.provider'), value: 'openAI' },
+ );
+
+ expect(next.tombstones).toEqual(['memory', 'memory.agent.model']);
+ });
+
+ it('removes only the tombstones at or below an unset path', () => {
+ const next = applyConfigChange(
+ state({ mcpServers: { a: { title: 'A' } } }, [
+ 'mcpServers.a.headers.X',
+ 'mcpServers.a',
+ 'mcpServers.b',
+ 'mcpServers',
+ ]),
+ { op: 'unset', segments: at('mcpServers.a') },
+ );
+
+ expect(next).toEqual(state({}, ['mcpServers.b', 'mcpServers']));
+ });
+
+ it('never leaves a null in an array or shifts its elements', () => {
+ const stored = state({ endpoints: { custom: [endpoint('a', { headers: { X: '1' } })] } });
+
+ expect(
+ applyConfigChange(stored, { op: 'unset', segments: at('endpoints.custom.0.headers') })
+ .overrides,
+ ).toEqual({ endpoints: { custom: [endpoint('a')] } });
+
+ const error = errorOf(() =>
+ applyConfigChange(stored, { op: 'unset', segments: at('endpoints.custom.0') }),
+ );
+ expect(isConfigPathError(error) && error.reason).toBe('array_element');
+ });
+
+ it('addresses a record key that contains a dot by its segments', () => {
+ const path = ['endpoints', 'bedrock', 'inferenceProfiles', 'us.anthropic.claude-sonnet-4-5'];
+ const set = applyConfigChange(state({}), { op: 'set', segments: path, value: 'arn:1' });
+ expect(set.overrides).toEqual({
+ endpoints: { bedrock: { inferenceProfiles: { 'us.anthropic.claude-sonnet-4-5': 'arn:1' } } },
+ });
+
+ expect(applyConfigChange(set, { op: 'unset', segments: path }).overrides).toEqual({});
+
+ const error = errorOf(() => applyConfigChange(set, { op: 'tombstone', segments: path }));
+ expect(isConfigPathError(error) && error.reason).toBe('dotted_segment');
+ });
+
+ it('returns the same state for changes that alter nothing', () => {
+ const stored = deepFreeze(state({ a: { b: { c: 1 } } }, ['x.y']));
+
+ expect(applyConfigChange(stored, { op: 'set', segments: at('a.b'), value: { c: 1 } })).toBe(
+ stored,
+ );
+ expect(applyConfigChange(stored, { op: 'unset', segments: at('a.missing') })).toBe(stored);
+ expect(applyConfigChange(stored, { op: 'tombstone', segments: at('x.y') })).toBe(stored);
+ expect(applyConfigChange(stored, { op: 'set', segments: at('a.b'), value: { c: 2 } })).not.toBe(
+ stored,
+ );
+ });
+
+ it('treats a same-value set over its own tombstone as a change, since it clears it', () => {
+ const stored = state({ a: { b: 1 } }, ['a.b']);
+ const next = applyConfigChange(stored, { op: 'set', segments: at('a.b'), value: 1 });
+
+ expect(next).not.toBe(stored);
+ expect(next.tombstones).toEqual([]);
+ });
+});
+
+describe('applyConfigChange: upsertEntry and removeEntry', () => {
+ it('appends a new entry, creating the array', () => {
+ const next = applyConfigChange(state({ endpoints: { agents: { disableBuilder: true } } }), {
+ op: 'upsertEntry',
+ segments: CUSTOM,
+ entry: endpoint('a'),
+ });
+
+ expect(next.overrides).toEqual({
+ endpoints: { agents: { disableBuilder: true }, custom: [endpoint('a')] },
+ });
+ });
+
+ it('replaces the entry with the same key in place and drops later duplicates of it', () => {
+ const stored = state({
+ endpoints: {
+ custom: [endpoint('a'), endpoint('b', { apiKey: 'v3:x' }), endpoint('c'), endpoint('b')],
+ },
+ });
+
+ const next = applyConfigChange(stored, {
+ op: 'upsertEntry',
+ segments: CUSTOM,
+ entry: endpoint('b', { baseURL: 'https://new' }),
+ });
+
+ expect(next.overrides).toEqual({
+ endpoints: {
+ custom: [endpoint('a'), endpoint('b', { baseURL: 'https://new' }), endpoint('c')],
+ },
+ });
+ });
+
+ it('keeps a whole-collection tombstone: adding an own entry does not unhide inherited ones', () => {
+ const next = applyConfigChange(state({}, ['endpoints.custom']), {
+ op: 'upsertEntry',
+ segments: CUSTOM,
+ entry: endpoint('a'),
+ });
+
+ expect(next.tombstones).toEqual(['endpoints.custom']);
+ });
+
+ it('returns the same state for an identical upsert and a missing removal', () => {
+ const stored = deepFreeze(state({ endpoints: { custom: [endpoint('a')] } }));
+
+ expect(
+ applyConfigChange(stored, { op: 'upsertEntry', segments: CUSTOM, entry: endpoint('a') }),
+ ).toBe(stored);
+ expect(applyConfigChange(stored, { op: 'removeEntry', segments: CUSTOM, key: 'zzz' })).toBe(
+ stored,
+ );
+ });
+
+ it('removes every own entry with the key, and the array and its emptied parents once empty', () => {
+ const stored = state({
+ endpoints: { custom: [endpoint('a'), endpoint('b'), endpoint('a')] },
+ interface: { modelSelect: true },
+ });
+
+ const once = applyConfigChange(stored, { op: 'removeEntry', segments: CUSTOM, key: 'a' });
+ expect(once.overrides).toEqual({
+ endpoints: { custom: [endpoint('b')] },
+ interface: { modelSelect: true },
+ });
+
+ const empty = applyConfigChange(once, { op: 'removeEntry', segments: CUSTOM, key: 'b' });
+ expect(empty.overrides).toEqual({ interface: { modelSelect: true } });
+ });
+
+ it('refuses entry changes outside a merged-by-key array and entries without a key', () => {
+ const notKeyed = errorOf(() =>
+ applyConfigChange(state({}), {
+ op: 'upsertEntry',
+ segments: at('modelSpecs.list'),
+ entry: { name: 'x' },
+ }),
+ );
+ expect(isConfigEntryError(notKeyed) && notKeyed.reason).toBe('not_collection');
+
+ const keyless = errorOf(() =>
+ applyConfigChange(state({}), {
+ op: 'upsertEntry',
+ segments: CUSTOM,
+ entry: { baseURL: 'https://x' },
+ }),
+ );
+ expect(isConfigEntryError(keyless) && keyless.reason).toBe('invalid_entry');
+
+ const malformed = errorOf(() =>
+ applyConfigChange(state({ endpoints: { custom: { a: 1 } } }), {
+ op: 'removeEntry',
+ segments: CUSTOM,
+ key: 'a',
+ }),
+ );
+ expect(isConfigEntryError(malformed) && malformed.reason).toBe('not_collection');
+ });
+});
+
+describe('applyConfigChange: rename', () => {
+ it('renames an own merged-by-key entry in place, keeping what is stored on it', () => {
+ const stored = deepFreeze(
+ state({
+ endpoints: {
+ custom: [
+ endpoint('a'),
+ endpoint('old', { apiKey: 'v3:cipher', apiKeyPreview: '...abcd' }),
+ endpoint('c'),
+ ],
+ },
+ }),
+ );
+
+ const next = applyConfigChange(stored, {
+ op: 'rename',
+ segments: CUSTOM,
+ from: 'old',
+ to: 'new',
+ });
+
+ expect(next.overrides).toEqual({
+ endpoints: {
+ custom: [
+ endpoint('a'),
+ { ...endpoint('old', { apiKey: 'v3:cipher', apiKeyPreview: '...abcd' }), name: 'new' },
+ endpoint('c'),
+ ],
+ },
+ });
+ });
+
+ it('renames a record key, keeping the key order and clearing a tombstone of the new key', () => {
+ const stored = state(
+ {
+ mcpServers: {
+ first: { url: 'https://1' },
+ old: { url: 'https://2', headers: { X: '1' } },
+ last: { url: 'https://3' },
+ },
+ },
+ ['mcpServers.new', 'mcpServers.other'],
+ );
+
+ const next = applyConfigChange(stored, {
+ op: 'rename',
+ segments: ['mcpServers'],
+ from: 'old',
+ to: 'new',
+ });
+
+ expect(Object.keys((next.overrides as Record<string, object>).mcpServers)).toEqual([
+ 'first',
+ 'new',
+ 'last',
+ ]);
+ expect(next.overrides).toEqual({
+ mcpServers: {
+ first: { url: 'https://1' },
+ new: { url: 'https://2', headers: { X: '1' } },
+ last: { url: 'https://3' },
+ },
+ });
+ expect(next.tombstones).toEqual(['mcpServers.other']);
+ });
+
+ it('keeps a `__proto__` record key as data', () => {
+ const record = JSON.parse('{"a":1,"__proto__":{"polluted":true}}') as Record<string, unknown>;
+ const next = applyConfigChange(state({ headers: record }), {
+ op: 'rename',
+ segments: ['headers'],
+ from: 'a',
+ to: 'b',
+ });
+
+ const headers = (next.overrides as { headers: Record<string, unknown> }).headers;
+ expect(Object.keys(headers)).toEqual(['b', '__proto__']);
+ expect(({} as { polluted?: boolean }).polluted).toBeUndefined();
+ });
+
+ it('refuses a missing entry and a taken name, and ignores a rename to the same name', () => {
+ const stored = state({ endpoints: { custom: [endpoint('a'), endpoint('b')] } });
+
+ const missing = errorOf(() =>
+ applyConfigChange(stored, { op: 'rename', segments: CUSTOM, from: 'zzz', to: 'c' }),
+ );
+ expect(isConfigEntryError(missing) && missing.reason).toBe('entry_not_found');
+
+ const taken = errorOf(() =>
+ applyConfigChange(stored, { op: 'rename', segments: CUSTOM, from: 'a', to: 'b' }),
+ );
+ expect(isConfigEntryError(taken) && taken.reason).toBe('entry_exists');
+
+ const missingRecord = errorOf(() =>
+ applyConfigChange(state({}), {
+ op: 'rename',
+ segments: ['mcpServers'],
+ from: 'a',
+ to: 'b',
+ }),
+ );
+ expect(isConfigEntryError(missingRecord) && missingRecord.reason).toBe('entry_not_found');
+
+ expect(applyConfigChange(stored, { op: 'rename', segments: CUSTOM, from: 'a', to: 'a' })).toBe(
+ stored,
+ );
+ });
+
+ it('lets a renamed entry be edited by its new name later in the same batch', () => {
+ const { state: next, changed } = applyConfigChanges(
+ state({ endpoints: { custom: [endpoint('old', { apiKey: 'v3:cipher' })] } }),
+ [
+ { op: 'rename', segments: CUSTOM, from: 'old', to: 'new' },
+ { op: 'set', segments: at('interface.modelSelect'), value: true },
+ {
+ op: 'upsertEntry',
+ segments: CUSTOM,
+ entry: endpoint('new', { apiKey: 'v3:cipher', baseURL: 'https://changed' }),
+ },
+ ],
+ );
+
+ expect(next.overrides).toEqual({
+ endpoints: {
+ custom: [endpoint('new', { apiKey: 'v3:cipher', baseURL: 'https://changed' })],
+ },
+ interface: { modelSelect: true },
+ });
+ expect(changed).toEqual([true, true, true]);
+ });
+});
+
+describe('getConfigChangeWrittenPaths', () => {
+ it('names a field change by its path and an entry change by the entry it wrote, a removal by nothing', () => {
+ const result = state({ endpoints: { custom: [endpoint('a'), endpoint('b')] } });
+
+ expect(
+ getConfigChangeWrittenPaths({ op: 'set', segments: at('a.b'), value: 1 }, result),
+ ).toEqual([['a', 'b']]);
+ expect(
+ getConfigChangeWrittenPaths(
+ { op: 'upsertEntry', segments: CUSTOM, entry: endpoint('b') },
+ result,
+ ),
+ ).toEqual([['endpoints', 'custom', '1']]);
+ expect(
+ getConfigChangeWrittenPaths({ op: 'rename', segments: CUSTOM, from: 'x', to: 'b' }, result),
+ ).toEqual([['endpoints', 'custom', '1']]);
+ expect(
+ getConfigChangeWrittenPaths({ op: 'removeEntry', segments: CUSTOM, key: 'a' }, result),
+ ).toEqual([]);
+ expect(
+ getConfigChangeWrittenPaths(
+ { op: 'rename', segments: ['mcpServers'], from: 'x', to: 'y' },
+ result,
+ ),
+ ).toEqual([
+ ['mcpServers', 'x'],
+ ['mcpServers', 'y'],
+ ]);
+ });
+});
+
+describe('getConfigBatchWrittenPaths', () => {
+ const written = (stored: ConfigOverrideState, changes: ConfigChange[]): string[][] =>
+ getConfigBatchWrittenPaths(changes, applyConfigChanges(stored, changes).state, stored);
+
+ it('leaves out what a later change of the batch puts back as stored', () => {
+ const balance = { enabled: true, startBalance: 'legacy' };
+ const stored = state({ balance });
+
+ expect(
+ written(stored, [
+ { op: 'set', segments: at('balance.startBalance'), value: 1000 },
+ { op: 'set', segments: at('balance'), value: balance },
+ { op: 'set', segments: at('interface.customWelcome'), value: 'hi' },
+ ]),
+ ).toEqual([['interface', 'customWelcome']]);
+ expect(
+ written(stored, [
+ { op: 'set', segments: at('balance.startBalance'), value: 1000 },
+ { op: 'set', segments: at('balance'), value: { ...balance, enabled: false } },
+ ]),
+ ).toEqual([['balance']]);
+ });
+
+ it('keeps a path whose inherited value a tombstone change hides or shows again', () => {
+ const stored = state({ memory: { agent: { id: 'a' } } }, ['interface']);
+
+ expect(
+ written(stored, [
+ { op: 'unset', segments: at('memory.agent.id') },
+ { op: 'set', segments: at('memory.agent.id'), value: 'a' },
+ ]),
+ ).toEqual([]);
+ expect(
+ written(stored, [
+ { op: 'set', segments: at('memory.agent.id'), value: 'a' },
+ { op: 'tombstone', segments: at('memory.agent') },
+ ]),
+ ).toEqual([
+ ['memory', 'agent', 'id'],
+ ['memory', 'agent'],
+ ]);
+ expect(written(stored, [{ op: 'unset', segments: at('interface') }])).toEqual([['interface']]);
+ });
+
+ it('names an entry where the batch leaves it and compares it with the stored entry of its key', () => {
+ const stored = state({ endpoints: { custom: [endpoint('a'), endpoint('b'), endpoint('c')] } });
+
+ expect(
+ written(stored, [
+ { op: 'upsertEntry', segments: CUSTOM, entry: { ...endpoint('b'), models: ['n'] } },
+ { op: 'removeEntry', segments: CUSTOM, key: 'a' },
+ ]),
+ ).toEqual([['endpoints', 'custom', '0']]);
+ expect(
+ written(stored, [
+ { op: 'rename', segments: CUSTOM, from: 'c', to: 'z' },
+ { op: 'rename', segments: CUSTOM, from: 'z', to: 'c' },
+ { op: 'removeEntry', segments: CUSTOM, key: 'a' },
+ ]),
+ ).toEqual([]);
+ });
+});
+
+describe('isSameConfigValue', () => {
+ it('compares JSON structurally, ignoring object key order but not array order', () => {
+ expect(isSameConfigValue({ a: 1, b: [1, { c: 2 }] }, { b: [1, { c: 2 }], a: 1 })).toBe(true);
+ expect(isSameConfigValue([1, 2], [2, 1])).toBe(false);
+ expect(isSameConfigValue({ a: undefined }, {})).toBe(false);
+ expect(isSameConfigValue({ a: 1 }, { a: '1' })).toBe(false);
+ expect(isSameConfigValue(null, {})).toBe(false);
+ });
+});
diff --git a/packages/data-schemas/src/app/changes.ts b/packages/data-schemas/src/app/changes.ts
new file mode 100644
index 0000000000..5a5353cfe0
--- /dev/null
+++ b/packages/data-schemas/src/app/changes.ts
@@ -0,0 +1,490 @@
+import type { TCustomConfig } from 'librechat-data-provider';
+import type { ConfigOverrideState } from './mutations';
+import type { ConfigPathSegments } from './paths';
+import {
+ getAtPath,
+ setAtPath,
+ unsetAtPath,
+ isPlainRecord,
+ parseFieldPath,
+ ConfigPathError,
+ isSegmentPrefix,
+ pruneEmptyAncestors,
+ getClearedTombstones,
+} from './paths';
+import { setConfigFields, unsetConfigPaths, tombstoneConfigPaths } from './mutations';
+import { getConfigArrayMergeKey } from './resolution';
+
+/**
+ * Atomic batches of override changes.
+ *
+ * Every change is a pure transform of a principal's {@link ConfigOverrideState}, applied in
+ * array order to the decoded document, so a batch is one read, any number of changes, and one
+ * compare-and-swap write. Nothing here knows how a document is stored: an engine only ever
+ * sees the finished document.
+ *
+ * Each transform returns its input state unchanged (the same object) when it changes nothing,
+ * so a caller can tell an effective change from a no-op by identity.
+ */
+
+/**
+ * The most changes one batch may carry. It is a fixed part of the admin API contract rather
+ * than a `librechat.yaml` setting: clients split larger saves against it, so it is the same on
+ * every deployment. The 3 MB JSON body limit bounds a batch's size; this bounds its work, since
+ * each change is checked, has its secrets resolved and is applied in turn within one request.
+ */
+export const MAX_CONFIG_CHANGE_OPS = 1000;
+
+export type ConfigChange =
+ /** Writes `value` at the path and clears the tombstones the write covers. */
+ | { op: 'set'; segments: ConfigPathSegments; value: unknown }
+ /** Removes the override at the path, its emptied parents, and tombstones at or below it. */
+ | { op: 'unset'; segments: ConfigPathSegments }
+ /** Removes the override at the path and records a tombstone that hides inherited values. */
+ | { op: 'tombstone'; segments: ConfigPathSegments }
+ /**
+ * Replaces the principal's own entry of a merged-by-key array whose key matches the entry's
+ * (every own entry with that key), or appends it. The array is created when missing.
+ */
+ | { op: 'upsertEntry'; segments: ConfigPathSegments; entry: Record<string, unknown> }
+ /** Removes the principal's own entries of a merged-by-key array that have this key. */
+ | { op: 'removeEntry'; segments: ConfigPathSegments; key: string }
+ /**
+ * Renames one of the principal's own entries, moving everything stored on it (encrypted
+ * secrets included): an entry of a merged-by-key array gets a new key value in place, and a
+ * record key is moved with its value, keeping the record's key order.
+ */
+ | { op: 'rename'; segments: ConfigPathSegments; from: string; to: string };
+
+export type ConfigChangeKind = ConfigChange['op'];
+
+/** Why an entry change cannot apply to the stored document. */
+export type ConfigEntryErrorReason =
+ /** The path holds neither a merged-by-key array nor (for a rename) an object. */
+ | 'not_collection'
+ /** The entry is not an object, or its key field is not a non-empty string. */
+ | 'invalid_entry'
+ /** A rename names an entry the principal does not have. */
+ | 'entry_not_found'
+ /** A rename's new key is already one of the principal's entries. */
+ | 'entry_exists';
+
+/**
+ * An entry change that cannot apply to the document as stored. Like `ConfigPathError`, the
+ * message never echoes submitted keys.
+ */
+export class ConfigEntryError extends Error {
+ readonly code = 'CONFIG_ENTRY_INVALID';
+
+ constructor(
+ readonly segments: string[],
+ readonly reason: ConfigEntryErrorReason,
+ ) {
+ super(`Config entry change cannot be applied: ${reason}`);
+ this.name = 'ConfigEntryError';
+ }
+}
+
+export function isConfigEntryError(error: unknown): error is ConfigEntryError {
+ return (
+ error instanceof ConfigEntryError ||
+ (error instanceof Error && (error as { code?: unknown }).code === 'CONFIG_ENTRY_INVALID')
+ );
+}
+
+type JsonRecord = { [key: string]: unknown };
+
+/** Structural equality of JSON values; object key order does not matter. */
+export function isSameConfigValue(left: unknown, right: unknown): boolean {
+ if (left === right) {
+ return true;
+ }
+ if (Array.isArray(left)) {
+ return (
+ Array.isArray(right) &&
+ left.length === right.length &&
+ left.every((item, index) => isSameConfigValue(item, right[index]))
+ );
+ }
+ if (!isPlainRecord(left) || !isPlainRecord(right)) {
+ return false;
+ }
+ const keys = Object.keys(left);
+ return (
+ keys.length === Object.keys(right).length &&
+ keys.every(
+ (key) =>
+ Object.prototype.hasOwnProperty.call(right, key) &&
+ isSameConfigValue(left[key], right[key]),
+ )
+ );
+}
+
+function hasPath(root: unknown, segments: ConfigPathSegments): boolean {
+ const parent = segments.length > 1 ? getAtPath(root, segments.slice(0, -1)) : root;
+ const key = segments[segments.length - 1];
+ if (Array.isArray(parent)) {
+ return /^(?:0|[1-9]\d*)$/.test(key) && Number(key) < parent.length;
+ }
+ return isPlainRecord(parent) && Object.prototype.hasOwnProperty.call(parent, key);
+}
+
+function isSameState(left: ConfigOverrideState, right: ConfigOverrideState): boolean {
+ return (
+ left.overrides === right.overrides &&
+ left.tombstones.length === right.tombstones.length &&
+ left.tombstones.every((path, index) => path === right.tombstones[index])
+ );
+}
+
+function asRecord(state: ConfigOverrideState): JsonRecord {
+ return state.overrides as JsonRecord;
+}
+
+function withOverrides(state: ConfigOverrideState, overrides: JsonRecord): ConfigOverrideState {
+ return { overrides: overrides as Partial<TCustomConfig>, tombstones: state.tombstones };
+}
+
+function applySet(
+ state: ConfigOverrideState,
+ segments: ConfigPathSegments,
+ value: unknown,
+): ConfigOverrideState {
+ const cleared = new Set(getClearedTombstones(segments));
+ const unchanged =
+ hasPath(state.overrides, segments) &&
+ isSameConfigValue(getAtPath(state.overrides, segments), value) &&
+ !state.tombstones.some((path) => cleared.has(path));
+ return unchanged ? state : setConfigFields(state, [{ segments, value }]);
+}
+
+function keepIfSame(state: ConfigOverrideState, next: ConfigOverrideState): ConfigOverrideState {
+ return isSameState(state, next) ? state : next;
+}
+
+/** The principal's own array at a merged-by-key path, `[]` when it has none. */
+function readKeyedArray(state: ConfigOverrideState, segments: ConfigPathSegments): unknown[] {
+ const current = getAtPath(state.overrides, segments);
+ if (current === undefined) {
+ return [];
+ }
+ if (!Array.isArray(current)) {
+ throw new ConfigEntryError([...segments], 'not_collection');
+ }
+ return current;
+}
+
+function requireKeyField(segments: ConfigPathSegments): string {
+ const keyField = getConfigArrayMergeKey(segments);
+ if (!keyField) {
+ throw new ConfigEntryError([...segments], 'not_collection');
+ }
+ return keyField;
+}
+
+function hasKey(item: unknown, keyField: string, key: string): boolean {
+ return isPlainRecord(item) && item[keyField] === key;
+}
+
+/** The key of an entry written into a merged-by-key array. */
+export function getConfigEntryKey(entry: unknown, keyField: string): string | undefined {
+ if (!isPlainRecord(entry)) {
+ return undefined;
+ }
+ const key = entry[keyField];
+ return typeof key === 'string' && key !== '' ? key : undefined;
+}
+
+/** Writes `items` back at `segments`, removing the array (and emptied parents) once empty. */
+function writeKeyedArray(
+ state: ConfigOverrideState,
+ segments: ConfigPathSegments,
+ items: unknown[],
+): ConfigOverrideState {
+ if (items.length > 0) {
+ return withOverrides(state, setAtPath(asRecord(state), segments, items));
+ }
+ const removed = unsetAtPath(asRecord(state), segments);
+ return withOverrides(state, pruneEmptyAncestors(removed, segments));
+}
+
+function applyUpsertEntry(
+ state: ConfigOverrideState,
+ segments: ConfigPathSegments,
+ entry: Record<string, unknown>,
+): ConfigOverrideState {
+ const keyField = requireKeyField(segments);
+ const key = getConfigEntryKey(entry, keyField);
+ if (key === undefined) {
+ throw new ConfigEntryError([...segments], 'invalid_entry');
+ }
+ const items = readKeyedArray(state, segments);
+ const index = items.findIndex((item) => hasKey(item, keyField, key));
+ const next =
+ index === -1
+ ? [...items, entry]
+ : items.flatMap((item, position) => {
+ if (position === index) {
+ return [entry];
+ }
+ return hasKey(item, keyField, key) ? [] : [item];
+ });
+ return isSameConfigValue(items, next) ? state : writeKeyedArray(state, segments, next);
+}
+
+function applyRemoveEntry(
+ state: ConfigOverrideState,
+ segments: ConfigPathSegments,
+ key: string,
+): ConfigOverrideState {
+ const keyField = requireKeyField(segments);
+ const items = readKeyedArray(state, segments);
+ const next = items.filter((item) => !hasKey(item, keyField, key));
+ return next.length === items.length ? state : writeKeyedArray(state, segments, next);
+}
+
+function renameKeyedEntry(
+ state: ConfigOverrideState,
+ segments: ConfigPathSegments,
+ keyField: string,
+ from: string,
+ to: string,
+): ConfigOverrideState {
+ const items = readKeyedArray(state, segments);
+ const index = items.findIndex((item) => hasKey(item, keyField, from));
+ if (index === -1) {
+ throw new ConfigEntryError([...segments], 'entry_not_found');
+ }
+ if (items.some((item) => hasKey(item, keyField, to))) {
+ throw new ConfigEntryError([...segments], 'entry_exists');
+ }
+ const next = items.map((item) =>
+ hasKey(item, keyField, from) ? { ...(item as JsonRecord), [keyField]: to } : item,
+ );
+ return writeKeyedArray(state, segments, next);
+}
+
+/** Moves record key `from` to `to`, keeping the key order. */
+function renameRecordKey(
+ state: ConfigOverrideState,
+ segments: ConfigPathSegments,
+ from: string,
+ to: string,
+): ConfigOverrideState {
+ const record = getAtPath(state.overrides, segments);
+ if (record !== undefined && !isPlainRecord(record)) {
+ throw new ConfigEntryError([...segments], 'not_collection');
+ }
+ if (!record || !Object.prototype.hasOwnProperty.call(record, from)) {
+ throw new ConfigEntryError([...segments], 'entry_not_found');
+ }
+ if (Object.prototype.hasOwnProperty.call(record, to)) {
+ throw new ConfigEntryError([...segments], 'entry_exists');
+ }
+ const renamed: JsonRecord = {};
+ for (const [key, value] of Object.entries(record)) {
+ /** Defined rather than assigned, so a `__proto__` key stays data. */
+ Object.defineProperty(renamed, key === from ? to : key, {
+ value,
+ enumerable: true,
+ writable: true,
+ configurable: true,
+ });
+ }
+ const cleared = new Set(getClearedTombstones([...segments, to]));
+ return {
+ overrides: setAtPath(asRecord(state), segments, renamed) as Partial<TCustomConfig>,
+ tombstones: state.tombstones.filter((path) => !cleared.has(path)),
+ };
+}
+
+function applyRename(
+ state: ConfigOverrideState,
+ segments: ConfigPathSegments,
+ from: string,
+ to: string,
+): ConfigOverrideState {
+ if (from === to) {
+ return state;
+ }
+ if (from === '' || to === '') {
+ throw new ConfigEntryError([...segments], 'invalid_entry');
+ }
+ const keyField = getConfigArrayMergeKey(segments);
+ return keyField
+ ? renameKeyedEntry(state, segments, keyField, from, to)
+ : renameRecordKey(state, segments, from, to);
+}
+
+/**
+ * Applies one change. A path the document cannot take throws a `ConfigPathError`; an entry
+ * change that cannot apply throws a {@link ConfigEntryError}. Returns `state` itself when the
+ * change leaves the document as it was.
+ */
+export function applyConfigChange(
+ state: ConfigOverrideState,
+ change: ConfigChange,
+): ConfigOverrideState {
+ if (change.segments.length === 0) {
+ throw new ConfigPathError([], 'empty_path');
+ }
+ switch (change.op) {
+ case 'set':
+ return applySet(state, change.segments, change.value);
+ case 'unset':
+ return keepIfSame(state, unsetConfigPaths(state, [change.segments]));
+ case 'tombstone':
+ return keepIfSame(state, tombstoneConfigPaths(state, [change.segments]));
+ case 'upsertEntry':
+ return applyUpsertEntry(state, change.segments, change.entry);
+ case 'removeEntry':
+ return applyRemoveEntry(state, change.segments, change.key);
+ case 'rename':
+ return applyRename(state, change.segments, change.from, change.to);
+ default: {
+ const unknownChange: never = change;
+ throw new Error(`Unknown config change: ${String((unknownChange as ConfigChange).op)}`);
+ }
+ }
+}
+
+/** The result of {@link applyConfigChanges}: the final state, and which changes had an effect. */
+export interface ConfigChangesResult {
+ state: ConfigOverrideState;
+ /** `changed[i]` is whether change `i` altered the document it was applied to. */
+ changed: boolean[];
+}
+
+/**
+ * Applies changes in array order, each to the result of the one before, exactly as the same
+ * changes sent one request at a time would. Throws on the first change that cannot apply,
+ * leaving the input untouched.
+ */
+export function applyConfigChanges(
+ state: ConfigOverrideState,
+ changes: readonly ConfigChange[],
+): ConfigChangesResult {
+ const changed: boolean[] = [];
+ let current = state;
+ for (const change of changes) {
+ const next = applyConfigChange(current, change);
+ changed.push(next !== current);
+ current = next;
+ }
+ return { state: current, changed };
+}
+
+/**
+ * The paths a change writes, for attributing validation issues to it: the path itself, or for
+ * an entry change, the entry by its index in `result`'s own array. A removed entry is gone, so
+ * `removeEntry` writes nothing an issue could sit on: the entries it leaves are unchanged, and
+ * their existing issues must not block the removal. Likewise an entry `result` no longer holds
+ * (a later change of the batch renamed it back) leaves nothing written behind.
+ */
+export function getConfigChangeWrittenPaths(
+ change: ConfigChange,
+ result: ConfigOverrideState,
+): string[][] {
+ const segments = [...change.segments];
+ if (change.op === 'set' || change.op === 'unset' || change.op === 'tombstone') {
+ return [segments];
+ }
+ if (change.op === 'removeEntry') {
+ return [];
+ }
+ const keyField = getConfigArrayMergeKey(change.segments);
+ if (change.op === 'rename' && !keyField) {
+ return [
+ [...segments, change.from],
+ [...segments, change.to],
+ ];
+ }
+ const key =
+ change.op === 'rename' ? change.to : keyField && getConfigEntryKey(change.entry, keyField);
+ const items = getAtPath(result.overrides, segments);
+ const index =
+ Array.isArray(items) && keyField && key
+ ? items.findIndex((item) => hasKey(item, keyField, key))
+ : -1;
+ return index === -1 ? [] : [[...segments, String(index)]];
+}
+
+/**
+ * The value `stored` holds at the location `segments` names in `result`: an entry of a
+ * merged-by-key array is the stored entry with the same key, wherever it sits.
+ */
+function getStoredCounterpart(
+ segments: ConfigPathSegments,
+ result: unknown,
+ stored: unknown,
+): unknown {
+ let current = result;
+ let counterpart = stored;
+ for (let index = 0; index < segments.length; index++) {
+ const segment = segments[index];
+ const next = getAtPath(current, [segment]);
+ const keyField = Array.isArray(current)
+ ? getConfigArrayMergeKey(segments.slice(0, index))
+ : undefined;
+ const key = keyField ? getConfigEntryKey(next, keyField) : undefined;
+ if (keyField && key !== undefined) {
+ counterpart = Array.isArray(counterpart)
+ ? counterpart.find((item) => hasKey(item, keyField, key))
+ : undefined;
+ } else {
+ counterpart = getAtPath(counterpart, [segment]);
+ }
+ current = next;
+ }
+ return counterpart;
+}
+
+/** The tombstones at, above or below `segments`: the ones that decide what it inherits. */
+function getRelatedTombstones(
+ tombstones: readonly string[],
+ segments: ConfigPathSegments,
+): Set<string> {
+ return new Set(
+ tombstones.filter((path) => {
+ const tombstone = parseFieldPath(path);
+ return isSegmentPrefix(tombstone, segments) || isSegmentPrefix(segments, tombstone);
+ }),
+ );
+}
+
+/** Whether `result` holds the location `segments` names there other than `stored` does. */
+function isChangedLocation(
+ segments: ConfigPathSegments,
+ result: ConfigOverrideState,
+ stored: ConfigOverrideState,
+): boolean {
+ const value = getAtPath(result.overrides, segments);
+ if (
+ !isSameConfigValue(value, getStoredCounterpart(segments, result.overrides, stored.overrides))
+ ) {
+ return true;
+ }
+ const before = getRelatedTombstones(stored.tombstones, segments);
+ const after = getRelatedTombstones(result.tombstones, segments);
+ return before.size !== after.size || [...after].some((path) => !before.has(path));
+}
+
+/**
+ * The paths a batch writes, judged on its end state, for attributing validation issues to it.
+ * Each change's paths ({@link getConfigChangeWrittenPaths}) are located in `result`, the state
+ * after the whole batch, so an entry a later change moves is still named by where it ends up.
+ * Only the paths `result` holds differently from `stored` are kept: a change a later one undoes
+ * (set a field, then restore its parent) writes nothing in the end, so issues the stored
+ * document already had there are left to merge time instead of blocking the rest of the batch.
+ */
+export function getConfigBatchWrittenPaths(
+ changes: readonly ConfigChange[],
+ result: ConfigOverrideState,
+ stored: ConfigOverrideState,
+): string[][] {
+ return changes.flatMap((change) =>
+ getConfigChangeWrittenPaths(change, result).filter((segments) =>
+ isChangedLocation(segments, result, stored),
+ ),
+ );
+}
diff --git a/packages/data-schemas/src/app/conformance.ts b/packages/data-schemas/src/app/conformance.ts
index 3b5a0200a1..ff191171dd 100644
--- a/packages/data-schemas/src/app/conformance.ts
+++ b/packages/data-schemas/src/app/conformance.ts
@@ -26,6 +26,8 @@ import {
getConfigRevision,
} from './store';
import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
+import { toConfigOverrideState } from './mutations';
+import { applyConfigChanges } from './changes';
export interface ConfigStoreHarness {
readonly name: string;
@@ -456,6 +458,69 @@ export function describeConfigStoreConformance(harness: ConfigStoreHarness): voi
expect(shown.configVersion).toBe(4);
});
+ it('stores a batch of changes, renames and awkward keys included, as one write', async () => {
+ const headers = keyedObject(2);
+ const created = await store.write(
+ role('batch'),
+ draft({
+ endpoints: {
+ custom: [{ name: 'old', apiKey: 'v3:cipher', baseURL: 'https://old.example.com' }],
+ },
+ mcpServers: { a: { url: 'https://a.example.com', headers } },
+ }),
+ ABSENT_CONFIG_REVISION,
+ );
+
+ const { state, changed } = applyConfigChanges(toConfigOverrideState(created), [
+ { op: 'rename', segments: ['endpoints', 'custom'], from: 'old', to: 'new' },
+ { op: 'rename', segments: ['mcpServers'], from: 'a', to: 'b' },
+ {
+ op: 'set',
+ segments: ['mcpServers', 'b', 'headers', '$set'],
+ value: { 'x.y': '$', 'ünï.cödé': 1 },
+ },
+ {
+ op: 'set',
+ segments: [
+ 'endpoints',
+ 'bedrock',
+ 'inferenceProfiles',
+ 'us.anthropic.claude-sonnet-4-5',
+ ],
+ value: 'arn:aws:bedrock:us-east-1:1:inference-profile/x',
+ },
+ { op: 'tombstone', segments: ['memory', 'agent'] },
+ { op: 'unset', segments: ['mcpServers', 'missing'] },
+ ]);
+ expect(changed).toEqual([true, true, true, true, true, false]);
+
+ const written = await store.write(
+ role('batch'),
+ draft(state.overrides as Record<string, unknown>, { tombstones: state.tombstones }),
+ getConfigRevision(created),
+ );
+
+ expect(written.configVersion).toBe(2);
+ const stored = await store.read(role('batch'));
+ expect(stored?.overrides).toEqual({
+ endpoints: {
+ custom: [{ name: 'new', apiKey: 'v3:cipher', baseURL: 'https://old.example.com' }],
+ bedrock: {
+ inferenceProfiles: {
+ 'us.anthropic.claude-sonnet-4-5': 'arn:aws:bedrock:us-east-1:1:inference-profile/x',
+ },
+ },
+ },
+ mcpServers: {
+ b: {
+ url: 'https://a.example.com',
+ headers: { ...headers, $set: { 'x.y': '$', 'ünï.cödé': 1 } },
+ },
+ },
+ });
+ expect(stored?.tombstones).toEqual(['memory.agent']);
+ });
+
it('surfaces a conflict when a caller-supplied revision is stale', async () => {
const operations = createConfigOperations(store);
const first = await operations.setFields(role('stale-op'), PrincipalModel.ROLE, {
diff --git a/packages/data-schemas/src/app/index.ts b/packages/data-schemas/src/app/index.ts
index ba0d00d0c2..0bc80cd458 100644
--- a/packages/data-schemas/src/app/index.ts
+++ b/packages/data-schemas/src/app/index.ts
@@ -10,3 +10,4 @@ export * from './resolution';
export * from './paths';
export * from './mutations';
export * from './store';
+export * from './changes';
diff --git a/packages/data-schemas/src/app/paths.ts b/packages/data-schemas/src/app/paths.ts
index 7bdbd266eb..c88b0596be 100644
--- a/packages/data-schemas/src/app/paths.ts
+++ b/packages/data-schemas/src/app/paths.ts
@@ -26,6 +26,8 @@ export type ConfigPathErrorReason =
| 'array_index'
/** The path ends on an array element, which a removal would leave as `null`. */
| 'array_element'
+ /** A tombstone names an array element or a path inside one; only whole arrays can be hidden. */
+ | 'inside_array'
/** A tombstone (or another dotted-path consumer) would have to split a segment with a dot. */
| 'dotted_segment'
/** A segment starts with `$` or names a reserved key (`__*`, `constructor`, `prototype`). */
diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.ts
index 0eca4e8a61..9f631fda2f 100644
--- a/packages/data-schemas/src/app/resolution.spec.ts
+++ b/packages/data-schemas/src/app/resolution.spec.ts
@@ -6,14 +6,22 @@ import {
import type { TCustomConfig, TWebSearchConfigInput } from 'librechat-data-provider';
import type { AppConfig, IConfig } from '~/types';
import {
+ isConfigRecordPath,
getConfigMergeRules,
mergeConfigOverrides,
+ isConfigArrayItemPath,
+ isAcceptedOverrideSection,
getConfigFieldIssues,
applyConfigTombstones,
+ getConfigChangeIssues,
+ getConfigArrayMergeKey,
getDottedSectionIssues,
getConfigOverrideIssues,
+ getIndexedMergeKeyIssues,
} from './resolution';
import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
+import { toConfigOverrideState } from './mutations';
+import { applyConfigChanges } from './changes';
import { loadWebSearchConfig } from './web';
import logger from '~/config/winston';
@@ -198,6 +206,10 @@ describe('mergeConfigOverrides', () => {
const removed = read([fakeConfig({}, 10, ['endpoints.agents.pullRequests.host'])]);
expect(removed.host).toBe('ghe.example.com');
+ for (const ancestor of ['endpoints', 'endpoints.agents', 'endpoints.agents.pullRequests']) {
+ expect(read([fakeConfig({}, 10, [ancestor])])).toEqual({ host: 'ghe.example.com' });
+ }
+
const unset = { endpoints: { agents: { pullRequests: {} } } } as unknown as AppConfig;
const added = mergeConfigOverrides(unset, [
fakeConfig({ endpoints: { agents: { pullRequests: { host: 'evil.example.com' } } } }, 10),
@@ -1955,3 +1967,262 @@ describe('getConfigFieldIssues', () => {
).toEqual([]);
});
});
+
+describe('getConfigFieldIssues: tombstones a write clears', () => {
+ const unionBase = {
+ memory: { agent: { id: 'agent_yaml' } },
+ } as unknown as Partial<TCustomConfig>;
+
+ it('lets a write replace a hidden field with its own value, as sequential clients do', () => {
+ const stored = {
+ overrides: { memory: { agent: { provider: 'openAI', model: 'gpt-4o' } } },
+ tombstones: ['memory.agent.id'],
+ };
+
+ expect(getConfigFieldIssues({ 'memory.agent.id': 'agent_other' }, unionBase, stored)).toEqual(
+ [],
+ );
+ });
+
+ it('reports stored fields that conflict with an inherited value a deeper write brings back', () => {
+ const stored = {
+ overrides: { memory: { agent: { provider: 'openAI', model: 'gpt-4o' } } },
+ tombstones: ['memory.agent'],
+ };
+
+ expect(
+ getConfigFieldIssues({ 'memory.agent.enabled': true }, unionBase, stored).map(
+ (issue) => issue.path,
+ ),
+ ).toEqual(['memory.agent.provider', 'memory.agent.model']);
+ });
+});
+
+describe('getConfigChangeIssues', () => {
+ const base = {
+ memory: { agent: { id: 'agent_yaml' } },
+ } as unknown as Partial<TCustomConfig>;
+
+ const paths = (issues: Array<{ path: string }>) => issues.map((issue) => issue.path);
+
+ it('judges a batch in its end state: a tombstone plus the fields that replace it pass', () => {
+ const changes = [
+ { op: 'tombstone' as const, segments: ['memory', 'agent', 'id'] },
+ { op: 'set' as const, segments: ['memory', 'agent', 'provider'], value: 'openAI' },
+ { op: 'set' as const, segments: ['memory', 'agent', 'model'], value: 'gpt-4o' },
+ ];
+ const { state } = applyConfigChanges({ overrides: {}, tombstones: [] }, changes);
+ const written = changes.map((change) => change.segments);
+
+ expect(getConfigChangeIssues(state, base, null, written)).toEqual([]);
+
+ const setsOnly = applyConfigChanges({ overrides: {}, tombstones: [] }, changes.slice(1));
+ expect(paths(getConfigChangeIssues(setsOnly.state, base, null, written.slice(1)))).toEqual([
+ 'memory.agent.provider',
+ 'memory.agent.model',
+ ]);
+ });
+
+ it('judges the stored document on its own tombstones, unless the change lifted them', () => {
+ const stored = {
+ overrides: { memory: { agent: { provider: 'openAI', model: 'gpt-4o' } } },
+ tombstones: ['memory.agent.id'],
+ };
+ const { state } = applyConfigChanges(
+ { overrides: stored.overrides, tombstones: stored.tombstones },
+ [{ op: 'set', segments: ['memory', 'agent', 'id'], value: 'agent_other' }],
+ );
+ const written = [['memory', 'agent', 'id']];
+
+ expect(paths(getConfigChangeIssues(state, base, stored, written))).toEqual([
+ 'memory.agent.provider',
+ 'memory.agent.model',
+ ]);
+ expect(getConfigChangeIssues(state, base, stored, written, ['memory.agent.id'])).toEqual([]);
+ });
+
+ it('refuses an unset that brings back an inherited value the stored fields conflict with', () => {
+ const stored = {
+ overrides: { memory: { agent: { provider: 'openAI', model: 'gpt-4o' } } },
+ tombstones: ['memory.agent.id'],
+ };
+ const { state } = applyConfigChanges(
+ { overrides: stored.overrides, tombstones: stored.tombstones },
+ [{ op: 'unset', segments: ['memory', 'agent', 'id'] }],
+ );
+
+ expect(state.tombstones).toEqual([]);
+ expect(paths(getConfigChangeIssues(state, base, stored, [['memory', 'agent', 'id']]))).toEqual([
+ 'memory.agent.provider',
+ 'memory.agent.model',
+ ]);
+ });
+
+ it('leaves issues the stored document already had to merge time unless the batch touches them', () => {
+ const stored = { overrides: { balance: { startBalance: 'many' }, interface: {} } };
+ const candidate = {
+ overrides: { balance: { startBalance: 'many' }, interface: { customWelcome: 'hi' } },
+ tombstones: [],
+ };
+
+ expect(getConfigChangeIssues(candidate, {}, stored, [['interface', 'customWelcome']])).toEqual(
+ [],
+ );
+ expect(paths(getConfigChangeIssues(candidate, {}, stored, [['balance']]))).toEqual([
+ 'balance.startBalance',
+ ]);
+ });
+
+ it('matches existing issues of entries by key, so removing one entry does not blame the ones it shifts', () => {
+ const entry = (name: string, extra: Record<string, unknown> = {}) => ({
+ name,
+ baseURL: `https://${name}.example.com/v1`,
+ ...extra,
+ });
+ const stored = {
+ overrides: {
+ endpoints: {
+ custom: [
+ entry('first'),
+ entry('legacy', { baseURL: 42 }),
+ { baseURL: 'https://keyless.example.com' },
+ entry('last'),
+ ],
+ },
+ },
+ };
+ const remove = (key: string) =>
+ applyConfigChanges(toConfigOverrideState(stored), [
+ { op: 'removeEntry', segments: ['endpoints', 'custom'], key },
+ ]).state;
+
+ expect(paths(getConfigChangeIssues(stored, {}, null, []))).toEqual([
+ 'endpoints.custom.2',
+ 'endpoints.custom.1.baseURL',
+ ]);
+ expect(getConfigChangeIssues(remove('first'), {}, stored, [])).toEqual([]);
+ expect(getConfigChangeIssues(remove('last'), {}, stored, [])).toEqual([]);
+ expect(getConfigChangeIssues(remove('legacy'), {}, stored, [])).toEqual([]);
+
+ const renamed = applyConfigChanges(remove('first'), [
+ { op: 'rename', segments: ['endpoints', 'custom'], from: 'last', to: 'legacy-2' },
+ {
+ op: 'upsertEntry',
+ segments: ['endpoints', 'custom'],
+ entry: entry('fresh', { baseURL: 7 }),
+ },
+ ]).state;
+ expect(paths(getConfigChangeIssues(renamed, {}, stored, []))).toEqual([
+ 'endpoints.custom.3.baseURL',
+ ]);
+ });
+
+ it('tells apart record keys that contain dots from the nested path their dots spell', () => {
+ const stored = {
+ overrides: { endpoints: { bedrock: { inferenceProfiles: { 'us.a.b': 5 } } } },
+ };
+ const candidate = {
+ overrides: {
+ endpoints: { bedrock: { inferenceProfiles: { 'us.a.b': 5, 'eu.a.b': 6 } } },
+ },
+ tombstones: [],
+ };
+ const written = [['endpoints', 'bedrock', 'inferenceProfiles', 'eu.a.b']];
+
+ expect(getConfigChangeIssues(candidate, {}, stored, written)).toEqual([
+ {
+ path: 'endpoints.bedrock.inferenceProfiles.eu.a.b',
+ segments: ['endpoints', 'bedrock', 'inferenceProfiles', 'eu.a.b'],
+ code: 'invalid_type',
+ },
+ ]);
+ });
+});
+
+describe('getIndexedMergeKeyIssues', () => {
+ it('reports a write inside a merged-by-key array by position, not one of the whole array', () => {
+ expect(getIndexedMergeKeyIssues([['endpoints', 'custom', '0', 'name']])).toEqual([
+ {
+ path: 'endpoints.custom',
+ segments: ['endpoints', 'custom'],
+ code: 'indexed_merge_key_write',
+ },
+ ]);
+ expect(getIndexedMergeKeyIssues([['endpoints', 'custom']])).toEqual([]);
+ expect(getIndexedMergeKeyIssues([['modelSpecs', 'list', '0', 'name']])).toEqual([]);
+ });
+});
+
+describe('getConfigArrayMergeKey', () => {
+ it('names the key field of merged-by-key arrays in override (YAML) paths only', () => {
+ expect(getConfigArrayMergeKey(['endpoints', 'custom'])).toBe('name');
+ expect(getConfigArrayMergeKey(['endpoints'])).toBeUndefined();
+ expect(getConfigArrayMergeKey(['modelSpecs', 'list'])).toBeUndefined();
+ expect(getConfigArrayMergeKey(['endpoints.custom'])).toBeUndefined();
+ expect(getConfigArrayMergeKey([])).toBeUndefined();
+ });
+});
+
+describe('isConfigRecordPath', () => {
+ it('accepts records whose keys are operator-chosen names, through unions and wrappers', () => {
+ expect(isConfigRecordPath(['mcpServers'])).toBe(true);
+ expect(isConfigRecordPath(['mcpServers', 'github', 'headers'])).toBe(true);
+ expect(isConfigRecordPath(['endpoints', 'bedrock', 'inferenceProfiles'])).toBe(true);
+ });
+
+ it('refuses fixed-shape objects, arrays, leaves and unknown sections', () => {
+ expect(isConfigRecordPath(['interface'])).toBe(false);
+ expect(isConfigRecordPath(['webSearch'])).toBe(false);
+ expect(isConfigRecordPath(['speech', 'tts'])).toBe(false);
+ expect(isConfigRecordPath(['endpoints', 'custom'])).toBe(false);
+ expect(isConfigRecordPath(['mcpServers', 'github', 'url'])).toBe(false);
+ expect(isConfigRecordPath(['paths'])).toBe(false);
+ expect(isConfigRecordPath([])).toBe(false);
+ });
+});
+
+describe('isConfigArrayItemPath', () => {
+ it('names paths that continue past an array: an element, or a path inside one', () => {
+ expect(isConfigArrayItemPath(['endpoints', 'custom', '0'])).toBe(true);
+ expect(isConfigArrayItemPath(['endpoints', 'custom', '0', 'baseURL'])).toBe(true);
+ expect(isConfigArrayItemPath(['endpoints', 'custom', 'yaml-endpoint'])).toBe(true);
+ expect(isConfigArrayItemPath(['modelSpecs', 'list', '0', 'preset'])).toBe(true);
+ expect(isConfigArrayItemPath(['mcpServers', 'local', 'args', '0'])).toBe(true);
+ });
+
+ it('takes an index below a field the schema cannot see into to name an array element', () => {
+ expect(isConfigArrayItemPath(['interface', 'futureList', '0'])).toBe(true);
+ expect(isConfigArrayItemPath(['interface', 'futureList', '0', 'name'])).toBe(true);
+ expect(isConfigArrayItemPath(['endpoints', 'azureOpenAI', 'groups', '0'])).toBe(true);
+ expect(isConfigArrayItemPath(['endpoints', 'azureOpenAI', 'groups', '1', 'models'])).toBe(true);
+ expect(
+ isConfigArrayItemPath(['webSearch', 'firecrawlOptions', 'changeTrackingOptions', 'schema']),
+ ).toBe(false);
+ expect(isConfigArrayItemPath(['interface', 'futureList'])).toBe(false);
+ expect(isConfigArrayItemPath(['interface', 'futureMap', 'key'])).toBe(false);
+ expect(isConfigArrayItemPath(['endpoints', 'azureOpenAI', 'groups'])).toBe(false);
+ });
+
+ it('accepts whole arrays, objects, records and paths the schema does not define', () => {
+ expect(isConfigArrayItemPath(['endpoints', 'custom'])).toBe(false);
+ expect(isConfigArrayItemPath(['modelSpecs', 'list'])).toBe(false);
+ expect(isConfigArrayItemPath(['memory', 'agent', 'id'])).toBe(false);
+ expect(isConfigArrayItemPath(['mcpServers', 'github', 'headers', 'X-Token'])).toBe(false);
+ expect(isConfigArrayItemPath(['paths', 'uploads', '0'])).toBe(false);
+ expect(isConfigArrayItemPath([])).toBe(false);
+ });
+});
+
+describe('isAcceptedOverrideSection', () => {
+ it('accepts exactly the top-level sections configSchema defines', () => {
+ for (const section of ['interface', 'mcpServers', 'endpoints', 'memory', 'filters']) {
+ expect(isAcceptedOverrideSection(section)).toBe(true);
+ }
+ for (const key of ['paths', 'config', 'availableTools', 'interfaceConfig', 'mcpConfig']) {
+ expect(isAcceptedOverrideSection(key)).toBe(false);
+ }
+ for (const key of ['', 'toString', 'constructor', '__proto__']) {
+ expect(isAcceptedOverrideSection(key)).toBe(false);
+ }
+ });
+});
diff --git a/packages/data-schemas/src/app/resolution.ts b/packages/data-schemas/src/app/resolution.ts
index 14f0525ab9..490ee9bff0 100644
--- a/packages/data-schemas/src/app/resolution.ts
+++ b/packages/data-schemas/src/app/resolution.ts
@@ -14,7 +14,7 @@ import type { ConfigFieldWrite } from './mutations';
import { setConfigFields, toConfigOverrideState } from './mutations';
import { webSearchPairedFields, unbindWebSearchKeys } from './web';
import { BASE_CONFIG_PRINCIPAL_ID } from '~/admin/capabilities';
-import { parseFieldPath } from './paths';
+import { parseFieldPath, isDotFreePath } from './paths';
import logger from '~/config/winston';
type AnyObject = { [key: string]: unknown };
@@ -26,6 +26,9 @@ export type ConfigOverrideLayer = Pick<Config, 'principalType' | 'priority' | 'o
};
const MAX_MERGE_DEPTH = 10;
+const ARRAY_INDEX = /^(?:0|[1-9]\d*)$/;
+/** Schemas whose children the path walk cannot see, so the stored value decides their shape. */
+const OPAQUE_SCHEMA_TYPES = new Set(['ZodAny', 'ZodUnknown', 'ZodIntersection']);
const MAX_STRIP_PASSES = 16;
const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
/** Filters are a fail-closed security boundary even during mixed-package rollouts. */
@@ -107,6 +110,18 @@ function isSafePath(path: string): boolean {
return true;
}
+/**
+ * The key field that identifies entries of the merged-by-key array at an override (YAML) path,
+ * such as `name` for `endpoints.custom`; `undefined` for any other path.
+ */
+export function getConfigArrayMergeKey(segments: readonly string[]): string | undefined {
+ if (segments.length === 0 || segments.some((segment) => segment.includes('.'))) {
+ return undefined;
+ }
+ const appConfigPath = remapOverridePath(segments.join('.'));
+ return hasOwn(ARRAY_MERGE_KEYS, appConfigPath) ? ARRAY_MERGE_KEYS[appConfigPath] : undefined;
+}
+
function remapOverridePath(path: string): string {
const [first, ...rest] = path.split('.');
const mappedFirst = OVERRIDE_KEY_MAP[first as keyof typeof OVERRIDE_KEY_MAP] ?? first;
@@ -309,6 +324,16 @@ function hasOwn(target: object, key: string): boolean {
return Object.prototype.hasOwnProperty.call(target, key);
}
+/**
+ * Whether `key` is a top-level section an override may hold: one `configSchema` defines.
+ * Anything else names runtime state the merge would otherwise reach (`paths`, the raw-YAML
+ * `config`, the AppService aliases `interfaceConfig`/`mcpConfig`/`turnstileConfig`), so it is
+ * rejected on write and ignored at merge. Unknown keys inside a known section stay accepted.
+ */
+export function isAcceptedOverrideSection(key: string): boolean {
+ return hasOwn(configSchema.shape, key);
+}
+
function toIssue(segments: string[], code: string): ConfigOverrideIssue {
return { path: segments.join('.'), segments, code };
}
@@ -490,6 +515,107 @@ function unwrapSchema(schema: SchemaNode): SchemaNode {
return node;
}
+/** The schema one segment below `node`, through objects, records, arrays and union options. */
+function getChildSchema(node: SchemaNode, segment: string, depth = 0): SchemaNode | undefined {
+ const inner = unwrapSchema(node);
+ const { typeName } = inner._def;
+ if (typeName === 'ZodObject' && inner.shape) {
+ return hasOwn(inner.shape, segment) ? inner.shape[segment] : undefined;
+ }
+ if (typeName === 'ZodRecord') {
+ return inner._def.valueType;
+ }
+ if (typeName === 'ZodArray') {
+ return ARRAY_INDEX.test(segment) ? inner._def.type : undefined;
+ }
+ if (
+ (typeName === 'ZodUnion' || typeName === 'ZodDiscriminatedUnion') &&
+ inner._def.options &&
+ depth < MAX_MERGE_DEPTH
+ ) {
+ for (const option of inner._def.options.values()) {
+ const child = getChildSchema(option, segment, depth + 1);
+ if (child) {
+ return child;
+ }
+ }
+ }
+ return undefined;
+}
+
+/** Whether {@link getChildSchema} reaches `segment` below `node` through an array. */
+function isArrayStep(node: SchemaNode, segment: string, depth = 0): boolean {
+ const inner = unwrapSchema(node);
+ const { typeName } = inner._def;
+ if (typeName === 'ZodArray') {
+ return true;
+ }
+ if (
+ (typeName !== 'ZodUnion' && typeName !== 'ZodDiscriminatedUnion') ||
+ !inner._def.options ||
+ depth >= MAX_MERGE_DEPTH
+ ) {
+ return false;
+ }
+ for (const option of inner._def.options.values()) {
+ if (getChildSchema(option, segment, depth + 1)) {
+ return isArrayStep(option, segment, depth + 1);
+ }
+ }
+ return false;
+}
+
+/**
+ * The `configSchema` node an override (YAML) path names (`undefined` when the schema does not
+ * define it), and whether the path continues past an array on the way. Below a field of a
+ * known section that the schema does not define (a key it does not know, or what an
+ * intersection or `any` holds), the stored value decides the shape, so an index segment there
+ * is taken to name an array element.
+ */
+function resolveConfigSchemaPath(segments: readonly string[]): {
+ node?: SchemaNode;
+ throughArray: boolean;
+} {
+ const [section, ...rest] = segments;
+ const shape = configSchema.shape as unknown as Record<string, SchemaNode>;
+ if (section === undefined || !hasOwn(shape, section)) {
+ return { throughArray: false };
+ }
+ let node: SchemaNode | undefined = shape[section];
+ let throughArray = false;
+ for (const segment of rest) {
+ if (!node || OPAQUE_SCHEMA_TYPES.has(unwrapSchema(node)._def.typeName ?? '')) {
+ node = undefined;
+ throughArray = throughArray || ARRAY_INDEX.test(segment);
+ continue;
+ }
+ throughArray = throughArray || isArrayStep(node, segment);
+ node = getChildSchema(node, segment);
+ }
+ return { node, throughArray };
+}
+
+/**
+ * Whether an override (YAML) path names a record in `configSchema`: an object whose keys are
+ * names the operator chooses (`mcpServers`, a `headers` map, `inferenceProfiles`), so one key
+ * can be renamed to another without changing what the value means. Fixed-shape objects are not
+ * records.
+ */
+export function isConfigRecordPath(segments: readonly string[]): boolean {
+ const { node } = resolveConfigSchemaPath(segments);
+ return node != null && unwrapSchema(node)._def.typeName === 'ZodRecord';
+}
+
+/**
+ * Whether an override (YAML) path continues past an array of `configSchema`, or may: it names
+ * an element of the array or a path inside one, or has an index segment below a field of a
+ * known section the schema does not define. A tombstone there hides nothing, because the merge
+ * removes inherited values from objects only (a whole array can be hidden).
+ */
+export function isConfigArrayItemPath(segments: readonly string[]): boolean {
+ return resolveConfigSchemaPath(segments).throughArray;
+}
+
/**
* The combined fixed shape of an intersection of objects (`a.and(b)`), or `undefined` when a
* side is not an object, so nothing is judged on a shape the walk cannot see whole.
@@ -716,16 +842,118 @@ export function applyConfigTombstones(
.reduce((current, path) => deletePath(current, path), base as AnyObject);
}
+/**
+ * An item of a merged-by-key array is identified by its key, not its position: a write by index
+ * can rename the stored item, which the runtime merge then treats as a new one. Reports the
+ * array once for any write that addresses inside it by position.
+ */
+export function getIndexedMergeKeyIssues(
+ written: ReadonlyArray<readonly string[]>,
+): ConfigOverrideIssue[] {
+ return Object.keys(ARRAY_MERGE_KEYS).flatMap((arrayPath) => {
+ const arraySegments = arrayPath.split('.');
+ return written.some(
+ (segments) =>
+ segments.length > arraySegments.length && isRelatedPath([...segments], arraySegments),
+ )
+ ? [toIssue(arraySegments, 'indexed_merge_key_write')]
+ : [];
+ });
+}
+
+function hasMergeKey(item: unknown, keyField: string): boolean {
+ return isPlainObject(item) && typeof item[keyField] === 'string' && item[keyField] !== '';
+}
+
+/**
+ * Where an issue sits in `overrides`, in a form that survives entries moving: an item of a
+ * merged-by-key array is named by its key, or (without one) by its place among the keyless
+ * items, rather than by its index. Removing one entry shifts the ones after it, and their
+ * issues must still match the ones the stored document already had.
+ */
+function getIssueLocation(segments: readonly string[], overrides: unknown): string {
+ const location: Array<string | { key: unknown } | { keyless: number }> = [];
+ let node: unknown = overrides;
+ for (let index = 0; index < segments.length; index++) {
+ const segment = segments[index];
+ const keyField = Array.isArray(node)
+ ? getConfigArrayMergeKey(segments.slice(0, index))
+ : undefined;
+ if (Array.isArray(node) && keyField) {
+ const position = Number(segment);
+ const item: unknown = node[position];
+ location.push(
+ hasMergeKey(item, keyField)
+ ? { key: (item as AnyObject)[keyField] }
+ : {
+ keyless: node.slice(0, position).filter((other) => !hasMergeKey(other, keyField))
+ .length,
+ },
+ );
+ node = item;
+ continue;
+ }
+ location.push(segment);
+ if (Array.isArray(node)) {
+ node = node[Number(segment)];
+ } else {
+ node = isPlainObject(node) && hasOwn(node, segment) ? node[segment] : undefined;
+ }
+ }
+ return JSON.stringify(location);
+}
+
+/**
+ * Checks a principal's next override document in its final state: `candidate` merged over
+ * `base` without the candidate's tombstones, so a batch that tombstones a field and sets its
+ * replacement is judged on the end result rather than step by step. An issue is reported when
+ * it touches a `written` path (in either direction), or when the change introduced it
+ * elsewhere (a related field the change made invalid); issues the stored document already had
+ * (at the same location, entries of merged-by-key arrays matched by key) are left to merge
+ * time so they do not block an unrelated change.
+ *
+ * The stored document is judged on the base its own tombstones leave, so an issue that a
+ * removed tombstone brings back counts as new. `lifted` names stored tombstones to treat as
+ * already removed there: tombstones the change replaced with values of its own.
+ */
+export function getConfigChangeIssues(
+ candidate: { overrides?: unknown; tombstones?: unknown[] },
+ base: Partial<TCustomConfig>,
+ stored: { overrides?: unknown; tombstones?: unknown[] } | null | undefined,
+ written: ReadonlyArray<readonly string[]>,
+ lifted: Iterable<string> = [],
+): ConfigOverrideIssue[] {
+ const candidateState = toConfigOverrideState(candidate);
+ const storedState = toConfigOverrideState(stored);
+ const existing = new Set(
+ getConfigOverrideIssues(
+ storedState.overrides,
+ applyConfigTombstones(base, storedState.tombstones, new Set(lifted)),
+ ).map((issue) => getIssueLocation(issue.segments, storedState.overrides)),
+ );
+ return getConfigOverrideIssues(
+ candidateState.overrides,
+ applyConfigTombstones(base, candidateState.tombstones),
+ ).filter(
+ (issue) =>
+ !existing.has(getIssueLocation(issue.segments, candidateState.overrides)) ||
+ written.some((segments) => isRelatedPath(issue.segments, [...segments])),
+ );
+}
+
/**
* Checks field writes on top of the principal's stored config, building the result with the
* same transform the write stores (`setConfigFields`): each path set in order, and the
* tombstones those paths clear removed. `fields` is either a map of dotted field paths or a
* list of segment writes (which can address keys that contain dots). A path the stored
* document cannot take (below a scalar, or a named key of an array) throws a
- * `ConfigPathError`. The principal's remaining tombstones are applied to the base. An issue is
- * reported when it touches a written path, or when the write introduced it elsewhere (a
- * related field the write made invalid); issues the stored config already had are left to
- * merge time so they do not block an unrelated write.
+ * `ConfigPathError`. See {@link getConfigChangeIssues} for which issues are reported.
+ *
+ * A tombstone a write replaces with its own value counts as lifted for the stored document
+ * too, so a client that sends one field per request can switch a union's shape (set the new
+ * field, then reset the old ones). A tombstone a deeper write clears as a side effect does
+ * not: setting `memory.agent.enabled` under a hidden `memory.agent` brings the inherited agent
+ * back, and a conflict with the stored fields is reported instead of being dropped at merge.
*/
export function getConfigFieldIssues(
fields: Record<string, unknown> | readonly ConfigFieldWrite[],
@@ -739,34 +967,13 @@ export function getConfigFieldIssues(
value,
}));
const written = writes.map(({ segments }) => [...segments]);
- /**
- * An item of a merged-by-key array is identified by its key, not its position: an indexed
- * write can rename the stored item, which the runtime merge then treats as a new one.
- */
- const indexed = Object.keys(ARRAY_MERGE_KEYS).flatMap((arrayPath) => {
- const arraySegments = arrayPath.split('.');
- return written.some(
- (segments) =>
- segments.length > arraySegments.length && isRelatedPath(segments, arraySegments),
- )
- ? [toIssue(arraySegments, 'indexed_merge_key_write')]
- : [];
- });
+ const indexed = getIndexedMergeKeyIssues(written);
if (indexed.length > 0) {
return indexed;
}
- const storedState = toConfigOverrideState(stored);
- const candidate = setConfigFields(storedState, writes);
- const effectiveBase = applyConfigTombstones(base, candidate.tombstones);
- const storedOverrides = storedState.overrides;
- const existing = new Set(
- getConfigOverrideIssues(storedOverrides, effectiveBase).map((issue) => issue.path),
- );
- return getConfigOverrideIssues(candidate.overrides, effectiveBase).filter(
- (issue) =>
- !existing.has(issue.path) ||
- written.some((segments) => isRelatedPath(issue.segments, segments)),
- );
+ const candidate = setConfigFields(toConfigOverrideState(stored), writes);
+ const lifted = written.filter(isDotFreePath).map((segments) => segments.join('.'));
+ return getConfigChangeIssues(candidate, base, stored, written, lifted);
}
function omitPath(target: unknown, segments: string[]): unknown {
diff --git a/packages/data-schemas/src/types/admin.ts b/packages/data-schemas/src/types/admin.ts
index 18d31fa0fe..a33d2d80ad 100644
--- a/packages/data-schemas/src/types/admin.ts
+++ b/packages/data-schemas/src/types/admin.ts
@@ -93,6 +93,141 @@ export type AdminConfigTombstoneRequest = AdminConfigWritePrecondition &
priority?: number;
};
+/**
+ * One change of a `POST …/changes` batch. The target is a `fieldPath` or `segments`, as in
+ * {@link AdminConfigFieldTarget}; for an entry change it names the collection.
+ *
+ * - `set` writes `value` at the path (encrypting registered secrets; an object that omits a
+ * stored secret keeps it) and clears the tombstones the write covers. A whole object replaces
+ * what is stored there; fields the API does not store are left out of it and reported as
+ * skipped, and when nothing is left the path is reset as by `unset`.
+ * - `unset` removes the principal's override at the path, the objects that leaves empty, and
+ * the tombstones at or below it: the path inherits again.
+ * - `tombstone` removes the override and hides inherited values at the path. Tombstones are
+ * stored as dotted paths, so no segment may contain a dot, and hide whole arrays only: a path
+ * to an element or inside one is refused, and so is an index segment below a field
+ * `configSchema` does not define, which may name an array element.
+ *
+ * Only sections `configSchema` defines can be written or hidden; `unset` may also remove what
+ * an older server stored outside them. Entries of a merged-by-key array are addressed by key,
+ * never by position: a `set`, `unset` or `rename` whose path runs into one
+ * (`endpoints.custom.0.headers`) is refused.
+ * - `upsertEntry` replaces the principal's own entry of a merged-by-key array (`endpoints.custom`,
+ * keyed by `name`) with `entry`, or appends it. An entry that omits a stored `apiKey` keeps it.
+ * - `removeEntry` removes the principal's own entry with that key; an inherited entry of the
+ * same name shows again.
+ * - `rename` renames one of the principal's own entries of a merged-by-key array, or one key of
+ * a record (`mcpServers`, a `headers` map). Everything stored on the entry moves with it,
+ * encrypted secrets included, so a rename never needs the secret again. An entry
+ * `librechat.yaml` defines cannot be renamed, and no entry can take the name of one.
+ */
+export type AdminConfigChangeOp = AdminConfigFieldTarget &
+ (
+ | { op: 'set'; value: unknown }
+ | { op: 'unset' }
+ | { op: 'tombstone' }
+ | { op: 'upsertEntry'; entry: Record<string, unknown> }
+ | { op: 'removeEntry'; key: string }
+ | { op: 'rename'; from: string; to: string }
+ );
+
+/**
+ * POST `/:principalType/:principalId/changes`: changes applied in array order to the stored
+ * document and written with one compare-and-swap, so all of them apply or none does. No two
+ * changes may address the same path, or the same entry of a collection.
+ */
+export type AdminConfigChangesRequest = AdminConfigWritePrecondition & {
+ /** 1 to 1000 changes. */
+ ops: AdminConfigChangeOp[];
+ /**
+ * Broad `manage:configs` only; anyone else's is ignored and the stored priority kept. A new
+ * priority is written even when no change alters the document, and on a principal without
+ * one it creates a document that holds only the priority, as PUT does.
+ */
+ priority?: number;
+ /** Validate and report without writing. */
+ dryRun?: boolean;
+};
+
+/**
+ * Why a change, or part of a `set` value, was not stored. The rest of the batch still applies.
+ * - `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`, …).
+ * - `dedicated_section`: a section with its own admin API (`langfuse`).
+ * - `interface_permission`: an interface field that is a role permission.
+ */
+export type AdminConfigSkipReason =
+ | 'base_only_section'
+ | 'base_only_path'
+ | 'dedicated_section'
+ | 'interface_permission';
+
+/**
+ * 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.
+ */
+export type AdminConfigIgnoreReason = 'process_mcp_server' | 'base_only_path';
+
+/** A change of the batch, by position, with the location it addressed. */
+export type AdminConfigChangeRef = {
+ /** Index of the change in the request's `ops`. */
+ opIndex: number;
+ op: AdminConfigChangeOp['op'];
+ segments: string[];
+ /** The entry key of an `upsertEntry` or `removeEntry`. */
+ key?: string;
+};
+
+/** 200 from `POST …/changes`. */
+export type AdminConfigChangesResponse = {
+ /**
+ * The stored document after the batch (redacted, and limited to the sections the caller can
+ * read or just wrote), or `null` when the principal has none. Absent on a dry run.
+ */
+ config?: AdminConfig | null;
+ /** The stored document's revision after the batch (before it, on a dry run). */
+ revision: string | null;
+ /**
+ * Whether a document was written: a batch that changes nothing, and sets no new `priority`,
+ * writes nothing.
+ */
+ written: boolean;
+ dryRun: boolean;
+ /** Changes that altered the document. */
+ applied: AdminConfigChangeRef[];
+ /** Changes, or parts of a `set` value (at their own `segments`), that were not stored. */
+ skipped: Array<AdminConfigChangeRef & { reason: AdminConfigSkipReason }>;
+ /** Applied changes, or parts of one (at their own `segments`), the runtime merge does not use. */
+ ignored: Array<AdminConfigChangeRef & { reason: AdminConfigIgnoreReason }>;
+ /**
+ * Valid changes that left the document as it was: it was already in that state, or the
+ * batch's changes cancel out (a `set`, then an `unset` of its parent), in which case every
+ * change is listed here and nothing is written.
+ */
+ unchanged: AdminConfigChangeRef[];
+};
+
+/**
+ * 400 from `POST …/changes`: a change that cannot apply, named by `opIndex`, or (code
+ * `CONFIG_OVERRIDE_INVALID`) the batch's end state failing validation, with its `issues` and
+ * the batch's `skipped` report.
+ */
+export type AdminConfigChangeErrorResponse = {
+ error: string;
+ code: string;
+ opIndex?: number;
+ reason?: string;
+ issues?: Array<{ path: string; segments: string[]; code: string }>;
+ skipped?: AdminConfigChangesResponse['skipped'];
+};
+
/* ── Admin config contract (GET /api/admin/config/meta) ─────────────── */
/**
@@ -129,6 +264,10 @@ export type AdminConfigTombstoneRequest = AdminConfigWritePrecondition &
* overrides rather than a cached merge, and a merge read before a clear is never cached. A read
* after a write's response therefore shows it; another instance shows it once the broadcast
* arrives, or, without Redis, within `limits.overrideCacheTtlMs`.
+ * - `changesBatch`: `POST /:principalType/:principalId/changes` applies up to
+ * `limits.maxChangeOps` set, unset, tombstone, entry upsert/remove and rename ops to one
+ * document in order, as one compare-and-swap write judged on the end state: an invalid op
+ * writes nothing, ops that cancel out write nothing, and `dryRun` reports without writing.
*/
export type AdminConfigFeatureFlag =
| 'dottedKeys'
@@ -137,7 +276,8 @@ export type AdminConfigFeatureFlag =
| 'webSearchStoredKeys'
| 'expectedRevision'
| 'prunesEmptyParents'
- | 'awaitedInvalidation';
+ | 'awaitedInvalidation'
+ | 'changesBatch';
export type AdminConfigFeatures = Record<AdminConfigFeatureFlag, boolean>;
@@ -209,6 +349,8 @@ export type AdminConfigMeta = {
limits: {
/** Most entries one `PATCH /fields` accepts. */
maxPatchEntries: number;
+ /** Most ops one `POST /changes` accepts. */
+ maxChangeOps: number;
/**
* The app config service's `overrideCacheTtl`: how long another server instance may serve
* resolved config from before a write.