feat: v0.7.3 成本收口 · 状态一致 · 死账清理 — Prompt Cache 根治 + SSRF DNS Pinning + 87 用例扩充全量回归
P1 修复面收口: Prompt Cache 根治(日期/记忆/附件三类易变内容出 system 入用户消息 前置块 user-context.ts, system 跨 run 字节级稳定; Anthropic system 块数组化 + cache_control ephemeral 断言, DeepSeek 自动缓存前缀命中 — 多轮对话输入 token 成本降数量级); 编辑重发/重新生成幽灵 Trace 双侧根治(DB truncateMessagesAfter 同步过滤 metadata.traceSteps + 前端 trimTraceStepsByAnchor 镜像, 严格小于锚点 时间戳, 同毫秒等值判废); sessions:deleteMessage 死通道全链路删除(渲染层零调用 + message_count 漂移面); Ollama vision 能力门控全链路(MetonaModelInfo .supportsVision 贯穿 adapter/IPC/store/UI, model-capabilities.ts 三道判定纯函数, 未知保守放行); 记忆固化节流(consolidation-policy 纯函数: 总开关 + 内容门控 [回答>=200字符或存在成功工具调用] + 会话级 10 分钟频率窗口, 三 memory.* 配置键) P2 安全纵深: SSRF DNS Pinning 关闭 rebinding 窗口(ssrf-guard 重构 resolvePublicAddresses 单源; ssrf-dispatcher 以 undici Agent.connect.lookup 钉死校验 IP, TLS SNI 保持原域名, 一次性 dispatcher 用后即毁; 代理激活显式 退化为仅入口校验); web_fetch 重写手动逐跳重定向循环(每跳先校验后连接, 替代 redirect:follow 内核跟跳的中间跳裸奔, 上限 5 跳); http_request 换用 pinned fetch; web_search 可达性预检加固(私有 URL 零请求 + 不跟跳, 3xx 视为 可达); Agent 浏览器 CORS 通配收紧为 Origin 回显 + Vary: Origin; ConfirmationHook.forgetSession 会话终态清理(会话删除/abort 联动/SubAgent 终结三处接线, 根治 rememberedDecisions 泄漏) P3 架构还债: agent.enableReflection 死配置全链路接线(main→shared→引擎→ Orchestrator→设置开关, REFLECTING 状态真实可达); AgentLoopConfig.timeoutMs 死字段删除; MemoryManager.cleanupExpired 挂入健康检查周期(expires_at 回收 管道真实化); buildSafeEnv 收敛 utils/safe-env.ts 单源(run_command 与 MCP stdio 共用, 终结双实现漂移); Trace 生命周期治理(metadata 只保留最近 20 个 run — keepRecentRuns 纯函数; JSONL 录制启动自动清理保留 200 个 + 设置页 手动清理); SLO/健康快照可视化(app:healthSnapshot IPC + 设置页只读卡片 + 审计链一键校验) P4 能力演进: 会话标题 LLM 自动生成(TitleGenerator — 每会话幂等/并发重入复用 同一 Promise/自定义标题不覆盖/失败静默回退, Sidebar 经 config:changed 实时 刷新); MCP 自动重连(5s/15s/60s 退避最多 3 次, reconnecting 状态机, teardownConnection 内部拆除保留簿记 — 用户断开/开关关闭即时取消, 设置页 显示第 N/3 次); 死循环检测 ABAB 乒乓模式(最近4轮 A→B→A→B 交替判定, 补齐 docs 第五章"两状态反复切换"检测契约); i18n 第三阶段(ChatInput/LLMSettings/ OnboardingWizard/MemoryViewer 主链路文案出层, zh-CN + en-US 双字典补齐) 测试: 737 → 824 用例(+87, 新增 8 个测试文件 + 扩展 3 个)。新覆盖: user-context 分组/空值收缩/拼接契约、context-builder 字节级稳定性、Anthropic cache_control 四态、consolidation-policy 九路判定矩阵、ssrf-dispatcher(pinned lookup/重定向 解析/IP 校验)、forget-session 会话隔离、trace-lifecycle run 淘汰、 trace-trim 严格小于边界、safe-env 净化矩阵、mcp-reconnect 退避状态机 (fake timers)、title-generator 并发重入、SQLite 侧 truncate×TRACE 联动 (Electron ABI)。测试驱动修复: GIT_*/ 注释终止块注释、重连计数被自身重试 前置断开重置(拆 teardownConnection 保留簿记)、TitleGenerator 幂等占位与 并发去重的检查顺序竞态(去重先于幂等) 版本: 0.7.3; README 同步(配置表新增 agent.enableReflection/memory.*/mcp.autoReconnect) 回归: typecheck 双端 0 错误; ESLint 0/0; 系统 Node 771 通过 53 跳过 (better-sqlite3 ABI); Electron ABI 全量 824/824 零跳过
This commit is contained in:
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* SSRF DNS Pinning Dispatcher(v0.7.3 P2-1)
|
||||
*
|
||||
* 关闭 M7 审查确认的 DNS rebinding 窗口:此前 validateSSRF 在校验阶段解析一次
|
||||
* DNS,fetch 实际连接时 undici 再次解析 —— 两次解析之间攻击者可切换 DNS 记录
|
||||
* (TTL=0)把连接导向内网。原注释断言"Node fetch 下无法彻底关闭",该结论只对
|
||||
* 全局 fetch 成立;主进程已依赖 undici(network-proxy 的 setGlobalDispatcher),
|
||||
* undici 的 Agent 支持 connect.lookup 自定义 —— 校验通过的 IP 集合可精确 pin 到
|
||||
* 连接层,TLS SNI/证书校验仍基于原始域名(undici 将 servername 保持为 hostname)。
|
||||
*
|
||||
* 契约:
|
||||
* - resolvePublicAddresses(ssrf-guard)是校验与地址解析的唯一事实来源,
|
||||
* 本模块 pin 的就是它返回的那批 IP —— 校验与连接同源,无双解析窗口;
|
||||
* - 代理激活(network-proxy.isProxyActive())时 pinning 不可实现(DNS 在代理端
|
||||
* 解析)且 per-request dispatcher 会旁路用户代理 —— 退化为"仅入口校验",
|
||||
* 走全局 dispatcher(保持既有语义与代理兼容);
|
||||
* - fetchWithTimeoutPinned 合并外部 abort signal 与超时控制,语义对齐
|
||||
* BaseAdapter.fetchWithTimeout(超时 → ETIMEDOUT 可重试;外部中断原样抛出);
|
||||
* - 每次 pinned 请求构造一次性 Agent 并在 finally 中 close(连接池即用即毁,
|
||||
* 防止把"上一请求的 pin 集合"泄漏给后续请求)。
|
||||
*/
|
||||
|
||||
import { Agent, fetch as undiciFetch } from 'undici';
|
||||
import { isIP } from 'node:net';
|
||||
import { resolvePublicAddresses } from './ssrf-guard';
|
||||
import { fetchWithTimeout } from './network-utils';
|
||||
import { isProxyActive } from '../../../utils/network-proxy';
|
||||
import log from 'electron-log';
|
||||
|
||||
/** 标准 dns.lookup 回调签名(undici connect.lookup 消费) */
|
||||
export type LookupCallback = (
|
||||
err: NodeJS.ErrnoException | null,
|
||||
addresses?: Array<{ address: string; family: number }>,
|
||||
) => void;
|
||||
|
||||
/** undici connect.lookup 的函数签名形态 */
|
||||
export type PinnedLookup = (hostname: string, options: unknown, callback: LookupCallback) => void;
|
||||
|
||||
/**
|
||||
* 构造"钉死 IP 集合"的 lookup 函数:无论传入什么 hostname,都只返回校验阶段
|
||||
* 锁定的公网地址(过滤非法 family)。集合为空时返回 ENOTFOUND(防御性——
|
||||
* 调用方在集合为空时不应构造 dispatcher)。
|
||||
*/
|
||||
export function createPinnedLookup(allowedIps: string[]): PinnedLookup {
|
||||
return (_hostname, _options, callback) => {
|
||||
process.nextTick(() => {
|
||||
const addresses = allowedIps
|
||||
.map((ip) => ({ address: ip, family: isIP(ip) }))
|
||||
.filter((a): a is { address: string; family: number } => a.family === 4 || a.family === 6);
|
||||
if (addresses.length === 0) {
|
||||
const err: NodeJS.ErrnoException = new Error('pinned lookup: no allowed addresses');
|
||||
err.code = 'ENOTFOUND';
|
||||
callback(err, undefined);
|
||||
return;
|
||||
}
|
||||
callback(null, addresses);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 URL 并返回 pinning 用的公网 IP 集合。
|
||||
* 校验失败原样抛出(调用方按 SSRF 阻断处理)。
|
||||
*/
|
||||
export async function resolvePinnedIps(url: string): Promise<string[]> {
|
||||
return resolvePublicAddresses(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* 带 SSRF pinning 的 fetch(http_request / web_fetch Phase1 / 可达性预检共用)。
|
||||
*
|
||||
* 行为:
|
||||
* 1. 代理激活 → 退化为普通 fetchWithTimeout(仅入口校验语义,见模块注释);
|
||||
* 2. 否则 → 解析并校验公网 IP → 一次性 undici Agent(pinned lookup)发起请求;
|
||||
* 3. 超时/外部中断语义与 fetchWithTimeout 对齐;
|
||||
* 4. 返回 Response 与全局 fetch 兼容(status/ok/headers/text/url/body)。
|
||||
*
|
||||
* @param url 目标 URL(调用方已保证 http/https;本函数再做一次全量 SSRF 校验)
|
||||
* @param init RequestInit(redirect 等由调用方决定)
|
||||
* @param timeoutMs 请求超时
|
||||
* @param externalSignal 外部 abort 信号(引擎中断透传,可选)
|
||||
*/
|
||||
export async function ssrfPinnedFetch(
|
||||
url: string,
|
||||
init: RequestInit,
|
||||
timeoutMs: number,
|
||||
externalSignal?: AbortSignal,
|
||||
): Promise<Response> {
|
||||
const ips = await resolvePublicAddresses(url);
|
||||
|
||||
// 代理激活:DNS 在代理端解析,pinning 不可实现;走全局 dispatcher 保持代理语义
|
||||
if (isProxyActive()) {
|
||||
return fetchWithTimeout(url, init, timeoutMs);
|
||||
}
|
||||
|
||||
// 外部信号已中止 → 直接抛 AbortError(对齐 fetchWithTimeout 行为)
|
||||
if (externalSignal?.aborted) {
|
||||
const err = new Error('Aborted');
|
||||
err.name = 'AbortError';
|
||||
throw err;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
controller.abort();
|
||||
}, timeoutMs);
|
||||
|
||||
const onExternalAbort = () => controller.abort();
|
||||
if (externalSignal) {
|
||||
externalSignal.addEventListener('abort', onExternalAbort, { once: true });
|
||||
}
|
||||
|
||||
// 一次性 pinned Agent(connect 超时对齐 network-proxy 的 15s 连接上限)
|
||||
const dispatcher = new Agent({
|
||||
connect: { timeout: 15_000, lookup: createPinnedLookup(ips) as never },
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await undiciFetch(url, {
|
||||
...(init as Record<string, unknown>),
|
||||
signal: controller.signal,
|
||||
dispatcher,
|
||||
} as never);
|
||||
return response as unknown as Response;
|
||||
} catch (err) {
|
||||
const externalAborted = externalSignal?.aborted === true;
|
||||
if (timedOut && !externalAborted) {
|
||||
const timeoutError = new Error(
|
||||
`Request timed out after ${timeoutMs}ms (url=${String(url).slice(0, 120)})`,
|
||||
);
|
||||
(timeoutError as Error & { code: string }).code = 'ETIMEDOUT';
|
||||
throw timeoutError;
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (externalSignal) {
|
||||
externalSignal.removeEventListener('abort', onExternalAbort);
|
||||
}
|
||||
// 一次性 dispatcher 用后即毁(连接池不跨请求复用,防止 pin 集合泄漏)
|
||||
void dispatcher.close().catch((closeErr) => {
|
||||
log.debug(`[SSRFDispatcher] dispatcher close failed: ${(closeErr as Error).message}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const REDIRECT_STATUS = new Set([301, 302, 303, 307, 308]);
|
||||
|
||||
/**
|
||||
* 解析重定向目标(纯函数,表测锁定)。
|
||||
*
|
||||
* @returns 下一跳绝对 URL;非重定向状态/缺失/非法 Location 返回 null
|
||||
* (表示当前响应即终态或无法跟随,由调用方按既有语义处理)。
|
||||
* 相对 Location 以 currentUrl 为基解析(RFC 7231)。
|
||||
*/
|
||||
export function resolveRedirectTarget(
|
||||
response: { status: number; headers: { get(name: string): string | null } },
|
||||
currentUrl: string,
|
||||
): string | null {
|
||||
if (!REDIRECT_STATUS.has(response.status)) return null;
|
||||
const location = response.headers.get('location');
|
||||
if (!location) return null;
|
||||
try {
|
||||
return new URL(location, currentUrl).toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user