ai-helper-agent 2.5.1 → 2.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{agent-store-D0oEv0PW.js → agent-store-TSvufiWG.js} +1 -1
- package/dist/assets/background.js +71 -70
- package/dist/assets/{chat-export-MTTSSIwM.js → chat-export-BFXv3fdM.js} +1 -1
- package/dist/assets/content.js +43 -43
- package/dist/{dist/assets/i18n-Br_sF5pb.js → assets/i18n-DJ3tjLY-.js} +4 -4
- package/dist/{dist/assets/markdown-render-lSSxW953.js → assets/markdown-render-C9SKCrR4.js} +4 -4
- package/dist/assets/{model-profiles-BdQaV4EZ.js → model-profiles-CfvHSLkL.js} +1 -1
- package/dist/{dist/assets/options-JtYgxtsc.css → assets/options-DU7Wz1w_.css} +1 -1
- package/dist/assets/options.js +89 -89
- package/dist/assets/{page-snapshot-renderer-Cl0qk7U1.js → page-snapshot-renderer-Cdzmf6hl.js} +1 -1
- package/dist/assets/session-store-CRTEYLCo.js +81 -0
- package/dist/assets/side_panel.css +1 -1
- package/dist/assets/side_panel.js +219 -215
- package/dist/{dist/assets/utils-ZJjxSlg_.js → assets/utils-DukUruXz.js} +26 -26
- package/dist/assets/{version-C0CY79zF.js → version-s8LDcTZ-.js} +1 -1
- package/dist/assets/voice-shortcut-Dtt3nhkz.js +1 -0
- package/dist/assets/workspace-manager-CgkNrxoo.js +1 -0
- package/dist/manifest.json +1 -1
- package/dist/offscreen/offscreen.js +6 -6
- package/dist/options.html +34 -4
- package/dist/side_panel.html +22 -13
- package/package.json +1 -1
- package/src/asr/install.js +26 -0
- package/src/documents/routes.js +4 -3
- package/src/locales/en.json +10 -1
- package/src/locales/zh.json +10 -1
- package/src/native-lib-guard.js +194 -0
- package/src/rag/embedding/embed-worker.mjs +182 -0
- package/src/rag/embedding/local.js +42 -62
- package/src/rag/embedding/worker-client.js +476 -0
- package/src/rag/errors.js +60 -2
- package/src/rag/install.js +27 -0
- package/src/rag/manager.js +5 -2
- package/src/rag/routes.js +4 -2
- package/src/search.js +4 -4
- package/src/security.js +97 -33
- package/src/server.js +284 -40
- package/src/session-workdirs.js +241 -0
- package/src/skill/executor.js +25 -9
- package/src/skill/registry.js +3 -2
- package/dist/assets/i18n-Br_sF5pb.js +0 -49
- package/dist/assets/markdown-render-Dq5F_dqP.js +0 -63
- package/dist/assets/options-JtYgxtsc.css +0 -1
- package/dist/assets/session-store-KkrAlIc6.js +0 -81
- package/dist/assets/utils-ZJjxSlg_.js +0 -112
- package/dist/dist/_locales/en/messages.json +0 -11
- package/dist/dist/_locales/zh_CN/messages.json +0 -11
- package/dist/dist/assets/__vite-browser-external-CM3Eme-n.js +0 -1
- package/dist/dist/assets/agent-store-D0oEv0PW.js +0 -1
- package/dist/dist/assets/background.js +0 -451
- package/dist/dist/assets/chat-export-7wjGjcA8.js +0 -37
- package/dist/dist/assets/chunk-CMxvf4Kt.js +0 -1
- package/dist/dist/assets/content.js +0 -985
- package/dist/dist/assets/dist-BUuoW_84.js +0 -24
- package/dist/dist/assets/dist-DuuG_8Br.js +0 -133
- package/dist/dist/assets/jszip.min-DO6SOhXU.js +0 -2
- package/dist/dist/assets/lib-YwkWjNcC.js +0 -220
- package/dist/dist/assets/marked.min.js-D2rXgLAQ.js +0 -56
- package/dist/dist/assets/marked.min.js-loader-tKH5SQVQ.js +0 -13
- package/dist/dist/assets/model-profiles-BdQaV4EZ.js +0 -24
- package/dist/dist/assets/network-scope-CNRYXk74.js +0 -1
- package/dist/dist/assets/options.js +0 -859
- package/dist/dist/assets/page-snapshot-renderer-Cl0qk7U1.js +0 -3
- package/dist/dist/assets/pdf-DnVqBaAN.js +0 -6
- package/dist/dist/assets/session-store-KkrAlIc6.js +0 -81
- package/dist/dist/assets/side_panel.css +0 -1
- package/dist/dist/assets/side_panel.js +0 -2595
- package/dist/dist/assets/theme-BRAX5X2F.css +0 -1
- package/dist/dist/assets/theme-CLwYsx9o.js +0 -1
- package/dist/dist/assets/version-C7x4HYX1.js +0 -1
- package/dist/dist/assets/xlsx-DGkz7cnk.js +0 -105
- package/dist/dist/icons/README.md +0 -11
- package/dist/dist/icons/design-philosophy.md +0 -41
- package/dist/dist/icons/icon128.png +0 -0
- package/dist/dist/icons/icon128.svg +0 -68
- package/dist/dist/icons/icon16.png +0 -0
- package/dist/dist/icons/icon16.svg +0 -32
- package/dist/dist/icons/icon48.png +0 -0
- package/dist/dist/icons/icon48.svg +0 -56
- package/dist/dist/libs/github-markdown-light.min.css +0 -8
- package/dist/dist/libs/html2canvas.min.js +0 -20
- package/dist/dist/libs/jspdf.min.js +0 -398
- package/dist/dist/libs/marked.min.js +0 -69
- package/dist/dist/libs/mermaid.min.js +0 -2024
- package/dist/dist/libs/pdf.worker.min.js +0 -22
- package/dist/dist/libs/qrcode.min.js +0 -7
- package/dist/dist/manifest.json +0 -94
- package/dist/dist/offscreen/offscreen.html +0 -11
- package/dist/dist/offscreen/offscreen.js +0 -49
- package/dist/dist/options.html +0 -1091
- package/dist/dist/service-worker-loader.js +0 -1
- package/dist/dist/side_panel.html +0 -1357
- package/dist/dist/styles/styles.css +0 -262
- package/dist/dist/voice-capture-worklet.js +0 -47
package/src/rag/errors.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// agent/src/rag/errors.js - RAG 业务错误(错误码 + 参数)
|
|
2
|
-
// 约定:manager/loader 等纯逻辑模块抛 RagError(语言无关),
|
|
2
|
+
// 约定:manager/loader/embedding 等纯逻辑模块抛 RagError(语言无关),
|
|
3
3
|
// routes.js 在响应层用 t(`rag.err_${code}`) 翻译为当前请求语言。
|
|
4
4
|
|
|
5
5
|
export class RagError extends Error {
|
|
@@ -8,7 +8,10 @@ export class RagError extends Error {
|
|
|
8
8
|
* @param {object} [params] - 翻译插值参数
|
|
9
9
|
*/
|
|
10
10
|
constructor(code, params = {}) {
|
|
11
|
-
|
|
11
|
+
// 附带底层原因:RagError 的 message 只用于日志(响应文案走 locale),
|
|
12
|
+
// 丢掉了底层 message 就等于丢掉了唯一的排障线索
|
|
13
|
+
const detail = params && typeof params.message === 'string' && params.message ? ` - ${params.message}` : '';
|
|
14
|
+
super(`RAG error: ${code}${detail}`);
|
|
12
15
|
this.name = 'RagError';
|
|
13
16
|
this.code = code;
|
|
14
17
|
this.params = params;
|
|
@@ -27,3 +30,58 @@ export function translateRagError(err, t) {
|
|
|
27
30
|
}
|
|
28
31
|
return { error: err.message, code: null };
|
|
29
32
|
}
|
|
33
|
+
|
|
34
|
+
// onnxruntime 原生库「同进程两份 dll」冲突的特征串(Windows 实测,2026-10):
|
|
35
|
+
// - "The operating system cannot run %1." → Win32 193 / ERROR_BAD_EXE_FORMAT
|
|
36
|
+
// - "API version [24] is not available" → binding 要求 vs 已加载 dll 的 ORT_API_VERSION 不一致
|
|
37
|
+
// 这两类只会由「抢句柄」产生,是强特征。
|
|
38
|
+
const ORT_CONFLICT_STRONG = [
|
|
39
|
+
/cannot run %1/i,
|
|
40
|
+
/ERROR_BAD_EXE_FORMAT/i,
|
|
41
|
+
/not a valid Win32 application/i,
|
|
42
|
+
/API version \[\d+\] is not available/i,
|
|
43
|
+
];
|
|
44
|
+
// 弱特征:只出现 binding 文件名可能是「包没装全 / 装了错架构 / ABI 不符 / 是 Cannot find module」,
|
|
45
|
+
// 那些给用户「重启代理」是误诊。必须与「加载失败」类措辞共现才算抢句柄。
|
|
46
|
+
const ORT_BINDING_LOAD_FAILURE = /(?:dlopen|LoadLibrary|cannot open shared object|error while loading shared libraries|failed to load|DLL load failed)[\s\S]{0,300}onnxruntime/i;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 是否属于 onnxruntime 原生库冲突(同进程加载了两份不同版本的 onnxruntime)
|
|
50
|
+
* @param {Error|string|null|undefined} err
|
|
51
|
+
* @returns {boolean}
|
|
52
|
+
*/
|
|
53
|
+
export function isOnnxRuntimeConflict(err) {
|
|
54
|
+
if (!err) return false;
|
|
55
|
+
const text = `${err.code ? `${err.code} ` : ''}${err.message ?? err}`;
|
|
56
|
+
return ORT_CONFLICT_STRONG.some((pattern) => pattern.test(text)) || ORT_BINDING_LOAD_FAILURE.test(text);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// 底层错误进文案/日志前的截断长度(子进程原始 message 可能带绝对路径与超长堆栈首行)
|
|
60
|
+
const DETAIL_MAX = 300;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 把底层错误压成一行可展示的细节(去换行 + 截断)
|
|
64
|
+
* @param {Error|string} err
|
|
65
|
+
* @returns {string}
|
|
66
|
+
*/
|
|
67
|
+
export function errorDetail(err) {
|
|
68
|
+
const text = err && err.message ? String(err.message) : String(err ?? '');
|
|
69
|
+
const oneLine = text.replace(/\s+/g, ' ').trim();
|
|
70
|
+
return oneLine.length > DETAIL_MAX ? `${oneLine.slice(0, DETAIL_MAX)}…` : oneLine;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* 把本地 embedding 子进程的错误转成可翻译的 RagError
|
|
75
|
+
* @param {Error|string} err
|
|
76
|
+
* @returns {RagError}
|
|
77
|
+
*/
|
|
78
|
+
export function toEmbeddingError(err) {
|
|
79
|
+
if (err instanceof RagError) return err;
|
|
80
|
+
const message = errorDetail(err);
|
|
81
|
+
if (isOnnxRuntimeConflict(err)) {
|
|
82
|
+
// 带上底层原因:locale 不插值,只落在 RagError.message 里供日志排障
|
|
83
|
+
// (冲突现场 Win32 193 / API version 最难复现,丢了就再也看不到)
|
|
84
|
+
return new RagError('ortConflict', { message });
|
|
85
|
+
}
|
|
86
|
+
return new RagError('embedWorkerFailed', { message });
|
|
87
|
+
}
|
package/src/rag/install.js
CHANGED
|
@@ -25,6 +25,7 @@ import { homedir } from 'os';
|
|
|
25
25
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
|
|
26
26
|
import { resetRagDetection, detectRagAvailable, getLastRagProbeError, isNodeVersionSupported } from './detect.js';
|
|
27
27
|
import { stopProcessTree } from '../process-tree.js';
|
|
28
|
+
import { pruneNativeDuplicates, summarizePruneReport } from '../native-lib-guard.js';
|
|
28
29
|
import { logSystem } from '../logger.js';
|
|
29
30
|
import { t as translate, parseAcceptLanguage } from '../i18n.js';
|
|
30
31
|
import { getRegistryUrl } from '../install-mode.js';
|
|
@@ -424,6 +425,32 @@ async function runInstall(task, t) {
|
|
|
424
425
|
return;
|
|
425
426
|
}
|
|
426
427
|
|
|
428
|
+
// 安装后收口(Windows 必做):npm 在部分版本/安装顺序下会把与 overrides 冲突的版本
|
|
429
|
+
// 嵌套装进 node_modules/@huggingface/transformers/node_modules/onnxruntime-node,
|
|
430
|
+
// 同进程两份 onnxruntime.dll 会让 embedding 加载失败(cannot run %1)。
|
|
431
|
+
// 详见 native-lib-guard.js 文件头。
|
|
432
|
+
//
|
|
433
|
+
// 先关掉 embedding 子进程:Windows 上已被映射的 onnxruntime.dll 在进程退出前删不掉,
|
|
434
|
+
// 子进程还活着(在途请求 / 空闲回收窗口内)时,下面的删除会拿到 EPERM/EBUSY,
|
|
435
|
+
// → 嵌套副本没清掉 → 用户「重启代理」也不收敛。
|
|
436
|
+
try {
|
|
437
|
+
const { closeEmbedWorker } = await import('./embedding/worker-client.js');
|
|
438
|
+
await closeEmbedWorker();
|
|
439
|
+
} catch { /* 从未启动或已关闭 */ }
|
|
440
|
+
|
|
441
|
+
const repair = pruneNativeDuplicates(getAgentRoot());
|
|
442
|
+
const repairSummary = summarizePruneReport(repair);
|
|
443
|
+
if (repairSummary) {
|
|
444
|
+
task.logTail.push(`[deps] ${repairSummary}`);
|
|
445
|
+
if (task.logTail.length > LOG_TAIL_LIMIT) task.logTail = task.logTail.slice(-LOG_TAIL_LIMIT);
|
|
446
|
+
logSystem('rag_native_dedupe', { removed: repair.removed.length, failed: repair.failed.length });
|
|
447
|
+
}
|
|
448
|
+
if (repair.failed.length > 0) {
|
|
449
|
+
// 删除失败(文件被占/权限)不判安装失败,但必须留下可诊断痕迹:
|
|
450
|
+
// 否则安装显示 success、磁盘上依旧是两份,问题只能靠用户反馈才能发现
|
|
451
|
+
logSystem('rag_native_dedupe_failed', { failed: repair.failed });
|
|
452
|
+
}
|
|
453
|
+
|
|
427
454
|
// npm 退出码 0 → 重新检测依赖可用性(以 detect 结果为准,避免假成功)
|
|
428
455
|
// 探测在全新子进程执行:反映磁盘真实状态,避免长驻进程内 import 失败被永久缓存(R8)
|
|
429
456
|
task.phase = 'verifying';
|
package/src/rag/manager.js
CHANGED
|
@@ -745,14 +745,17 @@ export class RagManager {
|
|
|
745
745
|
* - contentBase64 + fileName:前端上传内容(落临时文件解析后清理)
|
|
746
746
|
* @param {string} collectionId
|
|
747
747
|
* @param {{path?: string, fileName?: string, contentBase64?: string, metadata?: object, chunkConfig?: object}} input
|
|
748
|
+
* @param {{ sessionId?: string, workdir?: string }} [ctx] - 请求级会话上下文(会话级工作目录)
|
|
748
749
|
*/
|
|
749
|
-
async ingestFile(collectionId, input = {}) {
|
|
750
|
+
async ingestFile(collectionId, input = {}, ctx = {}) {
|
|
750
751
|
return this._runIngest(collectionId, async () => {
|
|
751
752
|
// 来源 1:agent 本地文件
|
|
752
753
|
if (input.path) {
|
|
753
754
|
// 文件沙箱:与 /api/fs/read 同一套规则(allowedPaths 白名单 + 硬阻止清单),
|
|
754
755
|
// 防止经 RAG 导入绕过沙箱读取宿主任意文件(如代理自身敏感文件)
|
|
755
|
-
|
|
756
|
+
// ctx = 请求级会话上下文:会话绑定不写 allowedPaths,
|
|
757
|
+
// 不带会话上下文时从会话目录导入会被误判为越界
|
|
758
|
+
const check = await checkPath(input.path, undefined, ctx);
|
|
756
759
|
if (!check.allowed) {
|
|
757
760
|
throw new RagError('pathNotAllowed', { reason: check.reason });
|
|
758
761
|
}
|
package/src/rag/routes.js
CHANGED
|
@@ -130,7 +130,7 @@ export async function resolveTestEmbeddingInput(payload = {}) {
|
|
|
130
130
|
* @param {Function} t - 请求级翻译函数
|
|
131
131
|
* @param {object} [body] - 已解析的 JSON body(GET 请求为 null)
|
|
132
132
|
*/
|
|
133
|
-
export async function ragRouter(req, res, pathname, url, t, body = {}) {
|
|
133
|
+
export async function ragRouter(req, res, pathname, url, t, body = {}, ctx = {}) {
|
|
134
134
|
const method = req.method;
|
|
135
135
|
const payload = body || {};
|
|
136
136
|
// 业务处理包装(绑定请求级翻译函数)
|
|
@@ -239,12 +239,14 @@ export async function ragRouter(req, res, pathname, url, t, body = {}) {
|
|
|
239
239
|
return manager.ingestText(collectionId, { content: payload.content, name: payload.name, ...common });
|
|
240
240
|
}
|
|
241
241
|
if (type === 'file') {
|
|
242
|
+
// ctx 透传到 ingestFile 的 checkPath:会话绑定不写 allowedPaths,
|
|
243
|
+
// 不带会话上下文时从会话目录导入文档会被误判为越界
|
|
242
244
|
return manager.ingestFile(collectionId, {
|
|
243
245
|
path: payload.path,
|
|
244
246
|
fileName: payload.fileName,
|
|
245
247
|
contentBase64: payload.contentBase64,
|
|
246
248
|
...common,
|
|
247
|
-
});
|
|
249
|
+
}, ctx);
|
|
248
250
|
}
|
|
249
251
|
if (type === 'url') {
|
|
250
252
|
return manager.ingestUrl(collectionId, { url: payload.url, ...common });
|
package/src/search.js
CHANGED
|
@@ -218,8 +218,8 @@ async function searchFilesNative(rootPath, filePattern, recursive, maxResults) {
|
|
|
218
218
|
* @param {Function} [tFn] - 可选的翻译函数(由 server.js 传入)
|
|
219
219
|
* @returns {Array<{path, name, size, mtime}>}
|
|
220
220
|
*/
|
|
221
|
-
export async function searchFiles(rootPath, filePattern = '*', recursive = true, maxResults = 200, tFn) {
|
|
222
|
-
const pathCheck = await checkPath(rootPath, tFn);
|
|
221
|
+
export async function searchFiles(rootPath, filePattern = '*', recursive = true, maxResults = 200, tFn, ctx = {}) {
|
|
222
|
+
const pathCheck = await checkPath(rootPath, tFn, ctx);
|
|
223
223
|
if (!pathCheck.allowed) {
|
|
224
224
|
return { success: false, error: pathCheck.reason };
|
|
225
225
|
}
|
|
@@ -409,8 +409,8 @@ async function searchContentNative(rootPath, pattern, filePattern, caseSensitive
|
|
|
409
409
|
* @param {Function} [tFn] - 可选的翻译函数(由 server.js 传入)
|
|
410
410
|
* @returns {{ success: boolean, results: Array, total: number, engine: string }}
|
|
411
411
|
*/
|
|
412
|
-
export async function searchContent(rootPath, pattern, filePattern = null, caseSensitive = false, recursive = true, maxResults = 100, contextLines = 2, tFn) {
|
|
413
|
-
const pathCheck = await checkPath(rootPath, tFn);
|
|
412
|
+
export async function searchContent(rootPath, pattern, filePattern = null, caseSensitive = false, recursive = true, maxResults = 100, contextLines = 2, tFn, ctx = {}) {
|
|
413
|
+
const pathCheck = await checkPath(rootPath, tFn, ctx);
|
|
414
414
|
if (!pathCheck.allowed) {
|
|
415
415
|
return { success: false, error: pathCheck.reason };
|
|
416
416
|
}
|
package/src/security.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// agent/src/security.js - 安全管控:文件沙箱 + 命令分级
|
|
2
|
-
import { resolve, normalize, sep, isAbsolute, join, dirname } from 'path';
|
|
2
|
+
import { resolve, normalize, sep, isAbsolute, join, dirname, basename } from 'path';
|
|
3
3
|
import { realpath } from 'fs/promises';
|
|
4
4
|
import { homedir, platform } from 'os';
|
|
5
5
|
import { loadConfig, MEMORY_DIR } from './config.js';
|
|
@@ -68,6 +68,8 @@ const HARD_BLOCKED_PATHS = [
|
|
|
68
68
|
join(AGENT_DIR, 'config.json'), // 代理配置文件
|
|
69
69
|
join(AGENT_DIR, 'pairings.json'), // 配对记录
|
|
70
70
|
join(AGENT_DIR, 'mcp_servers.json'),// MCP 服务器配置
|
|
71
|
+
join(AGENT_DIR, 'session-workdirs.json'), // 会话工作目录注册表(写入=自我扩权)
|
|
72
|
+
join(AGENT_DIR, 'session-workdirs.json.tmp'), // 同上,写入中断留下的临时文件
|
|
71
73
|
join(AGENT_DIR, 'logs') + sep, // 日志目录
|
|
72
74
|
join(AGENT_DIR, '.trash') + sep, // 回收站目录(通过 /api/trash 端点管理)
|
|
73
75
|
join(AGENT_DIR, 'builtin_skills_state.json'), // 内置技能状态
|
|
@@ -99,14 +101,45 @@ function isHardBlocked(normalizedPath, platformOverride) {
|
|
|
99
101
|
return false;
|
|
100
102
|
}
|
|
101
103
|
|
|
104
|
+
/**
|
|
105
|
+
* 解析真实路径;尾部尚不存在时用「最近存在的祖先」的 realpath 拼接剩余段。
|
|
106
|
+
*
|
|
107
|
+
* 为什么不能遇到 ENOENT 就直接放行:会话目录里可以存在指向沙箱外的符号链接
|
|
108
|
+
* (`link -> /outside`),此时 `link/new.txt` 自身不存在会让 realpath 抛 ENOENT,
|
|
109
|
+
* 但写入会跟随链接落到沙箱外——「路径不存在」≠「没有符号链接逃逸」。
|
|
110
|
+
* 因此必须把存在的祖先解析出来,拼上不存在的尾段后再做前缀判定。
|
|
111
|
+
*
|
|
112
|
+
* @param {string} target 已 resolve 的绝对路径
|
|
113
|
+
* @returns {Promise<string|null>} 归一后的真实路径;连根都解析不到时返回 null
|
|
114
|
+
*/
|
|
115
|
+
async function realpathLoose(target) {
|
|
116
|
+
let existing = target;
|
|
117
|
+
const tail = [];
|
|
118
|
+
while (true) {
|
|
119
|
+
try {
|
|
120
|
+
const real = await realpath(existing);
|
|
121
|
+
return tail.length ? join(real, ...tail.reverse()) : real;
|
|
122
|
+
} catch (err) {
|
|
123
|
+
if (err.code !== 'ENOENT') throw err;
|
|
124
|
+
const parent = dirname(existing);
|
|
125
|
+
if (parent === existing) return null;
|
|
126
|
+
tail.push(basename(existing));
|
|
127
|
+
existing = parent;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
102
132
|
/**
|
|
103
133
|
* 检查路径是否在白名单内
|
|
104
134
|
* 使用 realpath 防止符号链接绕过
|
|
105
135
|
* @param {string} pathStr - 待检查的路径
|
|
106
136
|
* @param {Function} [tFn] - 可选的翻译函数(由 server.js 传入)
|
|
137
|
+
* @param {{ sessionId?: string, workdir?: string }} [ctx] - 会话上下文
|
|
138
|
+
* workdir 为该会话的**有效工作目录**(由调用方从会话注册表解析后传入):
|
|
139
|
+
* 相对路径按它解析,且它本身永远放行。未传则回落 config.workdir,旧行为完全不变。
|
|
107
140
|
* @returns {{ allowed: boolean, reason?: string, resolved?: string }}
|
|
108
141
|
*/
|
|
109
|
-
async function checkPath(pathStr, tFn) {
|
|
142
|
+
async function checkPath(pathStr, tFn, ctx = {}) {
|
|
110
143
|
if (!pathStr || typeof pathStr !== 'string') {
|
|
111
144
|
return { allowed: false, reason: tr('security.pathInvalid', undefined, tFn) };
|
|
112
145
|
}
|
|
@@ -122,8 +155,15 @@ async function checkPath(pathStr, tFn) {
|
|
|
122
155
|
try {
|
|
123
156
|
const config = loadConfig();
|
|
124
157
|
|
|
158
|
+
// 会话级工作目录:请求级上下文优先,缺省回落全局默认。
|
|
159
|
+
// 注意这是 checkPath 内部唯一的相对路径基准来源——绝不能在这里读会话状态之外的东西,
|
|
160
|
+
// 否则并行会话之间会互相串目录。
|
|
161
|
+
const effectiveWorkdir = (ctx && typeof ctx.workdir === 'string' && ctx.workdir)
|
|
162
|
+
? ctx.workdir
|
|
163
|
+
: config.workdir;
|
|
164
|
+
|
|
125
165
|
const normalizedPathStr = normalizePathFormat(pathStr);
|
|
126
|
-
const normalizedWorkdir = normalizePathFormat(
|
|
166
|
+
const normalizedWorkdir = normalizePathFormat(effectiveWorkdir);
|
|
127
167
|
|
|
128
168
|
const resolved = isAbsolute(normalizedPathStr) ? resolve(normalizedPathStr) : resolve(normalizedWorkdir, normalizedPathStr);
|
|
129
169
|
const normalized = normalize(resolved);
|
|
@@ -139,23 +179,58 @@ async function checkPath(pathStr, tFn) {
|
|
|
139
179
|
return { allowed: true, resolved: normalized };
|
|
140
180
|
}
|
|
141
181
|
|
|
142
|
-
// 0.6.
|
|
143
|
-
// workdir
|
|
182
|
+
// 0.6. 有效工作目录永远放行(不受 allowedPaths 配置控制)
|
|
183
|
+
// workdir 是用户为当前会话选定的操作目录,必须始终可访问,即使未在 allowedPaths 中也不应被拦截
|
|
144
184
|
if (normalizedWorkdir) {
|
|
145
185
|
const workdirResolved = resolve(normalizedWorkdir);
|
|
146
186
|
const workdirPrefix = workdirResolved.endsWith(sep) ? workdirResolved : workdirResolved + sep;
|
|
147
187
|
if (normalized.startsWith(workdirPrefix) || normalized === workdirResolved) {
|
|
148
|
-
// realpath
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
188
|
+
// realpath 复查:符号链接不能借会话目录跳出沙箱
|
|
189
|
+
// 1) 命中硬阻止项一律拒绝(workdir 内链接指向代理系统文件)
|
|
190
|
+
// 2) 真实路径必须仍在有效目录 / allowedPaths / 记忆目录内,否则视为越界
|
|
191
|
+
const sameOrInside = (child, root) => {
|
|
192
|
+
const prefix = root.endsWith(sep) ? root : root + sep;
|
|
193
|
+
return child === root || child.startsWith(prefix);
|
|
194
|
+
};
|
|
195
|
+
/**
|
|
196
|
+
* 真实路径是否仍在允许面内(有效目录 / allowedPaths / 记忆目录)
|
|
197
|
+
* 基准自身也可能挂在符号链接路径上(macOS 的 /var → /private/var),
|
|
198
|
+
* 只比较原始字符串会把正常文件误判成越界,因此两边都做一次 realpath 归一
|
|
199
|
+
* @param {string} realPath
|
|
200
|
+
* @returns {Promise<boolean>}
|
|
201
|
+
*/
|
|
202
|
+
const insideAllowed = async (realPath) => {
|
|
203
|
+
const realWorkdir = await realpath(workdirResolved).catch(() => workdirResolved);
|
|
204
|
+
if (sameOrInside(realPath, realWorkdir) || sameOrInside(realPath, workdirResolved)) return true;
|
|
205
|
+
for (const allowed of (config.allowedPaths || [])) {
|
|
206
|
+
const allowedResolved = resolve(normalizePathFormat(allowed));
|
|
207
|
+
const realAllowed = await realpath(allowedResolved).catch(() => allowedResolved);
|
|
208
|
+
if (sameOrInside(realPath, realAllowed) || sameOrInside(realPath, allowedResolved)) return true;
|
|
153
209
|
}
|
|
210
|
+
return sameOrInside(realPath, normalize(MEMORY_DIR));
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
let realPath;
|
|
214
|
+
try {
|
|
215
|
+
realPath = await realpath(resolved);
|
|
154
216
|
} catch (err) {
|
|
155
217
|
if (err.code !== 'ENOENT') {
|
|
156
218
|
return { allowed: false, reason: tr('security.cannotResolvePath', { message: err.message }, tFn) };
|
|
157
219
|
}
|
|
158
|
-
//
|
|
220
|
+
// 路径尚不存在(如待创建的文件):不能直接放行。
|
|
221
|
+
// 会话目录里可以有指向沙箱外的符号链接,`link/new.txt` 本身不存在但写入会跟随链接,
|
|
222
|
+
// 因此仍要拿「最近存在的祖先」的真实路径复查(见 realpathLoose)。
|
|
223
|
+
realPath = await realpathLoose(resolved);
|
|
224
|
+
if (!realPath) {
|
|
225
|
+
return { allowed: false, reason: tr('security.pathCheckError', { message: 'realpath unavailable' }, tFn) };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (isHardBlocked(realPath)) {
|
|
230
|
+
return { allowed: false, reason: tr('security.forbiddenAgentFile', undefined, tFn) };
|
|
231
|
+
}
|
|
232
|
+
if (!(await insideAllowed(realPath))) {
|
|
233
|
+
return { allowed: false, reason: tr('security.pathOutOfRange', undefined, tFn) };
|
|
159
234
|
}
|
|
160
235
|
return { allowed: true, resolved: normalized };
|
|
161
236
|
}
|
|
@@ -182,30 +257,19 @@ async function checkPath(pathStr, tFn) {
|
|
|
182
257
|
try {
|
|
183
258
|
realPath = await realpath(resolved);
|
|
184
259
|
} catch (err) {
|
|
185
|
-
if (err.code
|
|
186
|
-
let existing = resolved;
|
|
187
|
-
while (true) {
|
|
188
|
-
const parent = dirname(existing);
|
|
189
|
-
if (parent === existing) {
|
|
190
|
-
break;
|
|
191
|
-
}
|
|
192
|
-
try {
|
|
193
|
-
realPath = await realpath(parent) + sep + normalized.slice(resolve(parent).length).replace(/^[/\\]/, '');
|
|
194
|
-
break;
|
|
195
|
-
} catch (parentErr) {
|
|
196
|
-
if (parentErr.code === 'ENOENT') {
|
|
197
|
-
existing = parent;
|
|
198
|
-
continue;
|
|
199
|
-
}
|
|
200
|
-
return { allowed: false, reason: tr('security.cannotResolvePath', { message: parentErr.message }, tFn) };
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
if (!realPath) {
|
|
204
|
-
return { allowed: false, reason: tr('security.pathCheckError', { message: err.message }, tFn) };
|
|
205
|
-
}
|
|
206
|
-
} else {
|
|
260
|
+
if (err.code !== 'ENOENT') {
|
|
207
261
|
return { allowed: false, reason: tr('security.cannotResolvePath', { message: err.message }, tFn) };
|
|
208
262
|
}
|
|
263
|
+
// 尾部尚不存在:用最近存在的祖先 realpath 拼尾段后再判前缀,
|
|
264
|
+
// 否则「链接目录 + 新文件名」会绕过符号链接检查
|
|
265
|
+
try {
|
|
266
|
+
realPath = await realpathLoose(resolved);
|
|
267
|
+
} catch (parentErr) {
|
|
268
|
+
return { allowed: false, reason: tr('security.cannotResolvePath', { message: parentErr.message }, tFn) };
|
|
269
|
+
}
|
|
270
|
+
if (!realPath) {
|
|
271
|
+
return { allowed: false, reason: tr('security.pathCheckError', { message: err.message }, tFn) };
|
|
272
|
+
}
|
|
209
273
|
}
|
|
210
274
|
|
|
211
275
|
// 对 realPath 做硬阻止检查(防止通过符号链接绕过)
|