判断子路径包含
灵感:热门库 is-path-inside(Check if a path is inside another path)。
> 小四原创:isPathInside(child, parent) → 是否在目录树内。
> 导出/缓存落盘前快速看路径有没有跑出允许根。
何时使用
- 检查目标文件是否落在
output/下 - 整理用户传入的相对路径是否越界(辅助,非唯一防线)
- 与 make-dir / path-exists 组合做落盘前检查
硬约束
- 依赖:
is-path-inside。 - 不解析 symlink、不验证存在性;不能单独当安全沙箱。
- 实现要点注释标 小四原创。
- 不做完整权限/沙箱系统。
推荐实现
import isPathInside from 'is-path-inside'
import path from 'node:path'
// 小四原创:判断子路径包含
export function isUnderRoot(target: string, root: string) {
const absTarget = path.resolve(target)
const absRoot = path.resolve(root)
return absTarget === absRoot || isPathInside(absTarget, absRoot)
}
Agent 步骤
npm i is-path-inside。- 落盘前用
isUnderRoot检查。 - 自测:子路径 true,旁路路径 false。
不要做
- 仅靠本库防路径穿越攻击(需再规范化、禁
..、鉴权等)。 - 与「路径是否存在」整篇复读:本 Skill 侧重 包含关系。
附加
- README.md · reference.md · templates/usage.md