Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 图像响应按魔数核验类型 + 内置凭证 IPC 业务体抽出可测 (#1117)
Chris Zhange51c09f24a2d
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 9238d433e7..21fc4dc17a 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -439,6 +439,12 @@ import {resolveOwnerScopedSecretStorageKey,getProviderSecretStore,} from './secrets/providerSecretStore.js';+import {+ builtinApiKeyHas,+ builtinApiKeyRemove,+ builtinApiKeyStore,+ type BuiltinApiKeyBridgeDeps,+} from './secrets/builtinApiKeyBridge.js';import {isRendererAccessibleSafeStorageKey,type ProviderSecretId,@@ -3490,39 +3496,20 @@ const registerIpcHandlers = () => {);// 内置 API-key 供应商专用 IPC(查/写/删,has 只回存在性,永不回读明文)。- // 这些键在 MAIN_ONLY_PROVIDER_SECRET_STORAGE_KEYS 里,通用 safeStorage IPC 已拦截;- // 此处是唯一合法的 renderer 访问通道。mutation 错误走统一 IPC 协议(throwIpcError),- // renderer 经 extractIpcError 解码;has 是查询,失败回 false 供 UI 按未配置渲染。- const BUILTIN_API_KEY_PROVIDER_IDS = new Set<ProviderSecretId>(['gemini', 'openai-images']);- // 真实 API key 远短于此(gemini ~39 / OpenAI 平台 ~200 字符);上限挡的是被攻陷- // renderer 塞超大字符串让 main 同步加密落盘耗资源(副作用前验证 payload 长度)。- const BUILTIN_API_KEY_MAX_LENGTH = 1024;- const requireBuiltinApiKeyProviderId = (providerId: unknown): ProviderSecretId => {- if (- typeof providerId !== 'string' ||- !BUILTIN_API_KEY_PROVIDER_IDS.has(providerId as ProviderSecretId)- ) {- throwIpcError('INVALID_PARAMS', `unsupported builtin api-key provider: ${String(providerId)}`);- }- return providerId as ProviderSecretId;+ // 业务体(白名单/类型/长度校验 + 统一错误协议)在 secrets/builtinApiKeyBridge.ts,+ // 边界行为有单测;这里只做 sender 守卫 + 依赖装配。+ const builtinApiKeyLog = createLogger('secrets:builtin-api-key');+ const builtinApiKeyDeps: BuiltinApiKeyBridgeDeps = {+ store: getProviderSecretStore(),+ onKeyChanged: (id) => notifyProviderKeyChanged(id),+ logError: (message, err) => builtinApiKeyLog.error(message, err),};ipcMain.handle('builtin-api-key-has',async (event: Electron.IpcMainInvokeEvent, providerId: unknown): Promise<boolean> => {assertTrustedAppRendererEvent(event);- if (- typeof providerId !== 'string' ||- !BUILTIN_API_KEY_PROVIDER_IDS.has(providerId as ProviderSecretId)- ) {- return false;- }- try {- return getProviderSecretStore().has(providerId as ProviderSecretId);- } catch (err) {- console.error('[builtin-api-key-has]', err);- return false;- }+ return builtinApiKeyHas(builtinApiKeyDeps, providerId);},);@@ -3530,18 +3517,7 @@ const registerIpcHandlers = () => {'builtin-api-key-store',async (event: Electron.IpcMainInvokeEvent, providerId: unknown, value: unknown): Promise<void> => {assertTrustedAppRendererEvent(event);- const id = requireBuiltinApiKeyProviderId(providerId);- if (typeof value !== 'string' || value.length > BUILTIN_API_KEY_MAX_LENGTH) {- throwIpcError('INVALID_PARAMS', 'api key must be a string within the length limit');- }- const trimmed = value.trim();- if (!trimmed) {- throwIpcError('INVALID_PARAMS', 'api key must not be empty');- }- if (!getProviderSecretStore().set(id, trimmed)) {- throwIpcError('INTERNAL', 'failed to store the api key');- }- notifyProviderKeyChanged(id);+ builtinApiKeyStore(builtinApiKeyDeps, providerId, value);},);@@ -3549,12 +3525,7 @@ const registerIpcHandlers = () => {'builtin-api-key-remove',async (event: Electron.IpcMainInvokeEvent, providerId: unknown): Promise<void> => {assertTrustedAppRendererEvent(event);- const id = requireBuiltinApiKeyProviderId(providerId);- const result = getProviderSecretStore().remove(id);- if (!result.success) {- throwIpcError('INTERNAL', 'failed to remove the api key');- }- notifyProviderKeyChanged(id);+ builtinApiKeyRemove(builtinApiKeyDeps, providerId);},);diff --git a/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.tsindex 8c0c29092a..19fb69334e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/imageChannelRegistry.test.ts@@ -6,7 +6,7 @@import { describe, expect, it, vi } from 'vitest';-import { ImageChannelRegistry, type ImageChannel } from '../imageChannelRegistry';+import { ImageChannelRegistry, decodeImageResponse, type ImageChannel } from '../imageChannelRegistry';function channel(ready: boolean, supportsEdit?: boolean): ImageChannel {return {@@ -60,3 +60,35 @@ describe('ImageChannelRegistry', () => {expect(registry.resolve('xai').supportsEdit).toBe(false);});});++describe('decodeImageResponse', () => {+ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);+ const JPEG_MAGIC = Buffer.from([0xff, 0xd8, 0xff, 0xe0]);++ it('mime 由字节魔数决定,不信任上游声明的 output_format', () => {+ // 上游谎报 webp,字节实为 JPEG → 按魔数落 image/jpeg。+ const decoded = decodeImageResponse({+ data: [{ b64_json: JPEG_MAGIC.toString('base64') }],+ output_format: 'webp',+ });+ expect(decoded.mimeType).toBe('image/jpeg');+ expect(decoded.buffer.equals(JPEG_MAGIC)).toBe(true);+ expect(+ decodeImageResponse({ data: [{ b64_json: PNG_MAGIC.toString('base64') }] }).mimeType,+ ).toBe('image/png');+ });++ it('非图片字节拒绝(上游/代理返回错误页等),不产出可落盘的结果', () => {+ expect(() =>+ decodeImageResponse({+ data: [{ b64_json: Buffer.from('<html>proxy error</html>').toString('base64') }],+ output_format: 'png',+ }),+ ).toThrow(/不是有效图片/);+ });++ it('空响应拒绝', () => {+ expect(() => decodeImageResponse({ data: [] })).toThrow(/返回为空/);+ expect(() => decodeImageResponse({ data: [{}] })).toThrow(/返回为空/);+ });+});diff --git a/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts b/apps/desktop/src/main/cindy-brain/imageChannelRegistry.tsindex 1563716df9..88fba94551 100644--- a/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts+++ b/apps/desktop/src/main/cindy-brain/imageChannelRegistry.ts@@ -19,13 +19,31 @@*/import type { GhostImageAspectRatio } from '../../shared/ghost.js';+import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';-/** 通道适配层的出参(与 decodeImageResponse 的入参同形:字节 + mime 由各通道自决)。 */+/** 通道适配层的出参(decodeImageResponse 的入参:字节 base64;声明格式仅作参考)。 */export interface ImageChannelResult {data: Array<{ b64_json?: string }>;output_format?: string;}+/**+ * 图片通道响应 → 字节 + mime(所有来源 gen / edit 的统一解码口径)。+ * mime 由字节魔数(sniffMediaMime)决定,不信任上游声明的 output_format:+ * 上游或出站代理返回非图片字节时在此拒绝,不落 cindy-media、不挂作品账本+ * (媒体规则:自报格式不能单独作为可信依据)。+ */+export function decodeImageResponse(res: ImageChannelResult): { buffer: Buffer; mimeType: string } {+ const first = res.data[0];+ if (!first?.b64_json) throw new Error('图片通道返回为空');+ const buffer = Buffer.from(first.b64_json, 'base64');+ const sniffed = sniffMediaMime(buffer);+ if (!sniffed || !sniffed.startsWith('image/')) {+ throw new Error('图片通道返回的数据不是有效图片,本次生成已取消');+ }+ return { buffer, mimeType: sniffed };+}+/*** 单条图像执行通道。参数面收敛为「意识意图」级(aspectRatio 而非具体尺寸):* 意图 → 各家 wire 参数(gpt-image 的 size 枚举 / Gemini 的 imageConfig.aspectRatio)diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 8bf6053cb6..255f5684cf 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -192,7 +192,7 @@ import {markGhostRecentlyUsed,} from './ghostRecentUsageStore.js';import { getCindyProxyMediaService } from '../mcp-integrations/cindyProxyMedia.js';-import { ImageChannelRegistry } from './imageChannelRegistry.js';+import { ImageChannelRegistry, decodeImageResponse } from './imageChannelRegistry.js';import { createGeminiImageChannel } from './geminiImageClient.js';import { createGatewayImageClient } from '../cindy-proxy-media/api/gatewayImageClient.js';import * as blobStore from '../cindy-media/blobStore.js';@@ -1959,20 +1959,6 @@ function resolveImageChannelForModel(model: string, operation: 'generate' | 'edireturn getImageChannelRegistry().resolve(entry.providerId);}-/** XD Gateway 图片响应 → 字节 + mime(gen / edit 同一解码口径)。 */-function decodeImageResponse(res: {- data: Array<{ b64_json?: string }>;- output_format?: string;-}): { buffer: Buffer; mimeType: string } {- const first = res.data[0];- if (!first?.b64_json) throw new Error('图片通道返回为空');- const buffer = Buffer.from(first.b64_json, 'base64');- const format = (res.output_format ?? 'png').toLowerCase();- const mimeType =- format === 'webp' ? 'image/webp' : format === 'jpeg' || format === 'jpg' ? 'image/jpeg' : 'image/png';- return { buffer, mimeType };-}-export function getGhostCindySlot(): GhostCindySlot {if (!cindySlotSingleton) {cindySlotSingleton = new GhostCindySlot({diff --git a/apps/desktop/src/main/secrets/__tests__/builtinApiKeyBridge.test.ts b/apps/desktop/src/main/secrets/__tests__/builtinApiKeyBridge.test.tsnew file mode 100644index 0000000000..6b2068682e--- /dev/null+++ b/apps/desktop/src/main/secrets/__tests__/builtinApiKeyBridge.test.ts@@ -0,0 +1,128 @@+/**+ * builtinApiKeyBridge.test.ts — 内置 API-key IPC 业务体的边界回归测试。+ * 这组桥承担 MAIN_ONLY 凭证写删的安全边界:白名单、类型/长度上限、空值拒绝、+ * 存储失败错误路径都在此锁住,防止后续改动回退(此前实审出过长度校验缺口)。+ */++import { describe, expect, it, vi } from 'vitest';++import {+ BUILTIN_API_KEY_MAX_LENGTH,+ builtinApiKeyHas,+ builtinApiKeyRemove,+ builtinApiKeyStore,+ type BuiltinApiKeyBridgeDeps,+} from '../builtinApiKeyBridge';++function makeDeps(overrides?: Partial<BuiltinApiKeyBridgeDeps['store']>) {+ const store = {+ set: vi.fn<BuiltinApiKeyBridgeDeps['store']['set']>(() => true),+ remove: vi.fn<BuiltinApiKeyBridgeDeps['store']['remove']>(() => ({ success: true })),+ has: vi.fn<BuiltinApiKeyBridgeDeps['store']['has']>(() => true),+ ...overrides,+ };+ const onKeyChanged = vi.fn<BuiltinApiKeyBridgeDeps['onKeyChanged']>();+ const logError = vi.fn<BuiltinApiKeyBridgeDeps['logError']>();+ const deps: BuiltinApiKeyBridgeDeps = { store, onKeyChanged, logError };+ return { deps, store, onKeyChanged, logError };+}++/** 断言抛出的是统一 IPC 协议错误(err.code + [CODE] 前缀话术)。 */+function expectIpcError(fn: () => void, code: string): void {+ let thrown: unknown;+ try {+ fn();+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(Error);+ expect((thrown as { code?: string }).code).toBe(code);+ expect((thrown as Error).message).toContain(`[${code}]`);+}++describe('builtinApiKeyStore', () => {+ it('白名单外 providerId 拒绝(INVALID_PARAMS),不触达存储', () => {+ const { deps, store } = makeDeps();+ expectIpcError(() => builtinApiKeyStore(deps, 'xd', 'sk-x'), 'INVALID_PARAMS');+ expectIpcError(() => builtinApiKeyStore(deps, 42, 'sk-x'), 'INVALID_PARAMS');+ expectIpcError(() => builtinApiKeyStore(deps, undefined, 'sk-x'), 'INVALID_PARAMS');+ expect(store.set).not.toHaveBeenCalled();+ });++ it('value 非字符串 / 超长拒绝(INVALID_PARAMS),不触达存储', () => {+ const { deps, store } = makeDeps();+ expectIpcError(() => builtinApiKeyStore(deps, 'gemini', 123), 'INVALID_PARAMS');+ expectIpcError(+ () => builtinApiKeyStore(deps, 'gemini', 'x'.repeat(BUILTIN_API_KEY_MAX_LENGTH + 1)),+ 'INVALID_PARAMS',+ );+ expect(store.set).not.toHaveBeenCalled();+ });++ it('空串 / 纯空白拒绝(INVALID_PARAMS)', () => {+ const { deps, store } = makeDeps();+ expectIpcError(() => builtinApiKeyStore(deps, 'gemini', ''), 'INVALID_PARAMS');+ expectIpcError(() => builtinApiKeyStore(deps, 'gemini', ' '), 'INVALID_PARAMS');+ expect(store.set).not.toHaveBeenCalled();+ });++ it('存储层写失败抛 INTERNAL,不广播变更', () => {+ const { deps, onKeyChanged } = makeDeps({ set: vi.fn(() => false) });+ expectIpcError(() => builtinApiKeyStore(deps, 'gemini', 'sk-good'), 'INTERNAL');+ expect(onKeyChanged).not.toHaveBeenCalled();+ });++ it('成功路径:trim 后入库 + 广播变更;上限内长 key 放行', () => {+ const { deps, store, onKeyChanged } = makeDeps();+ builtinApiKeyStore(deps, 'openai-images', ' sk-good ');+ expect(store.set).toHaveBeenCalledWith('openai-images', 'sk-good');+ expect(onKeyChanged).toHaveBeenCalledWith('openai-images');+ builtinApiKeyStore(deps, 'gemini', 'x'.repeat(BUILTIN_API_KEY_MAX_LENGTH));+ expect(store.set).toHaveBeenCalledWith('gemini', 'x'.repeat(BUILTIN_API_KEY_MAX_LENGTH));+ });+});++describe('builtinApiKeyRemove', () => {+ it('白名单外 providerId 拒绝(INVALID_PARAMS),不触达存储', () => {+ const { deps, store } = makeDeps();+ expectIpcError(() => builtinApiKeyRemove(deps, 'voice-asr'), 'INVALID_PARAMS');+ expect(store.remove).not.toHaveBeenCalled();+ });++ it('存储层删失败抛 INTERNAL,不广播变更', () => {+ const { deps, onKeyChanged } = makeDeps({+ remove: vi.fn(() => ({ success: false, error: 'io' })),+ });+ expectIpcError(() => builtinApiKeyRemove(deps, 'gemini'), 'INTERNAL');+ expect(onKeyChanged).not.toHaveBeenCalled();+ });++ it('成功路径:删除 + 广播变更', () => {+ const { deps, store, onKeyChanged } = makeDeps();+ builtinApiKeyRemove(deps, 'gemini');+ expect(store.remove).toHaveBeenCalledWith('gemini');+ expect(onKeyChanged).toHaveBeenCalledWith('gemini');+ });+});++describe('builtinApiKeyHas', () => {+ it('查询语义:白名单外 / 非字符串回 false,不触达存储、不抛错', () => {+ const { deps, store } = makeDeps();+ expect(builtinApiKeyHas(deps, 'xd')).toBe(false);+ expect(builtinApiKeyHas(deps, 7)).toBe(false);+ expect(store.has).not.toHaveBeenCalled();+ });++ it('透传存储层结果;存储层异常回 false(UI 按未配置渲染)并进注入 logger', () => {+ const ok = makeDeps({ has: vi.fn(() => true) });+ expect(builtinApiKeyHas(ok.deps, 'openai-images')).toBe(true);+ expect(ok.logError).not.toHaveBeenCalled();+ const boom = makeDeps({+ has: vi.fn(() => {+ throw new Error('io');+ }),+ });+ expect(builtinApiKeyHas(boom.deps, 'gemini')).toBe(false);+ expect(boom.logError).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/main/secrets/builtinApiKeyBridge.ts b/apps/desktop/src/main/secrets/builtinApiKeyBridge.tsnew file mode 100644index 0000000000..7c99af9224--- /dev/null+++ b/apps/desktop/src/main/secrets/builtinApiKeyBridge.ts@@ -0,0 +1,101 @@+/**+ * builtinApiKeyBridge.ts — 内置 API-key 供应商专用 IPC 的业务体(可注入、零 electron 依赖)。+ * ---------------------------------------------------------------------------+ * 这些键在 MAIN_ONLY_PROVIDER_SECRET_STORAGE_KEYS 里,通用 safeStorage IPC 已拦截,+ * 本模块是 renderer 触达它们的唯一合法通道的业务内核:白名单 / 类型 / 长度等+ * 边界校验与统一 IPC 错误协议都在这里,单测直测拒绝路径(bootstrap-electron 只做+ * sender 守卫 + 依赖装配)。+ *+ * - store / remove 是 mutation:失败走 throwIpcError(INVALID_PARAMS / INTERNAL),+ * renderer 经 extractIpcError 解码,永不回读明文;+ * - has 是查询:失败回 false 供 UI 按未配置渲染,只回存在性布尔。+ */++import type { ProviderSecretId } from '../../shared/providerSecrets.js';+import { throwIpcError } from '../utils/ipcValidate.js';++/**+ * 允许经本桥访问的内置 API-key 供应商(新增供应商时在此扩展)。+ * 模块私有:这是权限白名单,不导出可变引用(ReadonlySet 只是编译期约束,+ * 挡不住运行时 .add());外部只能经 isBuiltinApiKeyProviderId 查询。+ */+const BUILTIN_API_KEY_PROVIDER_IDS: ReadonlySet<ProviderSecretId> = new Set<ProviderSecretId>([+ 'gemini',+ 'openai-images',+]);++/** 白名单查询(只读语义,供测试与未来调用方使用,不暴露集合本体)。 */+export function isBuiltinApiKeyProviderId(providerId: unknown): providerId is ProviderSecretId {+ return (+ typeof providerId === 'string' && BUILTIN_API_KEY_PROVIDER_IDS.has(providerId as ProviderSecretId)+ );+}++/**+ * 真实 API key 远短于此(gemini ~39 / OpenAI 平台 ~200 字符);上限挡的是被攻陷+ * renderer 塞超大字符串让 main 同步加密落盘耗资源(副作用前验证 payload 长度)。+ */+export const BUILTIN_API_KEY_MAX_LENGTH = 1024;++/** 依赖注入面:providerSecretStore 的读写切片 + key 变更广播 + 统一日志。 */+export interface BuiltinApiKeyBridgeDeps {+ store: {+ set(id: ProviderSecretId, value: string): boolean;+ remove(id: ProviderSecretId): { success: boolean; error?: string };+ has(id: ProviderSecretId): boolean;+ };+ onKeyChanged: (providerId: ProviderSecretId) => void;+ /**+ * 查询路径吞掉的异常经此进 main 统一 logger(级别/轮转/持久化,规约 §1);+ * 本模块保持零 electron 依赖,logger 由装配方注入。+ */+ logError: (message: string, err: unknown) => void;+}++function requireBuiltinApiKeyProviderId(providerId: unknown): ProviderSecretId {+ if (!isBuiltinApiKeyProviderId(providerId)) {+ throwIpcError('INVALID_PARAMS', `unsupported builtin api-key provider: ${String(providerId)}`);+ }+ return providerId;+}++/** 写入 key。校验顺序:白名单 → 类型/长度 → 非空;存储失败抛 INTERNAL。 */+export function builtinApiKeyStore(+ deps: BuiltinApiKeyBridgeDeps,+ providerId: unknown,+ value: unknown,+): void {+ const id = requireBuiltinApiKeyProviderId(providerId);+ if (typeof value !== 'string' || value.length > BUILTIN_API_KEY_MAX_LENGTH) {+ throwIpcError('INVALID_PARAMS', 'api key must be a string within the length limit');+ }+ const trimmed = value.trim();+ if (!trimmed) {+ throwIpcError('INVALID_PARAMS', 'api key must not be empty');+ }+ if (!deps.store.set(id, trimmed)) {+ throwIpcError('INTERNAL', 'failed to store the api key');+ }+ deps.onKeyChanged(id);+}++/** 删除 key。存储层报失败时抛 INTERNAL,不广播变更。 */+export function builtinApiKeyRemove(deps: BuiltinApiKeyBridgeDeps, providerId: unknown): void {+ const id = requireBuiltinApiKeyProviderId(providerId);+ const result = deps.store.remove(id);+ if (!result.success) {+ throwIpcError('INTERNAL', 'failed to remove the api key');+ }+ deps.onKeyChanged(id);+}++/** 查询 key 是否已存。非白名单 / 存储层异常一律回 false(UI 按未配置渲染)。 */+export function builtinApiKeyHas(deps: BuiltinApiKeyBridgeDeps, providerId: unknown): boolean {+ if (!isBuiltinApiKeyProviderId(providerId)) return false;+ try {+ return deps.store.has(providerId);+ } catch (err) {+ deps.logError('[builtin-api-key-has] secret store query failed', err);+ return false;+ }+}