Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): validate custom MCP headers

宁凯00733c320d6a
diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-mcp-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-mcp-store.test.ts
index 34de78314b..4f3607996c 100644
--- a/apps/desktop/src/main/maker-host/__tests__/custom-mcp-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/custom-mcp-store.test.ts
@@ -103,6 +103,40 @@ describe('validateCustomMcpConfig', () => {
expect(validateCustomMcpConfig({ ...valid, headers: { X: 1 } }).ok).toBe(false);
});
+ it('rejects invalid HTTP header names', () => {
+ for (const name of ['X Name', '中文', 'X\nName']) {
+ const result = validateCustomMcpConfig({ ...valid, headers: { [name]: 'value' } });
+ expect(result.ok, `${JSON.stringify(name)} should be rejected`).toBe(false);
+ expect(result.ok === false && result.message).toContain('valid HTTP tokens');
+ }
+ });
+
+ it('accepts HTTP token header names after trimming', () => {
+ expect(
+ validateCustomMcpConfig({
+ ...valid,
+ headers: { ' X-API_Key ': 'value', "X-Trace.Id!#$%&'*+-.^_`|~": 'value' },
+ }),
+ ).toEqual({ ok: true });
+ });
+
+ it('rejects non-printable ASCII header values', () => {
+ for (const value of ['中文', '😀', 'line\nfeed', 'tab\tvalue']) {
+ const result = validateCustomMcpConfig({ ...valid, headers: { 'X-Name': value } });
+ expect(result.ok, `${JSON.stringify(value)} should be rejected`).toBe(false);
+ expect(result.ok === false && result.message).toContain('printable ASCII');
+ }
+ });
+
+ it('accepts printable ASCII header values', () => {
+ expect(
+ validateCustomMcpConfig({
+ ...valid,
+ headers: { 'X-Name': 'alice', Authorization: 'Bearer token-123/+_=' },
+ }),
+ ).toEqual({ ok: true });
+ });
+
// 撞名的自定义 MCP 会在装配层顶替同名内置 server,并继承 MCP 审批策略里对该
// server 名的信任(策略只看 serverName),所以 id 必须在 CRUD 阶段就拒收。
it('rejects ids reserved by builtin MCP servers', () => {
diff --git a/apps/desktop/src/main/maker-host/custom-mcp-store.ts b/apps/desktop/src/main/maker-host/custom-mcp-store.ts
index bb14cc01cb..8f1c138532 100644
--- a/apps/desktop/src/main/maker-host/custom-mcp-store.ts
+++ b/apps/desktop/src/main/maker-host/custom-mcp-store.ts
@@ -46,6 +46,20 @@ export function isUnsafeMcpServerId(id: string): boolean {
}
const MAX_ID_LEN = 40;
const MAX_NAME_LEN = 60;
+const HTTP_HEADER_NAME_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
+
+/**
+ * Claude Code requires custom HTTP header values to be printable ASCII. Keep
+ * this check at the persisted-config boundary so an invalid value cannot be
+ * saved and fail later during a non-interactive MCP startup.
+ */
+function isPrintableAsciiHeaderValue(value: string): boolean {
+ for (let i = 0; i < value.length; i += 1) {
+ const code = value.charCodeAt(i);
+ if (code < 0x20 || code > 0x7e) return false;
+ }
+ return true;
+}
/** 验证结果:ok 或带 code + message(供 handler 映射成 throwIpcError)。 */
export type ValidationResult =
@@ -105,6 +119,13 @@ export function validateCustomMcpConfig(
if (typeof k !== 'string' || typeof v !== 'string') {
return invalid('headers must be string→string');
}
+ const headerName = k.trim();
+ if (headerName.length > 0 && !HTTP_HEADER_NAME_RE.test(headerName)) {
+ return invalid('header names must be valid HTTP tokens');
+ }
+ if (!isPrintableAsciiHeaderValue(v)) {
+ return invalid('header values must contain printable ASCII characters');
+ }
}
}
return { ok: true };
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/custom-mcp-registry.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/custom-mcp-registry.test.ts
index 1352217d10..fec52dacbf 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/custom-mcp-registry.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/custom-mcp-registry.test.ts
@@ -14,11 +14,16 @@ import type { CustomMcpConfig } from '../../../shared/customMcp.js';
const storeMock = vi.hoisted(() => ({ listCustomMcpServers: vi.fn() }));
-vi.mock('../../maker-host/custom-mcp-store.js', () => ({
- listCustomMcpServers: storeMock.listCustomMcpServers,
- // 只把读库这一步换成 mock;判定逻辑用真实实现,避免名单在测试里漂移。
- isUnsafeMcpServerId: (id: string) => ['__proto__', 'constructor', 'prototype'].includes(id),
-}));
+vi.mock('../../maker-host/custom-mcp-store.js', async () => {
+ const actual = await vi.importActual<typeof import('../../maker-host/custom-mcp-store.js')>(
+ '../../maker-host/custom-mcp-store.js',
+ );
+ return {
+ ...actual,
+ // 只把读库这一步换成 mock;校验 / 判定逻辑用真实实现,避免名单在测试里漂移。
+ listCustomMcpServers: storeMock.listCustomMcpServers,
+ };
+});
vi.mock('../../secrets/providerSecretStore.js', () => ({
readCustomMcpToken: () => null,
@@ -113,6 +118,19 @@ describe('refreshCustomMcpProviders', () => {
expect(Object.getPrototypeOf({} as Record<string, unknown>)).toBe(Object.prototype);
});
+ it('quarantines persisted configs with invalid custom headers', async () => {
+ const arr: McpProvider[] = [builtin('cindy_browser')];
+ registerCustomMcpArrays(arr);
+ storeMock.listCustomMcpServers.mockResolvedValue([
+ { ...config('bad_header'), headers: { 'X-Feishu-Name': '中文' } },
+ config('safe_one'),
+ ]);
+
+ await refreshCustomMcpProviders();
+
+ expect(arr.map((p) => p.name)).toEqual(['cindy_browser', 'safe_one']);
+ });
+
it('still allows ids that merely resemble a builtin name', async () => {
const arr: McpProvider[] = [builtin('cindy_browser')];
registerCustomMcpArrays(arr);
diff --git a/apps/desktop/src/main/mcp-integrations/custom-mcp-registry.ts b/apps/desktop/src/main/mcp-integrations/custom-mcp-registry.ts
index bb3c343033..56d0fa78d3 100644
--- a/apps/desktop/src/main/mcp-integrations/custom-mcp-registry.ts
+++ b/apps/desktop/src/main/mcp-integrations/custom-mcp-registry.ts
@@ -16,7 +16,11 @@
import { createLogger } from '../logger.js';
import type { McpProvider } from '@cindy/maker-core';
-import { isUnsafeMcpServerId, listCustomMcpServers } from '../maker-host/custom-mcp-store.js';
+import {
+ isUnsafeMcpServerId,
+ listCustomMcpServers,
+ validateCustomMcpConfig,
+} from '../maker-host/custom-mcp-store.js';
import { readCustomMcpToken } from '../secrets/providerSecretStore.js';
import { CustomMcpProvider } from './custom-mcp-provider.js';
@@ -66,17 +70,32 @@ export const __resetCustomMcpRegistryForTest = resetCustomMcpRegistry;
*/
export async function refreshCustomMcpProviders(): Promise<void> {
let providers: CustomMcpProvider[] = [];
+ // 按名字去重统计:同一个撞名配置会在每个已注册数组各命中一次,累加会虚报。
+ const skippedNames = new Set<string>();
try {
const configs = await listCustomMcpServers();
- providers = configs.map((c) => new CustomMcpProvider(c, readCustomMcpToken));
+ const reservedIds = getBuiltinMcpServerNames();
+ providers = configs.flatMap((config) => {
+ const validation = validateCustomMcpConfig(config, reservedIds);
+ if (!validation.ok) {
+ const serverName = typeof config.id === 'string' ? config.id : '<invalid>';
+ if (!skippedNames.has(serverName)) {
+ log.warn('skipping invalid persisted custom MCP config; edit and save it again', {
+ serverName,
+ reason: validation.message,
+ });
+ }
+ skippedNames.add(serverName);
+ return [];
+ }
+ return [new CustomMcpProvider(config, readCustomMcpToken)];
+ });
} catch (err) {
log.warn('list custom mcp servers failed; leaving providers unchanged', {
error: err instanceof Error ? err.message : String(err),
});
return;
}
- // 按名字去重统计:同一个撞名配置会在每个已注册数组各命中一次,累加会虚报。
- const skippedNames = new Set<string>();
for (const arr of registeredArrays) {
// 原地移除旧的 custom provider,再追加新的一批(不换数组引用)。
for (let i = arr.length - 1; i >= 0; i--) {