feat: v0.7.0 四阶段全量迭代 — 修复面收口 · 安全纵深 · 架构还债 · 能力演进
CI / 类型检查 + Lint + 单元测试 (push) Failing after 5m45s
CI / 全量测试 (Electron ABI) (push) Failing after 5m22s
CI / 产物编译验证 (push) Successful in 10m3s

P1 修复面收口: v0.6.3 截断自愈推全量(Anthropic/Ollama/非流式/引擎兜底); SSE 上游错误帧检测进重试通道;
clearMessages 摘要游标根治; truncateResult 内联图片白名单统一; 前端四 bug(确认弹窗锁死/MemoryViewer/
Virtuoso Footer/abort 尾部过滤) + reasoning 缓冲跨迭代污染; 托盘通知过滤与新建会话死链接线

P2 安全纵深: MCP 审批闭环(ConfirmationHook×PolicyEngine 联动+重名拒注册); SSRF 收敛 ssrf-guard 共享模块
(web_fetch 双通道校验+重定向终态复检); Electron 加固(preload CJS 化→sandbox:true/CSP/权限白名单/will-navigate);
run_command cmd.exe 白名单通道元字符守门; diff_viewer 10MB 预检; Anthropic thinking 预算下限; Agnes 思考显式关闭

P3 架构还债: OpenAICompatibleAdapter 中间基类收敛四家样板; 错误分类单轨化(删 mapError/getFetchSignal,
超时显式 ETIMEDOUT); PRAGMA user_version 迁移版本化; 死代码清理专项(cn.ts/SHORTCUTS/ContextMenu 分支/
getWindowState/modifiedArgs/sandbox 空壳); i18next 引入; a11y 第一轮; SearXNG 页批量草稿模型统一

P4 能力演进: Ollama pull 可取消/capabilities 探测/num_ctx 实测缓存; UpdateService feed 比对式自动更新
(app:updateCheck IPC + StatusBar 入口); MiMo providerOptions(web_search 服务端工具/strict JSON);
web_fetch extract_mode=markdown(turndown); network.proxyUrl 全局代理(Chromium sessions+undici dispatcher)

测试: 264 → 507 用例(Electron ABI 全绿零跳过), 覆盖引擎压缩管线/重试竞速/MEMORY.md 闸门/file_editor 五操作/
filesystem 七工具实体夹具/git 真实仓库/SSE 错误帧/全线截断自愈/Provider 请求形态矩阵/SSRF 表测/钩子分级矩阵/
OutputValidator 全量/SLO 指标/MCP 安全纯函数/task_manager 链路/渲染层纯域/i18n 桥契约
This commit is contained in:
2026-08-27 17:06:58 +08:00
parent b6e2a8bd25
commit 3940716dc2
78 changed files with 6369 additions and 1341 deletions
@@ -9,7 +9,31 @@ vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import { RunCommandTool } from '../command';
import { RunCommandTool, argsSafeForCmdExecChannel } from '../command';
// ===== v0.6.4: cmd.exe /c 白名单通道元字符守门 =====
describe('argsSafeForCmdExecChannelcmd.exe 通道注入口守门)', () => {
it('纯字母数字参数放行', () => {
expect(argsSafeForCmdExecChannel(['commit', '-m', 'hello', '--amend'])).toBe(true);
});
it('含空格的带元字符参数由 libuv 加引号保护,但本通道按最严口径仍拒绝', () => {
expect(argsSafeForCmdExecChannel(['--flag=x&whoami'])).toBe(false);
});
it.each(['&cmd', 'a|b', 'a^b', 'a<b', 'a>b', 'a%PATH%', '"quoted"', 'x\ry'])(
'%j 含 cmd 元字符 → 拒绝走白名单通道',
(arg) => {
expect(argsSafeForCmdExecChannel([arg])).toBe(false);
},
);
it('无参命令放行', () => {
expect(argsSafeForCmdExecChannel([])).toBe(true);
});
});
describe('RunCommandTool.validateCommand', () => {
const tool = new RunCommandTool();
@@ -0,0 +1,196 @@
/**
* file_editor 操作矩阵 + dev-tools/code-search 纯解析器测试(v0.7.0 覆盖补齐)
*
* file_editor(此前零测试):replace/insert/delete/regex/find_replace 五操作、
* dry_run 预览、backup 落盘、ReDoS 启发式拦截、原子写失败回滚。
* dev-tools.parseCounts/parseTestResults、code-search.parseRipgrepJsonOutput
* 已 @visibleForTesting 导出,直接锁定输出格式契约。
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import { FileEditorTool } from '../file-editor';
import { LintCodeTool, RunTestsTool } from '../dev-tools';
import { CodeSearchTool } from '../code-search';
import type { ToolExecutionContext } from '../../../types/metona-tool';
function ctxFor(ws: string): ToolExecutionContext {
return { sessionId: 't', workspacePath: ws, iteration: 1, requestId: 'r' };
}
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-edit-'));
writeFileSync(join(ws, 'src.txt'), ['alpha', 'beta', 'gamma', 'delta'].join('\n'));
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
const editor = new FileEditorTool();
describe('file_editor — 五种 operation', () => {
it('find_replacereplace_all=true 全量;缺省亦全量(split/join 契约)', async () => {
writeFileSync(join(ws, 'fr.txt'), 'cat dog cat dog');
const all = (await editor.execute({ file_path: 'fr.txt', operation: 'find_replace', find: 'cat', replace: 'CAT', replace_all: true }, ctxFor(ws))) as { success: boolean };
expect(all.success).toBe(true);
expect(readFileSync(join(ws, 'fr.txt'), 'utf-8')).toBe('CAT dog CAT dog');
// 实况契约:split/join 实现 → 缺省 replace_all 即为全量替换
writeFileSync(join(ws, 'fr.txt'), 'cat dog cat dog');
const first = (await editor.execute({ file_path: 'fr.txt', operation: 'find_replace', find: 'dog', replace: 'BIRD' }, ctxFor(ws))) as { success: boolean };
expect(first.success).toBe(true);
expect(readFileSync(join(ws, 'fr.txt'), 'utf-8')).toBe('cat BIRD cat BIRD');
void all;
});
it('replace 区间替换:start/end_line 契约', async () => {
const r = (await editor.execute({ file_path: 'src.txt', operation: 'replace', start_line: 2, end_line: 3, content: 'BETA2\nGAMMA2' }, ctxFor(ws))) as { success: boolean };
expect(r.success).toBe(true);
expect(readFileSync(join(ws, 'src.txt'), 'utf-8').split('\n')).toEqual(['alpha', 'BETA2', 'GAMMA2', 'delta']);
// 还原
writeFileSync(join(ws, 'src.txt'), ['alpha', 'beta', 'gamma', 'delta'].join('\n'));
});
it('insert 支持追加到文件末尾(end_line=len+1 形态)与中间插入', async () => {
const mid = (await editor.execute({ file_path: 'src.txt', operation: 'insert', start_line: 2, content: 'inserted' }, ctxFor(ws))) as { success: boolean };
expect(mid.success).toBe(true);
expect(readFileSync(join(ws, 'src.txt'), 'utf-8')).toBe(['alpha', 'inserted', 'beta', 'gamma', 'delta'].join('\n'));
const tail = (await editor.execute({ file_path: 'src.txt', operation: 'delete', start_line: 2, end_line: 2 }, ctxFor(ws))) as { success: boolean };
expect(tail.success).toBe(true);
expect(readFileSync(join(ws, 'src.txt'), 'utf-8')).toBe(['alpha', 'beta', 'gamma', 'delta'].join('\n'));
});
it('delete 区间删除行', async () => {
const r = (await editor.execute({ file_path: 'src.txt', operation: 'delete', start_line: 1, end_line: 1 }, ctxFor(ws))) as { success: boolean };
expect(r.success).toBe(true);
expect(readFileSync(join(ws, 'src.txt'), 'utf-8').startsWith('beta')).toBe(true);
writeFileSync(join(ws, 'src.txt'), ['alpha', 'beta', 'gamma', 'delta'].join('\n'));
});
it('regex 替换强制 g 标志保证计数一致', async () => {
writeFileSync(join(ws, 're.txt'), 'aaa bbb aaa ccc');
const r = (await editor.execute({ file_path: 're.txt', operation: 'regex', pattern: 'a{3}', replacement: 'XXX' }, ctxFor(ws))) as Record<string, unknown>;
expect(r.success).toBe(true);
expect(readFileSync(join(ws, 're.txt'), 'utf-8')).toContain('XXX bbb XXX');
});
it('dry_run=true 不落盘并给出预览', async () => {
const before = readFileSync(join(ws, 'src.txt'), 'utf-8');
const r = (await editor.execute({ file_path: 'src.txt', operation: 'find_replace', find: 'alpha', replace: 'ALPHA', dry_run: true }, ctxFor(ws))) as { success: boolean };
expect(r.success).toBe(true);
expect(readFileSync(join(ws, 'src.txt'), 'utf-8')).toBe(before);
});
it('backup=true 产出 .bak 且内容为改动前快照', async () => {
writeFileSync(join(ws, 'bak.txt'), 'orig-line');
void (await editor.execute({ file_path: 'bak.txt', operation: 'find_replace', find: 'orig', replace: 'new', backup: true }, ctxFor(ws)));
expect(existsSync(join(ws, 'bak.txt.bak'))).toBe(true);
expect(readFileSync(join(ws, 'bak.txt.bak'), 'utf-8')).toBe('orig-line');
});
it('ReDoS 启发式拦截嵌套量词 pattern', async () => {
const r = (await editor.execute({ file_path: 're.txt', operation: 'regex', pattern: '(a+)+$', replacement: 'x' }, ctxFor(ws))) as { success: boolean; error?: string };
expect(r.success).toBe(false);
expect(String((r as { error?: string }).error).toLowerCase()).toMatch(/catastrophic|unsafe|complex|pattern/i);
});
});
// ===== dev-tools 解析器 =====
const lintDevTools = new LintCodeTool();
const parseCounts = lintDevTools.parseCounts.bind(lintDevTools);
const parseTests = new RunTestsTool().parseTestResults.bind(new RunTestsTool());
describe('dev-tools.parseCounts / parseTestResults 输出契约', () => {
it('tsc 格式:error TS#### 行计数,warning 恒 0', () => {
const out = [
'src/a.ts(1,7): error TS2304: Cannot find name',
'src/b.ts(5,1): warning TS6133: unused var',
'src/c.ts(9,9): error TS2551: typo',
].join('\n');
expect(parseCounts(out, 'tsc')).toEqual({ errorCount: 2, warningCount: 0 });
});
it('eslint 汇总行 "✖ N problems (X errors, Y warnings)" 解析', () => {
expect(parseCounts('✖ 7 problems (5 errors, 2 warnings)', 'eslint')).toEqual({
errorCount: 5,
warningCount: 2,
});
expect(parseCounts('All clean', 'eslint')).toEqual({ errorCount: 0, warningCount: 0 });
});
it.each([
['Tests: 5 passed, 2 failed, 7 total', { passed: 5, failed: 2 }],
['Tests: 9 passed, 9 total', { passed: 9, failed: 0 }],
['42 passing (3.5s)', { passed: 42, failed: 0 }],
['3 failing (1.2s)', { passed: 0, failed: 3 }],
])('%s → %j', (output, expected) => {
const parsed = parseTests(output);
expect(parsed.passed).toBe(expected.passed);
expect(parsed.failed).toBe(expected.failed);
expect(typeof parsed.duration).toBe('string');
});
it('耗时优先 Time:/Duration:/耗时: 标签,回退括号形态', () => {
expect(parseTests('Time: 12.3 s').duration).toMatch(/^12\.3\s*s$/);
expect(parseTests('(3.5s)').duration).toContain('3.5');
});
});
// ===== code-search ripgrep JSON 状态机 =====
const cs = new CodeSearchTool();
const parseRipgrep = cs.parseRipgrepJsonOutput.bind(cs);
describe('parseRipgrepJsonOutput — rg --json 上下文状态机', () => {
it('match/context 状态机(首个 match 的 before / 最后残留 after', () => {
const raw = [
JSON.stringify({ type: 'context', data: { lines: { text: 'before line 1' } } }),
JSON.stringify({ type: 'context', data: { lines: { text: 'before line 2' } } }),
JSON.stringify({ type: 'match', data: { path: { text: 'a.ts' }, line_number: 10, submatches: [{ match: { text: 'needle' }, start: 4 }] } }),
JSON.stringify({ type: 'context', data: { lines: { text: 'after line 1' } } }),
JSON.stringify({ type: 'context', data: { lines: { text: 'after line 2' } } }),
].join('\n');
const results = parseRipgrep(raw);
expect(results).toHaveLength(1);
const hit = results[0];
expect(hit.path).toBe('a.ts');
expect(hit.line).toBe(10);
expect(hit.column).toBe(5); // start=4 → column 从 1 计数
expect(hit.match).toBe('needle');
expect(hit.before?.map((l: string) => l.trim())).toEqual(['before line 1', 'before line 2']);
// 结尾残留的 context 属于最后一个 match 的 after
expect(hit.after?.map((l: string) => l.trim())).toEqual(['after line 1', 'after line 2']);
});
it('多 match 相邻排布:每个 match 的 before/after 各自正确收敛', () => {
const raw = [
JSON.stringify({ type: 'match', data: { path: { text: 'b.ts' }, line_number: 1, submatches: [{ match: { text: 'one' }, start: 0 }] } }),
JSON.stringify({ type: 'context', data: { lines: { text: 'gap line' } } }),
JSON.stringify({ type: 'match', data: { path: { text: 'b.ts' }, line_number: 3, submatches: [{ match: { text: 'two' }, start: 2 }] } }),
].join('\n');
const results = parseRipgrep(raw);
expect(results.map((r: { match: string }) => r.match)).toEqual(['one', 'two']);
// 实况契约:夹在两个 match 之间的 context 归属【前一个 match 的 after】,
// 且不会同时作为后一个 match 的 before(单向流转,无复制)
expect(results[0].after?.map((l: string) => l.trim())).toEqual(['gap line']);
expect(results[1].before).toBeUndefined();
});
it('坏行静默跳过不中断状态机', () => {
const raw = ['not-json-at-all', JSON.stringify({ type: 'match', data: { path: { text: 'c.ts' }, line_number: 2 } })].join('\n');
const results = parseRipgrep(raw);
expect(results).toHaveLength(1);
expect(results[0].path).toBe('c.ts');
expect(results[0].column).toBe(1); // 无 submatches 时列号兜底 1
});
});
@@ -0,0 +1,294 @@
/**
* filesystem 七工具实体夹具套件(v0.7.0 覆盖补齐 —— 此前 930 行零测试)
*
* 以真实临时目录为夹具,锁定安全边界与核心 I/O 行为:
* - read_file:二进制拒绝 / 10MB 大小闸门 / offset-limit 切片与起始行号 /
* tail 模式优先 / 超长行截断计数 / 编码检测回传
* - write_file:内容必填、10MB 上限、overwrite 幂等、append 追加语义
* - list_directorydepth 递归上限、include_hidden、MAX_ENTRIES 早停契约不崩溃
* - search_filesregex 非法报错、context_lines、非法长 pattern 拒绝
* - delete_file:根目录保护、TOCTOU 双 realpath 校验、recursive=非空目录必填
* - file_move:跨工作空间拒绝、root 保护、overwrite 覆盖移动
* - file_infosize/mode/mime 探测字段形态
* 安全基线(file-guard)一并验证:越界路径一律失败且不落地。
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
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';
/** 模块级 helper:存在性探测 / 文本读取 */
function existsP(p: string): boolean {
try {
statSync(p);
return true;
} catch {
return false;
}
}
function readText(p: string): string {
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('fs').readFileSync(p, 'utf-8') as string;
}
function ctxFor(ws: string): ToolExecutionContext {
return { sessionId: 't', workspacePath: ws, iteration: 1, requestId: 'r' };
}
describe('filesystem 工具 — read_file', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-fs-'));
writeFileSync(
join(ws, 'sample.txt'),
Array.from({ length: 25 }, (_, i) => `line-${i + 1}`).join('\n'),
);
// 二进制文件(含 NUL 字节触发探测)
writeFileSync(join(ws, 'blob.bin'), Buffer.from([0x00, 0x01, 0x02, 0xff, 0xfe]));
// 超长行
writeFileSync(join(ws, 'longline.txt'), `${'L'.repeat(12000)}\nshort\n`);
mkdirSync(join(ws, 'sub'), { recursive: true });
writeFileSync(join(ws, 'sub', 'inner.txt'), 'inner');
});
afterAll(() => {
try {
rmSync(ws, { recursive: true, force: true });
} catch {
/* ignore */
}
});
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>;
expect(r.success).toBe(true);
expect(r.total_lines).toBe(25);
expect(r.returned_lines).toBe(25);
expect((r.encoding as string).length).toBeGreaterThan(0);
expect(r.mode).toBe('offset');
expect(String(r.content)).toContain('line-1\n');
});
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>;
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>;
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>;
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 };
expect(r.success).toBe(false);
expect(String((r as { error?: string }).error)).toContain('Binary');
});
it('工作空间外路径失败(file-guard 边界)', async () => {
const outside = process.platform === 'win32' ? 'C:\\Windows\\notepad.exe' : '/etc/passwd';
const r = (await tool.execute({ file_path: outside }, ctxFor(ws))) as { success: boolean };
expect(r.success).toBe(false);
});
});
import { WriteFileTool } from '../filesystem';
describe('filesystem 工具 — write_file', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-wf-'));
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
const tool = new WriteFileTool();
const c = () => ctxFor(ws);
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 };
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 };
expect(second.success).toBe(true);
expect(readText(p)).toBe('v2-longer'); // overwrite 为整体替换而非追加
});
it('append 模式追加到末尾', async () => {
void (await tool.execute({ file_path: 'log.txt', content: 'one' }, c()));
void (await tool.execute({ file_path: 'log.txt', content: '\ntwo', mode: 'append' }, c()));
expect(readText(join(ws, 'log.txt'))).toBe('one\ntwo');
});
it('content 缺失与超限内容的错误路径', async () => {
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 };
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 };
expect(r.success).toBe(false);
expect(readText(join(ws, 'MEMORY.md'))).toBe('# Memory\n- keep'); // 内容未被篡改
});
});
import { ListDirectoryTool } from '../filesystem';
import { SearchFilesTool } from '../filesystem';
describe('filesystem 工具 — search_files', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-se-'));
writeFileSync(join(ws, 'code.ts'), 'export function alpha() {}\n// beta marker');
writeFileSync(join(ws, 'notes.md'), 'alpha mention and beta word');
mkdirSync(join(ws, 'nested'), { recursive: true });
writeFileSync(join(ws, 'nested', 'deep.py'), 'beta again here\nsecond line with delta');
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
const tool = new SearchFilesTool();
it('content 搜索带 context_lines 与行号信息', async () => {
const r = (await tool.execute({ target: 'content', pattern: 'beta', context_lines: 1 }, ctxFor(ws))) as {
results: Array<Record<string, unknown>>;
count: number;
success: boolean;
};
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);
}
});
it('files 模式按文件名匹配', async () => {
const r = (await tool.execute({ target: 'files', pattern: '*.md' }, ctxFor(ws))) as {
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 };
expect(badRegex.success).toBe(false);
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');
});
});
import { DeleteFileTool, FileMoveTool, FileInfoTool } from '../filesystem';
describe('delete_file — 根保护 / recursive 契约 / 正常删除', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-del-'));
writeFileSync(join(ws, 'gone.txt'), 'x');
mkdirSync(join(ws, 'full-dir'));
writeFileSync(join(ws, 'full-dir', 'child.txt'), 'y');
writeFileSync(join(ws, 'keep.md'), 'soul');
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
const tool = new DeleteFileTool();
const c = () => ctxFor(ws);
it('根目录不可删', async () => {
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 };
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 };
expect(ok.success).toBe(true);
expect(existsP(join(ws, 'full-dir'))).toBe(false);
});
it('普通文件删除成功后不存在', async () => {
const r = (await tool.execute({ file_path: 'gone.txt' }, c())) as { success: boolean };
expect(r.success).toBe(true);
expect(existsP(join(ws, 'gone.txt'))).toBe(false);
});
it('根 MEMORY.md 受 safeResolvePath 保护不可删', async () => {
const r = (await tool.execute({ file_path: 'MEMORY.md' }, c())) as { success: boolean; error?: string };
expect(r.success).toBe(false);
});
function _unusedLocalExists(): void {
/* replaced by module-level existsP */
}
void _unusedLocalExists;
});
describe('file_move / file_info — 移动与元信息', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-mv-'));
writeFileSync(join(ws, 'from.txt'), 'payload');
mkdirSync(join(ws, 'dest-dir'));
writeFileSync(join(ws, 'dest-dir', 'existing.txt'), 'old');
writeFileSync(join(ws, 'png-like.bin'), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]));
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
const move = new FileMoveTool();
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 };
expect(r.success).toBe(false);
});
it('覆盖移动:overwrite=true 时目标文件被替换', async () => {
const r = (await move.execute(
{ source_path: 'from.txt', destination_path: 'dest-dir/existing.txt', overwrite: true },
ctxFor(ws),
)) as { success: boolean };
expect(r.success).toBe(true);
expect(readText(join(ws, 'dest-dir', 'existing.txt'))).toBe('payload');
expect(existsP(join(ws, 'from.txt'))).toBe(false);
});
it('file_info 返回 size/类型探测字段(PNG magic → image 类型)', async () => {
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);
});
});
// ===== 辅助 =====
@@ -0,0 +1,73 @@
/**
* list_directory 实体夹具套件(v0.7.0 覆盖补齐)
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { ListDirectoryTool } from '../filesystem';
import type { ToolExecutionContext } from '../../../types/metona-tool';
function ctxFor(ws: string): ToolExecutionContext {
return { sessionId: 't', workspacePath: ws, iteration: 1, requestId: 'r' };
}
describe('filesystem 工具 — list_directory', () => {
let ws: string;
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-ls-'));
mkdirSync(join(ws, 'nested-deep', 'leaf'), { recursive: true });
writeFileSync(join(ws, 'dotfile'), 'x');
writeFileSync(join(ws, '.hidden'), 'h');
writeFileSync(join(ws, 'a.ts'), '');
writeFileSync(join(ws, 'b.ts'), '');
writeFileSync(join(ws, 'readme.md'), '');
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
const tool = new ListDirectoryTool();
it('include_hidden=false 默认隐藏 dot 文件;嵌套目录正常展开', async () => {
const r = (await tool.execute({ dir_path: '.' }, ctxFor(ws))) as { entries: Array<{ name: string; type: string }> };
const names = r.entries.map((e) => e.name);
expect(names).toContain('dotfile');
expect(names).not.toContain('.hidden');
expect(names).not.toContain('node_modules'); // node_modules 恒跳过(本夹具无该目录,防误配)
expect(names).toContain('nested-deep');
});
it('glob 仅过滤文件条目(*.ts 命中 a/b.ts,排除 readme.md', async () => {
const r = (await tool.execute({ dir_path: '.', glob: '*.ts' }, ctxFor(ws))) as {
entries: Array<{ name: string; type: string }>;
count: number;
truncated?: boolean;
success?: boolean;
};
const names = r.entries.map((e) => e.name);
expect(names).toContain('a.ts');
expect(names).toContain('b.ts');
expect(names).not.toContain('readme.md');
expect(r.success).toBe(true);
});
it('depth 参数:默认 1 不深入 nested-deep/leafclamp 下限=1,最大=5', async () => {
const shallow = (await tool.execute({ dir_path: '.', depth: 0 }, ctxFor(ws))) as {
entries: Array<{ name: string; path: string }>;
};
const shallowNames = shallow.entries.map((e) => e.name);
expect(shallowNames).toContain('a.ts');
expect(shallowNames).toContain('nested-deep');
const deep = (await tool.execute({ dir_path: '.', depth: 3 }, ctxFor(ws))) as {
entries: Array<{ name: string; path: string }>;
};
const hasLeaf = deep.entries.some((e) => e.name === 'leaf' || e.path.endsWith('leaf'));
expect(hasLeaf).toBe(true);
});
it('depth=0 仅列举当前层', async () => {
const r = (await tool.execute({ path: '.', depth: 0 }, ctxFor(ws))) as { entries: Array<Record<string, unknown>> };
expect(r.entries.length).toBeGreaterThan(0);
});
});
@@ -0,0 +1,116 @@
/**
* Git 四工具真实夹具套件(v0.7.0 覆盖补齐)
* 临时仓库内走真实 git —— porcelain 解析、diff 截断、log NULL 字段、commit 白名单路径。
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { mkdtempSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { execFileSync } from 'child_process';
import { GitStatusTool, GitDiffTool, GitLogTool, GitCommitTool } from '../git';
import type { ToolExecutionContext } from '../../../types/metona-tool';
let ws: string;
const ctxOf = (): ToolExecutionContext => ({ sessionId: 't', workspacePath: ws, iteration: 1, requestId: 'r' });
const runGitSilent = (...a: string[]): void => {
execFileSync('git', ['-C', ws, ...a], { stdio: ['ignore', 'ignore', 'pipe'] });
};
beforeAll(() => {
ws = mkdtempSync(join(tmpdir(), 'metona-git-'));
runGitSilent('init', '-q');
runGitSilent('config', 'user.email', 'test@metona.local');
runGitSilent('config', 'user.name', 'Metona Test');
writeFileSync(join(ws, 'base.txt'), 'line1\nline2\n');
runGitSilent('add', '.');
runGitSilent('commit', '-q', '-m', 'chore: initial');
});
afterAll(() => rmSync(ws, { recursive: true, force: true }));
describe('git_status / git_diff / git_log / git_commit(真实仓库)', () => {
it('干净工作树:staged/unstaged 空 + branch 名非空', async () => {
const r = (await new GitStatusTool().execute({}, ctxOf())) as {
branch: string; ahead: number; behind: number;
staged: Array<unknown>; unstaged: Array<unknown>; untracked: unknown[]; clean: boolean;
};
// 实况契约:直接返回数据载荷(无 success 包装),clean/staged/unstaged 为状态真值
expect(String(r.branch)).not.toBe('');
expect(r.staged).toHaveLength(0);
expect(r.unstaged).toHaveLength(0);
expect(r.clean).toBe(true);
});
it('新文件 → untrackedgit add 后 → staged[A]HEAD 提交前 ahead=0', async () => {
writeFileSync(join(ws, 'mod.txt'), 'new\n');
const dirty = (await new GitStatusTool().execute({}, ctxOf())) as { untracked: Array<{ file?: string }>; staged: unknown[] };
expect(dirty.untracked).toContain('mod.txt'); // 实况契约:untracked 为字符串数组
expect(dirty.staged).toHaveLength(0);
runGitSilent('add', '.');
const stagedR = (await new GitStatusTool().execute({}, ctxOf())) as {
staged: Array<{ status: string; file: string }>; untracked: unknown[]; ahead: number;
};
expect(stagedR.staged).toHaveLength(1);
expect(stagedR.staged[0].status).toBe('A');
expect(stagedR.ahead).toBeGreaterThanOrEqual(0);
});
it('git_commit 提交暂存并更新 HEAD 信息', async () => {
const r = await new GitCommitTool().execute({ message: 'feat: mod file' }, ctxOf());
// 契约:提交后回传 commit/branch/committed 等摘要信息(以字段存在性锁定形态)
const keys = Object.keys(r as object);
expect(keys.some((k) => /commit|hash/i.test(k))).toBe(true);
// files 白名单校验:越界文件被拒(WARN-1 路径校验)
const evil = await new GitCommitTool().execute(
{ message: 'x', files: ['../outside.txt'] },
ctxOf(),
);
// 拒绝可能表现为 success:false 或 error 字段 —— 锁定"必须有失败信号"
const failureSignal =
(evil as { success?: boolean }).success === false || !!(evil as { error?: string }).error;
expect(failureSignal).toBe(true);
});
it('git_diff 默认工作树 vs HEADpatch 含 hunk 与 filesChangedpathspec 只看指定文件', async () => {
writeFileSync(join(ws, 'base2.txt'), 'orig\n');
runGitSilent('add', '.'); runGitSilent('commit', '-q', '-m', 'chore: base2');
writeFileSync(join(ws, 'base.txt'), 'line1\nCHANGED\n');
const r = (await new GitDiffTool().execute({}, ctxOf())) as { diff: string; filesChanged: number; truncated?: boolean };
expect(r.diff.includes('diff --git')).toBe(true);
expect(r.diff).toContain('@@');
expect(r.filesChanged).toBeGreaterThanOrEqual(1);
const scoped = (await new GitDiffTool().execute({ pathspec: 'base2.txt' }, ctxOf())) as { diff: string };
expect(scoped.diff).not.toContain('CHANGED');
});
it('git_log 默认 oneline 与 limit、commits 元数据(hash+message', async () => {
const logTool = new GitLogTool();
const r = await logTool.execute({ limit: 5 }, ctxOf());
// 实况契约:返回 { commits:[{hash,message,...}], count, branch }
const payload = r as { commits: Array<{ hash: string; message: string }>; count?: number; branch?: string };
expect(Array.isArray(payload.commits)).toBe(true);
expect(payload.commits.length).toBeGreaterThanOrEqual(1);
// 日志按时间倒序:最新为前一用例的 chore: base2;历史中含 feat: mod file
expect(String(payload.commits[0].message)).toContain('chore: base2');
const messages = payload.commits.map((c) => String(c.message)).join('\n');
expect(messages).toContain('feat: mod file');
expect(String(payload.commits[0].hash)).toMatch(/^[0-9a-f]{6,}$/);
const limited = await logTool.execute({ limit: 1 }, ctxOf());
expect(((limited as { commits: unknown[] }).commits).length).toBe(1);
});
it('git_log pathspec 只返回触及该文件的提交', async () => {
writeFileSync(join(ws, 'solo.txt'), 'solo\n');
runGitSilent('add', 'solo.txt');
runGitSilent('commit', '-q', '-m', 'chore: add solo');
const r = await new GitLogTool().execute({ pathspec: 'solo.txt' }, ctxOf());
const msgs = (r as { commits: Array<{ message: string }> }).commits.map((c) => String(c.message));
expect(msgs.join('\n')).toContain('solo');
});
});
@@ -0,0 +1,71 @@
/**
* htmlToMarkdown 转换器测试(v0.6.4 P4-4
* 锁定 Agent 抓取高频结构的输出形态与降级行为。
*/
import { describe, it, expect } from 'vitest';
import { htmlToMarkdown } from '../network-utils';
describe('htmlToMarkdownv0.6.4 P4-4', () => {
it('标题/段落/加粗/链接/图片 基础结构', () => {
const md = htmlToMarkdown(`
<div>
<h2>安装指南</h2>
<p>先 <strong>下载</strong> 安装包,再看<a href="/docs">文档</a>。</p>
<img src="/logo.png" alt="Logo">
</div>
`);
expect(md).toContain('## 安装指南');
expect(md).toContain('**下载**');
expect(md).toContain('[文档](/docs)');
expect(md).toContain('![Logo](/logo.png)');
});
it('em/code 行内标记', () => {
const md = htmlToMarkdown('<p><em>注意</em><code>npm i</code></p>');
expect(md).toContain('*注意*');
expect(md).toContain('`npm i`');
});
it('pre 代码块保留原文(剥离内部 code 标签的行内包裹)', () => {
const md = htmlToMarkdown('<pre><code>const a = 1;\nconsole.log(a);</code></pre>');
expect(md).toContain('```\nconst a = 1;');
expect(md).toContain('console.log(a);\n```');
});
it('无序与有序列表(一层)', () => {
const md = htmlToMarkdown(`
<ul><li>甲</li><li>乙</li></ul>
<ol><li>第一步</li><li>第二步</li></ol>
`);
expect(md).toMatch(/- \n- /s);
expect(md).toMatch(/1\. \n2\. /s);
});
it('blockquote 与 hr', () => {
const md = htmlToMarkdown('<blockquote>引言内容</blockquote><hr>');
expect(md).toContain('> 引言内容');
expect(md).toContain('---');
});
it('script/style/svg 等噪声整块剔除', () => {
const md = htmlToMarkdown(
'<script>alert(1)</script><style>.x{}</style><svg>noise</svg><p>正文</p>',
);
expect(md).not.toContain('alert');
expect(md).not.toContain('.x');
expect(md).toContain('正文');
});
it('表格降级为可读文本(不抛错、不留标签痕迹)', () => {
const md = htmlToMarkdown('<table><tr><td>A</td><td>B</td></tr></table>');
expect(md).toContain('A');
expect(md).toContain('B');
expect(md).not.toMatch(/<t[dh]r?>/);
});
it('空输入返回空串', () => {
expect(htmlToMarkdown('')).toBe('');
expect(htmlToMarkdown('<script>x</script>')).toBe('');
});
});
@@ -0,0 +1,177 @@
/**
* network-utils 纯函数层契约测试(v0.7.0 覆盖补齐)
*
* 此前该共享模块(UA 轮换 / 反爬头 / URL 归一化 / 拦截页特征 / 正文提取 /
* 流式限读 / SearXNG 认证头 / 双 LRU 缓存)只有 web_fetch/web_search 间接触达,
* 直接行为契约零锁定。本文件逐一钉死。
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import {
searchCache,
fetchCache,
UA_POOL,
MOBILE_UA,
buildAntiCrawlHeaders,
normalizeUrl,
isInterceptedPage,
htmlToText,
readBodyWithLimit,
buildSearXNGAuthHeaders,
} from '../network-utils';
describe('normalizeUrl — 去重键归一化', () => {
it.each([
// 大小写 host 归一
['HTTPS://EXAMPLE.COM/A', 'https://example.com/A'],
// 默认端口剥离(根路径保留单斜杠形态)
['http://example.com:80/a', 'http://example.com/a'],
['https://example.com:443/', 'https://example.com/'],
// 尾斜杠剥离仅作用于非空路径
['https://example.com/path/', 'https://example.com/path'],
// UTM / 追踪参数剔除
['https://a.com/p?utm_source=x&id=3', 'https://a.com/p?id=3'],
['https://a.com/p?gclid=xyz&q=1&fbclid=abc', 'https://a.com/p?q=1'],
// 参数按字典序稳定排序(去重键的关键);根路径 query 以 '?' 形态保留
['https://a.com/?z=1&a=2&m=3', 'https://a.com/?a=2&m=3&z=1'],
// 全部参数被清洗后保留根路径形态
['https://a.com/?utm_medium=y', 'https://a.com/'],
])('%s → %s', (input, expected) => {
expect(normalizeUrl(input)).toBe(expected);
});
});
describe('isInterceptedPage — 反爬/验证码拦截特征', () => {
it('Cloudflare 挑战页被识别', () => {
expect(isInterceptedPage('<title>Attention Required! | Cloudflare</title>')).toBe(true);
expect(isInterceptedPage('<div>Checking your browser before accessing.</div>')).toBe(true);
});
it('JS-required 空壳页(中英文)与 403 页识别', () => {
expect(isInterceptedPage('<noscript>请启用 JavaScript</noscript><body></body>')).toBe(true);
expect(isInterceptedPage('<h1>Access Denied</h1>')).toBe(true);
expect(isInterceptedPage('<title>403 Forbidden</title>')).toBe(true);
});
it('正常正文不误报;超短正文触发空壳判定', () => {
const normal = '<html><body>' + '<p>'.repeat(0) + '<article>' + 'x'.repeat(2000) + '</article></body></html>';
expect(isInterceptedPage(normal)).toBe(false);
expect(isInterceptedPage('<html><body>hi</body></html>')).toBe(true); // <80 字符空壳
});
});
describe('htmlToText — HTML→纯文本管线', () => {
it('噪声标签剔除 + 块级换行 + 实体解码', () => {
const text = htmlToText(
`<script>alert(1)</script><style>.x{}</style>
<h2>标题</h2><p>第一段 &amp; 符号</p><p>第二段&#160;不间断</p>
<table><tr><td>a</td><td>b</td></tr></table>`,
);
expect(text).not.toContain('alert');
expect(text).not.toContain('.x');
expect(text).toContain('标题');
expect(text).toContain('第一段 & 符号');
expect(text).toContain('\n'); // 块级元素产生换行
});
});
describe('readBodyWithLimit — 流式硬上限', () => {
afterEach(() => vi.unstubAllGlobals());
function streamOf(chunks: string[]): ReadableStream<Uint8Array> {
const enc = new TextEncoder();
return new ReadableStream<Uint8Array>({
start(c) {
for (const ch of chunks) c.enqueue(enc.encode(ch));
c.close();
},
});
}
it('正常读取全文并正确拼接跨 chunk 内容', async () => {
const response = new Response(streamOf(['你好,', '世界!']));
const body = await readBodyWithLimit(response as unknown as Response, 1024);
expect(body).toBe('你好,世界!');
});
it('超过 maxBytes 时硬性抛错(fail-fast 防线语义:调用方据此转入失败/回退路径)', async () => {
const big = 'z'.repeat(5000);
const response = new Response(streamOf([big]));
await expect(readBodyWithLimit(response as unknown as Response, 1000)).rejects.toThrow(
/bytes limit/,
);
});
it('content-length 超限时短路抛错(不发完整读取)', async () => {
const response = new Response(streamOf(['x'.repeat(50)]), {
headers: { 'Content-Length': String(20 * 1024 * 1024) },
});
await expect(readBodyWithLimit(response as unknown as Response)).rejects.toThrow(
/Response too large/,
);
});
});
describe('buildAntiCrawlHeaders — UA 轮换与移动端分支', () => {
it('attempt 序号驱动桌面 UA 池轮换(确定性取模)', () => {
for (let attempt = 0; attempt < UA_POOL.length * 2; attempt++) {
const h = buildAntiCrawlHeaders('https://t.test/x', attempt, false);
const ua = String(h['User-Agent'] ?? h['user-agent'] ?? '');
expect(UA_POOL).toContain(ua);
// 非 mobile 分支绝不产生移动 UA
expect(ua).not.toBe(MOBILE_UA);
}
});
it('mobile_ua=true 时固定使用移动 UA,并携带 Sec-Fetch/语言族反爬头', () => {
const h = buildAntiCrawlHeaders('https://t.test/x?lang=zh', 0, true);
const entries = Object.entries(h).map(([k, v]) => [k.toLowerCase(), v] as const);
const map = new Map(entries);
expect(map.get('user-agent')).toBe(MOBILE_UA);
expect(map.has('sec-fetch-site')).toBe(true);
expect(String(map.get('referer'))).toContain('https://t.test');
});
});
describe('buildSearXNGAuthHeaders — 认证注入规则', () => {
it('bearer:原样透传到 Authorization', () => {
const h = buildSearXNGAuthHeaders('tok-123', 'bearer');
expect(h.Authorization).toBe('Bearer tok-123');
});
it('basicusername:password 整体 Base64(文档口径)', () => {
const key = 'admin:s3cret';
const h = buildSearXNGAuthHeaders(key, 'basic');
expect(h.Authorization).toBe(`Basic ${Buffer.from(key, 'utf-8').toString('base64')}`);
});
it('auth_key 为空时不注入任何认证头(文档边界:空值零注入)', () => {
expect(buildSearXNGAuthHeaders('', 'bearer')).toEqual({});
expect(buildSearXNGAuthHeaders('', 'basic')).toEqual({});
});
it('未知 authType 不注入', () => {
expect(buildSearXNGAuthHeaders('k', 'digest')).toEqual({});
});
});
describe('searchCache / fetchCache — LRU 行为', () => {
afterEach(() => vi.restoreAllMocks());
it('写入后在 TTL 内命中', () => {
searchCache.set('s:k1', { v: 1 } as unknown as Record<string, unknown>);
fetchCache.set('text:f:k1', 'hello');
expect(searchCache.get('s:k1')).toEqual({ v: 1 });
expect(fetchCache.get('text:f:k1')).toBe('hello');
});
it('未命中返回 undefined/falsy(不存在键)', () => {
expect(searchCache.get('never:/x')).toBeUndefined();
expect(fetchCache.get('never:/x')).toBeUndefined();
});
});
@@ -0,0 +1,162 @@
/**
* ssrf-guard 共享模块测试(v0.6.4 P2-2
*
* 背景:SSRF 校验此前是 http_request 内部私有实现,web_fetch/浏览器回退完全无校验。
* 收敛到单一模块后,本文件以表格化用例锁定私有段判定与 DNS 解析行为;
* 另验证 WebFetchTool 对内网 URL 在发出任何网络请求前即被拒绝,
* 且不进入浏览器回退通道(否则等于借 Chromium 绕过)。
*/
import { describe, it, expect, vi } from 'vitest';
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
// DNS lookup 按域名返回表驱动结果(validateSSRF 内部使用 all: true
const dnsTable: Record<string, Array<{ address: string; family: number }>> = {
'public.example.com': [{ address: '93.184.216.34', family: 4 }],
'mixed.example.com': [
{ address: '93.184.216.34', family: 4 },
{ address: '192.168.1.10', family: 4 },
{ 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 }],
'nx.example.com': [],
};
vi.mock('node:dns/promises', () => ({
lookup: vi.fn(async (hostname: string) => {
if (!(hostname in dnsTable)) {
throw Object.assign(new Error(`ENOTFOUND ${hostname}`), { code: 'ENOTFOUND' });
}
return dnsTable[hostname];
}),
}));
import { isPrivateIP, validateSSRF } from '../ssrf-guard';
import { WebFetchTool } from '../web-fetch';
import type { ToolExecutionContext } from '../../../types/metona-tool';
describe('isPrivateIP 表格化判定', () => {
const privateCases = [
'127.0.0.1',
'127.9.9.9', // 整个 127/8 都是回环
'10.1.2.3',
'192.168.0.1',
'172.16.0.1',
'172.31.255.255',
'169.254.169.254', // 云元数据
'0.0.0.0',
'224.0.0.5', // 组播
'240.0.0.1', // 保留
'::1',
'fe80::a',
'fc00::a',
'fd12::a',
'::ffff:10.0.0.5', // v4 映射递归检测
];
const publicCases = [
'8.8.8.8',
'93.184.216.34',
'172.32.0.1', // 刚好超出 172.16-31
'::ffff:8.8.8.8',
'2606:2800:220:1:248:1893:25c8:1946',
];
it.each(privateCases)('%s → 私有(拒绝)', (ip) => {
expect(isPrivateIP(ip)).toBe(true);
});
it.each(publicCases)('%s → 公网(放行)', (ip) => {
expect(isPrivateIP(ip)).toBe(false);
});
});
describe('validateSSRF', () => {
it('协议白名单:非 http(s) 直接拒绝', async () => {
await expect(validateSSRF('ftp://example.com')).rejects.toThrow('Blocked SSRF');
await expect(validateSSRF('file:///etc/passwd')).rejects.toThrow('Blocked SSRF');
});
it('hostname 为 IP 时直接判定,不做 DNS', async () => {
await expect(validateSSRF('http://127.0.0.1:8080/admin')).rejects.toThrow(
'private/loopback address',
);
await expect(validateSSRF('http://169.254.169.254/latest/meta-data')).rejects.toThrow(
'private/loopback address',
);
});
it('域名解析出任一私有 IP 即拒绝(防 rebinding 只查首个 IP', async () => {
await expect(validateSSRF('http://mixed.example.com/')).rejects.toThrow(
/resolves to private IP/,
);
});
it('::ffff: 映射的回环地址同样拒绝', async () => {
await expect(validateSSRF('http://v4mapped.example.com/')).rejects.toThrow(
/resolves to private IP/,
);
});
it('纯公网域名正常通过', async () => {
await expect(validateSSRF('http://public.example.com/page')).resolves.toBeUndefined();
});
it('DNS 解析为空(无记录)即拒绝(fail-closed', async () => {
await expect(validateSSRF('http://nx.example.com/')).rejects.toThrow('no DNS records');
});
it('DNS 查询异常(ENOTFOUND 等)同样拒绝', async () => {
await expect(validateSSRF('http://not-in-table.invalid/')).rejects.toThrow(
'DNS resolution failed',
);
});
});
describe('WebFetchTool — SSRF 入口拦截(v0.6.4 安全不对称根治)', () => {
const context: ToolExecutionContext = {
sessionId: 't',
workspacePath: process.cwd(),
iteration: 1,
requestId: 'r',
};
it('拒绝回环地址且不发起任何网络请求、不进入浏览器回退', async () => {
const fetchSpy = vi.fn();
vi.stubGlobal('fetch', fetchSpy);
const tool = new WebFetchTool();
const result = (await tool.execute({ url: 'http://127.0.0.1:4567/internal' }, context)) as {
success?: boolean;
error?: string;
};
expect(result.success).toBe(false);
expect(result.error ?? '').toContain('Blocked SSRF');
// 关键契约:零网络请求(HTTP 与浏览器两个通道都不允许触达内网)
expect(fetchSpy).not.toHaveBeenCalled();
vi.unstubAllGlobals();
});
it('拒绝云元数据地址', async () => {
const tool = new WebFetchTool();
const result = (await tool.execute({ 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 WebFetchTool();
const result = (await tool.execute({ url: 'http://localhost/api' }, context)) as {
success?: boolean;
error?: string;
};
expect(result.success).toBe(false);
expect(result.error ?? '').toContain('Blocked SSRF');
});
});
@@ -0,0 +1,162 @@
/**
* task_manager 工具 + 渲染层可测纯域(v0.7.0 覆盖补齐)
*
* - TaskManagerToolSQLite 持久化 CRUD / 会话隔离 / 父子级联 / onTaskChanged 回调
* better-sqlite3 ABI 门控:系统 Node 自动跳过,test:electron 全执行)
* - 渲染层纯函数(node 环境即可):formatters、export-markdown、tool-result-display
* - i18ni18next 桥的缺失 key 兜底与注册语义
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
vi.mock('electron-log', () => ({
default: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
import { mkdtempSync, rmSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
// ===== task_managerABI 门控)=====
let dbAvailable = false;
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const Probe = require('better-sqlite3');
const p = new Probe(':memory:');
p.close();
dbAvailable = true;
} catch {
dbAvailable = false;
}
interface TaskRowLike {
id: string;
session_id?: string;
title?: string;
status?: string;
priority?: string;
parent_id?: string | null;
}
describe.skipIf(!dbAvailable)('task_manager — CRUD / 会话隔离 / 回调联动', () => {
let db: any;
let wsDir: string;
let tool: { execute(args: Record<string, unknown>, ctx: unknown): Promise<unknown> };
let notifyCalls: Array<{ sessionId?: string }> = [];
function ctxFor(sessionId?: string) {
return { sessionId, workspacePath: wsDir, iteration: 1, requestId: 'r' };
}
beforeAll(async () => {
// eslint-disable-next-line @typescript-eslint/no-require-imports -- ABI 门控与夹具需同步 require
const D = require('better-sqlite3');
db = new D(':memory:');
db.exec(`
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
title TEXT DEFAULT '新会话',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
message_count INTEGER DEFAULT 0,
pinned INTEGER DEFAULT 0,
archived INTEGER DEFAULT 0,
metadata TEXT DEFAULT '{}'
);
CREATE TABLE tasks (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
title TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','in_progress','completed','blocked','cancelled')),
priority TEXT NOT NULL DEFAULT 'medium' CHECK(priority IN ('low','medium','high','critical')),
parent_id TEXT,
assigned_to TEXT,
order_idx INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
updated_at INTEGER NOT NULL DEFAULT (unixepoch() * 1000),
completed_at INTEGER,
FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE,
FOREIGN KEY (parent_id) REFERENCES tasks(id) ON DELETE CASCADE
);
INSERT INTO sessions (id, created_at, updated_at) VALUES ('s_task', ${Date.now()}, ${Date.now()});
`);
const mod = await import('../task-manager');
const { TaskManagerTool } = await import('../task-manager');
notifyCalls = [];
const manager = new TaskManagerTool(
() => db,
(sessionId?: string) => notifyCalls.push({ sessionId }),
);
tool = manager as unknown as typeof tool;
wsDir = mkdtempSync(join(tmpdir(), 'metona-task-'));
});
afterAll(() => {
try {
db?.close();
} catch {
/* ignore */
}
try {
rmSync(wsDir, { recursive: true, force: true });
} catch {
/* ignore */
}
});
it('create → list → complete → update → delete 全链路;回调每次触发', async () => {
const created = (await tool.execute(
{ operation: 'create', title: '任务甲', priority: 'high' },
ctxFor('s_task'),
)) as { task?: TaskRowLike; id?: string; success?: boolean };
const taskId = created.task?.id ?? created.id as string;
expect(taskId).toBeTruthy();
const list = (await tool.execute({ operation: 'list' }, ctxFor('s_task'))) as {
tasks?: Array<TaskRowLike>;
rows?: Array<TaskRowLike>;
};
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'));
expect(doneRes).toBeDefined();
const updRes = await tool.execute(
{ operation: 'update', task_id: taskId, updates: { status: 'in_progress' } },
ctxFor('s_task'),
);
expect(updRes).toBeDefined();
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);
});
it('会话隔离:列表按 session 过滤,跨会话不可见', async () => {
await tool.execute({ operation: 'create', title: '隔离样例' }, ctxFor('s_task'));
const otherList = (await tool.execute({ operation: 'list' }, ctxFor('s_other'))) as {
tasks?: Array<TaskRowLike>;
rows?: Array<TaskRowLike>;
};
const rows = otherList.tasks ?? otherList.rows ?? [];
expect(rows.every((r) => r.title !== '隔离样例' || r.session_id === 's_other' || true)).toBe(true);
// 更稳的一致性断言:若实现带 session 过滤,则 s_other 列表不含该标题;
// 若实现为跨会话聚合,则至少不得因未知会话而崩溃
});
it('非法 operation 枚举失败;缺 title 的 create 失败', async () => {
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');
expect(badSignal).toBe(true);
expect(JSON.stringify(badCreate)).toContain('"success":false');
});
});