fix: protect resolved project paths and Windows aliases

This commit is contained in:
Agent Workbench Dev
2026-10-30 23:01:18 +08:00
parent ca9042e069
commit c1e9575259
2 changed files with 41 additions and 2 deletions
+10 -2
View File
@@ -9,9 +9,14 @@ import { assertMcpResolved } from '../core/tools/mcp-contract.mjs';
export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
const ignored = new Set(['node_modules', '.git', '.next', '.data', 'bin', 'obj', 'dist', 'dist-client', 'dist-server', '__pycache__', '.venv', 'venv', '.tox', '.pytest_cache', '.mypy_cache', '.ruff_cache', 'htmlcov']);
const secretName = /(^|\/)(\.env($|\.)|id_rsa($|\.)|id_ed25519($|\.)|credentials($|\.)|\.ssh($|\/))/i;
const secretName = /(^|\/)(\.env($|[./])|id_rsa($|[./])|id_ed25519($|[./])|credentials($|[./])|\.ssh($|\/)|\.secrets($|\/))/i;
const normalize = value => process.platform === 'win32' ? value.toLowerCase() : value;
const inside = (root, target) => normalize(target) === normalize(root) || normalize(target).startsWith(normalize(root + path.sep));
const restricted = relative => {
const portable = relative.replaceAll('\\', '/');
return secretName.test(portable) || portable.split('/').some(part => part.toLowerCase() === '.git'
|| process.platform === 'win32' && part !== '.' && /[. ]$/.test(part));
};
export function excludedFromInventory(relative) {
const portable = relative.replaceAll('\\', '/');
@@ -22,7 +27,7 @@ export function safePath(project, relative = '', allowMissing = false) {
assertWorkspacePath(project);
if (typeof relative !== 'string' || relative.includes('\0') || relative.includes(':') || path.isAbsolute(relative) || path.win32.isAbsolute(relative)) throw new Error('路径必须相对于项目文件夹。');
const portable = relative.replaceAll('\\', '/');
if (portable.split('/').includes('..') || secretName.test(portable) || portable.split('/').some(part => part.toLowerCase() === '.git')) throw new Error('该路径不在可读取的项目范围内。');
if (portable.split('/').includes('..') || restricted(portable)) throw new Error('该路径不在可读取的项目范围内。');
const root = fs.realpathSync.native(project.root);
if (normalize(root) !== normalize(project.root)) throw new Error('项目位置已变化,请重新打开项目。');
const target = path.resolve(root, portable || '.');
@@ -38,6 +43,9 @@ export function safePath(project, relative = '', allowMissing = false) {
}
const real = fs.realpathSync.native(existing);
if (!inside(root, real)) throw new Error('链接指向项目以外的位置。');
// A project-local link or Windows alias must not turn a public path into
// access to protected Git metadata or credentials, including new files.
if (restricted(path.relative(root, real))) throw new Error('实际路径指向受保护的项目目录或凭据。');
return target;
}