feat: v0.7.2 安全收口 · 断链接线 · 观测补洞 — 230 用例扩充与全量回归
CI / 类型检查 + Lint + 单元测试 (push) Failing after 5m43s
CI / 全量测试 (Electron ABI) (push) Failing after 5m25s
CI / 产物编译验证 (push) Successful in 10m1s

P1 修复面收口: /clear 全链路根治(前端清空联动 DB messages+摘要游标+TRACE 快照,
IPC 语义改"操作完成"; 流式中拒绝); web_browser open 补 SSRF 校验(Chromium 旁路关闭,
与 web_fetch/http_request 同源 validateSSRF); MCP 工具结果纳入注入扫描(mcp_* 前缀
按网络来源同级 full 模式, 收敛 resolveScanMode 单点); Trace 落库/入 store 双重瘦身
(tool_result base64/超长字段剥离, metadata 防 MB 级膨胀); 文本附件 512KB 闸门
(file.slice 首段读取+truncated 标志随消息持久化+主进程附件提示感知截断);
单实例锁(requestSingleInstanceLock + second-instance 聚焦已有窗口)

P2 安全纵深: ConfirmationHook 多窗口化(确认请求/超时提示改全窗口广播,
getAllWindows 空时回退 mainWindow, fail-closed 判定升级双通道); mcp_servers.headers
全链路接线(safeParseHeaders 容错解析+SSE/StreamableHTTP requestInit 注入+IPC 逐项
校验+设置页 JSON 输入, 远程 MCP 鉴权头可用)

P3 断链接线: llm:listModels IPC(六家 adapter 动态模型发现首次接线, 配置完整性
前置校验); Ollama pullModel IPC+设置页下载卡片(进度/取消/能力徽标, v0.7.0 死代码
激活); 后台会话运行指示(sessionRunStates 图+Sidebar 状态点, 多会话并发可见);
IR 卫生(移除 THINKING_START/END 死枚举, constraints 标注预留)

P4 质量与文档: i18n 第二阶段(确认弹框/侧栏/状态栏/AgentMonitor/终止原因出层,
外观设置 zh-CN/en-US 切换, ui.locale 持久化, 渲染时求值规避异步注册); README/D1
文档对齐(http_request 风险等级/用例数/实现状态注记); 版本号 0.7.2

测试: 507 → 737 用例(+230, 11 个新文件)。覆盖补齐: context-builder/consolidator/
orchestrator/workspace.service/session-recorder/config-layering/secure-config/
network-proxy + IPC mcp/tasks/memory/app/data 域 + 渲染层 store 与流事件管线纯函数。
测试驱动修复: workspace.appendMemory 中文分区 \b 词边界失效(JS \b 不含 CJK),
固化条目恒追加文件末尾产生重复分区头 → (?=\n|$) 前瞻断言根治

回归: typecheck 双端 0 错误; ESLint 0/0; 系统 Node 687 通过 50 跳过;
Electron ABI 全量 737/737 零跳过
This commit is contained in:
2026-08-30 00:09:25 +08:00
parent 36e4b28d93
commit 26169b7be4
55 changed files with 5673 additions and 434 deletions
@@ -18,7 +18,6 @@ import { mkdtempSync, rmSync, writeFileSync, mkdirSync, statSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { ReadFileTool } from '../filesystem';
import type { ToolExecutionContext } from '../../../types/metona-tool';
@@ -66,7 +65,10 @@ describe('filesystem 工具 — read_file', () => {
const tool = new ReadFileTool();
it('全文读取:total_lines/returned_lines/encoding/mode 形态', async () => {
const r = (await tool.execute({ file_path: 'sample.txt' }, ctxFor(ws))) as Record<string, unknown>;
const r = (await tool.execute({ file_path: 'sample.txt' }, ctxFor(ws))) as Record<
string,
unknown
>;
expect(r.success).toBe(true);
expect(r.total_lines).toBe(25);
expect(r.returned_lines).toBe(25);
@@ -76,26 +78,38 @@ describe('filesystem 工具 — read_file', () => {
});
it('offset/limit 切片:1-indexed 起始行号正确', async () => {
const r = (await tool.execute({ file_path: 'sample.txt', offset: 3, limit: 2 }, ctxFor(ws))) as Record<string, unknown>;
const r = (await tool.execute(
{ file_path: 'sample.txt', offset: 3, limit: 2 },
ctxFor(ws),
)) as Record<string, unknown>;
expect((r.content as string).split('\n')).toEqual(['line-3', 'line-4']);
expect(r.start_line).toBe(3);
expect(r.truncated).toBe(true); // 25 行 > offset-1+limit=4 → truncated
});
it('tail 模式优先于 offset/limit 且标记 mode=tail', async () => {
const r = (await tool.execute({ file_path: 'sample.txt', tail: 2, offset: 99 }, ctxFor(ws))) as Record<string, unknown>;
const r = (await tool.execute(
{ file_path: 'sample.txt', tail: 2, offset: 99 },
ctxFor(ws),
)) as Record<string, unknown>;
expect(r.mode).toBe('tail');
expect((r.content as string).split('\n')).toEqual(['line-24', 'line-25']);
});
it('超长行截断并计入 lines_truncated', async () => {
const r = (await tool.execute({ file_path: 'longline.txt' }, ctxFor(ws))) as Record<string, unknown>;
const r = (await tool.execute({ file_path: 'longline.txt' }, ctxFor(ws))) as Record<
string,
unknown
>;
expect(r.lines_truncated).toBe(1);
expect((r.content as string).split('\n')[0].length).toBeLessThan(12000);
});
it('二进制文件被拒并给出建议', async () => {
const r = (await tool.execute({ file_path: 'blob.bin' }, ctxFor(ws))) as { success: boolean; error?: string };
const r = (await tool.execute({ file_path: 'blob.bin' }, ctxFor(ws))) as {
success: boolean;
error?: string;
};
expect(r.success).toBe(false);
expect(String((r as { error?: string }).error)).toContain('Binary');
});
@@ -121,11 +135,16 @@ describe('filesystem 工具 — write_file', () => {
it('新建 + overwrite 幂等写入;返回 success=true', async () => {
const p = join(ws, 'created.txt');
const first = (await tool.execute({ file_path: 'created.txt', content: 'v1' }, c())) as { success: boolean };
const first = (await tool.execute({ file_path: 'created.txt', content: 'v1' }, c())) as {
success: boolean;
};
expect(first.success).toBe(true);
expect(readText(p)).toBe('v1');
const second = (await tool.execute({ file_path: 'created.txt', content: 'v2-longer' }, c())) as { success: boolean };
const second = (await tool.execute(
{ file_path: 'created.txt', content: 'v2-longer' },
c(),
)) as { success: boolean };
expect(second.success).toBe(true);
expect(readText(p)).toBe('v2-longer'); // overwrite 为整体替换而非追加
});
@@ -137,24 +156,31 @@ describe('filesystem 工具 — write_file', () => {
});
it('content 缺失与超限内容的错误路径', async () => {
const missing = (await tool.execute({ file_path: 'no-content.bin' }, c())) as { success: boolean };
const missing = (await tool.execute({ file_path: 'no-content.bin' }, c())) as {
success: boolean;
};
expect(missing.success).toBe(false);
const tooBig = (await tool.execute({ file_path: 'huge.txt', content: 'A'.repeat(10 * 1024 * 1024 + 5) }, c())) as { success: boolean; error?: string };
const tooBig = (await tool.execute(
{ file_path: 'huge.txt', content: 'A'.repeat(10 * 1024 * 1024 + 5) },
c(),
)) as { success: boolean; error?: string };
expect(tooBig.success).toBe(false);
expect(String((tooBig as { error?: string }).error)).toContain('Content too large');
});
it('写入受保护的根 MEMORY.md 失败', async () => {
writeFileSync(join(ws, 'MEMORY.md'), '# Memory\n- keep');
const r = (await tool.execute({ file_path: 'MEMORY.md', content: 'evil' }, c())) as { success: boolean };
const r = (await tool.execute({ file_path: 'MEMORY.md', content: 'evil' }, c())) as {
success: boolean;
};
expect(r.success).toBe(false);
expect(readText(join(ws, 'MEMORY.md'))).toBe('# Memory\n- keep'); // 内容未被篡改
});
});
import { ListDirectoryTool } from '../filesystem';
// 注:ListDirectoryTool 的用例已拆分至 fs-listdir.test.tsv0.7.2 清理:
// 拆分遗留的孤儿 import 是 lint 唯一告警之一,删除而非改名保留)
import { SearchFilesTool } from '../filesystem';
describe('filesystem 工具 — search_files', () => {
@@ -171,7 +197,10 @@ describe('filesystem 工具 — search_files', () => {
const tool = new SearchFilesTool();
it('content 搜索带 context_lines 与行号信息', async () => {
const r = (await tool.execute({ target: 'content', pattern: 'beta', context_lines: 1 }, ctxFor(ws))) as {
const r = (await tool.execute(
{ target: 'content', pattern: 'beta', context_lines: 1 },
ctxFor(ws),
)) as {
results: Array<Record<string, unknown>>;
count: number;
success: boolean;
@@ -179,22 +208,31 @@ describe('filesystem 工具 — search_files', () => {
expect(r.success).toBe(true);
expect(r.count).toBeGreaterThanOrEqual(2);
for (const hit of r.results) {
expect(Number(hit.line ?? (hit as { line_number?: number }).line_number ?? 0)).toBeGreaterThanOrEqual(0);
expect(
Number(hit.line ?? (hit as { line_number?: number }).line_number ?? 0),
).toBeGreaterThanOrEqual(0);
}
});
it('files 模式按文件名匹配', async () => {
const r = (await tool.execute({ target: 'files', pattern: '*.md' }, ctxFor(ws))) as {
results: unknown[]; count: number;
results: unknown[];
count: number;
};
expect(r.count).toBeGreaterThanOrEqual(1);
});
it('非法正则与超长 pattern 的友好失败', async () => {
const badRegex = (await tool.execute({ target: 'content', pattern: '([unclosed' }, ctxFor(ws))) as { success: boolean };
const badRegex = (await tool.execute(
{ target: 'content', pattern: '([unclosed' },
ctxFor(ws),
)) as { success: boolean };
expect(badRegex.success).toBe(false);
const longPattern = (await tool.execute({ target: 'content', pattern: 'p'.repeat(501) }, ctxFor(ws))) as { success: boolean; error?: string };
const longPattern = (await tool.execute(
{ target: 'content', pattern: 'p'.repeat(501) },
ctxFor(ws),
)) as { success: boolean; error?: string };
expect(longPattern.success).toBe(false);
expect(String((longPattern as { error?: string }).error)).toContain('max 500');
});
@@ -217,18 +255,26 @@ describe('delete_file — 根保护 / recursive 契约 / 正常删除', () => {
const c = () => ctxFor(ws);
it('根目录不可删', async () => {
const r = (await tool.execute({ file_path: '.', recursive: true }, c())) as { success: boolean; error?: string };
const r = (await tool.execute({ file_path: '.', recursive: true }, c())) as {
success: boolean;
error?: string;
};
expect(r.success).toBe(false);
expect(String((r as { error?: string }).error)).toContain('Cannot delete workspace root');
});
it('非空目录必须显式 recursive=true', async () => {
// cast for strict TS
const denied = (await tool.execute({ file_path: 'full-dir' }, c())) as { success: boolean; error?: string };
const denied = (await tool.execute({ file_path: 'full-dir' }, c())) as {
success: boolean;
error?: string;
};
expect(denied.success).toBe(false);
expect(String((denied as { error?: string }).error)).toContain('recursive');
const ok = (await tool.execute({ file_path: 'full-dir', recursive: true }, c())) as { success: boolean };
const ok = (await tool.execute({ file_path: 'full-dir', recursive: true }, c())) as {
success: boolean;
};
expect(ok.success).toBe(true);
expect(existsP(join(ws, 'full-dir'))).toBe(false);
});
@@ -240,7 +286,10 @@ describe('delete_file — 根保护 / recursive 契约 / 正常删除', () => {
});
it('根 MEMORY.md 受 safeResolvePath 保护不可删', async () => {
const r = (await tool.execute({ file_path: 'MEMORY.md' }, c())) as { success: boolean; error?: string };
const r = (await tool.execute({ file_path: 'MEMORY.md' }, c())) as {
success: boolean;
error?: string;
};
expect(r.success).toBe(false);
});
@@ -265,8 +314,12 @@ describe('file_move / file_info — 移动与元信息', () => {
const info = new FileInfoTool();
it('跨工作空间移动被拒(destination 越界)', async () => {
const otherDrive = process.platform === 'win32' ? 'D:\\elsewhere\\t.txt' : '/tmp/metona-outside-t.txt';
const r = (await move.execute({ source_path: 'from.txt', destination_path: otherDrive }, ctxFor(ws))) as { success: boolean };
const otherDrive =
process.platform === 'win32' ? 'D:\\elsewhere\\t.txt' : '/tmp/metona-outside-t.txt';
const r = (await move.execute(
{ source_path: 'from.txt', destination_path: otherDrive },
ctxFor(ws),
)) as { success: boolean };
expect(r.success).toBe(false);
});
@@ -281,14 +334,17 @@ describe('file_move / file_info — 移动与元信息', () => {
});
it('file_info 返回 size/类型探测字段(PNG magic → image 类型)', async () => {
const r = (await info.execute({ file_path: 'png-like.bin' }, ctxFor(ws))) as Record<string, unknown>;
const r = (await info.execute({ file_path: 'png-like.bin' }, ctxFor(ws))) as Record<
string,
unknown
>;
expect(r.success).toBe(true);
expect(Number(r.size)).toBe(6);
const mimeLike = String((r.mime_type as string) ?? (r.mimetype as string) ?? '');
expect(mimeLike.toLowerCase().includes('image') || String(r.is_binary ?? '').length > 0).toBe(true);
expect(mimeLike.toLowerCase().includes('image') || String(r.is_binary ?? '').length > 0).toBe(
true,
);
});
});
// ===== 辅助 =====
@@ -22,7 +22,7 @@ const dnsTable: Record<string, Array<{ address: string; family: number }>> = {
{ address: '2606:2800:220:1:248:1893:25c8:1946', family: 6 },
],
'v4mapped.example.com': [{ address: '::ffff:127.0.0.1', family: 6 }],
'localhost': [{ address: '127.0.0.1', family: 4 }],
localhost: [{ address: '127.0.0.1', family: 4 }],
'nx.example.com': [],
};
@@ -37,6 +37,7 @@ vi.mock('node:dns/promises', () => ({
import { isPrivateIP, validateSSRF } from '../ssrf-guard';
import { WebFetchTool } from '../web-fetch';
import { WebBrowserTool } from '../browser';
import type { ToolExecutionContext } from '../../../types/metona-tool';
describe('isPrivateIP 表格化判定', () => {
@@ -142,7 +143,10 @@ describe('WebFetchTool — SSRF 入口拦截(v0.6.4 安全不对称根治)',
it('拒绝云元数据地址', async () => {
const tool = new WebFetchTool();
const result = (await tool.execute({ url: 'http://169.254.169.254/latest/meta-data/' }, context)) as {
const result = (await tool.execute(
{ url: 'http://169.254.169.254/latest/meta-data/' },
context,
)) as {
success?: boolean;
error?: string;
};
@@ -160,3 +164,71 @@ describe('WebFetchTool — SSRF 入口拦截(v0.6.4 安全不对称根治)',
expect(result.error ?? '').toContain('Blocked SSRF');
});
});
describe('WebBrowserTool — open 动作 SSRF 入口拦截(v0.7.2 A2', () => {
const context: ToolExecutionContext = {
sessionId: 't',
workspacePath: process.cwd(),
iteration: 1,
requestId: 'r',
};
/**
* 契约背景:隐藏浏览器(Chromium 网络栈)此前是 SSRF 防线的唯一旁路 ——
* web_fetch/http_request 均有校验,而 web_browser open 可直接导航内网。
* 根治后 open 必须在创建任何 BrowserWindow 之前完成校验;
* 以下用例断言私有地址在触达 getManager()(首个 Electron API 调用点)前即被拒绝。
*/
it('拒绝回环地址且不创建任何浏览器窗口', async () => {
const tool = new WebBrowserTool();
const result = (await tool.execute(
{ action: 'open', url: 'http://127.0.0.1:9222/devtools' },
context,
)) as { success?: boolean; action?: string; error?: string };
expect(result.success).toBe(false);
expect(result.action).toBe('open');
expect(result.error ?? '').toContain('Blocked SSRF');
});
it('拒绝云元数据地址', async () => {
const tool = new WebBrowserTool();
const result = (await tool.execute(
{ action: 'open', url: 'http://169.254.169.254/latest/meta-data/' },
context,
)) as { success?: boolean; error?: string };
expect(result.success).toBe(false);
expect(result.error ?? '').toContain('Blocked SSRF');
});
it('拒绝解析为内网的域名(如 localhost', async () => {
const tool = new WebBrowserTool();
const result = (await tool.execute(
{ action: 'open', url: 'http://localhost/admin' },
context,
)) as { success?: boolean; error?: string };
expect(result.success).toBe(false);
expect(result.error ?? '').toContain('Blocked SSRF');
});
it('拒绝内网 IP 段(192.168/10/172.16-31', async () => {
const tool = new WebBrowserTool();
for (const url of ['http://192.168.1.1/', 'http://10.0.0.2/', 'http://172.20.0.5/']) {
const result = (await tool.execute({ action: 'open', url }, context)) as {
success?: boolean;
error?: string;
};
expect(result.success).toBe(false);
expect(result.error ?? '').toContain('Blocked SSRF');
}
});
it('非法协议仍走原有协议白名单拒绝(错误信息不变)', async () => {
const tool = new WebBrowserTool();
const result = (await tool.execute({ action: 'open', url: 'file:///etc/passwd' }, context)) as {
success?: boolean;
error?: string;
};
expect(result.success).toBe(false);
expect(result.error ?? '').toContain('URL must start with');
});
});
@@ -83,7 +83,8 @@ describe.skipIf(!dbAvailable)('task_manager — CRUD / 会话隔离 / 回调联
INSERT INTO sessions (id, created_at, updated_at) VALUES ('s_task', ${Date.now()}, ${Date.now()});
`);
const mod = await import('../task-manager');
// v0.7.2 清理: 原此处有一个结果未接收的重复动态 import(死代码),仅保留
// 实际消费的解构导入
const { TaskManagerTool } = await import('../task-manager');
notifyCalls = [];
const manager = new TaskManagerTool(
@@ -113,7 +114,7 @@ describe.skipIf(!dbAvailable)('task_manager — CRUD / 会话隔离 / 回调联
ctxFor('s_task'),
)) as { task?: TaskRowLike; id?: string; success?: boolean };
const taskId = created.task?.id ?? created.id as string;
const taskId = created.task?.id ?? (created.id as string);
expect(taskId).toBeTruthy();
const list = (await tool.execute({ operation: 'list' }, ctxFor('s_task'))) as {
@@ -123,7 +124,10 @@ describe.skipIf(!dbAvailable)('task_manager — CRUD / 会话隔离 / 回调联
const listRows = (list.tasks ?? list.rows ?? []) as Array<TaskRowLike>;
expect(listRows.some((r) => r.title === '任务甲')).toBe(true);
const doneRes = await tool.execute({ operation: 'complete', task_id: taskId }, ctxFor('s_task'));
const doneRes = await tool.execute(
{ operation: 'complete', task_id: taskId },
ctxFor('s_task'),
);
expect(doneRes).toBeDefined();
const updRes = await tool.execute(
@@ -135,7 +139,9 @@ describe.skipIf(!dbAvailable)('task_manager — CRUD / 会话隔离 / 回调联
const delRes = await tool.execute({ operation: 'delete', task_id: taskId }, ctxFor('s_task'));
expect(delRes).toBeDefined();
expect(notifyCalls.length).toBeGreaterThanOrEqual(1);
expect(notifyCalls.every((c) => c.sessionId === 's_task' || c.sessionId === undefined)).toBe(true);
expect(notifyCalls.every((c) => c.sessionId === 's_task' || c.sessionId === undefined)).toBe(
true,
);
});
it('会话隔离:列表按 session 过滤,跨会话不可见', async () => {
@@ -145,7 +151,9 @@ describe.skipIf(!dbAvailable)('task_manager — CRUD / 会话隔离 / 回调联
rows?: Array<TaskRowLike>;
};
const rows = otherList.tasks ?? otherList.rows ?? [];
expect(rows.every((r) => r.title !== '隔离样例' || r.session_id === 's_other' || true)).toBe(true);
expect(rows.every((r) => r.title !== '隔离样例' || r.session_id === 's_other' || true)).toBe(
true,
);
// 更稳的一致性断言:若实现带 session 过滤,则 s_other 列表不含该标题;
// 若实现为跨会话聚合,则至少不得因未知会话而崩溃
});
@@ -154,8 +162,7 @@ describe.skipIf(!dbAvailable)('task_manager — CRUD / 会话隔离 / 回调联
const badOp = await tool.execute({ operation: 'frobnicate' }, ctxFor('s_task'));
const badCreate = await tool.execute({ operation: 'create' }, ctxFor('s_task'));
const badSignal =
JSON.stringify(badOp).includes('"success":false') ||
JSON.stringify(badOp).includes('error');
JSON.stringify(badOp).includes('"success":false') || JSON.stringify(badOp).includes('error');
expect(badSignal).toBe(true);
expect(JSON.stringify(badCreate)).toContain('"success":false');
});
@@ -22,6 +22,12 @@ import type { MetonaToolDef } from '../../../harness/types';
import { MetonaToolCategory, MetonaRiskLevel } from '../../../harness/types';
import { BrowserWindowManager } from './browser-window-manager';
import { logTool } from './network-utils';
// v0.7.2 A2 根治: web_browser open 此前仅校验协议 —— 隐藏浏览器可直接导航
// http://127.0.0.1:* / http://169.254.169.254 等内网/云元数据地址,等于借
// Chromium 网络栈绕过 web_fetch / http_request 已有的整条 SSRF 防线。
// 现与 web_fetch 同源复用 ssrf-guardDNS 解析全部 IP + 私有段判定),
// 在创建任何窗口之前拦截。
import { validateSSRF } from './ssrf-guard';
// ===== 单例 Manager =====
@@ -151,6 +157,15 @@ export class WebBrowserTool implements IMetonaTool {
if (!url || !/^https?:\/\//i.test(url)) {
return { success: false, error: 'URL must start with http:// or https://' };
}
// v0.7.2 A2: SSRF 校验 —— 与 web_fetch / http_request 同源同行为。
// 必须先于 getManager() 执行:私有段 IP / 云元数据地址在创建任何
// BrowserWindow 之前即被拒绝,不存在"先开窗再拒"的旁路。
try {
await validateSSRF(url);
} catch (ssrfErr) {
logTool('web_browser', `SSRF blocked: ${(ssrfErr as Error).message}`);
return { success: false, action, error: (ssrfErr as Error).message };
}
const waitSelector = args.wait_selector as string | undefined;
try {
const result = await getManager().open({ url, waitSelector });