本次升级基于完整代码审查,修复 Critical/High/Medium/Low 四级共 96 项问题, 并通过返工审计修复 10 项遗留问题,tsc 双端类型检查零错误。 Critical (10/10 完成): - C-4: command.ts 接入 shell-quote 进行 token-level 注入检测,替代原有正则匹配 可防御 r"m" -rf /、$'rm'、$(echo rm) 等字符串拼接绕过 High (11/11 完成): - 竞态保护、Promise.allSettled、AbortController 资源泄漏、IPC 参数校验等 Medium (55/55 完成): - 事务保护、敏感数据脱敏、枚举校验、MUI v9 Stack prop 迁移、 React 组件 cancelled 标志、类型收窄等 Low (20/20 完成): - 辅助方法提取(flushToolCallBuffer/scoreAndPushMemory/tryAddColumn 等) - nanoid 统一替代 Date.now()+Math.random() - confirm() 替换为 MUI Dialog、useMemo 缓存、魔法数字命名化等 返工审计修复 (10/10 完成): - L-11: LogsSettings 残留的原生 confirm()/alert() 全部替换为 MUI Dialog/Alert - M-53: MemoryViewer handleSearch 独立 ref,修复 searching 状态卡死 - M-42: 脱敏短值(length <= 4)泄露修复 - M-47: tasks:update 补全 title/description 类型校验 - L-9: ollama.adapter 非流式路径 nanoid 统一 - M-45: audit:query limit 策略与 memory:listAll 一致化 - SettingsModal handleConfirmRemove 补全 try/catch + loadServers cleanup - L-15: CommandPalette useMemo 补全 sessions 响应式依赖 - useAgentStream 事件类型补全 seq/timestamp 字段 新增依赖: shell-quote + @types/shell-quote 版本号: 0.3.0 -> 0.3.1
276 lines
9.1 KiB
TypeScript
276 lines
9.1 KiB
TypeScript
/**
|
||
* Confirmation Hook — 工具执行前用户确认钩子(v0.2.0 新增)
|
||
*
|
||
* 对 requiresPermission=true 或 riskLevel >= HIGH 的工具,
|
||
* 通过 IPC 请求用户确认后再执行。
|
||
*
|
||
* 支持两种自动执行机制:
|
||
* 1. 持久化自动执行(跨会话):存储在 ConfigService `tools.{toolName}.autoExecute`
|
||
* 2. 会话内记忆:同一会话内不再重复询问(rememberDecisions)
|
||
*
|
||
* @see docs/生产级通用 AI Agent 智能体桌面应用:完整设计与构建指南.html — 第五章
|
||
*/
|
||
|
||
import { BrowserWindow } from 'electron';
|
||
import type { MetonaToolCall, MetonaToolDef } from '../types';
|
||
import type { PreToolHook, HookResult } from './pre-tool';
|
||
import type { ConfigService } from '../../services/config.service';
|
||
|
||
export interface ConfirmationRequest {
|
||
toolCallId: string;
|
||
toolName: string;
|
||
args: Record<string, unknown>;
|
||
riskLevel: string;
|
||
reason: string;
|
||
}
|
||
|
||
export class ConfirmationHook implements PreToolHook {
|
||
/** 需要确认的风险等级 */
|
||
private static REQUIRES_CONFIRMATION = ['high', 'critical'];
|
||
|
||
/** L-12 修复: 确认超时范围魔法数字提取为命名常量(30 秒 ~ 600 秒) */
|
||
private static readonly MIN_CONFIRMATION_TIMEOUT_MS = 30_000;
|
||
private static readonly MAX_CONFIRMATION_TIMEOUT_MS = 600_000;
|
||
|
||
/** 工具定义缓存(由外部设置) */
|
||
private toolDefs = new Map<string, MetonaToolDef>();
|
||
|
||
/** 用户选择记忆(同一会话内不再重复询问) */
|
||
private rememberedDecisions = new Map<string, boolean>();
|
||
|
||
/** 持久化自动执行的工具集合(从 ConfigService 加载,跨会话生效) */
|
||
private autoExecuteTools = new Set<string>();
|
||
|
||
/** 等待确认的 Promise 解析器 */
|
||
private pendingConfirmations = new Map<string, { resolve: (v: boolean) => void; timer: NodeJS.Timeout; toolName: string; expiresAt: number }>();
|
||
|
||
/** 确认超时时间(可从配置读取,默认 120 秒) */
|
||
private confirmationTimeoutMs = 120_000;
|
||
|
||
constructor(
|
||
private mainWindow: BrowserWindow | null = null,
|
||
private configService: ConfigService | null = null,
|
||
) {
|
||
this.loadAutoExecuteList();
|
||
this.loadConfirmationTimeout();
|
||
}
|
||
|
||
/** 设置主窗口(用于发送 IPC 消息) */
|
||
setMainWindow(window: BrowserWindow): void {
|
||
this.mainWindow = window;
|
||
}
|
||
|
||
/**
|
||
* 从 ConfigService 加载已设置为自动执行的工具列表
|
||
* 配置键格式:tools.{toolName}.autoExecute = true
|
||
*/
|
||
private loadAutoExecuteList(): void {
|
||
if (!this.configService) return;
|
||
try {
|
||
const all = this.configService.getAll();
|
||
this.autoExecuteTools.clear();
|
||
for (const [key, value] of Object.entries(all)) {
|
||
// 匹配 tools.{toolName}.autoExecute 键
|
||
const match = /^tools\.(.+)\.autoExecute$/.exec(key);
|
||
if (match && value === true) {
|
||
this.autoExecuteTools.add(match[1]);
|
||
}
|
||
}
|
||
} catch {
|
||
// 配置加载失败,忽略(不阻塞启动)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 设置/取消工具的持久化自动执行
|
||
* @param toolName 工具名
|
||
* @param enabled true=自动执行(不再询问),false=每次询问
|
||
*/
|
||
setAutoExecute(toolName: string, enabled: boolean): void {
|
||
const configKey = `tools.${toolName}.autoExecute`;
|
||
if (this.configService) {
|
||
this.configService.set(configKey, enabled);
|
||
}
|
||
if (enabled) {
|
||
this.autoExecuteTools.add(toolName);
|
||
// 自动执行时同步清除会话内"拒绝"记忆(避免冲突)
|
||
this.rememberedDecisions.delete(toolName);
|
||
} else {
|
||
this.autoExecuteTools.delete(toolName);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取当前自动执行的工具列表
|
||
*/
|
||
getAutoExecuteList(): string[] {
|
||
return Array.from(this.autoExecuteTools);
|
||
}
|
||
|
||
/**
|
||
* 从 ConfigService 加载确认超时时间
|
||
* 配置键:agent.confirmationTimeoutMs(单位毫秒,最小 30 秒,最大 600 秒)
|
||
*/
|
||
private loadConfirmationTimeout(): void {
|
||
if (!this.configService) return;
|
||
try {
|
||
const timeout = this.configService.get<number>('agent.confirmationTimeoutMs');
|
||
if (timeout != null) {
|
||
// L-12 修复: 使用命名常量替代魔法数字
|
||
this.confirmationTimeoutMs = Math.min(
|
||
ConfirmationHook.MAX_CONFIRMATION_TIMEOUT_MS,
|
||
Math.max(ConfirmationHook.MIN_CONFIRMATION_TIMEOUT_MS, timeout),
|
||
);
|
||
}
|
||
} catch {
|
||
// 配置加载失败,使用默认值
|
||
}
|
||
}
|
||
|
||
/** 设置确认超时时间(运行时更新) */
|
||
setConfirmationTimeout(ms: number): void {
|
||
// L-12 修复: 使用命名常量替代魔法数字
|
||
this.confirmationTimeoutMs = Math.min(
|
||
ConfirmationHook.MAX_CONFIRMATION_TIMEOUT_MS,
|
||
Math.max(ConfirmationHook.MIN_CONFIRMATION_TIMEOUT_MS, ms),
|
||
);
|
||
}
|
||
|
||
/** 获取当前确认超时时间 */
|
||
getConfirmationTimeout(): number {
|
||
return this.confirmationTimeoutMs;
|
||
}
|
||
|
||
/** 注入工具定义列表(用于查询风险等级) */
|
||
setToolDefs(defs: MetonaToolDef[]): void {
|
||
this.toolDefs.clear();
|
||
for (const def of defs) {
|
||
this.toolDefs.set(def.name, def);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 处理用户确认响应(由 IPC handler 调用)
|
||
* @param remember 会话内记住决定
|
||
* @param autoExecute 永久自动执行(持久化)
|
||
*/
|
||
resolveConfirmation(toolCallId: string, approved: boolean, remember: boolean, autoExecute: boolean = false): void {
|
||
const pending = this.pendingConfirmations.get(toolCallId);
|
||
if (pending) {
|
||
clearTimeout(pending.timer);
|
||
pending.resolve(approved);
|
||
// 永久自动执行(仅当用户批准时才设置)
|
||
if (autoExecute && approved) {
|
||
this.setAutoExecute(pending.toolName, true);
|
||
}
|
||
// 会话内记忆
|
||
if (remember) {
|
||
this.rememberedDecisions.set(pending.toolName, approved);
|
||
}
|
||
this.pendingConfirmations.delete(toolCallId);
|
||
}
|
||
}
|
||
|
||
async beforeExecute(toolCall: MetonaToolCall, _sessionId: string): Promise<HookResult> {
|
||
const def = this.toolDefs.get(toolCall.name);
|
||
if (!def) {
|
||
// 未知工具,放行(由 ToolRegistry 处理未知工具错误)
|
||
return { blocked: false };
|
||
}
|
||
|
||
// 检查是否需要确认
|
||
const needsConfirmation = def.requiresPermission ||
|
||
ConfirmationHook.REQUIRES_CONFIRMATION.includes(def.riskLevel);
|
||
|
||
if (!needsConfirmation) {
|
||
return { blocked: false };
|
||
}
|
||
|
||
// 优先检查持久化自动执行(跨会话生效)
|
||
if (this.autoExecuteTools.has(toolCall.name)) {
|
||
return { blocked: false };
|
||
}
|
||
|
||
// 检查是否有记住的决策
|
||
const remembered = this.rememberedDecisions.get(toolCall.name);
|
||
if (remembered !== undefined) {
|
||
if (remembered) return { blocked: false };
|
||
return { blocked: true, reason: `User previously denied tool "${toolCall.name}"` };
|
||
}
|
||
|
||
// 如果没有主窗口,安全起见阻止执行
|
||
if (!this.mainWindow || this.mainWindow.isDestroyed()) {
|
||
return { blocked: true, reason: 'Cannot request confirmation: no main window available' };
|
||
}
|
||
|
||
// 发送确认请求到渲染进程
|
||
const request: ConfirmationRequest = {
|
||
toolCallId: toolCall.id,
|
||
toolName: toolCall.name,
|
||
args: toolCall.args,
|
||
riskLevel: def.riskLevel,
|
||
reason: def.requiresPermission
|
||
? `Tool "${toolCall.name}" requires permission (risk: ${def.riskLevel})`
|
||
: `Tool "${toolCall.name}" has high risk level: ${def.riskLevel}`,
|
||
};
|
||
|
||
// 等待用户响应(带超时)
|
||
const approved = await this.waitForConfirmation(request);
|
||
|
||
if (!approved) {
|
||
return { blocked: true, reason: `User denied execution of tool "${toolCall.name}"` };
|
||
}
|
||
|
||
return { blocked: false };
|
||
}
|
||
|
||
/**
|
||
* 等待用户确认(带超时)
|
||
* 发送 expiresAt 到前端,供倒计时 UI 使用;超时时发送 toast 通知
|
||
*/
|
||
private waitForConfirmation(request: ConfirmationRequest): Promise<boolean> {
|
||
return new Promise<boolean>((resolve) => {
|
||
const expiresAt = Date.now() + this.confirmationTimeoutMs;
|
||
|
||
// 设置超时
|
||
const timer = setTimeout(() => {
|
||
this.pendingConfirmations.delete(request.toolCallId);
|
||
// 超时发送 toast 通知用户
|
||
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
|
||
this.mainWindow.webContents.send('toast:show', {
|
||
type: 'warning',
|
||
message: `工具确认超时(${Math.round(this.confirmationTimeoutMs / 1000)}秒),"${request.toolName}" 未执行`,
|
||
});
|
||
}
|
||
resolve(false); // 超时视为拒绝
|
||
}, this.confirmationTimeoutMs);
|
||
|
||
this.pendingConfirmations.set(request.toolCallId, {
|
||
resolve,
|
||
timer,
|
||
toolName: request.toolName,
|
||
expiresAt,
|
||
});
|
||
|
||
// 发送确认请求到渲染进程(携带过期时间戳,供前端倒计时)
|
||
if (this.mainWindow && !this.mainWindow.isDestroyed()) {
|
||
this.mainWindow.webContents.send('tool:confirmationRequest', {
|
||
...request,
|
||
expiresAt,
|
||
});
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 清理所有等待中的确认(会话结束时调用)
|
||
*/
|
||
clearPending(): void {
|
||
for (const [, pending] of this.pendingConfirmations) {
|
||
clearTimeout(pending.timer);
|
||
pending.resolve(false);
|
||
}
|
||
this.pendingConfirmations.clear();
|
||
}
|
||
}
|