eslint-plugin-node-security 6.0.2 → 6.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-node-security",
3
- "version": "6.0.2",
3
+ "version": "6.0.3",
4
4
  "description": "ESLint plugin for Node.js security — detects command injection, path traversal, SSRF, zip slip, and weak crypto (MD5/SHA-1, ECB, static IV) in fs, child_process, vm, and crypto.",
5
5
  "type": "commonjs",
6
6
  "sideEffects": false,
package/src/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"detect-child-process"(){return require("./rules/detect-child-process").detectChildProcess},get"detect-eval-with-expression"(){return require("./rules/detect-eval-with-expression").detectEvalWithExpression},get"detect-non-literal-fs-filename"(){return require("./rules/detect-non-literal-fs-filename").detectNonLiteralFsFilename},get"no-unsafe-dynamic-require"(){return require("./rules/no-unsafe-dynamic-require").noUnsafeDynamicRequire},get"no-buffer-overread"(){return require("./rules/no-buffer-overread").noBufferOverread},get"no-deprecated-buffer"(){return require("./rules/no-deprecated-buffer").noDeprecatedBuffer},get"no-unsafe-buffer-alloc"(){return require("./rules/no-unsafe-buffer-alloc").noUnsafeBufferAlloc},get"no-toctou-vulnerability"(){return require("./rules/no-toctou-vulnerability").noToctouVulnerability},get"no-zip-slip"(){return require("./rules/no-zip-slip").noZipSlip},get"no-arbitrary-file-access"(){return require("./rules/no-arbitrary-file-access").noArbitraryFileAccess},get"no-data-in-temp-storage"(){return require("./rules/no-data-in-temp-storage").noDataInTempStorage},get"no-ssrf"(){return require("./rules/no-ssrf").noSsrf},get"no-shell-injection"(){return require("./rules/no-shell-injection").noShellInjection},get"no-dynamic-command-string"(){return require("./rules/no-dynamic-command-string").noDynamicCommandString},get"no-env-injection"(){return require("./rules/no-env-injection").noEnvInjection},get"no-dynamic-algorithm-selection"(){return require("./rules/no-dynamic-algorithm-selection").noDynamicAlgorithmSelection},get"detect-suspicious-dependencies"(){return require("./rules/detect-suspicious-dependencies").detectSuspiciousDependencies},get"lock-file"(){return require("./rules/lock-file").lockFile},get"no-dynamic-dependency-loading"(){return require("./rules/no-dynamic-dependency-loading").noDynamicDependencyLoading},get"require-dependency-integrity"(){return require("./rules/require-dependency-integrity").requireDependencyIntegrity},get"require-secure-credential-storage"(){return require("./rules/require-secure-credential-storage").requireSecureCredentialStorage},get"require-secure-deletion"(){return require("./rules/require-secure-deletion").requireSecureDeletion},get"require-storage-encryption"(){return require("./rules/require-storage-encryption").requireStorageEncryption},get"no-dynamic-require"(){return require("./rules/no-dynamic-require").noDynamicRequire},get"no-cryptojs"(){return require("./rules/no-cryptojs").noCryptojs},get"no-cryptojs-weak-random"(){return require("./rules/no-cryptojs-weak-random").noCryptojsWeakRandom},get"no-deprecated-cipher-method"(){return require("./rules/no-deprecated-cipher-method").noDeprecatedCipherMethod},get"no-ecb-mode"(){return require("./rules/no-ecb-mode").noEcbMode},get"no-insecure-key-derivation"(){return require("./rules/no-insecure-key-derivation").noInsecureKeyDerivation},get"no-insecure-rsa-padding"(){return require("./rules/no-insecure-rsa-padding").noInsecureRsaPadding},get"no-math-random-crypto"(){return require("./rules/no-math-random-crypto").noMathRandomCrypto},get"no-self-signed-certs"(){return require("./rules/no-self-signed-certs").noSelfSignedCerts},get"no-sha1-hash"(){return require("./rules/no-sha1-hash").noSha1Hash},get"no-static-iv"(){return require("./rules/no-static-iv").noStaticIv},get"no-timing-unsafe-compare"(){return require("./rules/no-timing-unsafe-compare").noTimingUnsafeCompare},get"no-weak-cipher-algorithm"(){return require("./rules/no-weak-cipher-algorithm").noWeakCipherAlgorithm},get"no-weak-dh-parameters"(){return require("./rules/no-weak-dh-parameters").noWeakDhParameters},get"no-weak-hash-algorithm"(){return require("./rules/no-weak-hash-algorithm").noWeakHashAlgorithm},get"prefer-native-crypto"(){return require("./rules/prefer-native-crypto").preferNativeCrypto},get"require-aead-tag-verification"(){return require("./rules/require-aead-tag-verification").requireAeadTagVerification},get"no-unbounded-decompression"(){return require("./rules/no-unbounded-decompression").noUnboundedDecompression},get"no-insecure-http-parser"(){return require("./rules/no-insecure-http-parser").noInsecureHttpParser},get"require-stream-error-handler"(){return require("./rules/require-stream-error-handler").requireStreamErrorHandler}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-node-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-node-security",version:"6.0.2"},rules:exports.rules};const recommendedRules={"node-security/detect-child-process":"error","node-security/detect-eval-with-expression":"error","node-security/detect-non-literal-fs-filename":"warn","node-security/no-unsafe-dynamic-require":"error","node-security/no-buffer-overread":"warn","node-security/no-deprecated-buffer":"error","node-security/no-unsafe-buffer-alloc":"warn","node-security/no-toctou-vulnerability":"error","node-security/no-zip-slip":"error","node-security/no-arbitrary-file-access":"error","node-security/no-data-in-temp-storage":"error","node-security/no-ssrf":"warn","node-security/no-shell-injection":"error","node-security/no-dynamic-command-string":"error","node-security/no-env-injection":"error","node-security/no-dynamic-algorithm-selection":"error","node-security/no-timing-unsafe-compare":"warn","node-security/detect-suspicious-dependencies":"warn","node-security/require-dependency-integrity":"error","node-security/no-weak-hash-algorithm":"error","node-security/no-weak-cipher-algorithm":"error","node-security/no-weak-dh-parameters":"error","node-security/no-static-iv":"error","node-security/no-ecb-mode":"error","node-security/no-math-random-crypto":"error","node-security/no-cryptojs":"error","node-security/no-self-signed-certs":"error","node-security/require-aead-tag-verification":"error","node-security/no-unbounded-decompression":"error","node-security/no-insecure-http-parser":"error","node-security/require-stream-error-handler":"error"};exports.configs={recommended:{plugins:{"node-security":exports.plugin},rules:recommendedRules},strict:{plugins:{"node-security":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`node-security/${ruleName}`,"error"]))}};exports.default=exports.plugin;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"detect-child-process"(){return require("./rules/detect-child-process").detectChildProcess},get"detect-eval-with-expression"(){return require("./rules/detect-eval-with-expression").detectEvalWithExpression},get"detect-non-literal-fs-filename"(){return require("./rules/detect-non-literal-fs-filename").detectNonLiteralFsFilename},get"no-unsafe-dynamic-require"(){return require("./rules/no-unsafe-dynamic-require").noUnsafeDynamicRequire},get"no-buffer-overread"(){return require("./rules/no-buffer-overread").noBufferOverread},get"no-deprecated-buffer"(){return require("./rules/no-deprecated-buffer").noDeprecatedBuffer},get"no-unsafe-buffer-alloc"(){return require("./rules/no-unsafe-buffer-alloc").noUnsafeBufferAlloc},get"no-toctou-vulnerability"(){return require("./rules/no-toctou-vulnerability").noToctouVulnerability},get"no-zip-slip"(){return require("./rules/no-zip-slip").noZipSlip},get"no-arbitrary-file-access"(){return require("./rules/no-arbitrary-file-access").noArbitraryFileAccess},get"no-data-in-temp-storage"(){return require("./rules/no-data-in-temp-storage").noDataInTempStorage},get"no-ssrf"(){return require("./rules/no-ssrf").noSsrf},get"no-shell-injection"(){return require("./rules/no-shell-injection").noShellInjection},get"no-dynamic-command-string"(){return require("./rules/no-dynamic-command-string").noDynamicCommandString},get"no-env-injection"(){return require("./rules/no-env-injection").noEnvInjection},get"no-dynamic-algorithm-selection"(){return require("./rules/no-dynamic-algorithm-selection").noDynamicAlgorithmSelection},get"detect-suspicious-dependencies"(){return require("./rules/detect-suspicious-dependencies").detectSuspiciousDependencies},get"lock-file"(){return require("./rules/lock-file").lockFile},get"no-dynamic-dependency-loading"(){return require("./rules/no-dynamic-dependency-loading").noDynamicDependencyLoading},get"require-dependency-integrity"(){return require("./rules/require-dependency-integrity").requireDependencyIntegrity},get"require-secure-credential-storage"(){return require("./rules/require-secure-credential-storage").requireSecureCredentialStorage},get"require-secure-deletion"(){return require("./rules/require-secure-deletion").requireSecureDeletion},get"require-storage-encryption"(){return require("./rules/require-storage-encryption").requireStorageEncryption},get"no-dynamic-require"(){return require("./rules/no-dynamic-require").noDynamicRequire},get"no-cryptojs"(){return require("./rules/no-cryptojs").noCryptojs},get"no-cryptojs-weak-random"(){return require("./rules/no-cryptojs-weak-random").noCryptojsWeakRandom},get"no-deprecated-cipher-method"(){return require("./rules/no-deprecated-cipher-method").noDeprecatedCipherMethod},get"no-ecb-mode"(){return require("./rules/no-ecb-mode").noEcbMode},get"no-insecure-key-derivation"(){return require("./rules/no-insecure-key-derivation").noInsecureKeyDerivation},get"no-insecure-rsa-padding"(){return require("./rules/no-insecure-rsa-padding").noInsecureRsaPadding},get"no-math-random-crypto"(){return require("./rules/no-math-random-crypto").noMathRandomCrypto},get"no-self-signed-certs"(){return require("./rules/no-self-signed-certs").noSelfSignedCerts},get"no-sha1-hash"(){return require("./rules/no-sha1-hash").noSha1Hash},get"no-static-iv"(){return require("./rules/no-static-iv").noStaticIv},get"no-timing-unsafe-compare"(){return require("./rules/no-timing-unsafe-compare").noTimingUnsafeCompare},get"no-weak-cipher-algorithm"(){return require("./rules/no-weak-cipher-algorithm").noWeakCipherAlgorithm},get"no-weak-dh-parameters"(){return require("./rules/no-weak-dh-parameters").noWeakDhParameters},get"no-weak-hash-algorithm"(){return require("./rules/no-weak-hash-algorithm").noWeakHashAlgorithm},get"prefer-native-crypto"(){return require("./rules/prefer-native-crypto").preferNativeCrypto},get"require-aead-tag-verification"(){return require("./rules/require-aead-tag-verification").requireAeadTagVerification},get"no-unbounded-decompression"(){return require("./rules/no-unbounded-decompression").noUnboundedDecompression},get"no-insecure-http-parser"(){return require("./rules/no-insecure-http-parser").noInsecureHttpParser},get"require-stream-error-handler"(){return require("./rules/require-stream-error-handler").requireStreamErrorHandler}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-node-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-node-security",version:"6.0.3"},rules:exports.rules};const recommendedRules={"node-security/detect-child-process":"error","node-security/detect-eval-with-expression":"error","node-security/detect-non-literal-fs-filename":"warn","node-security/no-unsafe-dynamic-require":"error","node-security/no-buffer-overread":"warn","node-security/no-deprecated-buffer":"error","node-security/no-unsafe-buffer-alloc":"warn","node-security/no-toctou-vulnerability":"error","node-security/no-zip-slip":"error","node-security/no-arbitrary-file-access":"error","node-security/no-data-in-temp-storage":"error","node-security/no-ssrf":"warn","node-security/no-shell-injection":"error","node-security/no-dynamic-command-string":"error","node-security/no-env-injection":"error","node-security/no-dynamic-algorithm-selection":"error","node-security/no-timing-unsafe-compare":"warn","node-security/detect-suspicious-dependencies":"warn","node-security/require-dependency-integrity":"error","node-security/no-weak-hash-algorithm":"error","node-security/no-weak-cipher-algorithm":"error","node-security/no-weak-dh-parameters":"error","node-security/no-static-iv":"error","node-security/no-ecb-mode":"error","node-security/no-math-random-crypto":"error","node-security/no-cryptojs":"error","node-security/no-self-signed-certs":"error","node-security/require-aead-tag-verification":"error","node-security/no-unbounded-decompression":"error","node-security/no-insecure-http-parser":"error","node-security/require-stream-error-handler":"error"};exports.configs={recommended:{plugins:{"node-security":exports.plugin},rules:recommendedRules},strict:{plugins:{"node-security":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`node-security/${ruleName}`,"error"]))}};exports.default=exports.plugin;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectNonLiteralFsFilename=exports.determineRiskLevel=exports.generateRefactoringSteps=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const separator_anchored_1=require("../../utils/separator-anchored");const module_binding_1=require("../../utils/module-binding");const FS_OPERATIONS=[{method:"readFile",dangerous:true,safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))"},{method:"writeFile",dangerous:true,safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))"},{method:"stat",dangerous:true,safePattern:"path.resolve(baseDir, userInput) with validation"},{method:"readdir",dangerous:true,safePattern:"Validate directory is within allowed paths"}];const hasTraversalPatterns=pathStr=>{return/\.\.[/\\]/.test(pathStr)};const PROCESS_INPUT_MEMBERS=new Set(["env","argv","argv0","execArgv","stdin"]);const SENSITIVE_SEGMENTS=["etc/passwd","etc/shadow","etc/hosts","etc/sudoers","proc/self",".ssh/id_rsa",".ssh/id_dsa",".ssh/authorized_keys",".aws/credentials",".npmrc",".git/config","windows/system32/config/sam"];const targetsSensitiveLocation=value=>{const normalised=value.replace(/\\/g,"/").toLowerCase();if(!/(^|\/)\.\.(\/|$)/.test(normalised)){return false}const withoutPrefix=normalised.replace(/^(?:\.{1,2}\/)+/,"");return SENSITIVE_SEGMENTS.some(seg=>withoutPrefix===seg||withoutPrefix.endsWith(`/${seg}`)||withoutPrefix.startsWith(`${seg}/`))};const generateRefactoringSteps=operation=>{switch(operation.method){case"readFile":case"writeFile":return[" 1. Define a SAFE_DIR constant for allowed operations"," 2. Use path.basename() to strip directory components"," 3. Combine with SAFE_DIR: path.join(SAFE_DIR, path.basename(userPath))"," 4. Optionally validate file extensions"," 5. Add error handling for invalid paths"].join("\n");case"stat":return[" 1. Use path.resolve() to normalize the path"," 2. Check the resolved path starts with the base PLUS path.sep \u2014 a bare"," prefix lets /safebad through a /safe check"," 3. Reject requests that escape the allowed directory"," 4. Use path.relative() for additional validation"," 5. Log security events for monitoring"].join("\n");case"readdir":return[" 1. Resolve the directory path: path.resolve(ALLOWED_DIRS, userDir)"," 2. Validate resolved path starts with ALLOWED_DIRS"," 3. Check directory exists and is readable"," 4. Consider whitelisting allowed directories"," 5. Add rate limiting to prevent enumeration attacks"].join("\n");default:return[" 1. Identify the specific file operation needed"," 2. Define safe base directories for operations"," 3. Use path.resolve() and validate containment"," 4. Sanitize user input (basename, extension validation)"," 5. Add comprehensive error handling"].join("\n")}};exports.generateRefactoringSteps=generateRefactoringSteps;const PATH_BUILDERS=new Set(["join","resolve"]);const FS_MODULE_EQUIVALENTS={"fs-extra":"fs","graceful-fs":"fs","fs/promises":"fs"};const determineRiskLevel=(operation,pathStr)=>{if(hasTraversalPatterns(pathStr)){return"CRITICAL"}if(operation.dangerous){return"HIGH"}return"MEDIUM"};exports.determineRiskLevel=determineRiskLevel;exports.detectNonLiteralFsFilename=(0,eslint_devkit_2.createRule)({name:"detect-non-literal-fs-filename",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-non-literal-fs-filename.md",description:"Detects variable in filename argument of fs calls, which might allow an attacker to access anything on your system",cwe:"CWE-22",confidence:"medium"},messages:{fsPathTraversal:(0,eslint_devkit_1.formatLLMMessage)({icon:"\u{1F511}",issueName:"Path traversal",cwe:"CWE-22",description:"Path traversal vulnerability",severity:"{{riskLevel}}",fix:"{{safePattern}} \u2014 Not a finding when the value is path.basename()d, checked against an allowlist, or resolved and then prefix-checked WITH a trailing separator",documentationLink:"https://owasp.org/www-community/attacks/Path_Traversal"})},schema:[{type:"object",properties:{taintSources:{type:"array",items:{type:"string"},default:["process"],description:"Identifier roots treated as attacker-reachable. Default: ['process'] (process.argv and process.env). Request roots (req/request/ctx/event) are deliberately NOT included \u2014 no-arbitrary-file-access owns those, and listing them here would double-report one line at two severities. Add them only if you run this rule without that one."},reportUnresolvedPaths:{type:"boolean",default:false,description:"Report paths whose provenance cannot be resolved. Restores the pre-inversion behaviour; measured at 7% precision on real code."},reportWholeProcessValues:{type:"boolean",default:false,description:"Report process.argv / process.env used as the whole path (fs.readFileSync(process.argv[2])). Off by default: whoever sets argv or the environment already chooses which files the process opens. True matches eslint-plugin-security."},allowLiterals:{type:"boolean",default:false,description:"Silence hardcoded paths altogether. With the default (false) a literal reports only when it traverses (a `..` segment) into a sensitive location such as `../../etc/passwd`; a relative literal like `../config.json` never reports \u2014 measured as this rule's largest FP class on real code."},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional fs methods to check"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowLiterals:false,additionalMethods:[]}],createOnce(context){let allowLiterals;let additionalMethods;let WHOLE_VALUE_TRUSTED_ROOTS;let AMBIGUOUS_ROOTS;let REQUEST_SURFACE;let taintRoots;let reportUnresolvedPaths;let PATH_ARGUMENT_INDICES;let dangerousMethods;let pendingCalls;const resolvedVariable=id=>context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id).resolved;const readsRequestSurface=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),REQUEST_SURFACE);const hasRequestEvidence=variable=>variable.references.some(ref=>readsRequestSurface(ref.identifier.parent));const isLocallyConstructed=id=>{const variable=resolvedVariable(id);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1){return false}const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression};const constBindingInit=id=>{const variable=resolvedVariable(id);if(!variable||variable.defs.length!==1)return void 0;const def=variable.defs[0];if(def.type!=="Variable")return void 0;const declarator=def.node;if(def.parent.kind!=="const")return void 0;return declarator.init??void 0};const viaConst=(id,onPath,walk)=>{const init=constBindingInit(id);if(init===void 0||onPath.has(init))return false;onPath.add(init);const verdict=walk(init,onPath);onPath.delete(init);return verdict};const readsTaintSource=(rawNode,onPath=new Set)=>{const node=(0,eslint_devkit_1.unwrapTypeSyntax)(rawNode);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name)){if(AMBIGUOUS_ROOTS.has(node.name)){const variable=resolvedVariable(node);if(variable!==null&&!hasRequestEvidence(variable))return false}return!isLocallyConstructed(node)}return viaConst(node,onPath,readsTaintSource)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="process"&&!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),PROCESS_INPUT_MEMBERS)){return false}return readsTaintSource(node.object,onPath)}case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>readsTaintSource(e,onPath));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return readsTaintSource(node.left,onPath)||readsTaintSource(node.right,onPath);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"&&(0,eslint_devkit_1.propertyName)(callee)==="basename"){return false}if((0,eslint_devkit_1.isModuleBinding)(callee,context.sourceCode.getScope(callee),"path",["basename"])){return false}return node.arguments.some(arg=>readsTaintSource(arg,onPath))}default:return false}};const containsUntrustedRoot=(node,onPath=new Set)=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return!WHOLE_VALUE_TRUSTED_ROOTS.has(node.name);return viaConst(node,onPath,containsUntrustedRoot)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return containsUntrustedRoot(node.object,onPath);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>containsUntrustedRoot(e,onPath));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return containsUntrustedRoot(node.left,onPath)||containsUntrustedRoot(node.right,onPath);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>containsUntrustedRoot(a,onPath));default:return false}};const isWholeTaintValue=(node,onPath=new Set)=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return WHOLE_VALUE_TRUSTED_ROOTS.has(node.name);return viaConst(node,onPath,isWholeTaintValue)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isWholeTaintValue(node.object,onPath);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;const isPathCall=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"||(0,eslint_devkit_1.resolveModuleBinding)(callee,context.sourceCode.getScope(callee),{})?.module==="path";if(!isPathCall)return false;return isWholeTaintValue(node.arguments[0],onPath)&&!containsUntrustedRoot(node)}default:return false}};const isDangerousPath=pathNode=>{if(!pathNode)return reportUnresolvedPaths;const literal=(0,eslint_devkit_1.staticString)(pathNode);if(literal!==null){return!allowLiterals&&targetsSensitiveLocation(literal)}if(hasPathValidation(pathNode))return false;if(readsTaintSource(pathNode))return!isWholeTaintValue(pathNode);if(isBuildTimeConstant(pathNode))return false;if(containsFreeVariable(pathNode))return true;return reportUnresolvedPaths};let commentGlobals;const declaredByGlobalComment=name=>{commentGlobals??=new Set(context.sourceCode.getAllComments().flatMap(comment=>comment.type==="Block"?/^\s*globals?\s([\s\S]*)$/.exec(comment.value)?.[1].split(",")??[]:[]).map(entry=>entry.split(":")[0].trim()));return commentGlobals.has(name)};function isFreeVariable(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&declaredByGlobalComment(node.name)){return false}const through=context.sourceCode.getScope(node).through;return through.some(ref=>ref.identifier===node&&ref.resolved===null)}const containsFreeVariable=node=>{if(isBuildTimeConstant(node))return false;if(isFreeVariable(node))return true;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>containsFreeVariable(e));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>containsFreeVariable(a));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return containsFreeVariable(node.left)||containsFreeVariable(node.right);case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return node.computed&&containsFreeVariable(node.property);default:return false}};const isBuildTimeConstant=(node,onPath=new Set)=>{const literal=(0,eslint_devkit_1.staticString)(node);if(literal!==null){return!hasTraversalPatterns(literal)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(node.name==="__dirname"||node.name==="__filename")return true;return viaConst(node,onPath,isBuildTimeConstant)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const literalText=node.quasis.map(q=>q.value.raw).join("");if(hasTraversalPatterns(literalText))return false;return node.expressions.every(e=>isBuildTimeConstant(e,onPath))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="process"&&(0,eslint_devkit_1.propertyName)(callee)==="cwd"){return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),PATH_BUILDERS)){return node.arguments.length>0&&node.arguments.every(arg=>isBuildTimeConstant(arg,onPath))}return false}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return isBuildTimeConstant(node.left,onPath)&&isBuildTimeConstant(node.right,onPath)}return false};const hasPathValidation=pathNode=>{if(pathNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){const parts=[];const collect=n=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){collect(n.left);collect(n.right);return}if(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){n.expressions.forEach(e=>collect(e));return}if(n.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){n.arguments.forEach(a=>collect(a));return}if(readsTaintSource(n))parts.push(n)};collect(pathNode);return parts.length>0&&parts.every(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&hasPathValidation(p))}const varName=pathNode.name;const isValidationCall=testNode=>{if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&testNode.operator==="!"&&testNode.argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){testNode=testNode.argument}if(testNode.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression){return false}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&testNode.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.callee.object.name===varName&&((0,eslint_devkit_1.propertyName)(testNode.callee)==="startsWith"||(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes")){return(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes"?true:(0,separator_anchored_1.isSeparatorAnchored)(testNode.arguments[0],context.sourceCode)}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes"){for(const arg of testNode.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.name===varName){return true}}}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(testNode.callee)==="test"){for(const arg of testNode.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.name===varName){return true}}}return false};const hasEarlyExit=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement};let child=pathNode;let current=pathNode.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&isValidationCall(current.test)){return true}if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=current.body;const index=body.indexOf(child);for(let i=0;i<index;i++){const stmt=body[i];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&isValidationCall(stmt.test)&&hasEarlyExit(stmt.consequent)){return true}}}child=current;current=current.parent}return false};const checkFsCall=node=>{const scope=context.sourceCode.getScope(node);const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope,{equivalents:FS_MODULE_EQUIVALENTS})??(0,module_binding_1.undeclaredFsBinding)(node.callee,scope);if(binding?.module!=="fs")return;const[first,second]=binding.path;const methodName=binding.path.length===1?first:binding.path.length===2&&first==="promises"?second:void 0;if(methodName===void 0)return;if(!dangerousMethods.has(methodName)){return}const method=methodName;const indices=PATH_ARGUMENT_INDICES.get(method)??[0];const pathNode=indices.map(index=>node.arguments[index]).find(candidate=>candidate!==void 0&&isDangerousPath(candidate))??null;if(pathNode===null){if(node.arguments.length===0&&isDangerousPath(null)){context.report({node,messageId:"fsPathTraversal",data:{riskLevel:"MEDIUM",safePattern:"Use path.resolve() with validation"}})}return}const operation=FS_OPERATIONS.find(op=>op.method===method);context.report({node,messageId:"fsPathTraversal",data:{riskLevel:(0,exports.determineRiskLevel)(operation??FS_OPERATIONS[0],context.sourceCode.getText(pathNode)),safePattern:operation?.safePattern??"Use path.resolve() with validation"}})};return{before(){const options=context.options[0]||{};({allowLiterals=false,additionalMethods=[]}=options);commentGlobals=void 0;const DEFAULT_TAINT_ROOTS=["process","req","request","ctx","context","event"];WHOLE_VALUE_TRUSTED_ROOTS=new Set(options.reportWholeProcessValues?[]:["process"]);AMBIGUOUS_ROOTS=new Set(["ctx","context"]);REQUEST_SURFACE=new Set(["query","params","body","request","req","headers","cookies","searchParams","originalUrl"]);taintRoots=new Set(options.taintSources??DEFAULT_TAINT_ROOTS);reportUnresolvedPaths=options.reportUnresolvedPaths??false;PATH_ARGUMENT_INDICES=new Map([["copyFile",[0,1]],["copyFileSync",[0,1]],["cp",[0,1]],["cpSync",[0,1]],["rename",[0,1]],["renameSync",[0,1]],["link",[0,1]],["linkSync",[0,1]],["symlink",[0,1]],["symlinkSync",[0,1]]]);dangerousMethods=new Set(["readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","stat","statSync","lstat","lstatSync","readdir","readdirSync","unlink","unlinkSync","mkdir","mkdirSync","rmdir","rmdirSync","access","accessSync","createReadStream","createWriteStream","open","openSync","rm","rmSync","rename","renameSync","copyFile","copyFileSync","cp","cpSync","truncate","truncateSync","chmod","chmodSync","chown","chownSync","lchown","lchownSync","utimes","utimesSync","readlink","readlinkSync","symlink","symlinkSync","link","linkSync","opendir","opendirSync",...additionalMethods]);pendingCalls=[]},CallExpression(node){pendingCalls.push(node)},"Program:exit"(){for(const call of pendingCalls)checkFsCall(call)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectNonLiteralFsFilename=exports.determineRiskLevel=exports.generateRefactoringSteps=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const separator_anchored_1=require("../../utils/separator-anchored");const module_binding_1=require("../../utils/module-binding");const FS_OPERATIONS=[{method:"readFile",dangerous:true,safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))"},{method:"writeFile",dangerous:true,safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))"},{method:"stat",dangerous:true,safePattern:"path.resolve(baseDir, userInput) with validation"},{method:"readdir",dangerous:true,safePattern:"Validate directory is within allowed paths"}];const hasTraversalPatterns=pathStr=>{return/\.\.[/\\]/.test(pathStr)};const PROCESS_INPUT_MEMBERS=new Set(["env","argv","argv0","execArgv","stdin"]);const SENSITIVE_SEGMENTS=["etc/passwd","etc/shadow","etc/hosts","etc/sudoers","proc/self",".ssh/id_rsa",".ssh/id_dsa",".ssh/authorized_keys",".aws/credentials",".npmrc",".git/config","windows/system32/config/sam"];const targetsSensitiveLocation=value=>{const normalised=value.replace(/\\/g,"/").toLowerCase();if(!/(^|\/)\.\.(\/|$)/.test(normalised)){return false}const withoutPrefix=normalised.replace(/^(?:\.{1,2}\/)+/,"");return SENSITIVE_SEGMENTS.some(seg=>withoutPrefix===seg||withoutPrefix.endsWith(`/${seg}`)||withoutPrefix.startsWith(`${seg}/`))};const generateRefactoringSteps=operation=>{switch(operation.method){case"readFile":case"writeFile":return[" 1. Define a SAFE_DIR constant for allowed operations"," 2. Use path.basename() to strip directory components"," 3. Combine with SAFE_DIR: path.join(SAFE_DIR, path.basename(userPath))"," 4. Optionally validate file extensions"," 5. Add error handling for invalid paths"].join("\n");case"stat":return[" 1. Use path.resolve() to normalize the path"," 2. Check the resolved path starts with the base PLUS path.sep \u2014 a bare"," prefix lets /safebad through a /safe check"," 3. Reject requests that escape the allowed directory"," 4. Use path.relative() for additional validation"," 5. Log security events for monitoring"].join("\n");case"readdir":return[" 1. Resolve the directory path: path.resolve(ALLOWED_DIRS, userDir)"," 2. Validate resolved path starts with ALLOWED_DIRS"," 3. Check directory exists and is readable"," 4. Consider whitelisting allowed directories"," 5. Add rate limiting to prevent enumeration attacks"].join("\n");default:return[" 1. Identify the specific file operation needed"," 2. Define safe base directories for operations"," 3. Use path.resolve() and validate containment"," 4. Sanitize user input (basename, extension validation)"," 5. Add comprehensive error handling"].join("\n")}};exports.generateRefactoringSteps=generateRefactoringSteps;const PATH_BUILDERS=new Set(["join","resolve"]);const FS_MODULE_EQUIVALENTS={"fs-extra":"fs","graceful-fs":"fs","fs/promises":"fs"};const determineRiskLevel=(operation,pathStr)=>{if(hasTraversalPatterns(pathStr)){return"CRITICAL"}if(operation.dangerous){return"HIGH"}return"MEDIUM"};exports.determineRiskLevel=determineRiskLevel;const GLOBAL_DIRECTIVE=/^\s*globals?\s([\s\S]*)/;exports.detectNonLiteralFsFilename=(0,eslint_devkit_2.createRule)({name:"detect-non-literal-fs-filename",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-non-literal-fs-filename.md",description:"Detects variable in filename argument of fs calls, which might allow an attacker to access anything on your system",cwe:"CWE-22",confidence:"medium"},messages:{fsPathTraversal:(0,eslint_devkit_1.formatLLMMessage)({icon:"\u{1F511}",issueName:"Path traversal",cwe:"CWE-22",description:"Path traversal vulnerability",severity:"{{riskLevel}}",fix:"{{safePattern}} \u2014 Not a finding when the value is path.basename()d, checked against an allowlist, or resolved and then prefix-checked WITH a trailing separator",documentationLink:"https://owasp.org/www-community/attacks/Path_Traversal"})},schema:[{type:"object",properties:{taintSources:{type:"array",items:{type:"string"},default:["process"],description:"Identifier roots treated as attacker-reachable. Default: ['process'] (process.argv and process.env). Request roots (req/request/ctx/event) are deliberately NOT included \u2014 no-arbitrary-file-access owns those, and listing them here would double-report one line at two severities. Add them only if you run this rule without that one."},reportUnresolvedPaths:{type:"boolean",default:false,description:"Report paths whose provenance cannot be resolved. Restores the pre-inversion behaviour; measured at 7% precision on real code."},reportWholeProcessValues:{type:"boolean",default:false,description:"Report process.argv / process.env used as the whole path (fs.readFileSync(process.argv[2])). Off by default: whoever sets argv or the environment already chooses which files the process opens. True matches eslint-plugin-security."},allowLiterals:{type:"boolean",default:false,description:"Silence hardcoded paths altogether. With the default (false) a literal reports only when it traverses (a `..` segment) into a sensitive location such as `../../etc/passwd`; a relative literal like `../config.json` never reports \u2014 measured as this rule's largest FP class on real code."},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional fs methods to check"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowLiterals:false,additionalMethods:[]}],createOnce(context){let allowLiterals;let additionalMethods;let WHOLE_VALUE_TRUSTED_ROOTS;let AMBIGUOUS_ROOTS;let REQUEST_SURFACE;let taintRoots;let reportUnresolvedPaths;let PATH_ARGUMENT_INDICES;let dangerousMethods;let pendingCalls;const resolvedVariable=id=>context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id).resolved;const readsRequestSurface=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),REQUEST_SURFACE);const hasRequestEvidence=variable=>variable.references.some(ref=>readsRequestSurface(ref.identifier.parent));const isLocallyConstructed=id=>{const variable=resolvedVariable(id);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1){return false}const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression};const constBindingInit=id=>{const variable=resolvedVariable(id);if(!variable||variable.defs.length!==1)return void 0;const def=variable.defs[0];if(def.type!=="Variable")return void 0;const declarator=def.node;if(def.parent.kind!=="const")return void 0;return declarator.init??void 0};const viaConst=(id,onPath,walk)=>{const init=constBindingInit(id);if(init===void 0||onPath.has(init))return false;onPath.add(init);const verdict=walk(init,onPath);onPath.delete(init);return verdict};const readsTaintSource=(rawNode,onPath=new Set)=>{const node=(0,eslint_devkit_1.unwrapTypeSyntax)(rawNode);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name)){if(AMBIGUOUS_ROOTS.has(node.name)){const variable=resolvedVariable(node);if(variable!==null&&!hasRequestEvidence(variable))return false}return!isLocallyConstructed(node)}return viaConst(node,onPath,readsTaintSource)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if(node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="process"&&!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),PROCESS_INPUT_MEMBERS)){return false}return readsTaintSource(node.object,onPath)}case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>readsTaintSource(e,onPath));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return readsTaintSource(node.left,onPath)||readsTaintSource(node.right,onPath);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"&&(0,eslint_devkit_1.propertyName)(callee)==="basename"){return false}if((0,eslint_devkit_1.isModuleBinding)(callee,context.sourceCode.getScope(callee),"path",["basename"])){return false}return node.arguments.some(arg=>readsTaintSource(arg,onPath))}default:return false}};const containsUntrustedRoot=(node,onPath=new Set)=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return!WHOLE_VALUE_TRUSTED_ROOTS.has(node.name);return viaConst(node,onPath,containsUntrustedRoot)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return containsUntrustedRoot(node.object,onPath);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>containsUntrustedRoot(e,onPath));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return containsUntrustedRoot(node.left,onPath)||containsUntrustedRoot(node.right,onPath);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>containsUntrustedRoot(a,onPath));default:return false}};const isWholeTaintValue=(node,onPath=new Set)=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return WHOLE_VALUE_TRUSTED_ROOTS.has(node.name);return viaConst(node,onPath,isWholeTaintValue)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isWholeTaintValue(node.object,onPath);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;const isPathCall=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"||(0,eslint_devkit_1.resolveModuleBinding)(callee,context.sourceCode.getScope(callee),{})?.module==="path";if(!isPathCall)return false;return isWholeTaintValue(node.arguments[0],onPath)&&!containsUntrustedRoot(node)}default:return false}};const isDangerousPath=pathNode=>{if(!pathNode)return reportUnresolvedPaths;const literal=(0,eslint_devkit_1.staticString)(pathNode);if(literal!==null){return!allowLiterals&&targetsSensitiveLocation(literal)}if(hasPathValidation(pathNode))return false;if(readsTaintSource(pathNode))return!isWholeTaintValue(pathNode);if(isBuildTimeConstant(pathNode))return false;if(containsFreeVariable(pathNode))return true;return reportUnresolvedPaths};let commentGlobals;const readGlobalComments=()=>{const names=new Set;for(const comment of context.sourceCode.getAllComments()){const directive=comment.type==="Block"&&GLOBAL_DIRECTIVE.exec(comment.value);if(!directive)continue;const body=directive[1].split(/\s-{2,}\s/)[0].replace(/\s*:\s*/g,":");for(const[item]of body.matchAll(/[^\s,]+/g)){const[global,value]=item.split(":");if(value==="off")names.delete(global);else names.add(global)}}return names};const declaredByGlobalComment=name=>{commentGlobals??=readGlobalComments();return commentGlobals.has(name)};function isFreeVariable(node){const through=context.sourceCode.getScope(node).through;return through.some(ref=>ref.identifier===node&&!declaredByGlobalComment(ref.identifier.name)&&ref.resolved===null)}const containsFreeVariable=node=>{if(isBuildTimeConstant(node))return false;if(isFreeVariable(node))return true;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>containsFreeVariable(e));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>containsFreeVariable(a));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return containsFreeVariable(node.left)||containsFreeVariable(node.right);case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return node.computed&&containsFreeVariable(node.property);default:return false}};const isBuildTimeConstant=(node,onPath=new Set)=>{const literal=(0,eslint_devkit_1.staticString)(node);if(literal!==null){return!hasTraversalPatterns(literal)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(node.name==="__dirname"||node.name==="__filename")return true;return viaConst(node,onPath,isBuildTimeConstant)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const literalText=node.quasis.map(q=>q.value.raw).join("");if(hasTraversalPatterns(literalText))return false;return node.expressions.every(e=>isBuildTimeConstant(e,onPath))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="process"&&(0,eslint_devkit_1.propertyName)(callee)==="cwd"){return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),PATH_BUILDERS)){return node.arguments.length>0&&node.arguments.every(arg=>isBuildTimeConstant(arg,onPath))}return false}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return isBuildTimeConstant(node.left,onPath)&&isBuildTimeConstant(node.right,onPath)}return false};const hasPathValidation=pathNode=>{if(pathNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){const parts=[];const collect=n=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){collect(n.left);collect(n.right);return}if(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){n.expressions.forEach(e=>collect(e));return}if(n.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){n.arguments.forEach(a=>collect(a));return}if(readsTaintSource(n))parts.push(n)};collect(pathNode);return parts.length>0&&parts.every(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&hasPathValidation(p))}const varName=pathNode.name;const isValidationCall=testNode=>{if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&testNode.operator==="!"&&testNode.argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){testNode=testNode.argument}if(testNode.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression){return false}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&testNode.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.callee.object.name===varName&&((0,eslint_devkit_1.propertyName)(testNode.callee)==="startsWith"||(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes")){return(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes"?true:(0,separator_anchored_1.isSeparatorAnchored)(testNode.arguments[0],context.sourceCode)}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes"){for(const arg of testNode.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.name===varName){return true}}}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(testNode.callee)==="test"){for(const arg of testNode.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.name===varName){return true}}}return false};const hasEarlyExit=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement};let child=pathNode;let current=pathNode.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&isValidationCall(current.test)){return true}if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=current.body;const index=body.indexOf(child);for(let i=0;i<index;i++){const stmt=body[i];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&isValidationCall(stmt.test)&&hasEarlyExit(stmt.consequent)){return true}}}child=current;current=current.parent}return false};const checkFsCall=node=>{const scope=context.sourceCode.getScope(node);const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope,{equivalents:FS_MODULE_EQUIVALENTS})??(0,module_binding_1.undeclaredFsBinding)(node.callee,scope);if(binding?.module!=="fs")return;const[first,second]=binding.path;const methodName=binding.path.length===1?first:binding.path.length===2&&first==="promises"?second:void 0;if(methodName===void 0)return;if(!dangerousMethods.has(methodName)){return}const method=methodName;const indices=PATH_ARGUMENT_INDICES.get(method)??[0];const pathNode=indices.map(index=>node.arguments[index]).find(candidate=>candidate!==void 0&&isDangerousPath(candidate))??null;if(pathNode===null){if(node.arguments.length===0&&isDangerousPath(null)){context.report({node,messageId:"fsPathTraversal",data:{riskLevel:"MEDIUM",safePattern:"Use path.resolve() with validation"}})}return}const operation=FS_OPERATIONS.find(op=>op.method===method);context.report({node,messageId:"fsPathTraversal",data:{riskLevel:(0,exports.determineRiskLevel)(operation??FS_OPERATIONS[0],context.sourceCode.getText(pathNode)),safePattern:operation?.safePattern??"Use path.resolve() with validation"}})};return{before(){const options=context.options[0]||{};({allowLiterals=false,additionalMethods=[]}=options);commentGlobals=void 0;const DEFAULT_TAINT_ROOTS=["process","req","request","ctx","context","event"];WHOLE_VALUE_TRUSTED_ROOTS=new Set(options.reportWholeProcessValues?[]:["process"]);AMBIGUOUS_ROOTS=new Set(["ctx","context"]);REQUEST_SURFACE=new Set(["query","params","body","request","req","headers","cookies","searchParams","originalUrl"]);taintRoots=new Set(options.taintSources??DEFAULT_TAINT_ROOTS);reportUnresolvedPaths=options.reportUnresolvedPaths??false;PATH_ARGUMENT_INDICES=new Map([["copyFile",[0,1]],["copyFileSync",[0,1]],["cp",[0,1]],["cpSync",[0,1]],["rename",[0,1]],["renameSync",[0,1]],["link",[0,1]],["linkSync",[0,1]],["symlink",[0,1]],["symlinkSync",[0,1]]]);dangerousMethods=new Set(["readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","stat","statSync","lstat","lstatSync","readdir","readdirSync","unlink","unlinkSync","mkdir","mkdirSync","rmdir","rmdirSync","access","accessSync","createReadStream","createWriteStream","open","openSync","rm","rmSync","rename","renameSync","copyFile","copyFileSync","cp","cpSync","truncate","truncateSync","chmod","chmodSync","chown","chownSync","lchown","lchownSync","utimes","utimesSync","readlink","readlinkSync","symlink","symlinkSync","link","linkSync","opendir","opendirSync",...additionalMethods]);pendingCalls=[]},CallExpression(node){pendingCalls.push(node)},"Program:exit"(){for(const call of pendingCalls)checkFsCall(call)}}}});