eslint-plugin-node-security 4.13.0 → 5.0.0

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.
Files changed (46) hide show
  1. package/README.md +40 -1
  2. package/package.json +2 -2
  3. package/src/index.js +1 -1
  4. package/src/rules/detect-child-process/index.js +1 -1
  5. package/src/rules/detect-eval-with-expression/index.js +1 -1
  6. package/src/rules/detect-non-literal-fs-filename/index.js +1 -1
  7. package/src/rules/detect-suspicious-dependencies/index.js +1 -1
  8. package/src/rules/lock-file/index.js +1 -1
  9. package/src/rules/no-buffer-overread/index.js +1 -1
  10. package/src/rules/no-cryptojs/index.js +1 -1
  11. package/src/rules/no-cryptojs-weak-random/index.js +1 -1
  12. package/src/rules/no-data-in-temp-storage/index.js +1 -1
  13. package/src/rules/no-deprecated-buffer/index.js +1 -1
  14. package/src/rules/no-deprecated-cipher-method/index.js +1 -1
  15. package/src/rules/no-dynamic-command-string/index.js +1 -1
  16. package/src/rules/no-dynamic-dependency-loading/index.js +1 -1
  17. package/src/rules/no-dynamic-require/index.js +1 -1
  18. package/src/rules/no-ecb-mode/index.js +1 -1
  19. package/src/rules/no-env-injection/index.js +1 -1
  20. package/src/rules/no-insecure-http-parser/index.js +1 -1
  21. package/src/rules/no-insecure-key-derivation/index.js +1 -1
  22. package/src/rules/no-insecure-rsa-padding/index.js +1 -1
  23. package/src/rules/no-math-random-crypto/index.js +1 -1
  24. package/src/rules/no-self-signed-certs/index.js +1 -1
  25. package/src/rules/no-sha1-hash/index.js +1 -1
  26. package/src/rules/no-shell-injection/index.js +1 -1
  27. package/src/rules/no-ssrf/index.js +1 -1
  28. package/src/rules/no-static-iv/index.js +1 -1
  29. package/src/rules/no-timing-unsafe-compare/index.js +1 -1
  30. package/src/rules/no-toctou-vulnerability/index.js +1 -1
  31. package/src/rules/no-unbounded-decompression/index.js +1 -1
  32. package/src/rules/no-unsafe-buffer-alloc/index.js +1 -1
  33. package/src/rules/no-unsafe-dynamic-require/index.js +1 -1
  34. package/src/rules/no-weak-cipher-algorithm/index.js +1 -1
  35. package/src/rules/no-weak-hash-algorithm/index.js +1 -1
  36. package/src/rules/no-zip-slip/index.js +1 -1
  37. package/src/rules/prefer-native-crypto/index.js +1 -1
  38. package/src/rules/require-aead-tag-verification/index.js +1 -1
  39. package/src/rules/require-dependency-integrity/index.js +1 -1
  40. package/src/rules/require-secure-credential-storage/index.js +1 -1
  41. package/src/rules/require-secure-deletion/index.js +1 -1
  42. package/src/rules/require-storage-encryption/index.js +1 -1
  43. package/src/rules/require-stream-error-handler/index.js +1 -1
  44. package/src/utils/const-value.js +1 -0
  45. package/src/utils/credential-evidence.js +1 -0
  46. package/src/utils/provenance.js +1 -1
package/README.md CHANGED
@@ -31,6 +31,45 @@ This plugin provides Security rules for Node.js core modules (fs, child_process,
31
31
 
32
32
  **Interlace** fosters **strength through integration**. Instead of stacking isolated rules, we **interlace** security directly into your workflow to create a resilient fabric of code. We believe tools should **guide rather than gatekeep**, providing educational feedback that strengthens the developer with every interaction.
33
33
 
34
+ <!-- AUTO-GENERATED:DOCTRINE:START - Do not edit manually -->
35
+
36
+ ## Why these rules are quiet
37
+
38
+ **Noise creates apathy, and apathy is not a security posture.** A linter that reports
39
+ a thousand things a week gets switched off in a month, and the real finding goes with
40
+ it. So every rule here is built to be worth reading: we would rather miss a finding
41
+ than spend your attention on one that was never real.
42
+
43
+ That is a trade, and it is made deliberately. It costs recall, and we measure what it
44
+ costs rather than assuming it is free.
45
+
46
+ ## How the rules decide
47
+
48
+ **Evidence, not names.** A rule fires on what the code *does*, resolved through the
49
+ AST and ESLint's own scope analysis — not on an identifier that happens to contain
50
+ `query`, a method called `setItem`, or a file whose path contains `key`. Every one of
51
+ those was a real false positive in this ecosystem, found by reading our own output on
52
+ open-source projects and fixed with a test that fails on the unfixed rule.
53
+
54
+ Where a rule has known false-positive shapes, its page carries a **Not a finding**
55
+ section: what it deliberately stays quiet on, and what to check first when it fires
56
+ and you disagree.
57
+
58
+ ## What you get
59
+
60
+ The rules below. Security rules carry a CWE mapping and, where one is assigned, a
61
+ CVSS score; every rule carries a fix on its message — in prose for a human and as
62
+ structured JSON for an agent. Install it, enable
63
+ `recommended`, and read the findings. If one of them is wrong,
64
+ [open an issue](https://github.com/ofri-peretz/eslint/issues) — a false positive is a
65
+ bug here, not a tuning exercise for you.
66
+
67
+ How that is measured, on which projects, and where it falls short:
68
+ [benchmark methodology](https://github.com/ofri-peretz/eslint/blob/main/BENCHMARK-METHODOLOGY.md)
69
+ and [results](https://github.com/ofri-peretz/eslint/blob/main/BENCHMARK-RESULTS.md).
70
+
71
+ <!-- AUTO-GENERATED:DOCTRINE:END -->
72
+
34
73
  ## Getting Started
35
74
 
36
75
  - To check out the [guide](https://eslint.interlace.tools/docs/security/plugin-node-security?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security), visit [eslint.interlace.tools](https://eslint.interlace.tools/?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security). 📚
@@ -124,7 +163,7 @@ See the [ESLint Version Support Policy](../../docs/ESLINT_VERSION_SUPPORT.md)
124
163
  | [prefer-native-crypto](https://eslint.interlace.tools/docs/security/plugin-node-security/rules/prefer-native-crypto?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security) | CWE-1104 | A06:2021 | | Prefer native crypto over third-party libraries | 🟢 | | | | | |
125
164
  | [require-aead-tag-verification](https://eslint.interlace.tools/docs/security/plugin-node-security/rules/require-aead-tag-verification?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security) | CWE-327 | A02:2021 | | Require AEAD decryption to verify the authentication tag (setAuthTag + final) | 🟢 | 💼 | | | | |
126
165
  | [require-dependency-integrity](https://eslint.interlace.tools/docs/security/plugin-node-security/rules/require-dependency-integrity?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security) | CWE-494 | | | CWE: [CWE-494](https://cwe.mitre.org/data/definitions/494.html) | 🟢 | 💼 | | | | |
127
- | [require-secure-credential-storage](https://eslint.interlace.tools/docs/security/plugin-node-security/rules/require-secure-credential-storage?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security) | CWE-312 | | | This rule detects when credentials are stored using localStorage.setItem() or fs.writeFile() without encryp… | 🟢 | | | | | |
166
+ | [require-secure-credential-storage](https://eslint.interlace.tools/docs/security/plugin-node-security/rules/require-secure-credential-storage?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security) | CWE-312 | | | This rule detects a credential written to localStorage, sessionStorage or AsyncStorage without encryption | 🟢 | | | | | |
128
167
  | [require-secure-deletion](https://eslint.interlace.tools/docs/security/plugin-node-security/rules/require-secure-deletion?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security) | CWE-459 | | | CWE: [CWE-459](https://cwe.mitre.org/data/definitions/459.html) | 🟢 | | | | | |
129
168
  | [require-storage-encryption](https://eslint.interlace.tools/docs/security/plugin-node-security/rules/require-storage-encryption?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security) | CWE-312 | | | CWE: [CWE-312](https://cwe.mitre.org/data/definitions/312.html) | 🟢 | | | | | |
130
169
  | [require-stream-error-handler](https://eslint.interlace.tools/docs/security/plugin-node-security/rules/require-stream-error-handler?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-node-security) | CWE-248 | A04:2021 | | Require an error listener on streams passed to pipe, which does not forward errors | 🟢 | 💼 | | | | |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-node-security",
3
- "version": "4.13.0",
3
+ "version": "5.0.0",
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
  "main": "./src/index.js",
@@ -79,7 +79,7 @@
79
79
  "node": ">=18.0.0"
80
80
  },
81
81
  "dependencies": {
82
- "@interlace/eslint-devkit": "^1.15.0"
82
+ "@interlace/eslint-devkit": "^1.16.1"
83
83
  },
84
84
  "peerDependencies": {
85
85
  "eslint": "^8.40.0 || ^9.0.0 || ^10.0.0"
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-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:"4.13.0"},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-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-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:"5.0.0"},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-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.detectChildProcess=exports.generateRefactoringSteps=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const DEFAULT_TAINT_SOURCES=["req","request","ctx","event","process"];const LOCAL_TAINT_ROOT="process";const SHELL_BINARIES=new Set(["sh","bash","zsh","dash","ksh","csh","tcsh","fish","ash","busybox","cmd","cmd.exe","powershell","powershell.exe","pwsh","pwsh.exe","env"]);const EVAL_FLAGS=new Set(["-c","-e","--eval","-e:","/c","/k","-command","-encodedcommand"]);const COMMAND_PATTERNS=[{method:"exec",dangerous:true,vulnerability:"command-injection",safeAlternatives:["execFile","spawn"],example:{bad:"exec(`git clone ${repoUrl}`)",good:["execFile('git', ['clone', repoUrl], {shell: false})","spawn('git', ['clone', repoUrl], {shell: false})"]},effort:"15-25 minutes"},{method:"execSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["execFileSync","spawnSync"],example:{bad:"execSync(`npm install ${packageName}`)",good:["execFileSync('npm', ['install', packageName], {shell: false})","spawnSync('npm', ['install', packageName], {shell: false})"]},effort:"15-25 minutes"},{method:"spawn",dangerous:false,vulnerability:"argument-injection",safeAlternatives:["spawn with validation"],example:{bad:"spawn('bash', ['-c', userCommand])",good:["spawn(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"20-30 minutes"},{method:"execFile",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawn"],example:{bad:"execFile(userCommand, userArgs, callback)",good:["spawn(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"10-15 minutes"},{method:"execFileSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawnSync"],example:{bad:"execFileSync(userCommand, userArgs)",good:["spawnSync(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"10-15 minutes"},{method:"spawnSync",dangerous:false,vulnerability:"argument-injection",safeAlternatives:["spawnSync with validation"],example:{bad:"spawnSync('bash', ['-c', userCommand])",good:["spawnSync(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"15-20 minutes"},{method:"fork",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawn"],example:{bad:"fork(userScript)",good:["spawn('node', [validatedScript], {shell: false})","// Validate script path first"]},effort:"15-20 minutes"},{method:"forkSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawnSync"],example:{bad:"forkSync(userScript)",good:["spawnSync('node', [validatedScript], {shell: false, stdio: 'inherit'})","// Validate script path first"]},effort:"15-20 minutes"}];const generateRefactoringSteps=pattern=>{switch(pattern.method){case"exec":case"execSync":return[" 1. Replace exec() with execFile() or spawn()"," 2. Split command and arguments into separate array elements"," 3. Use {shell: false} option to prevent shell interpretation"," 4. Validate and sanitize all user inputs"," 5. Consider using execa library for better security"].join("\n");case"spawn":return[" 1. Ensure first argument is a safe, validated command path"," 2. Pass arguments as separate array elements"," 3. Use {shell: false} to prevent shell injection"," 4. Validate command exists and is executable"," 5. Consider using cross-spawn for cross-platform safety"].join("\n");case"execFile":return[" 1. Replace execFile() with spawn() for better security"," 2. Validate command path before execution"," 3. Ensure arguments are properly sanitized"," 4. Use {shell: false} option"," 5. Consider using execa library"].join("\n");case"execFileSync":return[" 1. Replace execFileSync() with spawnSync() for better security"," 2. Validate command path before execution"," 3. Ensure arguments are properly sanitized"," 4. Use {shell: false} option"," 5. Consider using execa library"].join("\n");case"spawnSync":return[" 1. Ensure first argument is a safe, validated command path"," 2. Pass arguments as separate array elements"," 3. Use {shell: false} to prevent shell injection"," 4. Validate command exists and is executable"," 5. Handle synchronous execution properly"].join("\n");case"fork":return[" 1. Replace fork() with spawn() for Node.js scripts"," 2. Validate script path exists and is readable"," 3. Use spawn('node', [scriptPath], options) instead"," 4. Add proper error handling"," 5. Consider using child_process.execFile() for simple scripts"].join("\n");case"forkSync":return[" 1. Replace forkSync() with spawnSync() for Node.js scripts"," 2. Validate script path exists and is readable"," 3. Use spawnSync('node', [scriptPath], options) instead"," 4. Add proper error handling and synchronous waiting"," 5. Consider using child_process.execFileSync() for simple scripts"].join("\n");default:return[" 1. Identify the specific command execution need"," 2. Choose appropriate child_process method"," 3. Use argument arrays instead of string interpolation"," 4. Add comprehensive input validation"," 5. Test with malicious inputs"].join("\n")}};exports.generateRefactoringSteps=generateRefactoringSteps;exports.detectChildProcess=(0,eslint_devkit_2.createRule)({name:"detect-child-process",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-child-process.md",description:"Detects child_process usage that may allow command injection",cwe:"CWE-78",cvss:9.8,confidence:"medium"},hasSuggestions:true,messages:{childProcessCommandInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Command injection",cwe:"CWE-78",description:"Command injection detected",severity:"CRITICAL",fix:"Use execFile/spawn with {shell: false} and array args",documentationLink:"https://owasp.org/www-community/attacks/Command_Injection"}),argumentInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Argument injection",cwe:"CWE-88",description:"An attacker-steered value sits in the argv vector with no `--` before it. There is no shell here, but the callee still parses a leading `-` as an option \u2014 `--upload-pack=` (git), `--to-command=` (tar), `-o ProxyCommand=` (ssh) all execute arbitrary programs.",severity:"HIGH",fix:"Insert a literal '--' before the first attacker-controlled element, or reject values beginning with '-'.",documentationLink:"https://cwe.mitre.org/data/definitions/88.html"}),useEndOfOptions:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use end-of-options",description:"Add a literal '--' before user-controlled arguments",severity:"LOW",fix:"execFile('git', ['ls-remote', '--', remote])",documentationLink:"https://cwe.mitre.org/data/definitions/88.html"}),useExecFile:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use execFile",description:"Use execFile() with argument array",severity:"LOW",fix:"execFile(cmd, [arg1, arg2], { shell: false })",documentationLink:"https://nodejs.org/api/child_process.html#child_processexecfilefile-args-options-callback"}),useSpawn:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use spawn",description:"Use spawn() with separate arguments",severity:"LOW",fix:"spawn(cmd, [arg1, arg2], { shell: false })",documentationLink:"https://nodejs.org/api/child_process.html#child_processspawncommand-args-options"}),useSaferLibrary:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Safer Library",description:"Consider safer command execution libraries",severity:"LOW",fix:"Use execa, zx, or cross-spawn instead",documentationLink:"https://github.com/sindresorhus/execa"}),validateInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Validate Input",description:"Add input validation and sanitization",severity:"LOW",fix:"Validate user input before passing to command",documentationLink:"https://owasp.org/www-community/attacks/Command_Injection"}),useShellFalse:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Disable Shell",description:"Use shell: false option",severity:"LOW",fix:"{ shell: false } to prevent shell interpretation",documentationLink:"https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows"}),strategyValidate:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.STRATEGY,issueName:"Validate Strategy",description:"Comprehensive input validation",severity:"LOW",fix:"Add allowlist validation before command execution",documentationLink:"https://owasp.org/www-community/attacks/Command_Injection"}),strategySanitize:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.STRATEGY,issueName:"Sanitize Strategy",description:"Sanitize and escape command arguments",severity:"LOW",fix:"Escape special characters in command arguments",documentationLink:"https://owasp.org/www-community/attacks/Command_Injection"}),strategyRestrict:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.STRATEGY,issueName:"Restrict Strategy",description:"Restrict to predefined safe commands",severity:"LOW",fix:"Define allowlist of permitted commands",documentationLink:"https://owasp.org/www-community/attacks/Command_Injection"})},schema:[{type:"object",properties:{allowLiteralStrings:{type:"boolean",default:false,description:"Allow exec() with literal strings"},allowLiteralSpawn:{type:"boolean",default:false,description:"Allow spawn() with literal arguments"},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional child_process methods to check"},strategy:{type:"string",enum:["validate","sanitize","restrict","auto"],default:"auto",description:"Strategy for fixing command injection (auto = smart detection)"},taintSources:{type:"array",items:{type:"string"},default:DEFAULT_TAINT_SOURCES,description:"Identifier roots treated as attacker-reachable (default: req, request, ctx, event, process)"},reportUnresolvedCommands:{type:"boolean",default:false,description:'Report a command whose provenance cannot be resolved. Restores the pre-inversion "any dynamic argument is dangerous" behaviour.'}},additionalProperties:false}]},defaultOptions:[{allowLiteralStrings:false,allowLiteralSpawn:false,additionalMethods:[],strategy:"auto"}],create(context){const options=context.options[0]||{};const{allowLiteralStrings=false,allowLiteralSpawn=false,additionalMethods=[]}=options;const taintRoots=new Set((options.taintSources??DEFAULT_TAINT_SOURCES).map(source=>source.toLowerCase()));const readsTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,taintRoots);const readsRemoteTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,new Set([...taintRoots].filter(root=>root!==LOCAL_TAINT_ROOT)));const reportUnresolvedCommands=options.reportUnresolvedCommands??false;const dangerousMethodsSet=new Set(["exec","execSync","execFile","execFileSync","spawn","spawnSync","fork","forkSync",...additionalMethods]);const isChildProcessSpecifier=value=>value==="child_process"||value==="node:child_process";const moduleAliases=new Set(["child_process"]);const importedMethods=new Set;const containsDynamicStrings=node=>!(0,eslint_devkit_2.isStaticExpression)({node,scope:context.sourceCode.getScope(node)});const isFreeReference=node=>{const name=node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node:node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.callee:null;if(!name)return false;return context.sourceCode.getScope(name).through.some(ref=>ref.identifier===name&&ref.resolved===null)};const isStaticArg=argument=>(0,eslint_devkit_2.isStaticExpression)({node:argument,scope:context.sourceCode.getScope(argument)});const hasOnlyLiteralArgs=args=>{if(args.length===0)return false;if(!isStaticArg(args[0])){return false}if(args.length>=2){const argsArray=args[1];if(argsArray.type==="ArrayExpression"){const allLiteralElements=argsArray.elements.every(el=>el!==null&&isStaticArg(el));if(!allLiteralElements){return false}}else if(!isStaticArg(argsArray)){return false}}return true};const usesShell=(node,method)=>{if(method==="exec"||method==="execSync")return true;const command=node.arguments[0];if(command!==void 0&&command.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof command.value==="string"&&SHELL_BINARIES.has(command.value.replace(/^.*[/\\]/,"").toLowerCase())){return true}const argv=node.arguments[1];if(argv?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){for(const element of argv.elements){if(element?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof element.value==="string"&&EVAL_FLAGS.has(element.value.toLowerCase())){return true}}}for(const candidate of[node.arguments[1],node.arguments[2]]){if(!candidate||candidate.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)continue;for(const property of candidate.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||property.key.name!=="shell"){continue}return!(property.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.value.value===false)}}return false};const cannotStartWithDash=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const first=node.quasis[0].value.raw;return first.length>0&&!first.startsWith("-")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=node.left;return left.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof left.value==="string"&&left.value.length>0&&!left.value.startsWith("-")}return false};const argumentInjectionSite=node=>{const argv=node.arguments[1];if(argv?.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;for(const element of argv.elements){if(element===null)continue;if(element.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&element.value==="--"){return null}if(!readsRemoteTaintSource(element))continue;const target=element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement?element.argument:element;if(cannotStartWithDash(target))continue;return element}return null};const hasShellFalseOption=node=>{const optionsArg=node.arguments[2];if(!optionsArg||optionsArg.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){return true}for(const prop of optionsArg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="shell"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value===false){return true}return false}}return true};const hasPrecedingAllowlistValidation=node=>{const makeArgChecker=validatedVarNames=>{const check=argNode=>{if(argNode.type==="Identifier"&&validatedVarNames.has(argNode.name))return true;if(argNode.type==="TemplateLiteral"){return argNode.expressions.some(e=>e.type==="Identifier"&&validatedVarNames.has(e.name))}if(argNode.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return argNode.elements.some(el=>el!==null&&check(el))}return false};return check};const checkGuardClause=ifNode=>{const test=ifNode.test;if(test.type==="CallExpression"&&test.callee.type==="MemberExpression"&&test.callee.property.type==="Identifier"&&test.callee.property.name==="includes"){const validatedVarNames=new Set;for(const testArg of test.arguments){if(testArg.type==="Identifier")validatedVarNames.add(testArg.name)}const check=makeArgChecker(validatedVarNames);for(const arg of node.arguments){if(check(arg))return true}}if(test.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&test.operator==="!"&&test.argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&test.argument.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&test.argument.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&test.argument.callee.property.name==="includes"){const consequent=ifNode.consequent;const isGuardBody=consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&consequent.body.length>0&&(consequent.body[0].type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||consequent.body[0].type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement);if(isGuardBody){const validatedVarNames=new Set;for(const testArg of test.argument.arguments){if(testArg.type==="Identifier")validatedVarNames.add(testArg.name)}const check=makeArgChecker(validatedVarNames.size>0?validatedVarNames:new Set(["*"]));if(validatedVarNames.size>0){for(const arg of node.arguments){if(check(arg))return true}}else{for(const arg of node.arguments){if(arg.type==="Identifier"||arg.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&arg.elements.some(el=>el?.type==="Identifier")){return true}}}}}return false};let current=node.parent;while(current){if(current.type==="IfStatement"){if(checkGuardClause(current))return true}current=current.parent}let stmt=node.parent;while(stmt&&stmt.parent&&stmt.parent.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement){stmt=stmt.parent}if(stmt&&stmt.parent&&stmt.parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const block=stmt.parent;const callIndex=block.body.indexOf(stmt);if(callIndex>0){for(let i=0;i<callIndex;i++){const sibling=block.body[i];if(sibling.type==="IfStatement"){if(checkGuardClause(sibling))return true}}}}return false};const extractCommandInfo=(node,method)=>{const sourceCode=context.sourceCode;const args=node.arguments.map(arg=>sourceCode.getText(arg)).join(", ");const pattern=COMMAND_PATTERNS.find(p=>p.method===method)||null;const injectableArgs=node.arguments.slice(0,1);const argvArray=node.arguments[1];if(argvArray?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){injectableArgs.push(...argvArray.elements.filter(el=>el!==null))}const isDynamic=injectableArgs.some(arg=>containsDynamicStrings(arg));return{args,pattern,isDynamic}};const determineRiskLevel=(pattern,isDynamic)=>{if(pattern?.dangerous&&isDynamic){return"critical"}if(pattern?.dangerous||isDynamic){return"high"}return"medium"};const isChildProcessRequire=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&isChildProcessSpecifier(node.arguments[0].value);const getChildProcessCall=node=>{if(node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"){const methodName=node.callee.property.name;if(!dangerousMethodsSet.has(methodName)){return null}if(node.callee.object.type==="Identifier"&&moduleAliases.has(node.callee.object.name)){return{method:methodName,calleeNode:node.callee}}if(isChildProcessRequire(node.callee.object)){return{method:methodName,calleeNode:node.callee}}}if(node.callee.type==="Identifier"&&dangerousMethodsSet.has(node.callee.name)){if(importedMethods.has(node.callee.name)){return{method:node.callee.name,calleeNode:node.callee}}}return null};const checkChildProcessCall=node=>{const detected=getChildProcessCall(node);if(!detected){return}const{method}=detected;const{args,pattern,isDynamic}=extractCommandInfo(node,method);if((method==="exec"||method==="execSync")&&!isDynamic&&hasOnlyLiteralArgs(node.arguments)){return}if(allowLiteralStrings&&method==="exec"&&!isDynamic){return}const saferMethods=new Set(["spawn","spawnSync","execFile","execFileSync"]);if(allowLiteralSpawn&&saferMethods.has(method)&&hasOnlyLiteralArgs(node.arguments)){return}if(saferMethods.has(method)&&hasOnlyLiteralArgs(node.arguments)){const isExecFile=method==="execFile"||method==="execFileSync";if(isExecFile||hasShellFalseOption(node)){return}}const allSafeMethods=["execFile","execFileSync","spawn","spawnSync"];if(allSafeMethods.includes(method)&&hasPrecedingAllowlistValidation(node)){return}const command=node.arguments[0];const commandIsSteerable=command===void 0||isFreeReference(command)||readsRemoteTaintSource(command);if(!usesShell(node,method)&&!commandIsSteerable){const injected=argumentInjectionSite(node);if(injected===null)return;context.report({node:injected,messageId:"argumentInjection",suggest:[{messageId:"useEndOfOptions",fix:()=>null},{messageId:"validateInput",fix:()=>null}]});return}const injectablePositions=node.arguments.slice(0,1);const argvVector=node.arguments[1];if(argvVector?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){injectablePositions.push(...argvVector.elements.filter(el=>el!==null))}const unknowable=injectablePositions.some(argument=>isFreeReference(argument));if(!reportUnresolvedCommands&&!unknowable&&!node.arguments.some(argument=>readsTaintSource(argument))){return}const riskLevel=determineRiskLevel(pattern,isDynamic);const steps=pattern?(0,exports.generateRefactoringSteps)(pattern):"Review and secure command execution";const alternatives=pattern?.safeAlternatives.join(", ")||"execFile, spawn with validation";context.report({node,messageId:"childProcessCommandInjection",data:{method,args,riskLevel,vulnerability:pattern?.vulnerability||"command injection",alternatives,steps,effort:pattern?.effort||"15-30 minutes"},suggest:[{messageId:"useExecFile",fix:()=>null},{messageId:"useSpawn",fix:()=>null},{messageId:"useSaferLibrary",fix:()=>null},{messageId:"validateInput",fix:()=>null},{messageId:"useShellFalse",fix:()=>null}]})};const trackChildProcessImport=node=>{if(!isChildProcessSpecifier(node.source.value)){return}for(const specifier of node.specifiers){if(specifier.type==="ImportDefaultSpecifier"||specifier.type==="ImportNamespaceSpecifier"){moduleAliases.add(specifier.local.name)}if(specifier.type==="ImportSpecifier"){importedMethods.add(specifier.local.name)}}};const trackChildProcessRequire=node=>{if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]&&node.init.arguments[0].type==="Literal"&&isChildProcessSpecifier(node.init.arguments[0].value)){moduleAliases.add(node.id.name);return}if(node.id.type==="ObjectPattern"&&node.init?.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]&&node.init.arguments[0].type==="Literal"&&isChildProcessSpecifier(node.init.arguments[0].value)){for(const prop of node.id.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){importedMethods.add(prop.value.type==="Identifier"?prop.value.name:prop.key.name)}}}};const checkBareChildProcessRequire=node=>{if(!isChildProcessRequire(node))return;const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===node)return;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===node)return;context.report({node,messageId:"childProcessCommandInjection",data:{method:"require",riskLevel:"MEDIUM",vulnerability:"command-injection",safeAlternatives:"execFile, spawn",refactoringSteps:" 1. Avoid importing child_process where it is not needed\n 2. If required, prefer execFile()/spawn() with {shell: false}\n 3. Validate any command or argument that is not a literal",effort:"10-15 minutes",badExample:"require('child_process')",goodExample:"const { execFile } = require('node:child_process')"}})};return{CallExpression(node){checkChildProcessCall(node);checkBareChildProcessRequire(node)},ImportDeclaration:trackChildProcessImport,VariableDeclarator:trackChildProcessRequire}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectChildProcess=exports.generateRefactoringSteps=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const DEFAULT_TAINT_SOURCES=["req","request","ctx","event","process"];const LOCAL_TAINT_ROOT="process";const SHELL_BINARIES=new Set(["sh","bash","zsh","dash","ksh","csh","tcsh","fish","ash","busybox","cmd","cmd.exe","powershell","powershell.exe","pwsh","pwsh.exe","env"]);const EVAL_FLAGS=new Set(["-c","-e","--eval","-e:","/c","/k","-command","-encodedcommand"]);const COMMAND_PATTERNS=[{method:"exec",dangerous:true,vulnerability:"command-injection",safeAlternatives:["execFile","spawn"],example:{bad:"exec(`git clone ${repoUrl}`)",good:["execFile('git', ['clone', repoUrl], {shell: false})","spawn('git', ['clone', repoUrl], {shell: false})"]},effort:"15-25 minutes"},{method:"execSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["execFileSync","spawnSync"],example:{bad:"execSync(`npm install ${packageName}`)",good:["execFileSync('npm', ['install', packageName], {shell: false})","spawnSync('npm', ['install', packageName], {shell: false})"]},effort:"15-25 minutes"},{method:"spawn",dangerous:false,vulnerability:"argument-injection",safeAlternatives:["spawn with validation"],example:{bad:"spawn('bash', ['-c', userCommand])",good:["spawn(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"20-30 minutes"},{method:"execFile",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawn"],example:{bad:"execFile(userCommand, userArgs, callback)",good:["spawn(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"10-15 minutes"},{method:"execFileSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawnSync"],example:{bad:"execFileSync(userCommand, userArgs)",good:["spawnSync(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"10-15 minutes"},{method:"spawnSync",dangerous:false,vulnerability:"argument-injection",safeAlternatives:["spawnSync with validation"],example:{bad:"spawnSync('bash', ['-c', userCommand])",good:["spawnSync(validatedCommand, validatedArgs, {shell: false})","// Validate command and args first"]},effort:"15-20 minutes"},{method:"fork",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawn"],example:{bad:"fork(userScript)",good:["spawn('node', [validatedScript], {shell: false})","// Validate script path first"]},effort:"15-20 minutes"},{method:"forkSync",dangerous:true,vulnerability:"command-injection",safeAlternatives:["spawnSync"],example:{bad:"forkSync(userScript)",good:["spawnSync('node', [validatedScript], {shell: false, stdio: 'inherit'})","// Validate script path first"]},effort:"15-20 minutes"}];const generateRefactoringSteps=pattern=>{switch(pattern.method){case"exec":case"execSync":return[" 1. Replace exec() with execFile() or spawn()"," 2. Split command and arguments into separate array elements"," 3. Use {shell: false} option to prevent shell interpretation"," 4. Validate and sanitize all user inputs"," 5. Consider using execa library for better security"].join("\n");case"spawn":return[" 1. Ensure first argument is a safe, validated command path"," 2. Pass arguments as separate array elements"," 3. Use {shell: false} to prevent shell injection"," 4. Validate command exists and is executable"," 5. Consider using cross-spawn for cross-platform safety"].join("\n");case"execFile":return[" 1. Replace execFile() with spawn() for better security"," 2. Validate command path before execution"," 3. Ensure arguments are properly sanitized"," 4. Use {shell: false} option"," 5. Consider using execa library"].join("\n");case"execFileSync":return[" 1. Replace execFileSync() with spawnSync() for better security"," 2. Validate command path before execution"," 3. Ensure arguments are properly sanitized"," 4. Use {shell: false} option"," 5. Consider using execa library"].join("\n");case"spawnSync":return[" 1. Ensure first argument is a safe, validated command path"," 2. Pass arguments as separate array elements"," 3. Use {shell: false} to prevent shell injection"," 4. Validate command exists and is executable"," 5. Handle synchronous execution properly"].join("\n");case"fork":return[" 1. Replace fork() with spawn() for Node.js scripts"," 2. Validate script path exists and is readable"," 3. Use spawn('node', [scriptPath], options) instead"," 4. Add proper error handling"," 5. Consider using child_process.execFile() for simple scripts"].join("\n");case"forkSync":return[" 1. Replace forkSync() with spawnSync() for Node.js scripts"," 2. Validate script path exists and is readable"," 3. Use spawnSync('node', [scriptPath], options) instead"," 4. Add proper error handling and synchronous waiting"," 5. Consider using child_process.execFileSync() for simple scripts"].join("\n");default:return[" 1. Identify the specific command execution need"," 2. Choose appropriate child_process method"," 3. Use argument arrays instead of string interpolation"," 4. Add comprehensive input validation"," 5. Test with malicious inputs"].join("\n")}};exports.generateRefactoringSteps=generateRefactoringSteps;exports.detectChildProcess=(0,eslint_devkit_2.createRule)({name:"detect-child-process",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-child-process.md",description:"Detects child_process usage that may allow command injection",cwe:"CWE-78",cvss:9.8,confidence:"medium"},messages:{childProcessCommandInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Command injection",cwe:"CWE-78",description:"Command injection detected",severity:"CRITICAL",fix:"Use execFile/spawn with {shell: false} and array args",documentationLink:"https://owasp.org/www-community/attacks/Command_Injection"}),argumentInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Argument injection",cwe:"CWE-88",description:"An attacker-steered value sits in the argv vector with no `--` before it. There is no shell here, but the callee still parses a leading `-` as an option \u2014 `--upload-pack=` (git), `--to-command=` (tar), `-o ProxyCommand=` (ssh) all execute arbitrary programs.",severity:"HIGH",fix:"Insert a literal '--' before the first attacker-controlled element, or reject values beginning with '-'.",documentationLink:"https://cwe.mitre.org/data/definitions/88.html"})},schema:[{type:"object",properties:{allowLiteralStrings:{type:"boolean",default:false,description:"Allow exec() with literal strings"},allowLiteralSpawn:{type:"boolean",default:false,description:"Allow spawn() with literal arguments"},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional child_process methods to check"},taintSources:{type:"array",items:{type:"string"},default:DEFAULT_TAINT_SOURCES,description:"Identifier roots treated as attacker-reachable (default: req, request, ctx, event, process)"},reportUnresolvedCommands:{type:"boolean",default:false,description:'Report a command whose provenance cannot be resolved. Restores the pre-inversion "any dynamic argument is dangerous" behaviour.'}},additionalProperties:false}]},defaultOptions:[{allowLiteralStrings:false,allowLiteralSpawn:false,additionalMethods:[]}],create(context){const options=context.options[0]||{};const{allowLiteralStrings=false,allowLiteralSpawn=false,additionalMethods=[]}=options;const taintRoots=new Set((options.taintSources??DEFAULT_TAINT_SOURCES).map(source=>source.toLowerCase()));const readsTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,taintRoots);const readsRemoteTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,new Set([...taintRoots].filter(root=>root!==LOCAL_TAINT_ROOT)));const reportUnresolvedCommands=options.reportUnresolvedCommands??false;const dangerousMethodsSet=new Set(["exec","execSync","execFile","execFileSync","spawn","spawnSync","fork","forkSync",...additionalMethods]);const isChildProcessSpecifier=value=>value==="child_process"||value==="node:child_process";const moduleAliases=new Set(["child_process"]);const importedMethods=new Set;const containsDynamicStrings=node=>!(0,eslint_devkit_2.isStaticExpression)({node,scope:context.sourceCode.getScope(node)});const isFreeReference=node=>{const name=node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node:node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.callee:null;if(!name)return false;return context.sourceCode.getScope(name).through.some(ref=>ref.identifier===name&&ref.resolved===null)};const isStaticArg=argument=>(0,eslint_devkit_2.isStaticExpression)({node:argument,scope:context.sourceCode.getScope(argument)});const hasOnlyLiteralArgs=args=>{if(args.length===0)return false;if(!isStaticArg(args[0])){return false}if(args.length>=2){const argsArray=args[1];if(argsArray.type==="ArrayExpression"){const allLiteralElements=argsArray.elements.every(el=>el!==null&&isStaticArg(el));if(!allLiteralElements){return false}}else if(!isStaticArg(argsArray)){return false}}return true};const usesShell=(node,method)=>{if(method==="exec"||method==="execSync")return true;const command=node.arguments[0];if(command!==void 0&&command.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof command.value==="string"&&SHELL_BINARIES.has(command.value.replace(/^.*[/\\]/,"").toLowerCase())){return true}const argv=node.arguments[1];if(argv?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){for(const element of argv.elements){if(element?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof element.value==="string"&&EVAL_FLAGS.has(element.value.toLowerCase())){return true}}}for(const candidate of[node.arguments[1],node.arguments[2]]){if(!candidate||candidate.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)continue;for(const property of candidate.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||property.key.name!=="shell"){continue}return!(property.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.value.value===false)}}return false};const cannotStartWithDash=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const first=node.quasis[0].value.raw;return first.length>0&&!first.startsWith("-")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=node.left;return left.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof left.value==="string"&&left.value.length>0&&!left.value.startsWith("-")}return false};const argumentInjectionSite=node=>{const argv=node.arguments[1];if(argv?.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;for(const element of argv.elements){if(element===null)continue;if(element.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&element.value==="--"){return null}if(!readsRemoteTaintSource(element))continue;const target=element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement?element.argument:element;if(cannotStartWithDash(target))continue;return element}return null};const hasShellFalseOption=node=>{const optionsArg=node.arguments[2];if(!optionsArg||optionsArg.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){return true}for(const prop of optionsArg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.key.name==="shell"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value===false){return true}return false}}return true};const hasPrecedingAllowlistValidation=node=>{const makeArgChecker=validatedVarNames=>{const check=argNode=>{if(argNode.type==="Identifier"&&validatedVarNames.has(argNode.name))return true;if(argNode.type==="TemplateLiteral"){return argNode.expressions.some(e=>e.type==="Identifier"&&validatedVarNames.has(e.name))}if(argNode.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return argNode.elements.some(el=>el!==null&&check(el))}return false};return check};const checkGuardClause=ifNode=>{const test=ifNode.test;if(test.type==="CallExpression"&&test.callee.type==="MemberExpression"&&test.callee.property.type==="Identifier"&&test.callee.property.name==="includes"){const validatedVarNames=new Set;for(const testArg of test.arguments){if(testArg.type==="Identifier")validatedVarNames.add(testArg.name)}const check=makeArgChecker(validatedVarNames);for(const arg of node.arguments){if(check(arg))return true}}if(test.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&test.operator==="!"&&test.argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&test.argument.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&test.argument.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&test.argument.callee.property.name==="includes"){const consequent=ifNode.consequent;const isGuardBody=consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&consequent.body.length>0&&(consequent.body[0].type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||consequent.body[0].type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement);if(isGuardBody){const validatedVarNames=new Set;for(const testArg of test.argument.arguments){if(testArg.type==="Identifier")validatedVarNames.add(testArg.name)}const check=makeArgChecker(validatedVarNames.size>0?validatedVarNames:new Set(["*"]));if(validatedVarNames.size>0){for(const arg of node.arguments){if(check(arg))return true}}else{for(const arg of node.arguments){if(arg.type==="Identifier"||arg.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&arg.elements.some(el=>el?.type==="Identifier")){return true}}}}}return false};let current=node.parent;while(current){if(current.type==="IfStatement"){if(checkGuardClause(current))return true}current=current.parent}let stmt=node.parent;while(stmt&&stmt.parent&&stmt.parent.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement){stmt=stmt.parent}if(stmt&&stmt.parent&&stmt.parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){const block=stmt.parent;const callIndex=block.body.indexOf(stmt);if(callIndex>0){for(let i=0;i<callIndex;i++){const sibling=block.body[i];if(sibling.type==="IfStatement"){if(checkGuardClause(sibling))return true}}}}return false};const extractCommandInfo=(node,method)=>{const sourceCode=context.sourceCode;const args=node.arguments.map(arg=>sourceCode.getText(arg)).join(", ");const pattern=COMMAND_PATTERNS.find(p=>p.method===method)||null;const injectableArgs=node.arguments.slice(0,1);const argvArray=node.arguments[1];if(argvArray?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){injectableArgs.push(...argvArray.elements.filter(el=>el!==null))}const isDynamic=injectableArgs.some(arg=>containsDynamicStrings(arg));return{args,pattern,isDynamic}};const determineRiskLevel=(pattern,isDynamic)=>{if(pattern?.dangerous&&isDynamic){return"critical"}if(pattern?.dangerous||isDynamic){return"high"}return"medium"};const isChildProcessRequire=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&isChildProcessSpecifier(node.arguments[0].value);const childProcessMemberName=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;for(let scope=context.sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const[def]=variable.defs;if(def?.type==="ImportBinding"){const declaration=def.parent;if(declaration?.type!==eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration||!isChildProcessSpecifier(declaration.source.value)||def.node.type!==eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier){return null}return def.node.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?def.node.imported.name:String(def.node.imported.value)}if(def?.type==="Variable"){const declarator=def.node;if(declarator.init==null||!isChildProcessRequire(declarator.init)||declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern){return null}for(const property of declarator.id.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===node.name&&property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return property.key.name}}}return null}return null};const resolvesToChildProcess=(node,fallback)=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let scope=context.sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const[def]=variable.defs;if(def?.type==="ImportBinding"){const declaration=def.parent;return declaration?.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&isChildProcessSpecifier(declaration.source.value)}if(def?.type==="Variable"){return def.node.init!=null&&isChildProcessRequire(def.node.init)}return false}return fallback.has(node.name)};const getChildProcessCall=node=>{if(node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"){const methodName=node.callee.property.name;if(!dangerousMethodsSet.has(methodName)){return null}if(resolvesToChildProcess(node.callee.object,moduleAliases)){return{method:methodName,calleeNode:node.callee}}if(isChildProcessRequire(node.callee.object)){return{method:methodName,calleeNode:node.callee}}}const member=childProcessMemberName(node.callee);if(member!==null&&dangerousMethodsSet.has(member)){return{method:member,calleeNode:node.callee}}if(node.callee.type==="Identifier"&&dangerousMethodsSet.has(node.callee.name)){if(resolvesToChildProcess(node.callee,importedMethods)){return{method:node.callee.name,calleeNode:node.callee}}}return null};const checkChildProcessCall=node=>{const detected=getChildProcessCall(node);if(!detected){return}const{method}=detected;const{args,pattern,isDynamic}=extractCommandInfo(node,method);if((method==="exec"||method==="execSync")&&!isDynamic&&hasOnlyLiteralArgs(node.arguments)){return}if(allowLiteralStrings&&method==="exec"&&!isDynamic){return}const saferMethods=new Set(["spawn","spawnSync","execFile","execFileSync"]);if(allowLiteralSpawn&&saferMethods.has(method)&&hasOnlyLiteralArgs(node.arguments)){return}if(saferMethods.has(method)&&hasOnlyLiteralArgs(node.arguments)){const isExecFile=method==="execFile"||method==="execFileSync";if(isExecFile||hasShellFalseOption(node)){return}}const allSafeMethods=["execFile","execFileSync","spawn","spawnSync"];if(allSafeMethods.includes(method)&&hasPrecedingAllowlistValidation(node)){return}const command=node.arguments[0];const commandIsSteerable=command===void 0||isFreeReference(command)||readsRemoteTaintSource(command);if(!usesShell(node,method)&&!commandIsSteerable){const injected=argumentInjectionSite(node);if(injected===null)return;context.report({node:injected,messageId:"argumentInjection"});return}const injectablePositions=node.arguments.slice(0,1);const argvVector=node.arguments[1];if(argvVector?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){injectablePositions.push(...argvVector.elements.filter(el=>el!==null))}const unknowable=injectablePositions.some(argument=>isFreeReference(argument));if(!reportUnresolvedCommands&&!unknowable&&!node.arguments.some(argument=>readsTaintSource(argument))){return}const riskLevel=determineRiskLevel(pattern,isDynamic);const steps=pattern?(0,exports.generateRefactoringSteps)(pattern):"Review and secure command execution";const alternatives=pattern?.safeAlternatives.join(", ")||"execFile, spawn with validation";context.report({node,messageId:"childProcessCommandInjection",data:{method,args,riskLevel,vulnerability:pattern?.vulnerability||"command injection",alternatives,steps,effort:pattern?.effort||"15-30 minutes"}})};const trackChildProcessImport=node=>{if(!isChildProcessSpecifier(node.source.value)){return}for(const specifier of node.specifiers){if(specifier.type==="ImportDefaultSpecifier"||specifier.type==="ImportNamespaceSpecifier"){moduleAliases.add(specifier.local.name)}if(specifier.type==="ImportSpecifier"){importedMethods.add(specifier.local.name)}}};const trackChildProcessRequire=node=>{if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]&&node.init.arguments[0].type==="Literal"&&isChildProcessSpecifier(node.init.arguments[0].value)){moduleAliases.add(node.id.name);return}if(node.id.type==="ObjectPattern"&&node.init?.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]&&node.init.arguments[0].type==="Literal"&&isChildProcessSpecifier(node.init.arguments[0].value)){for(const prop of node.id.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){importedMethods.add(prop.value.type==="Identifier"?prop.value.name:prop.key.name)}}}};const checkBareChildProcessRequire=node=>{if(!isChildProcessRequire(node))return;const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===node)return;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===node)return;context.report({node,messageId:"childProcessCommandInjection",data:{method:"require",riskLevel:"MEDIUM",vulnerability:"command-injection",safeAlternatives:"execFile, spawn",refactoringSteps:" 1. Avoid importing child_process where it is not needed\n 2. If required, prefer execFile()/spawn() with {shell: false}\n 3. Validate any command or argument that is not a literal",effort:"10-15 minutes",badExample:"require('child_process')",goodExample:"const { execFile } = require('node:child_process')"}})};return{CallExpression(node){checkChildProcessCall(node);checkBareChildProcessRequire(node)},ImportDeclaration:trackChildProcessImport,VariableDeclarator:trackChildProcessRequire}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectEvalWithExpression=exports.generateRefactoringSteps=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const EVAL_PATTERNS=[{pattern:"JSON\\.parse|parse\\(.*\\)",category:"json",safeAlternative:"JSON.parse()",example:{bad:`eval('{"key": "' + value + '"}"')`,good:`JSON.parse('{"key": "' + value + '"}"')`},effort:"2 minutes"},{pattern:"Math\\.|parseInt|parseFloat",category:"math",safeAlternative:"Math functions or parseInt/parseFloat",example:{bad:"eval('Math.' + method + '(' + arg + ')')",good:"const mathMethods = {sin: Math.sin, cos: Math.cos}; mathMethods[method](arg)"},effort:"5 minutes"},{pattern:"\\$\\{|template|interpolat",category:"template",safeAlternative:"Template literals or template engine",example:{bad:"eval('Hello ' + userName + '!')",good:"const template = `Hello ${userName}!`;"},effort:"3 minutes"},{pattern:"\\[.*\\]|object\\[|obj\\.|\\.",category:"object",safeAlternative:"Direct property access or Map",example:{bad:"eval('obj.' + property)",good:"const allowedProps = {name: true, age: true}; if (allowedProps[property]) obj[property]"},effort:"8 minutes"}];const VM_CODE_SINK_METHODS=new Set(["runInNewContext","runInThisContext","runInContext","compileFunction"]);const VM_CODE_CONSTRUCTORS=new Set(["Script","SourceTextModule"]);const VM2_SANDBOX_CONSTRUCTORS=new Set(["VM","NodeVM"]);const VM2_CODE_CONSTRUCTORS=new Set(["VMScript"]);const VM_MODULES=new Set(["vm","node:vm"]);const VM2_MODULES=new Set(["vm2"]);const NAMESPACE="*";function requiredModule(node){if(!node||node.type!=="CallExpression")return null;if(node.callee.type!=="Identifier"||node.callee.name!=="require"){return null}const[source]=node.arguments;if(!source||source.type!=="Literal")return null;return typeof source.value==="string"?source.value:null}function resolveModuleMember(callee,bindings){const name=calleeTrailingName(callee);if(name===null)return null;if(callee.type==="Identifier"){const bound=bindings.get(name);return bound!==void 0&&bound!==NAMESPACE?bound:null}const{object}=callee;if(object.type!=="Identifier")return null;return bindings.get(object.name)===NAMESPACE?name:null}function calleeTrailingName(callee){if(callee.type==="Identifier")return callee.name;if(callee.type!=="MemberExpression"||callee.computed)return null;return callee.property.type==="Identifier"?callee.property.name:null}function isStaticStringNode(node){if(node.type==="Literal")return typeof node.value==="string";if(node.type==="TemplateLiteral")return node.expressions.length===0;return false}const generateRefactoringSteps=pattern=>{if(!pattern){return[" 1. Remove eval() usage entirely"," 2. Identify what the code is trying to achieve"," 3. Use appropriate safe alternative (JSON.parse, Map, etc.)"," 4. Add input validation if dynamic behavior needed"," 5. Test thoroughly for edge cases"].join("\n")}switch(pattern.category){case"json":return[" 1. Replace eval() with JSON.parse()"," 2. Ensure input is valid JSON string"," 3. Add try/catch for JSON parsing errors"," 4. Consider using a JSON schema validator"].join("\n");case"math":return[" 1. Create whitelist of allowed Math functions"," 2. Use direct function calls: Math.sin(x)"," 3. Validate inputs are numbers"," 4. Consider using a math expression parser library"].join("\n");case"template":return[" 1. Use template literals: `Hello ${name}`"," 2. Sanitize variables before interpolation"," 3. Use a template engine like Handlebars if complex"," 4. Validate template structure"].join("\n");case"object":return[" 1. Use Map or plain object for key-value access"," 2. Whitelist allowed property names"," 3. Use hasOwnProperty() check"," 4. Consider Object.create(null) for clean objects"].join("\n");default:return[" 1. Identify the specific use case"," 2. Find a safer alternative approach"," 3. Add comprehensive input validation"," 4. Use static analysis if possible"].join("\n")}};exports.generateRefactoringSteps=generateRefactoringSteps;exports.detectEvalWithExpression=(0,eslint_devkit_2.createRule)({name:"detect-eval-with-expression",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-eval-with-expression.md",description:"Detects strings turned into running code \u2014 eval(variable), the Function constructor, and the vm / vm2 sinks that are mistaken for sandboxes",cwe:"CWE-95",cvss:9.8,confidence:"high"},hasSuggestions:true,messages:{vmCodeExecution:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Code Execution Through the vm Module (CWE-94)",cwe:"CWE-94",cvss:9.8,description:'vm.{{api}}() compiles and runs its first argument as JavaScript, and that argument is not written out in full here. The vm module is NOT a security boundary \u2014 Node documents it as such \u2014 because any object reachable from the context carries a constructor chain back out: `this.constructor.constructor("return process")()`. A string that is not a constant is a string an attacker may be able to steer.',severity:"CRITICAL",fix:"Do not evaluate the value as code. Parse it (JSON.parse, an expression parser) or dispatch through a fixed map of allowed operations; if untrusted code genuinely has to run, isolate it in a separate process with its own privileges \u2014 not in vm.",documentationLink:"https://nodejs.org/api/vm.html#vm-executing-javascript"}),vm2CodeExecution:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Code Execution Through vm2 (CWE-94)",cwe:"CWE-94",cvss:9.8,description:"vm2 is abandoned and was retired by its maintainer after sandbox escapes that it could not fix (CVE-2023-37903, CVE-2023-37466). Running source that is not a constant inside it is arbitrary code execution on the host, not sandboxed execution.",severity:"CRITICAL",fix:"Stop using vm2. Run untrusted code out-of-process under an OS-level boundary (a separate process with dropped privileges, a container, or isolated-vm), or remove the need to execute caller-supplied source.",documentationLink:"https://github.com/patriksimek/vm2/issues/533"}),evalWithExpression:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"eval() with dynamic code",cwe:"CWE-95",description:"eval() with dynamic code",severity:"CRITICAL",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),useJsonParse:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe eval() for JSON parsing",cwe:"CWE-95",description:"Use JSON.parse() instead of eval() for JSON string parsing",severity:"HIGH",fix:"Replace eval() with JSON.parse()",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),useObjectAccess:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe eval() for property access",cwe:"CWE-95",description:"Use direct property access instead of eval() for dynamic property access",severity:"HIGH",fix:"Use obj[key] or Map.get(key) instead of eval()",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),useTemplateLiteral:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe eval() for string interpolation",cwe:"CWE-95",description:"Use template literals instead of eval() for string interpolation",severity:"HIGH",fix:"Replace eval() with template literals: `Hello ${name}`",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),useFunctionConstructor:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe eval() for function creation",cwe:"CWE-95",description:"Use Function constructor with validation instead of eval()",severity:"HIGH",fix:"Replace eval() with validated Function constructor",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),useSaferAlternative:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe eval() usage detected",cwe:"CWE-95",description:"eval() with dynamic code execution detected",severity:"HIGH",fix:"{{alternative}}",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),strategyRemove:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Critical eval() security vulnerability",cwe:"CWE-95",description:"eval() usage poses severe security risk",severity:"CRITICAL",fix:"Remove eval() entirely - security risk too high",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),strategyRefactor:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"eval() refactoring required",cwe:"CWE-95",description:"eval() can be refactored to safer alternative",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),strategyValidate:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"eval() input validation needed",cwe:"CWE-95",description:"eval() requires input validation for security",severity:"MEDIUM",fix:"Add input validation before using eval()",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"})},schema:[{type:"object",properties:{allowLiteralStrings:{type:"boolean",default:false,description:"Allow eval with literal strings (false = stricter)"},additionalEvalFunctions:{type:"array",items:{type:"string"},default:[],description:"Additional functions to treat as eval-like"},strategy:{type:"string",enum:["remove","refactor","validate","auto"],default:"auto",description:"Strategy for fixing eval usage (auto = smart detection)"}},additionalProperties:false}]},defaultOptions:[{allowLiteralStrings:false,additionalEvalFunctions:[],strategy:"auto"}],create(context){const options=context.options[0]||{};const{allowLiteralStrings=false,additionalEvalFunctions=[],strategy="auto"}=options;const evalFunctions=new Set(["eval","Function",...additionalEvalFunctions]);const isLiteralString=node=>{return node.type==="Literal"&&typeof node.value==="string"};const selectStrategyMessage=pattern=>{switch(strategy){case"remove":return"strategyRemove";case"refactor":return"strategyRefactor";case"validate":return"strategyValidate";case"auto":default:if(pattern&&pattern.category==="json"){return"useJsonParse"}if(pattern&&pattern.category==="object"){return"useObjectAccess"}if(pattern&&pattern.category==="template"){return"useTemplateLiteral"}return"strategyRefactor"}};const detectPattern=expression=>{for(const pattern of EVAL_PATTERNS){if(new RegExp(pattern.pattern,"i").test(expression)){return pattern}}return null};const extractExpression=node=>{const sourceCode=context.sourceCode;if(node.arguments.length>0){return sourceCode.getText(node.arguments[0])}return"dynamic expression"};const checkCallExpression=node=>{if(node.callee.type==="Identifier"&&evalFunctions.has(node.callee.name)){if(allowLiteralStrings&&node.arguments.length>0&&isLiteralString(node.arguments[0])){return}if(node.arguments.length>0&&node.callee.name==="eval"&&isLiteralString(node.arguments[0])){return}const expression=extractExpression(node);const pattern=detectPattern(expression);const steps=(0,exports.generateRefactoringSteps)(pattern);const strategyMessageId=selectStrategyMessage(pattern);context.report({node,messageId:strategyMessageId,data:{expression,patternCategory:pattern?.category||"dynamic code execution",safeAlternative:pattern?.safeAlternative||"Remove eval entirely",steps,effort:pattern?.effort||"15-30 minutes"},suggest:pattern?[{messageId:strategyMessageId,data:{safeAlternative:pattern.safeAlternative,alternative:pattern.safeAlternative},fix:()=>null}]:void 0})}if(node.callee.type==="NewExpression"&&node.callee.callee.type==="Identifier"&&node.callee.callee.name==="Function"){const expression=extractExpression(node);const pattern=detectPattern(expression);const strategyMessageId=selectStrategyMessage(pattern);context.report({node,messageId:strategyMessageId,data:{expression:`new Function(${expression})`,patternCategory:"function constructor",safeAlternative:"Arrow function or regular function",steps:[" 1. Replace Function constructor with arrow function"," 2. Use regular function declaration"," 3. Validate any dynamic parts"," 4. Consider module imports instead"].join("\n"),effort:"10 minutes"}})}};const checkNewExpression=node=>{if(node.callee.type==="Identifier"&&node.callee.name==="Function"){const sourceCode=context.sourceCode;const expression=node.arguments.map(arg=>sourceCode.getText(arg)).join(", ");const pattern=detectPattern(expression);const strategyMessageId=selectStrategyMessage(pattern);context.report({node,messageId:strategyMessageId,data:{expression:`new Function(${expression})`,patternCategory:"function constructor",safeAlternative:"Arrow function or regular function",steps:[" 1. Replace Function constructor with arrow function"," 2. Use regular function declaration"," 3. Validate any dynamic parts"," 4. Consider module imports instead"].join("\n"),effort:"10 minutes"}})}};const vmBindings=new Map;const vm2Bindings=new Map;const vm2SandboxCandidates=[];const pendingVmCalls=[];const pendingVmNews=[];const findVariable=node=>{let scope=context.sourceCode.getScope(node);while(scope){const found=scope.variables.find(v=>v.name===node.name);if(found)return found;scope=scope.upper}return null};const isStaticCode=node=>{if(!node)return true;if(isStaticStringNode(node))return true;if(node.type!=="Identifier")return false;const variable=findVariable(node);if(!variable)return false;if(variable.references.filter(ref=>ref.isWrite()).length!==1){return false}const[def]=variable.defs;if(!def||def.node.type!=="VariableDeclarator")return false;const init=def.node.init;return init!=null&&isStaticStringNode(init)};const bindModuleName=(moduleName,local,imported)=>{if(VM_MODULES.has(moduleName))vmBindings.set(local,imported);else if(VM2_MODULES.has(moduleName))vm2Bindings.set(local,imported)};const bindRequire=node=>{const moduleName=requiredModule(node.init);if(moduleName===null)return;if(node.id.type==="Identifier"){bindModuleName(moduleName,node.id.name,NAMESPACE);return}if(node.id.type!=="ObjectPattern")return;for(const property of node.id.properties){if(property.type!=="Property")continue;if(property.key.type!=="Identifier")continue;if(property.value.type!=="Identifier")continue;bindModuleName(moduleName,property.value.name,property.key.name)}};const reportVmSite=(node,code,messageId,api)=>{if(isStaticCode(code))return;context.report({node,messageId,data:{api}})};const isVm2Run=(node,sandboxes)=>{const{callee}=node;if(callee.type!=="MemberExpression")return false;if(calleeTrailingName(callee)!=="run")return false;if(callee.object.type==="Identifier"){return sandboxes.has(callee.object.name)}if(callee.object.type!=="NewExpression")return false;const constructed=resolveModuleMember(callee.object.callee,vm2Bindings);return constructed!==null&&VM2_SANDBOX_CONSTRUCTORS.has(constructed)};const judgeVmSites=()=>{const sandboxes=new Set;for(const candidate of vm2SandboxCandidates){const constructed=resolveModuleMember(candidate.init.callee,vm2Bindings);if(constructed!==null&&VM2_SANDBOX_CONSTRUCTORS.has(constructed)){sandboxes.add(candidate.local)}}for(const node of pendingVmCalls){const vmApi=resolveModuleMember(node.callee,vmBindings);if(vmApi!==null&&VM_CODE_SINK_METHODS.has(vmApi)){reportVmSite(node,node.arguments[0],"vmCodeExecution",vmApi);continue}if(isVm2Run(node,sandboxes)){reportVmSite(node,node.arguments[0],"vm2CodeExecution","run")}}for(const node of pendingVmNews){const vmCtor=resolveModuleMember(node.callee,vmBindings);if(vmCtor!==null&&VM_CODE_CONSTRUCTORS.has(vmCtor)){reportVmSite(node,node.arguments[0],"vmCodeExecution",vmCtor);continue}const vm2Ctor=resolveModuleMember(node.callee,vm2Bindings);if(vm2Ctor!==null&&VM2_CODE_CONSTRUCTORS.has(vm2Ctor)){reportVmSite(node,node.arguments[0],"vm2CodeExecution",vm2Ctor)}}};return{CallExpression(node){checkCallExpression(node);const name=calleeTrailingName(node.callee);if(name!==null&&(VM_CODE_SINK_METHODS.has(name)||name==="run")){pendingVmCalls.push(node)}},NewExpression(node){checkNewExpression(node);const name=calleeTrailingName(node.callee);if(name!==null&&(VM_CODE_CONSTRUCTORS.has(name)||VM2_CODE_CONSTRUCTORS.has(name))){pendingVmNews.push(node)}},ImportDeclaration(node){const moduleName=node.source.value;for(const specifier of node.specifiers){if(specifier.type==="ImportSpecifier"){if(specifier.imported.type!=="Identifier")continue;bindModuleName(moduleName,specifier.local.name,specifier.imported.name);continue}bindModuleName(moduleName,specifier.local.name,NAMESPACE)}},VariableDeclarator(node){bindRequire(node);if(node.id.type==="Identifier"&&node.init?.type==="NewExpression"){vm2SandboxCandidates.push({local:node.id.name,init:node.init})}},"Program:exit":judgeVmSites}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectEvalWithExpression=exports.generateRefactoringSteps=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const EVAL_PATTERNS=[{pattern:"JSON\\.parse|parse\\(.*\\)",category:"json",safeAlternative:"JSON.parse()",example:{bad:`eval('{"key": "' + value + '"}"')`,good:`JSON.parse('{"key": "' + value + '"}"')`},effort:"2 minutes"},{pattern:"Math\\.|parseInt|parseFloat",category:"math",safeAlternative:"Math functions or parseInt/parseFloat",example:{bad:"eval('Math.' + method + '(' + arg + ')')",good:"const mathMethods = {sin: Math.sin, cos: Math.cos}; mathMethods[method](arg)"},effort:"5 minutes"},{pattern:"\\$\\{|template|interpolat",category:"template",safeAlternative:"Template literals or template engine",example:{bad:"eval('Hello ' + userName + '!')",good:"const template = `Hello ${userName}!`;"},effort:"3 minutes"},{pattern:"\\[.*\\]|object\\[|obj\\.|\\.",category:"object",safeAlternative:"Direct property access or Map",example:{bad:"eval('obj.' + property)",good:"const allowedProps = {name: true, age: true}; if (allowedProps[property]) obj[property]"},effort:"8 minutes"}];const VM_CODE_SINK_METHODS=new Set(["runInNewContext","runInThisContext","runInContext","compileFunction"]);const VM_CODE_CONSTRUCTORS=new Set(["Script","SourceTextModule"]);const VM2_SANDBOX_CONSTRUCTORS=new Set(["VM","NodeVM"]);const VM2_CODE_CONSTRUCTORS=new Set(["VMScript"]);const VM_MODULES=new Set(["vm","node:vm"]);const VM2_MODULES=new Set(["vm2"]);const NAMESPACE="*";function requiredModule(node){if(!node||node.type!=="CallExpression")return null;if(node.callee.type!=="Identifier"||node.callee.name!=="require"){return null}const[source]=node.arguments;if(!source||source.type!=="Literal")return null;return typeof source.value==="string"?source.value:null}function resolveModuleMember(callee,bindings,modules,name){if(name===null)return null;if(callee.type==="Identifier"){const bound=bindings.get(name);return bound!==void 0&&bound!==NAMESPACE?bound:null}const{object}=callee;if(object.type==="Identifier"){return bindings.get(object.name)===NAMESPACE?name:null}const inline=requiredModule(object);return inline!==null&&modules.has(inline)?name:null}function calleeTrailingName(callee){if(callee.type==="Identifier")return callee.name;if(callee.type!=="MemberExpression"||callee.computed)return null;return callee.property.type==="Identifier"?callee.property.name:null}function isStaticStringNode(node){if(node.type==="Literal")return typeof node.value==="string";if(node.type==="TemplateLiteral")return node.expressions.length===0;return false}const generateRefactoringSteps=pattern=>{if(!pattern){return[" 1. Remove eval() usage entirely"," 2. Identify what the code is trying to achieve"," 3. Use appropriate safe alternative (JSON.parse, Map, etc.)"," 4. Add input validation if dynamic behavior needed"," 5. Test thoroughly for edge cases"].join("\n")}switch(pattern.category){case"json":return[" 1. Replace eval() with JSON.parse()"," 2. Ensure input is valid JSON string"," 3. Add try/catch for JSON parsing errors"," 4. Consider using a JSON schema validator"].join("\n");case"math":return[" 1. Create whitelist of allowed Math functions"," 2. Use direct function calls: Math.sin(x)"," 3. Validate inputs are numbers"," 4. Consider using a math expression parser library"].join("\n");case"template":return[" 1. Use template literals: `Hello ${name}`"," 2. Sanitize variables before interpolation"," 3. Use a template engine like Handlebars if complex"," 4. Validate template structure"].join("\n");case"object":return[" 1. Use Map or plain object for key-value access"," 2. Whitelist allowed property names"," 3. Use hasOwnProperty() check"," 4. Consider Object.create(null) for clean objects"].join("\n");default:return[" 1. Identify the specific use case"," 2. Find a safer alternative approach"," 3. Add comprehensive input validation"," 4. Use static analysis if possible"].join("\n")}};exports.generateRefactoringSteps=generateRefactoringSteps;exports.detectEvalWithExpression=(0,eslint_devkit_2.createRule)({name:"detect-eval-with-expression",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-eval-with-expression.md",description:"Detects strings turned into running code \u2014 eval(variable), the Function constructor, and the vm / vm2 sinks that are mistaken for sandboxes",cwe:"CWE-95",cvss:9.8,confidence:"high"},hasSuggestions:false,messages:{vmCodeExecution:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Code Execution Through the vm Module (CWE-94)",cwe:"CWE-94",cvss:9.8,description:'vm.{{api}}() compiles and runs its first argument as JavaScript, and that argument is not written out in full here. The vm module is NOT a security boundary \u2014 Node documents it as such \u2014 because any object reachable from the context carries a constructor chain back out: `this.constructor.constructor("return process")()`. A string that is not a constant is a string an attacker may be able to steer.',severity:"CRITICAL",fix:"Do not evaluate the value as code. Parse it (JSON.parse, an expression parser) or dispatch through a fixed map of allowed operations; if untrusted code genuinely has to run, isolate it in a separate process with its own privileges \u2014 not in vm.",documentationLink:"https://nodejs.org/api/vm.html#vm-executing-javascript"}),vm2CodeExecution:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Code Execution Through vm2 (CWE-94)",cwe:"CWE-94",cvss:9.8,description:"vm2 is abandoned and was retired by its maintainer after sandbox escapes that it could not fix (CVE-2023-37903, CVE-2023-37466). Running source that is not a constant inside it is arbitrary code execution on the host, not sandboxed execution.",severity:"CRITICAL",fix:"Stop using vm2. Run untrusted code out-of-process under an OS-level boundary (a separate process with dropped privileges, a container, or isolated-vm), or remove the need to execute caller-supplied source.",documentationLink:"https://github.com/patriksimek/vm2/issues/533"}),useJsonParse:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe eval() for JSON parsing",cwe:"CWE-95",description:"Use JSON.parse() instead of eval() for JSON string parsing",severity:"HIGH",fix:"Replace eval() with JSON.parse()",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),useObjectAccess:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe eval() for property access",cwe:"CWE-95",description:"Use direct property access instead of eval() for dynamic property access",severity:"HIGH",fix:"Use obj[key] or Map.get(key) instead of eval()",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),useTemplateLiteral:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe eval() for string interpolation",cwe:"CWE-95",description:"Use template literals instead of eval() for string interpolation",severity:"HIGH",fix:"Replace eval() with template literals: `Hello ${name}`",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),strategyRemove:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Critical eval() security vulnerability",cwe:"CWE-95",description:"eval() usage poses severe security risk",severity:"CRITICAL",fix:"Remove eval() entirely - security risk too high",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),strategyRefactor:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"eval() refactoring required",cwe:"CWE-95",description:"eval() can be refactored to safer alternative",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),strategyValidate:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"eval() input validation needed",cwe:"CWE-95",description:"eval() requires input validation for security",severity:"MEDIUM",fix:"Add input validation before using eval()",documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"})},schema:[{type:"object",properties:{allowLiteralStrings:{type:"boolean",default:false,description:"Allow eval with literal strings (false = stricter)"},additionalEvalFunctions:{type:"array",items:{type:"string"},default:[],description:"Additional functions to treat as eval-like"},strategy:{type:"string",enum:["remove","refactor","validate","auto"],default:"auto",description:"Strategy for fixing eval usage (auto = smart detection)"}},additionalProperties:false}]},defaultOptions:[{allowLiteralStrings:false,additionalEvalFunctions:[],strategy:"auto"}],create(context){const options=context.options[0]||{};const{allowLiteralStrings=false,additionalEvalFunctions=[],strategy="auto"}=options;const evalFunctions=new Set(["eval","Function",...additionalEvalFunctions]);const isLiteralString=node=>{return node.type==="Literal"&&typeof node.value==="string"};const selectStrategyMessage=pattern=>{switch(strategy){case"remove":return"strategyRemove";case"refactor":return"strategyRefactor";case"validate":return"strategyValidate";case"auto":default:if(pattern&&pattern.category==="json"){return"useJsonParse"}if(pattern&&pattern.category==="object"){return"useObjectAccess"}if(pattern&&pattern.category==="template"){return"useTemplateLiteral"}return"strategyRefactor"}};const detectPattern=expression=>{for(const pattern of EVAL_PATTERNS){if(new RegExp(pattern.pattern,"i").test(expression)){return pattern}}return null};const extractExpression=node=>{const sourceCode=context.sourceCode;if(node.arguments.length>0){return sourceCode.getText(node.arguments[0])}return"dynamic expression"};const GLOBAL_OBJECTS=new Set(["globalThis","global","window","self"]);const evalCalleeName=(callee,depth=0)=>{if(depth>3)return null;if(callee.type==="Identifier"){if(evalFunctions.has(callee.name))return callee.name;const init=(0,const_value_1.constInitializerOf)(context.sourceCode,callee);return init?evalCalleeName(init,depth+1):null}if(callee.type==="SequenceExpression"){const[last]=callee.expressions.slice(-1);return evalCalleeName(last,depth+1)}if(callee.type==="MemberExpression"&&!callee.computed&&callee.object.type==="Identifier"&&GLOBAL_OBJECTS.has(callee.object.name)&&callee.property.type==="Identifier"&&evalFunctions.has(callee.property.name)){return callee.property.name}return null};const checkCallExpression=node=>{const evalName=evalCalleeName(node.callee);if(evalName!==null){if(allowLiteralStrings&&node.arguments.length>0&&isLiteralString(node.arguments[0])){return}if(node.arguments.length>0&&evalName==="eval"&&isLiteralString(node.arguments[0])){return}const expression=extractExpression(node);const pattern=detectPattern(expression);const steps=(0,exports.generateRefactoringSteps)(pattern);context.report({node,messageId:selectStrategyMessage(pattern),data:{expression,patternCategory:pattern?.category||"dynamic code execution",safeAlternative:pattern?.safeAlternative||"Remove eval entirely",steps,effort:pattern?.effort||"15-30 minutes"}})}};const checkNewExpression=node=>{if(node.callee.type==="Identifier"&&node.callee.name==="Function"){const sourceCode=context.sourceCode;const expression=node.arguments.map(arg=>sourceCode.getText(arg)).join(", ");const pattern=detectPattern(expression);context.report({node,messageId:selectStrategyMessage(pattern),data:{expression:`new Function(${expression})`,patternCategory:"function constructor",safeAlternative:"Arrow function or regular function",steps:[" 1. Replace Function constructor with arrow function"," 2. Use regular function declaration"," 3. Validate any dynamic parts"," 4. Consider module imports instead"].join("\n"),effort:"10 minutes"}})}};const vmBindings=new Map;const vm2Bindings=new Map;const vm2SandboxCandidates=[];const pendingVmCalls=[];const pendingVmNews=[];const findVariable=node=>{let scope=context.sourceCode.getScope(node);while(scope){const found=scope.variables.find(v=>v.name===node.name);if(found)return found;scope=scope.upper}return null};const isStaticCode=node=>{if(!node)return true;if(isStaticStringNode(node))return true;if(node.type!=="Identifier")return false;const variable=findVariable(node);if(!variable)return false;const lastWrite=variable.references.filter(ref=>ref.isWrite()).map(ref=>ref.writeExpr).filter(write=>write!=null).filter(write=>write.range[1]<=node.range[0]).sort((a,b)=>a.range[1]-b.range[1]).at(-1);return lastWrite!==void 0&&isStaticStringNode(lastWrite)};const bindModuleName=(moduleName,local,imported)=>{if(VM_MODULES.has(moduleName))vmBindings.set(local,imported);else if(VM2_MODULES.has(moduleName))vm2Bindings.set(local,imported)};const bindRequire=node=>{const moduleName=requiredModule(node.init);if(moduleName===null)return;if(node.id.type==="Identifier"){bindModuleName(moduleName,node.id.name,NAMESPACE);return}if(node.id.type!=="ObjectPattern")return;for(const property of node.id.properties){if(property.type!=="Property")continue;if(property.key.type!=="Identifier")continue;if(property.value.type!=="Identifier")continue;bindModuleName(moduleName,property.value.name,property.key.name)}};const reportVmSite=(node,code,messageId,api)=>{if(isStaticCode(code))return;context.report({node,messageId,data:{api}})};const trailingName=callee=>{if(callee.type==="MemberExpression"&&callee.computed){return(0,const_value_1.resolveConstantString)(context.sourceCode,callee.property)?.value??null}return calleeTrailingName(callee)};const isVm2Run=(node,sandboxes)=>{const{callee}=node;if(callee.type!=="MemberExpression")return false;if(trailingName(callee)!=="run")return false;if(callee.object.type==="Identifier"){return sandboxes.has(callee.object.name)}if(callee.object.type!=="NewExpression")return false;const constructed=resolveModuleMember(callee.object.callee,vm2Bindings,VM2_MODULES,trailingName(callee.object.callee));return constructed!==null&&VM2_SANDBOX_CONSTRUCTORS.has(constructed)};const judgeVmSites=()=>{const sandboxes=new Set;for(const candidate of vm2SandboxCandidates){const constructed=resolveModuleMember(candidate.init.callee,vm2Bindings,VM2_MODULES,trailingName(candidate.init.callee));if(constructed!==null&&VM2_SANDBOX_CONSTRUCTORS.has(constructed)){sandboxes.add(candidate.local)}}for(const node of pendingVmCalls){const name=trailingName(node.callee);const vmApi=resolveModuleMember(node.callee,vmBindings,VM_MODULES,name);if(vmApi!==null&&VM_CODE_SINK_METHODS.has(vmApi)){reportVmSite(node,node.arguments[0],"vmCodeExecution",vmApi);continue}if(isVm2Run(node,sandboxes)){reportVmSite(node,node.arguments[0],"vm2CodeExecution","run")}}for(const node of pendingVmNews){const name=trailingName(node.callee);const vmCtor=resolveModuleMember(node.callee,vmBindings,VM_MODULES,name);if(vmCtor!==null&&VM_CODE_CONSTRUCTORS.has(vmCtor)){reportVmSite(node,node.arguments[0],"vmCodeExecution",vmCtor);continue}const vm2Ctor=resolveModuleMember(node.callee,vm2Bindings,VM2_MODULES,name);if(vm2Ctor!==null&&VM2_CODE_CONSTRUCTORS.has(vm2Ctor)){reportVmSite(node,node.arguments[0],"vm2CodeExecution",vm2Ctor)}}};return{CallExpression(node){checkCallExpression(node);if(node.callee.type==="Identifier"){pendingVmCalls.push(node);return}const name=trailingName(node.callee);if(name!==null&&(VM_CODE_SINK_METHODS.has(name)||name==="run")){pendingVmCalls.push(node)}},NewExpression(node){checkNewExpression(node);if(node.callee.type==="Identifier"){pendingVmNews.push(node);return}const name=trailingName(node.callee);if(name!==null&&(VM_CODE_CONSTRUCTORS.has(name)||VM2_CODE_CONSTRUCTORS.has(name))){pendingVmNews.push(node)}},ImportDeclaration(node){const moduleName=node.source.value;for(const specifier of node.specifiers){if(specifier.type==="ImportSpecifier"){if(specifier.imported.type!=="Identifier")continue;bindModuleName(moduleName,specifier.local.name,specifier.imported.name);continue}bindModuleName(moduleName,specifier.local.name,NAMESPACE)}},VariableDeclarator(node){bindRequire(node);if(node.id.type==="Identifier"&&node.init?.type==="NewExpression"){vm2SandboxCandidates.push({local:node.id.name,init:node.init})}},"Program:exit":judgeVmSites}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectNonLiteralFsFilename=exports.determineRiskLevel=exports.isFsModule=exports.generateRefactoringSteps=void 0;exports.fsMethodName=fsMethodName;exports.isFsRequire=isFsRequire;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const FS_OPERATIONS=[{method:"readFile",dangerous:true,vulnerability:"file-access",safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))",example:{bad:"fs.readFile(userPath, callback)",good:"const safePath = path.join(SAFE_UPLOADS_DIR, path.basename(userPath)); fs.readFile(safePath, callback)"},effort:"10-15 minutes"},{method:"writeFile",dangerous:true,vulnerability:"file-access",safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))",example:{bad:"fs.writeFile(userPath, data, callback)",good:"const safePath = path.join(SAFE_WRITES_DIR, path.basename(userPath)); fs.writeFile(safePath, data, callback)"},effort:"10-15 minutes"},{method:"stat",dangerous:true,vulnerability:"path-traversal",safePattern:"path.resolve(baseDir, userInput) with validation",example:{bad:"fs.stat(userPath, callback)",good:"const resolvedPath = path.resolve(SAFE_DIR, userPath);\nif (!resolvedPath.startsWith(SAFE_DIR)) return;\nfs.stat(resolvedPath, callback)"},effort:"15-20 minutes"},{method:"readdir",dangerous:true,vulnerability:"directory-traversal",safePattern:"Validate directory is within allowed paths",example:{bad:"fs.readdir(userDir, callback)",good:"const resolvedDir = path.resolve(ALLOWED_DIRS, userDir);\nif (!resolvedDir.startsWith(ALLOWED_DIRS)) return;\nfs.readdir(resolvedDir, callback)"},effort:"15-20 minutes"}];const hasTraversalPatterns=pathStr=>{return/\.\.[/\\]/.test(pathStr)||/^\.\.[/\\]/.test(pathStr)};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 if resolved path starts with allowed base directory"," 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 FS_MODULE_EQUIVALENTS={"fs-extra":"fs","graceful-fs":"fs","fs/promises":"fs"};const FS_MODULES=new Set(["fs","node:fs","fs/promises","node:fs/promises","fs-extra","graceful-fs"]);const isFsModule=source=>typeof source==="string"&&FS_MODULES.has(source);exports.isFsModule=isFsModule;function fsMethodName(callee,namespaces,named){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return named.get(callee.name);if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed||callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return void 0}const object=callee.object;if(object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&namespaces.has(object.name)){return callee.property.name}if(object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!object.computed&&object.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&namespaces.has(object.object.name)&&object.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&object.property.name==="promises"){return callee.property.name}return void 0}function isFsRequire(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments.length>0&&node.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(0,exports.isFsModule)(node.arguments[0].value)}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:{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"},hasSuggestions:true,messages:{fsPathTraversal:(0,eslint_devkit_1.formatLLMMessage)({icon:"\u{1F511}",issueName:"Path traversal",cwe:"CWE-22",description:"Path traversal vulnerability",severity:"{{riskLevel}}",fix:"{{safePattern}}",documentationLink:"https://owasp.org/www-community/attacks/Path_Traversal"}),usePathResolve:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use path.resolve",description:"Use path.resolve() to normalize paths",severity:"LOW",fix:"path.resolve(SAFE_DIR, userInput)",documentationLink:"https://nodejs.org/api/path.html#pathresolvepaths"}),validatePath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Validate Path",description:"Validate resolved path starts with allowed base",severity:"LOW",fix:"if (!resolved.startsWith(SAFE_DIR)) throw new Error()",documentationLink:"https://owasp.org/www-community/attacks/Path_Traversal"}),useBasename:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use path.basename",description:"Use path.basename() to strip directory components",severity:"LOW",fix:"path.basename(userInput)",documentationLink:"https://nodejs.org/api/path.html#pathbasenamepath-suffix"}),createSafeDir:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Define Safe Directory",description:"Define SAFE_DIR constant",severity:"LOW",fix:'const SAFE_DIR = path.resolve(__dirname, "uploads")',documentationLink:"https://owasp.org/www-community/attacks/Path_Traversal"}),whitelistExtensions:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Whitelist Extensions",description:"Whitelist allowed file extensions",severity:"LOW",fix:'const ALLOWED_EXT = [".txt", ".pdf"]; if (!ALLOWED_EXT.includes(ext)) throw',documentationLink:"https://owasp.org/www-community/attacks/Path_Traversal"})},schema:[{type:"object",properties:{taintSources:{type:"array",items:{type:"string"},description:"Identifier roots treated as attacker-reachable (default: req, request, ctx, event, process)"},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."},allowLiterals:{type:"boolean",default:false,description:"Allow literal string paths"},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional fs methods to check"},allowedExtensions:{type:"array",items:{type:"string"},default:[],description:'Allowed file extensions (e.g., [".txt", ".json"])'}},additionalProperties:false}]},defaultOptions:[{allowLiterals:false,additionalMethods:[]}],create(context){const options=context.options[0]||{};const{allowLiterals=false,additionalMethods=[]}=options;const DEFAULT_TAINT_ROOTS=["process"];const taintRoots=new Set(options.taintSources??DEFAULT_TAINT_ROOTS);const reportUnresolvedPaths=options.reportUnresolvedPaths??false;const 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]]]);const 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]);const isLiteralString=node=>{return node.type==="Literal"&&typeof node.value==="string"};const readsTaintSource=(node,depth=0)=>{if(depth>6)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return true;const bound=constBindings.get(node.name);return bound!==void 0&&readsTaintSource(bound,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{return readsTaintSource(node.object,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>readsTaintSource(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return readsTaintSource(node.left,depth+1)||readsTaintSource(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(arg=>arg.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&readsTaintSource(arg,depth+1));default:return false}};const isWholeTaintValue=node=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return true;const bound=constBindings.get(node.name);return bound!==void 0&&isWholeTaintValue(bound)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isWholeTaintValue(node.object);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"&&node.arguments.length===1&&isWholeTaintValue(node.arguments[0])}default:return false}};const isDangerousPath=(pathNode,pathStr)=>{if(!pathNode)return reportUnresolvedPaths;if(isLiteralString(pathNode)){return!allowLiterals&&hasTraversalPatterns(pathStr)}if(hasPathValidation(pathNode))return false;if(readsTaintSource(pathNode))return!isWholeTaintValue(pathNode);if(isBuildTimeConstant(pathNode))return false;if(isFreeVariable(pathNode))return true;if(containsFreeVariable(pathNode))return true;return reportUnresolvedPaths};function isFreeVariable(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const through=context.sourceCode.getScope(node).through;return through.some(ref=>ref.identifier===node&&ref.resolved===null)}const containsFreeVariable=(node,depth=0)=>{if(depth>4)return false;if(isBuildTimeConstant(node,depth))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,depth+1));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>a.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&containsFreeVariable(a,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return node.operator==="+"&&(containsFreeVariable(node.left,depth+1)||containsFreeVariable(node.right,depth+1));default:return false}};const isBuildTimeConstant=(node,depth=0)=>{if(depth>4)return false;if(isLiteralString(node)){return!hasTraversalPatterns(node.value)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(node.name==="__dirname"||node.name==="__filename")return true;const bound=constBindings.get(node.name);return bound!==void 0&&isBuildTimeConstant(bound,depth+1)}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,depth+1))}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"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name==="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"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["join","resolve"].includes(callee.property.name)){return node.arguments.length>0&&node.arguments.every(arg=>isBuildTimeConstant(arg,depth+1))}return false}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return isBuildTimeConstant(node.left,depth+1)&&isBuildTimeConstant(node.right,depth+1)}return false};const hasPathValidation=pathNode=>{if(pathNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}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&&testNode.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(testNode.callee.property.name==="startsWith"||testNode.callee.property.name==="includes")){return true}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&testNode.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.callee.property.name==="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&&testNode.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.callee.property.name==="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 current=pathNode.parent;let foundFunctionBody=false;while(current&&!foundFunctionBody){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(isValidationCall(current.test)){return true}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&current.parent&&(current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression)){foundFunctionBody=true;const blockBody=current.body;const nodeIndex=blockBody.findIndex(stmt=>{let check=pathNode;while(check){if(check===stmt)return true;check=check.parent}return false});for(let i=0;i<nodeIndex;i++){const stmt=blockBody[i];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&isValidationCall(stmt.test)&&hasEarlyExit(stmt.consequent)){return true}}}current=current.parent}return false};const fsNamespaces=new Set(["fs"]);const fsNamedMethods=new Map;const pendingCalls=[];const constBindings=new Map;function bindFsName(local,imported){if(imported==="promises")fsNamespaces.add(local);else fsNamedMethods.set(local,imported)}const checkFsCall=node=>{let methodName=fsMethodName(node.callee,fsNamespaces,fsNamedMethods);if(methodName===void 0){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,context.sourceCode.getScope(node),{equivalents:FS_MODULE_EQUIVALENTS});if(binding?.module!=="fs")return;const[first,second]=binding.path;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 sourceCode=context.sourceCode;let pathNode=null;let path="";for(const index of indices){const candidate=node.arguments[index];if(candidate===void 0||candidate.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;if(isDangerousPath(candidate,sourceCode.getText(candidate))){pathNode=candidate;path=sourceCode.getText(candidate);break}}if(pathNode===null){const present=indices.some(index=>node.arguments[index]!==void 0);if(!present&&isDangerousPath(null,"")){context.report({node,messageId:"fsPathTraversal",data:{method,path:"",riskLevel:"MEDIUM",vulnerability:"path traversal",safePattern:"Use path.resolve() with validation",steps:"Review file system access patterns"},suggest:[{messageId:"validatePath",fix:()=>null},{messageId:"usePathResolve",fix:()=>null},{messageId:"whitelistExtensions",fix:()=>null}]})}return}const operation=FS_OPERATIONS.find(op=>op.method===method)??null;const riskLevel=(0,exports.determineRiskLevel)(operation||FS_OPERATIONS[0],path);const steps=operation?(0,exports.generateRefactoringSteps)(operation):"Review file system access patterns";const safePattern=operation?.safePattern||"Use path.resolve() with validation";context.report({node,messageId:"fsPathTraversal",data:{method,path,riskLevel,vulnerability:operation?.vulnerability||"path traversal",safePattern,steps,effort:operation?.effort||"15-20 minutes"},suggest:[{messageId:"usePathResolve",fix:()=>null},{messageId:"validatePath",fix:()=>null},{messageId:"useBasename",fix:()=>null},{messageId:"createSafeDir",fix:()=>null},{messageId:"whitelistExtensions",fix:()=>null}]})};return{ImportDeclaration(node){if(!(0,exports.isFsModule)(node.source.value))return;for(const spec of node.specifiers){if(spec.type===eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier){const imported=spec.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?spec.imported.name:spec.imported.value;bindFsName(spec.local.name,imported);continue}fsNamespaces.add(spec.local.name)}},VariableDeclarator(node){if(node.init!==null&&node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration&&node.parent.kind==="const"){constBindings.set(node.id.name,node.init)}if(node.init===null||!isFsRequire(node.init))return;if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){fsNamespaces.add(node.id.name);return}if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return;for(const prop of node.id.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property||prop.computed)continue;if(prop.value.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;const key=prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.key.name:prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"?prop.key.value:void 0;if(key===void 0)continue;bindFsName(prop.value.name,key)}},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.isFsModule=exports.generateRefactoringSteps=void 0;exports.fsMethodName=fsMethodName;exports.isFsRequire=isFsRequire;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const FS_OPERATIONS=[{method:"readFile",dangerous:true,vulnerability:"file-access",safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))",example:{bad:"fs.readFile(userPath, callback)",good:"const safePath = path.join(SAFE_UPLOADS_DIR, path.basename(userPath)); fs.readFile(safePath, callback)"},effort:"10-15 minutes"},{method:"writeFile",dangerous:true,vulnerability:"file-access",safePattern:"path.resolve(SAFE_DIR, path.basename(userInput))",example:{bad:"fs.writeFile(userPath, data, callback)",good:"const safePath = path.join(SAFE_WRITES_DIR, path.basename(userPath)); fs.writeFile(safePath, data, callback)"},effort:"10-15 minutes"},{method:"stat",dangerous:true,vulnerability:"path-traversal",safePattern:"path.resolve(baseDir, userInput) with validation",example:{bad:"fs.stat(userPath, callback)",good:"const resolvedPath = path.resolve(SAFE_DIR, userPath);\nif (!resolvedPath.startsWith(SAFE_DIR + path.sep)) return;\nfs.stat(resolvedPath, callback)"},effort:"15-20 minutes"},{method:"readdir",dangerous:true,vulnerability:"directory-traversal",safePattern:"Validate directory is within allowed paths",example:{bad:"fs.readdir(userDir, callback)",good:"const resolvedDir = path.resolve(ALLOWED_DIRS, userDir);\nif (!resolvedDir.startsWith(ALLOWED_DIRS + path.sep)) return;\nfs.readdir(resolvedDir, callback)"},effort:"15-20 minutes"}];const hasTraversalPatterns=pathStr=>{return/\.\.[/\\]/.test(pathStr)||/^\.\.[/\\]/.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=pathStr=>{const unquoted=pathStr.replace(/^['"`]|['"`]$/g,"");const normalised=unquoted.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 FS_MODULE_EQUIVALENTS={"fs-extra":"fs","graceful-fs":"fs","fs/promises":"fs"};const FS_MODULES=new Set(["fs","node:fs","fs/promises","node:fs/promises","fs-extra","graceful-fs"]);const isFsModule=source=>typeof source==="string"&&FS_MODULES.has(source);exports.isFsModule=isFsModule;function fsMethodName(callee,namespaces,named){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return named.get(callee.name);if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed||callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return void 0}const object=callee.object;if(object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&namespaces.has(object.name)){return callee.property.name}if(object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!object.computed&&object.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&namespaces.has(object.object.name)&&object.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&object.property.name==="promises"){return callee.property.name}return void 0}function isFsRequire(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments.length>0&&node.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(0,exports.isFsModule)(node.arguments[0].value)}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:{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."},allowLiterals:{type:"boolean",default:false,description:`Allow literal string paths. Default true: a rule named "non-literal" reporting a literal contradicts its contract. Set false to also flag hardcoded paths containing "../" \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:[]}],create(context){const options=context.options[0]||{};const{allowLiterals=false,additionalMethods=[]}=options;const DEFAULT_TAINT_ROOTS=["process","req","request","ctx","context","event"];const WHOLE_VALUE_TRUSTED_ROOTS=new Set(["process"]);const AMBIGUOUS_ROOTS=new Set(["ctx","context"]);const REQUEST_SURFACE=new Set(["query","params","body","request","req","headers","cookies","searchParams","originalUrl"]);const resolvesInFile=id=>context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved!=null;const readsRequestSurface=node=>node?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_SURFACE.has(node.property.name);const hasRequestEvidence=id=>{if(readsRequestSurface(id.parent))return true;const variable=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id).resolved;return variable.references.some(ref=>readsRequestSurface(ref.identifier.parent))};const taintRoots=new Set(options.taintSources??DEFAULT_TAINT_ROOTS);const reportUnresolvedPaths=options.reportUnresolvedPaths??false;const 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]]]);const 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]);const isLiteralString=node=>{return node.type==="Literal"&&typeof node.value==="string"};const isLocallyConstructed=id=>{const variable=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved;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 readsTaintSource=(node,depth=0)=>{if(depth>6)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name)){if(AMBIGUOUS_ROOTS.has(node.name)&&resolvesInFile(node)&&!hasRequestEvidence(node)){return false}return!isLocallyConstructed(node)}const bound=constBindings.get(node.name);return bound!==void 0&&readsTaintSource(bound,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if(!node.computed&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="process"&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!PROCESS_INPUT_MEMBERS.has(node.property.name)){return false}return readsTaintSource(node.object,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>readsTaintSource(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return readsTaintSource(node.left,depth+1)||readsTaintSource(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="path"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name==="basename"){return false}return node.arguments.some(arg=>arg.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&readsTaintSource(arg,depth+1))}default:return false}};const containsUntrustedRoot=(node,depth=0)=>{if(depth>6)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return!WHOLE_VALUE_TRUSTED_ROOTS.has(node.name);const bound=constBindings.get(node.name);return bound!==void 0&&containsUntrustedRoot(bound,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return containsUntrustedRoot(node.object,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>containsUntrustedRoot(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return containsUntrustedRoot(node.left,depth+1)||containsUntrustedRoot(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>a.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&containsUntrustedRoot(a,depth+1));default:return false}};const isWholeTaintValue=node=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(taintRoots.has(node.name))return WHOLE_VALUE_TRUSTED_ROOTS.has(node.name);const bound=constBindings.get(node.name);return bound!==void 0&&isWholeTaintValue(bound)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isWholeTaintValue(node.object);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;if(node.arguments.length===1)return isWholeTaintValue(node.arguments[0]);return isWholeTaintValue(node.arguments[0])&&!containsUntrustedRoot(node)}default:return false}};const isDangerousPath=(pathNode,pathStr)=>{if(!pathNode)return reportUnresolvedPaths;if(isLiteralString(pathNode)){return!allowLiterals&&targetsSensitiveLocation(pathStr)}if(hasPathValidation(pathNode))return false;if(readsTaintSource(pathNode))return!isWholeTaintValue(pathNode);if(isBuildTimeConstant(pathNode))return false;if(isFreeVariable(pathNode))return true;if(containsFreeVariable(pathNode))return true;return reportUnresolvedPaths};function isFreeVariable(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const through=context.sourceCode.getScope(node).through;return through.some(ref=>ref.identifier===node&&ref.resolved===null)}const containsFreeVariable=(node,depth=0)=>{if(depth>4)return false;if(isBuildTimeConstant(node,depth))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,depth+1));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(a=>a.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&containsFreeVariable(a,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return node.operator==="+"&&(containsFreeVariable(node.left,depth+1)||containsFreeVariable(node.right,depth+1));default:return false}};const isBuildTimeConstant=(node,depth=0)=>{if(depth>4)return false;if(isLiteralString(node)){return!hasTraversalPatterns(node.value)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(node.name==="__dirname"||node.name==="__filename")return true;const bound=constBindings.get(node.name);return bound!==void 0&&isBuildTimeConstant(bound,depth+1)}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,depth+1))}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"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name==="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"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["join","resolve"].includes(callee.property.name)){return node.arguments.length>0&&node.arguments.every(arg=>isBuildTimeConstant(arg,depth+1))}return false}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return isBuildTimeConstant(node.left,depth+1)&&isBuildTimeConstant(node.right,depth+1)}return false};const isSeparatorAnchored=arg=>{if(arg===void 0)return false;const endsWithSep=n=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!n.computed&&n.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&n.object.name==="path"&&n.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&n.property.name==="sep"){return true}if(n.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof n.value==="string"){return n.value.endsWith("/")||n.value.endsWith("\\")}return false};if(endsWithSep(arg))return true;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){return endsWithSep(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const last=arg.quasis[arg.quasis.length-1].value.cooked;if(last.endsWith("/")||last.endsWith("\\"))return true;if(last===""){const tail=arg.expressions[arg.expressions.length-1];return tail!==void 0&&endsWithSep(tail)}return false}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&&n.operator==="+"){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=>{if(a.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement)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&&testNode.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(testNode.callee.property.name==="startsWith"||testNode.callee.property.name==="includes")){return testNode.callee.property.name==="includes"?true:isSeparatorAnchored(testNode.arguments[0])}if(testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&testNode.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.callee.property.name==="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&&testNode.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.callee.property.name==="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 current=pathNode.parent;let foundFunctionBody=false;while(current&&!foundFunctionBody){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(isValidationCall(current.test)){return true}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&current.parent&&(current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression)){foundFunctionBody=true;const blockBody=current.body;const nodeIndex=blockBody.findIndex(stmt=>{let check=pathNode;while(check){if(check===stmt)return true;check=check.parent}return false});for(let i=0;i<nodeIndex;i++){const stmt=blockBody[i];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&isValidationCall(stmt.test)&&hasEarlyExit(stmt.consequent)){return true}}}current=current.parent}return false};const fsNamespaces=new Set(["fs"]);const fsNamedMethods=new Map;const pendingCalls=[];const constBindings=new Map;function bindFsName(local,imported){if(imported==="promises")fsNamespaces.add(local);else fsNamedMethods.set(local,imported)}const checkFsCall=node=>{let methodName=fsMethodName(node.callee,fsNamespaces,fsNamedMethods);if(methodName===void 0){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,context.sourceCode.getScope(node),{equivalents:FS_MODULE_EQUIVALENTS});if(binding?.module!=="fs")return;const[first,second]=binding.path;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 sourceCode=context.sourceCode;let pathNode=null;let path="";for(const index of indices){const candidate=node.arguments[index];if(candidate===void 0||candidate.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;if(isDangerousPath(candidate,sourceCode.getText(candidate))){pathNode=candidate;path=sourceCode.getText(candidate);break}}if(pathNode===null){const present=indices.some(index=>node.arguments[index]!==void 0);if(!present&&isDangerousPath(null,"")){context.report({node,messageId:"fsPathTraversal",data:{method,path:"",riskLevel:"MEDIUM",vulnerability:"path traversal",safePattern:"Use path.resolve() with validation",steps:"Review file system access patterns"}})}return}const operation=FS_OPERATIONS.find(op=>op.method===method)??null;const riskLevel=(0,exports.determineRiskLevel)(operation||FS_OPERATIONS[0],path);const steps=operation?(0,exports.generateRefactoringSteps)(operation):"Review file system access patterns";const safePattern=operation?.safePattern||"Use path.resolve() with validation";context.report({node,messageId:"fsPathTraversal",data:{method,path,riskLevel,vulnerability:operation?.vulnerability||"path traversal",safePattern,steps,effort:operation?.effort||"15-20 minutes"}})};return{ImportDeclaration(node){if(!(0,exports.isFsModule)(node.source.value))return;for(const spec of node.specifiers){if(spec.type===eslint_devkit_1.AST_NODE_TYPES.ImportSpecifier){const imported=spec.imported.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?spec.imported.name:spec.imported.value;bindFsName(spec.local.name,imported);continue}fsNamespaces.add(spec.local.name)}},VariableDeclarator(node){if(node.init!==null&&node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration&&node.parent.kind==="const"){constBindings.set(node.id.name,node.init)}if(node.init===null||!isFsRequire(node.init))return;if(node.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){fsNamespaces.add(node.id.name);return}if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return;for(const prop of node.id.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property||prop.computed)continue;if(prop.value.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;const key=prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.key.name:prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"?prop.key.value:void 0;if(key===void 0)continue;bindFsName(prop.value.name,key)}},CallExpression(node){pendingCalls.push(node)},"Program:exit"(){for(const call of pendingCalls)checkFsCall(call)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectSuspiciousDependencies=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.detectSuspiciousDependencies=(0,eslint_devkit_1.createRule)({name:"detect-suspicious-dependencies",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-suspicious-dependencies.md",description:"Detect typosquatting in package names",cwe:"CWE-506",cvss:7.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Suspicious Dependency",cwe:"CWE-506",description:"Suspicious package name detected - possible typosquatting",severity:"HIGH",fix:"Verify package authenticity on npm registry",documentationLink:"https://cwe.mitre.org/data/definitions/506.html"})},schema:[]},defaultOptions:[],create(context){const popularPackages=["react","lodash","express","axios","webpack"];const KNOWN_LEGITIMATE=new Set(["preact","recast","react-dom","reactor","redux","lodash-es","expressive","axios-retry","webpack-cli"]);function levenshtein(a,b){const matrix=[];for(let i=0;i<=b.length;i++){matrix[i]=[i]}for(let j=0;j<=a.length;j++){matrix[0][j]=j}for(let i=1;i<=b.length;i++){for(let j=1;j<=a.length;j++){if(b.charAt(i-1)===a.charAt(j-1)){matrix[i][j]=matrix[i-1][j-1]}else{matrix[i][j]=Math.min(matrix[i-1][j-1]+1,matrix[i][j-1]+1,matrix[i-1][j]+1);if(i>1&&j>1&&b.charAt(i-1)===a.charAt(j-2)&&b.charAt(i-2)===a.charAt(j-1)){matrix[i][j]=Math.min(matrix[i][j],matrix[i-2][j-2]+1)}}}}return matrix[b.length][a.length]}const checkSpecifier=(node,source)=>{if(typeof source!=="string")return;if(source.startsWith(".")||source.startsWith("@"))return;for(const popular of popularPackages){const distance=levenshtein(source,popular);if(distance===1&&!KNOWN_LEGITIMATE.has(source)){context.report({node,messageId:"violationDetected",data:{name:source,similar:popular}})}}};return{ImportDeclaration(node){checkSpecifier(node,node.source.value)},TSImportEqualsDeclaration(node){const ref=node.moduleReference;if(ref.type!==eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference)return;checkSpecifier(node,ref.expression.value)},ImportExpression(node){if(node.source.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return;checkSpecifier(node,node.source.value)},CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(node.callee.name!=="require")return;const[arg]=node.arguments;if(arg?.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return;checkSpecifier(node,arg.value)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectSuspiciousDependencies=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");exports.detectSuspiciousDependencies=(0,eslint_devkit_1.createRule)({name:"detect-suspicious-dependencies",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/detect-suspicious-dependencies.md",description:"Detect typosquatting in package names",cwe:"CWE-506",cvss:9.8},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Suspicious Dependency",cwe:"CWE-506",description:"Suspicious package name detected - possible typosquatting",severity:"HIGH",fix:"Verify package authenticity on npm registry",documentationLink:"https://cwe.mitre.org/data/definitions/506.html"})},schema:[]},defaultOptions:[],create(context){const popularPackages=["react","lodash","express","axios","webpack"];const KNOWN_LEGITIMATE=new Set(["preact","recast","react-dom","reactor","redux","lodash-es","expressive","axios-retry","webpack-cli"]);function levenshtein(a,b){const matrix=[];for(let i=0;i<=b.length;i++){matrix[i]=[i]}for(let j=0;j<=a.length;j++){matrix[0][j]=j}for(let i=1;i<=b.length;i++){for(let j=1;j<=a.length;j++){if(b.charAt(i-1)===a.charAt(j-1)){matrix[i][j]=matrix[i-1][j-1]}else{matrix[i][j]=Math.min(matrix[i-1][j-1]+1,matrix[i][j-1]+1,matrix[i-1][j]+1);if(i>1&&j>1&&b.charAt(i-1)===a.charAt(j-2)&&b.charAt(i-2)===a.charAt(j-1)){matrix[i][j]=Math.min(matrix[i][j],matrix[i-2][j-2]+1)}}}}return matrix[b.length][a.length]}const checkSpecifier=(node,source)=>{if(source.startsWith(".")||source.startsWith("@"))return;const name=source.slice(0,source.indexOf("/")===-1?source.length:source.indexOf("/"));for(const popular of popularPackages){const distance=levenshtein(name,popular);if(distance===1&&!KNOWN_LEGITIMATE.has(name)){context.report({node,messageId:"violationDetected",data:{name,similar:popular}})}}};const checkExpression=(node,specifier)=>{const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,(0,eslint_devkit_1.unwrapTypeSyntax)(specifier));if(resolved===null)return;checkSpecifier(node,resolved.value)};const isModuleLoader=callee=>{if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(callee.name==="require")return true;const init=(0,const_value_1.constInitializerOf)(context.sourceCode,callee);if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const binding=(0,eslint_devkit_1.resolveModuleBinding)(init.callee,context.sourceCode.getScope(init));return binding?.module==="module"&&binding.path.join(".")==="createRequire"};return{ImportDeclaration(node){checkSpecifier(node,node.source.value)},ExportNamedDeclaration(node){if(node.source===null)return;checkSpecifier(node,node.source.value)},ExportAllDeclaration(node){checkSpecifier(node,node.source.value)},TSImportEqualsDeclaration(node){const ref=node.moduleReference;if(ref.type!==eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference)return;checkSpecifier(node,ref.expression.value)},ImportExpression(node){checkExpression(node,node.source)},CallExpression(node){if(!isModuleLoader(node.callee))return;const[arg]=node.arguments;if(arg===void 0)return;checkExpression(node,arg)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.lockFile=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const reportedRoots=new Set;exports.lockFile=(0,eslint_devkit_1.createRule)({name:"lock-file",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/lock-file.md",description:"Ensure package lock file exists for the configured package manager",cwe:"CWE-829",cvss:7.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Lock File Missing",cwe:"CWE-829",description:"Package lock file missing ({{ lockFile }}) for {{ packageManager }}. Commit the lock file to ensure supply chain integrity.",severity:"HIGH",fix:"Generate and commit the {{ lockFile }} file.",documentationLink:"https://cwe.mitre.org/data/definitions/829.html"})},schema:[{type:"object",properties:{packageManager:{type:"string",enum:["npm","yarn","pnpm"],description:"Package manager whose lock file is required"}},additionalProperties:false}]},defaultOptions:[{}],create(context){const fs=require("node:fs");const path=require("node:path");const options=context.options[0]||{};const userPackageManager=options.packageManager;const lockFiles={npm:"package-lock.json",yarn:"yarn.lock",pnpm:"pnpm-lock.yaml"};const targetLockFiles=userPackageManager?[lockFiles[userPackageManager]]:Object.values(lockFiles);const targetLockFile=userPackageManager?lockFiles[userPackageManager]:"package-lock.json | yarn.lock | pnpm-lock.yaml";const reportedManager=userPackageManager??"any";const findUpward=(from,names)=>{let dir=from;for(;;){for(const name of names){if(fs.existsSync(path.join(dir,name)))return dir}const parent=path.dirname(dir);if(parent===dir)return void 0;dir=parent}};return{Program(node){const found=findUpward(path.dirname(context.filename),targetLockFiles)!==void 0;if(!found){const root=findUpward(path.dirname(context.filename),["package.json"]);if(root===void 0)return;if(reportedRoots.has(root))return;reportedRoots.add(root);context.report({node,messageId:"violationDetected",data:{packageManager:reportedManager,lockFile:targetLockFile}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.lockFile=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const reportedRoots=new Set;exports.lockFile=(0,eslint_devkit_1.createRule)({name:"lock-file",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/lock-file.md",description:"Ensure package lock file exists for the configured package manager",cwe:"CWE-829",cvss:7.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Lock File Missing",cwe:"CWE-829",description:"Package lock file missing ({{ lockFile }}) for {{ packageManager }}. Commit the lock file to ensure supply chain integrity.",severity:"HIGH",fix:"Generate and commit the {{ lockFile }} file.",documentationLink:"https://cwe.mitre.org/data/definitions/829.html"})},schema:[{type:"object",properties:{packageManager:{type:"string",enum:["any","npm","yarn","pnpm"],default:"any",description:"Package manager whose lock file is required. `any` accepts package-lock.json, yarn.lock or pnpm-lock.yaml \u2014 the right setting for a repo that has not standardised."}},additionalProperties:false}]},defaultOptions:[{}],create(context){const fs=require("node:fs");const path=require("node:path");const options=context.options[0]||{};const packageManager=options.packageManager??"any";const lockFiles={npm:"package-lock.json",yarn:"yarn.lock",pnpm:"pnpm-lock.yaml"};const specific=packageManager!=="any";const targetLockFiles=specific?[lockFiles[packageManager]]:Object.values(lockFiles);const targetLockFile=specific?lockFiles[packageManager]:"package-lock.json | yarn.lock | pnpm-lock.yaml";const reportedManager=packageManager;const findUpward=(from,names)=>{let dir=from;for(;;){for(const name of names){if(fs.existsSync(path.join(dir,name)))return dir}const parent=path.dirname(dir);if(parent===dir)return void 0;dir=parent}};return{Program(node){const found=findUpward(path.dirname(context.filename),targetLockFiles)!==void 0;if(!found){const root=findUpward(path.dirname(context.filename),["package.json"]);if(root===void 0)return;if(reportedRoots.has(root))return;reportedRoots.add(root);context.report({node,messageId:"violationDetected",data:{packageManager:reportedManager,lockFile:targetLockFile}})}}}}});