// engine/runtime-security/checkers/file-permissions.ts — SPEC-084 AC-09
// Validates file operations stay within allowed directories.
import path from 'node:path';
import os from 'node:os';
function getDefaultAllowedDirs(projectPath) {
    const dirs = [os.tmpdir()];
    if (projectPath) {
        dirs.push(path.resolve(projectPath));
    }
    // data/ directory relative to process.cwd()
    dirs.push(path.resolve(process.cwd(), 'data'));
    return dirs;
}
function isPathAllowed(filePath, allowedDirs) {
    const resolved = path.resolve(filePath);
    return allowedDirs.some((dir) => resolved.startsWith(dir));
}
function extractPaths(inputs) {
    const result = [];
    const pathFields = ['projectPath', 'filePath', 'outputPath', 'configPath', 'targetPath'];
    for (const [key, value] of Object.entries(inputs)) {
        if (typeof value === 'string' &&
            (pathFields.includes(key) || key.toLowerCase().includes('path'))) {
            result.push({ field: key, path: value });
        }
        if (key === 'codeFiles' && Array.isArray(value)) {
            for (const item of value) {
                if (typeof item === 'string') {
                    result.push({ field: key, path: item });
                }
            }
        }
    }
    return result;
}
export const filePermissionsChecker = {
    type: 'file-permission',
    check(_toolName, inputs, config) {
        const threats = [];
        const projectPath = typeof inputs.projectPath === 'string' ? inputs.projectPath : undefined;
        const defaultDirs = getDefaultAllowedDirs(projectPath);
        const allowedDirs = [...defaultDirs, ...config.allowedDirectories.map((d) => path.resolve(d))];
        const pathEntries = extractPaths(inputs);
        for (const entry of pathEntries) {
            if (!path.isAbsolute(entry.path)) {
                continue;
            } // Relative paths handled by path-traversal checker
            if (!isPathAllowed(entry.path, allowedDirs)) {
                threats.push({
                    type: 'file-permission',
                    severity: 'critical',
                    message: `File operation outside allowed directories: ${entry.path}`,
                    field: entry.field,
                });
            }
        }
        return threats;
    },
};
//# sourceMappingURL=file-permissions.js.map