Files
metona-ai-desktop/electron/utils/__tests__/secure-config.test.ts
T
thzxx 99d0c54129
CI / 类型检查 + Lint + 单元测试 (push) Failing after 6m27s
CI / 产物编译验证 (push) Successful in 9m57s
CI / 全量测试 (Electron ABI) (push) Failing after 5m19s
feat: v0.7.4 时序语义修正 · 防线实效补漏 · 全量测试翻倍 — 2406 用例 + jsdom 组件测试全量回归
P1 修复面收口:
- 超时三态区分(aborted→USER_INTERRUPT / ETIMEDOUT→TIMEOUT / 其余→ERROR),
  根治"真实网络超时被误报为用户中断"
- 流空闲超时统一(SSE/Ollama/Anthropic 读循环 60s 无数据抛 504 进重试通道)
- 同会话并发 sendMessage 防重入(isRunning 守卫)+ 会话存在性预检 +
  前置调用移入 try(ERROR+DONE 双事件保证,根治 isStreaming 假死)
- 清空审计后 resetChainCache(根治 verifyChain 误报 TAMPERED)
- DONE 不再提前清理 TRACE(TERMINATED 统一收尾,补全最终迭代录制)
- IME 合成回车不发送(普通 Enter + Cmd/Ctrl+Enter 双分支)+ handleSend 闭包修复

P2 安全纵深:
- preload 移除原始 electronAPI 暴露(渲染层零使用,关掉 XSS invoke 任意通道单点风险)
- CORS 同源回显根治(仅当前浏览页面 Origin,did-navigate 同步)
- MEMORY.md 命令保护正则扩展(括号/$/反引号/< 重定向边界 + 前导路径)
- write_file append TOCTOU 统一(open 后 realpath 校验,新文件分支补漏)
- 敏感键归一化(authKey 驼峰/连字符命中)+ MCP headers 鉴权值加密落库
- ReDoS 检测共享化(search_files/file_editor 统一拦截)
- run_tests/lint_code 升风险 + 需确认 + npx --no-install(执行边界对齐 run_command)
- MCP/SearXNG/llm.baseURL/updateFeedUrl 配置类 URL 高危目标校验(IPv6 去括号 +
  十六进制映射解析 + 尾点剥离)

P3 架构还债:
- temperature/maxTokens 热生效(引擎/编排器/SubAgent 三处接线)+ setBatch 单事务落盘
- SessionRecorder flush 竞态根治(flushPromise 等待 + 超限内联落盘 + stopRecording async)
- 内存收口(lastConsolidationBySession LRU / subTraces 清理 / 会话删除 disposeEngine)
- i18n 全量收口(28 组件 + 353 key 双字典,状态标签改渲染时函数)
- 死代码清理(updateTraceStep/HEADER_HEIGHT/void preA/失实注释)
- 斜杠菜单 MUI 化 + 删除逻辑收敛 resetSessionState + Blob URL 统一释放 +
  用户消息"仅保存"落库(saveMessage 透传前端 id 修复 id 错位)

P4 能力演进:
- 死循环检测拆分(驻留前置 + 乒乓后置带进度信号,合法交替不误报)
- run-lock 30s 超时强制 abort(旧 run 卡死不无限排队)
- RETRY 双通道 stream_reset(前端按 run 归属精确清空,根治重试文本重复)
- FTS5 trigram 中文子串搜索(迁移 9 版本化 SCHEMA_VERSION=2,≤2 字符 LIKE 回退)
- getContextWindow 兜底 1M→128K(未知模型防 413)

测试:
- 855 → 2406 用例(+1551,2.8 倍):服务层 +325(含 MemoryManager 51 新用例)、
  工具实体 +483、IPC/适配器 +390(含 OpenAI/Anthropic/Ollama 独立套件)、
  纯函数表格化 +330;引入 jsdom + @testing-library(14 组件测试文件 249 用例)
- 修复 R1(saveMessage id 透传)/ R2(stream_reset 精确归属)两个回归缺陷
- 遗留低危项清零:git-tools 顺序耦合 / web-fetch 真实时间退避 / slo 内存断言 /
  mcp-security 多余 skipIf / deepseek-balance 命名误导 / 组件 mock 注入脆弱性

版本: 0.7.4; README 同步(工具风险表/版本徽章); 依赖: 移除 @electron-toolkit/preload,
新增 jsdom/@testing-library(devDependencies 不打包)

回归: typecheck 双端 0 错误; ESLint 0/0; Electron ABI 全量 2406/2406 零跳过;
系统 Node 2110 通过 296 跳过(better-sqlite3 ABI)
2026-08-30 19:19:07 +08:00

184 lines
6.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Secure Config 测试(v0.7.2 覆盖补齐 —— 此前零测试)
*
* 锁定敏感配置加密存储契约(P0-1 的回归防线):
* 1. 敏感 key 判定模式(apikey/token/secret/password/auth_key
* 2. safeStorage 可用 → 加密前缀格式 + 解密还原
* 3. safeStorage 不可用 → 明文降级(可用性优先)+ WARN
* 4. 解密失败(跨机器/重装)→ 返回空串(引导重录而非崩溃)
* 5. 加密幂等(已加密值不二次加密)与非字符串透传
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
// 可控的 safeStorage 桩:可逆 fake 加密(enc: 前缀),可用性开关可编程
const mockState = vi.hoisted(() => ({
encryptionAvailable: true,
failDecrypt: false,
}));
vi.mock('electron', () => ({
safeStorage: {
isEncryptionAvailable: () => mockState.encryptionAvailable,
encryptString: (value: string) => Buffer.from(`enc:${value}`, 'utf-8'),
decryptString: (buffer: Buffer) => {
const raw = buffer.toString('utf-8');
if (mockState.failDecrypt || !raw.startsWith('enc:')) {
throw new Error('decryption failed');
}
return raw.slice(4);
},
},
}));
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import {
isSensitiveConfigKey,
isEncryptedValue,
encryptConfigValue,
decryptConfigValue,
} from '../secure-config';
beforeEach(() => {
mockState.encryptionAvailable = true;
mockState.failDecrypt = false;
});
describe('isSensitiveConfigKey — 敏感 key 判定', () => {
it.each([
['llm.apiKey', true],
['llm.api_key', true],
['searxng.auth_key', true],
// v0.7.4 P2-5: 驼峰/连字符/点分隔的 authKey 类命名全部命中(去分隔符归一化)
['searxng.authKey', true],
['searxng.auth-key', true],
['mcp.server.authToken', true],
['db.api-key', true],
['llm.fallbackApiKey', true],
['proxy.token', true],
['db.secret', true],
['GITHUB_PASSWORD', true],
['ui.theme', false],
['llm.model', false],
['agent.maxIterations', false],
['network.proxyUrl', false],
['searxng.language', false],
])('%s → %j', (key, expected) => {
expect(isSensitiveConfigKey(key)).toBe(expected);
});
});
describe('encrypt/decrypt — 加密回环', () => {
it('加密值带版本化前缀(metona-enc:v1:),解密还原原文', () => {
const encrypted = encryptConfigValue('sk-my-secret-key');
expect(typeof encrypted).toBe('string');
expect(isEncryptedValue(encrypted)).toBe(true);
expect(String(encrypted)).toMatch(/^metona-enc:v1:/);
const decrypted = decryptConfigValue(encrypted);
expect(decrypted).toBe('sk-my-secret-key');
});
it('非字符串值原样透传(number/boolean/null 不加密)', () => {
expect(encryptConfigValue(42)).toBe(42);
expect(encryptConfigValue(true)).toBe(true);
expect(encryptConfigValue(null)).toBe(null);
expect(decryptConfigValue(42)).toBe(42);
});
it('空字符串不加密(避免无意义前缀包裹)', () => {
expect(encryptConfigValue('')).toBe('');
});
it('已加密值幂等 —— 二次加密不再包裹前缀', () => {
const once = encryptConfigValue('sk-key') as string;
const twice = encryptConfigValue(once);
expect(twice).toBe(once);
expect(decryptConfigValue(twice)).toBe('sk-key');
});
it('非加密格式的值解密时原样返回(历史明文平滑兼容)', () => {
expect(decryptConfigValue('plain-old-key')).toBe('plain-old-key');
});
});
describe('加密降级与失败语义', () => {
it('safeStorage 不可用 → 明文存储(可用性优先 + WARN)', () => {
mockState.encryptionAvailable = false;
const value = encryptConfigValue('sk-plaintext-fallback');
expect(value).toBe('sk-plaintext-fallback');
expect(isEncryptedValue(value)).toBe(false);
});
it('加密过程抛错 → 回退明文存储(不阻断配置保存)', () => {
// decryptString 抛错不影响 encrypt;此处验证 decrypt 失败语义
mockState.failDecrypt = true;
const encrypted = encryptConfigValue('sk-x') as string;
expect(decryptConfigValue(encrypted)).toBe(''); // 失败 → 空串(createAdapter 判定未配置,引导重录)
});
it('safeStorage 不可用时已加密值仍可识别且不被二次"加密"', () => {
const once = encryptConfigValue('sk-again') as string;
mockState.encryptionAvailable = false;
// 已加密值幂等:不重新走明文降级
expect(encryptConfigValue(once)).toBe(once);
});
it('前缀残缺的加密值(metona-enc:v1: 后无 base64)解密返回空串', () => {
expect(decryptConfigValue('metona-enc:v1:')).toBe('');
});
it('非 base64 内容的加密值解密失败返回空串(不抛错)', () => {
expect(decryptConfigValue('metona-enc:v1:@@@not-base64@@@')).toBe('');
});
it('不同版本前缀(metona-enc:v2:)不被识别为加密值(原样返回)', () => {
expect(isEncryptedValue('metona-enc:v2:abc')).toBe(false);
expect(decryptConfigValue('metona-enc:v2:abc')).toBe('metona-enc:v2:abc');
});
it('含非敏感子串的 key 不加密(大写化归一后仍不命中)', () => {
expect(isSensitiveConfigKey('ui.theme')).toBe(false);
expect(isSensitiveConfigKey('network.proxyUrl')).toBe(false);
expect(isSensitiveConfigKey('logging.traceEnabled')).toBe(false);
});
it('敏感 key 判定覆盖 token 类与 secret 类更多形态', () => {
expect(isSensitiveConfigKey('mcp.githubToken')).toBe(true);
expect(isSensitiveConfigKey('db.clientSecret')).toBe(true);
expect(isSensitiveConfigKey('registry.authToken')).toBe(true);
expect(isSensitiveConfigKey('SMTP_PASSWORD')).toBe(true);
expect(isSensitiveConfigKey('sshPrivateKey')).toBe(false); // 无分隔符且不含模式
expect(isSensitiveConfigKey('keyboard.layout')).toBe(false);
});
it('encrypt/decrypt 往返多种敏感字符串(含特殊字符/中文/emoji)', () => {
const samples = [
'sk-hello world',
'含中文密钥值',
'with,comma"quotes"',
'emoji-🔑-key',
'a'.repeat(5000),
];
for (const s of samples) {
const encrypted = encryptConfigValue(s) as string;
expect(isEncryptedValue(encrypted)).toBe(true);
expect(decryptConfigValue(encrypted)).toBe(s);
}
});
it('decrypt 对 undefined/null 原样透传', () => {
expect(decryptConfigValue(undefined)).toBeUndefined();
expect(decryptConfigValue(null)).toBeNull();
});
it('encrypt 对 0/空串/false 等 falsy 非字符串原样透传', () => {
expect(encryptConfigValue(0)).toBe(0);
expect(encryptConfigValue('')).toBe('');
expect(encryptConfigValue(false)).toBe(false);
});
});