import path from 'path';
export function createTarSecurityFilter(options) {
    const { cwd, blockSymbolicLinks = true, blockHardLinks = true, verbose = false } = options;
    return (filePath, entry) => {
        if (entry.type === 'SymbolicLink') {
            if (blockSymbolicLinks) {
                if (verbose) {
                    console.warn(`[TAR安全过滤] 阻止符号链接: ${filePath} (防御 Unicode 竞态条件漏洞)`);
                }
                return false;
            }
            const linkpath = entry.linkpath;
            if (linkpath && (path.isAbsolute(linkpath) || linkpath.includes('..'))) {
                if (verbose) {
                    console.warn(`[TAR安全过滤] 阻止危险符号链接: ${filePath} -> ${linkpath}`);
                }
                return false;
            }
        }
        if (entry.type === 'Link') {
            if (blockHardLinks) {
                if (verbose) {
                    console.warn(`[TAR安全过滤] 阻止硬链接: ${filePath}`);
                }
                return false;
            }
            const linkpath = entry.linkpath;
            if (linkpath && (path.isAbsolute(linkpath) || linkpath.includes('..'))) {
                if (verbose) {
                    console.warn(`[TAR安全过滤] 阻止危险硬链接: ${filePath} -> ${linkpath}`);
                }
                return false;
            }
        }
        if (path.isAbsolute(filePath)) {
            if (verbose) {
                console.warn(`[TAR安全过滤] 阻止绝对路径: ${filePath}`);
            }
            return false;
        }
        if (filePath.includes('..')) {
            if (verbose) {
                console.warn(`[TAR安全过滤] 阻止路径遍历: ${filePath}`);
            }
            return false;
        }
        const resolvedPath = path.resolve(cwd, filePath);
        const resolvedCwd = path.resolve(cwd);
        if (!resolvedPath.startsWith(resolvedCwd)) {
            if (verbose) {
                console.warn(`[TAR安全过滤] 阻止目录逃逸: ${filePath} -> ${resolvedPath}`);
            }
            return false;
        }
        return true;
    };
}
export function createSimpleTarSecurityFilter(cwd) {
    return createTarSecurityFilter({
        cwd,
        blockSymbolicLinks: true,
        blockHardLinks: true,
        verbose: true
    });
}
export function createSafeTarExtractOptions(file, cwd, additionalOptions) {
    return {
        file,
        cwd,
        filter: createTarSecurityFilter({ cwd, blockSymbolicLinks: true, blockHardLinks: true }),
        ...additionalOptions
    };
}
export default {
    createTarSecurityFilter,
    createSimpleTarSecurityFilter,
    createSafeTarExtractOptions
};
