Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

2.7 KB
Raw Blame
import fsSync from "node:fs";
import fs from "node:fs/promises";
import path from "node:path";
import { isNotFoundPathError, isPathRelativeEscape } from "./path.js";
function resolvePathWalk(params) {
    const root = path.resolve(params.rootDir);
    const target = path.resolve(params.targetPath);
    const relative = path.relative(root, target);
    if (isPathRelativeEscape(relative)) {
        if (params.allowOutsideRoot) {
            return null;
        }
        throw new Error(`${params.messagePrefix ?? "Path"} must stay under ${root}.`);
    }
    return {
        root,
        segments: relative && relative !== "." ? relative.split(path.sep).filter(Boolean) : [],
    };
}
function formatUnsafePath(params, current) {
    return `${params.messagePrefix ?? "Path"} must not traverse symlinked directory: ${current}`;
}
export async function assertNoSymlinkParents(params) {
    const walk = resolvePathWalk(params);
    if (!walk) {
        return;
    }
    let current = walk.root;
    for (const segment of walk.segments) {
        current = path.join(current, segment);
        try {
            const stat = await fs.lstat(current);
            if (stat.isSymbolicLink()) {
                if (params.allowRootChildSymlink && path.dirname(current) === walk.root) {
                    continue;
                }
                throw new Error(formatUnsafePath(params, current));
            }
            if (params.requireDirectories && !stat.isDirectory()) {
                throw new Error(`${params.messagePrefix ?? "Path"} must traverse directories: ${current}`);
            }
        }
        catch (err) {
            if (isNotFoundPathError(err) && params.allowMissing !== false) {
                return;
            }
            throw err;
        }
    }
}
export function assertNoSymlinkParentsSync(params) {
    const walk = resolvePathWalk(params);
    if (!walk) {
        return;
    }
    let current = walk.root;
    for (const segment of walk.segments) {
        current = path.join(current, segment);
        try {
            const stat = fsSync.lstatSync(current);
            if (stat.isSymbolicLink()) {
                if (params.allowRootChildSymlink && path.dirname(current) === walk.root) {
                    continue;
                }
                throw new Error(formatUnsafePath(params, current));
            }
            if (params.requireDirectories && !stat.isDirectory()) {
                throw new Error(`${params.messagePrefix ?? "Path"} must traverse directories: ${current}`);
            }
        }
        catch (err) {
            if (err.code === "ENOENT" && params.allowMissing !== false) {
                return;
            }
            throw err;
        }
    }
}