eslint-plugin-secure-coding 3.7.1 → 4.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.
package/README.md CHANGED
@@ -16,6 +16,7 @@
16
16
  <a href="https://opensource.org/licenses/MIT" target="_blank"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="Package License" /></a>
17
17
  <a href="https://app.codecov.io/gh/ofri-peretz/eslint/components?components%5B0%5D=eslint-plugin-secure-coding" target="_blank"><img src="https://codecov.io/gh/ofri-peretz/eslint/graph/badge.svg?component=eslint-plugin-secure-coding" alt="Codecov" /></a>
18
18
  <a href="https://github.com/ofri-peretz/eslint" target="_blank"><img src="https://img.shields.io/badge/Since-Dec_2025-blue?logo=rocket&logoColor=white" alt="Since Dec 2025" /></a>
19
+ <a href="https://scorecard.dev/viewer/?uri=github.com/ofri-peretz/eslint" target="_blank"><img src="https://api.securityscorecards.dev/projects/github.com/ofri-peretz/eslint/badge" alt="OpenSSF Scorecard" /></a>
19
20
  </p>
20
21
 
21
22
  > ⭐ If this plugin caught a real bug for you, [**star the repo**](https://github.com/ofri-peretz/eslint) — it's the signal that keeps these rules maintained.
@@ -124,24 +125,28 @@ See the [ESLint Version Support Policy](../../docs/ESLINT_VERSION_SUPPORT.md)
124
125
  | [detect-weak-password-validation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/detect-weak-password-validation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-521 | A07:2021 | | Detects weak password length requirements (less than 8 characters) in validation code. | 🟢 | | | | | |
125
126
  | [no-directive-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-directive-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-94 | | | Detects directive injection vulnerabilities in template systems | 🟢 | | | | | |
126
127
  | [no-electron-security-issues](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-electron-security-issues?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-16 | | | Detects Electron security vulnerabilities and insecure configurations | 🟢 | | | | | |
128
+ | [no-fail-open-auth](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-fail-open-auth?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-636 | A10:2025 | | Detects authentication and authorization checks whose catch block fails open | 🟢 | 💼 | | | | |
127
129
  | [no-format-string-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-format-string-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-134 | | | Detects format string injection vulnerabilities | 🟢 | | | | | |
128
- | [no-graphql-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-graphql-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-943 | | | Detects GraphQL injection vulnerabilities and DoS attacks | 🟢 | 💼 | | | | |
130
+ | [no-graphql-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-graphql-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-943 | | | Detects GraphQL injection vulnerabilities and DoS attacks | 🟢 | | ⚠️ | | | |
129
131
  | [no-hardcoded-credentials](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-hardcoded-credentials?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-798 | | | Detects hardcoded passwords, API keys, tokens, and other sensitive credentials in source code | 🟢 | 💼 | | | | |
130
132
  | [no-hardcoded-session-tokens](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-hardcoded-session-tokens?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-798 | | | This rule detects hardcoded JWT tokens (starting with eyJ), Bearer tokens, and session identifiers | 🟢 | | | | | |
131
- | [no-improper-sanitization](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-improper-sanitization?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-116 | | | Detects improper sanitization of user input | 🟢 | | | | | |
132
- | [no-improper-type-validation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-improper-type-validation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-1287 | | | Detects improper type validation in user input handling | 🟢 | 💼 | | | | |
133
+ | [no-homoglyph-identifiers](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-homoglyph-identifiers?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-1007 | A08:2021 | | Detects homoglyph identifiers and invisible characters that hide what the code actually does | 🟢 | 💼 | | | | |
134
+ | [no-improper-sanitization](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-improper-sanitization?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-116 | | | Detects improper sanitization of user input | 🟢 | 💼 | | | | |
135
+ | [no-improper-type-validation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-improper-type-validation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-1287 | | | Detects improper type validation in user input handling | 🟢 | | | | | |
133
136
  | [no-insecure-comparison](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-insecure-comparison?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-697 | | | Detects insecure comparison operators (==, !=) that can lead to type coercion vulnerabilities | 🟢 | | | | | |
134
137
  | [no-ldap-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-ldap-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-90 | | | Detects LDAP injection vulnerabilities | 🟢 | 💼 | | | | |
138
+ | [no-log-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-log-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-117 | A09:2021 | | Detects request data concatenated into a log message, which lets an attacker forge log records | 🟢 | 💼 | | | | |
135
139
  | [no-missing-authentication](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-missing-authentication?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-287 | | | CWE: [CWE-287](https://cwe.mitre.org/data/definitions/287.html) | 🟢 | | | | | |
136
140
  | [no-pii-in-logs](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-pii-in-logs?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-359 | | | Prevent personally identifiable information (PII) — emails, SSNs, credit cards, phone numbers — from reachi… | 🟢 | | | | 💡 | |
137
141
  | [no-privilege-escalation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-privilege-escalation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-269 | | | Detects potential privilege escalation vulnerabilities where user input is used to assign roles or permissi… | 🟢 | | ⚠️ | | | |
138
- | [no-redos-vulnerable-regex](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-redos-vulnerable-regex?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-400 | | | ESLint Rule: no-redos-vulnerable-regex | 🟢 | | | | | |
142
+ | [no-redos-vulnerable-regex](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-redos-vulnerable-regex?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-400 | | | ESLint Rule: no-redos-vulnerable-regex | 🟢 | 💼 | | | | |
139
143
  | [no-sensitive-data-exposure](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-sensitive-data-exposure?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-532 | | | ESLint Rule: no-sensitive-data-exposure | 🟢 | | ⚠️ | | | |
144
+ | [no-sql-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-sql-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-89 | A03:2021 | | Detects SQL statements built from attacker-controlled input in files that import no SQL driver | 🟢 | 💼 | | | | |
140
145
  | [no-unchecked-loop-condition](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-unchecked-loop-condition?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-400 | | | Detects unchecked loop conditions that could cause DoS | 🟢 | | | | | |
141
- | [no-unlimited-resource-allocation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-unlimited-resource-allocation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-770 | | | Detects unlimited resource allocation that could cause DoS | 🟢 | | | | | |
142
- | [no-unsafe-deserialization](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-unsafe-deserialization?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-502 | | | Detects unsafe deserialization of untrusted data | 🟢 | 💼 | | | | |
143
- | [no-unsafe-regex-construction](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-unsafe-regex-construction?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-400 | | | ESLint Rule: no-unsafe-regex-construction with LLM-optimized suggestions and auto-fix capabilities | 🟢 | | | | | |
144
- | [no-weak-password-recovery](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-weak-password-recovery?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-640 | | | ESLint Rule: no-weak-password-recovery with LLM-optimized suggestions and auto-fix capabilities | 🟢 | 💼 | | | | |
146
+ | [no-unlimited-resource-allocation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-unlimited-resource-allocation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-770 | | | Detects unlimited resource allocation that could cause DoS | 🟢 | | ⚠️ | | | |
147
+ | [no-unsafe-deserialization](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-unsafe-deserialization?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-502 | | | Detects unsafe deserialization of untrusted data | 🟢 | | ⚠️ | | | |
148
+ | [no-unsafe-regex-construction](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-unsafe-regex-construction?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-400 | | | ESLint Rule: no-unsafe-regex-construction with LLM-optimized suggestions and auto-fix capabilities | 🟢 | 💼 | | | | |
149
+ | [no-weak-password-recovery](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-weak-password-recovery?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-640 | | | ESLint Rule: no-weak-password-recovery with LLM-optimized suggestions and auto-fix capabilities | 🟢 | | ⚠️ | | | |
145
150
  | [no-xpath-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-xpath-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-643 | | | Detects XPath injection vulnerabilities | 🟢 | 💼 | | | | |
146
151
  | [no-xxe-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-xxe-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-611 | | | Detects XML External Entity (XXE) injection vulnerabilities | 🟢 | 💼 | | | | |
147
152
  | [require-backend-authorization](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/require-backend-authorization?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-602 | | | CWE: [CWE-602](https://cwe.mitre.org/data/definitions/602.html) | 🟢 | | | | | |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-secure-coding",
3
- "version": "3.7.1",
3
+ "version": "4.0.0",
4
4
  "description": "ESLint plugin for secure coding — detects LDAP, XPath, XXE, GraphQL and template injection, unsafe deserialization, ReDoS, missing authentication, and PII in logs.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -77,7 +77,7 @@
77
77
  "node": ">=18.0.0"
78
78
  },
79
79
  "dependencies": {
80
- "@interlace/eslint-devkit": "^1.13.0",
80
+ "@interlace/eslint-devkit": "^1.14.0",
81
81
  "scslre": "^0.3.0",
82
82
  "@eslint-community/regexpp": "^4.10.0"
83
83
  },
package/src/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;exports.rules={get"no-graphql-injection"(){return require("./rules/no-graphql-injection").noGraphqlInjection},get"no-xxe-injection"(){return require("./rules/no-xxe-injection").noXxeInjection},get"no-xpath-injection"(){return require("./rules/no-xpath-injection").noXpathInjection},get"no-ldap-injection"(){return require("./rules/no-ldap-injection").noLdapInjection},get"no-directive-injection"(){return require("./rules/no-directive-injection").noDirectiveInjection},get"no-format-string-injection"(){return require("./rules/no-format-string-injection").noFormatStringInjection},get"no-template-injection"(){return require("./rules/no-template-injection").noTemplateInjection},get"detect-non-literal-regexp"(){return require("./rules/detect-non-literal-regexp").detectNonLiteralRegexp},get"no-redos-vulnerable-regex"(){return require("./rules/no-redos-vulnerable-regex").noRedosVulnerableRegex},get"no-unsafe-regex-construction"(){return require("./rules/no-unsafe-regex-construction").noUnsafeRegexConstruction},get"detect-object-injection"(){return require("./rules/detect-object-injection").detectObjectInjection},get"no-unsafe-deserialization"(){return require("./rules/no-unsafe-deserialization").noUnsafeDeserialization},get"no-insecure-comparison"(){return require("./rules/no-insecure-comparison").noInsecureComparison},get"no-improper-sanitization"(){return require("./rules/no-improper-sanitization").noImproperSanitization},get"no-improper-type-validation"(){return require("./rules/no-improper-type-validation").noImproperTypeValidation},get"no-missing-authentication"(){return require("./rules/no-missing-authentication").noMissingAuthentication},get"no-privilege-escalation"(){return require("./rules/no-privilege-escalation").noPrivilegeEscalation},get"no-weak-password-recovery"(){return require("./rules/no-weak-password-recovery").noWeakPasswordRecovery},get"require-backend-authorization"(){return require("./rules/require-backend-authorization").requireBackendAuthorization},get"no-hardcoded-credentials"(){return require("./rules/no-hardcoded-credentials").noHardcodedCredentials},get"no-sensitive-data-exposure"(){return require("./rules/no-sensitive-data-exposure").noSensitiveDataExposure},get"no-pii-in-logs"(){return require("./rules/no-pii-in-logs").noPiiInLogs},get"no-unlimited-resource-allocation"(){return require("./rules/no-unlimited-resource-allocation").noUnlimitedResourceAllocation},get"no-unchecked-loop-condition"(){return require("./rules/no-unchecked-loop-condition").noUncheckedLoopCondition},get"detect-weak-password-validation"(){return require("./rules/detect-weak-password-validation").detectWeakPasswordValidation},get"no-electron-security-issues"(){return require("./rules/no-electron-security-issues").noElectronSecurityIssues},get"no-hardcoded-session-tokens"(){return require("./rules/no-hardcoded-session-tokens").noHardcodedSessionTokens},get"require-secure-defaults"(){return require("./rules/require-secure-defaults").requireSecureDefaults}};exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"3.7.1"},rules:exports.rules};const recommendedRules={"secure-coding/no-graphql-injection":"warn","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-unsafe-deserialization":"warn","secure-coding/detect-non-literal-regexp":"warn","secure-coding/no-redos-vulnerable-regex":"error","secure-coding/no-unsafe-regex-construction":"error","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-template-injection":"error","secure-coding/no-improper-sanitization":"error","secure-coding/no-privilege-escalation":"warn","secure-coding/no-weak-password-recovery":"warn","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-unlimited-resource-allocation":"warn"};exports.configs={flagship:{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-hardcoded-credentials":"error","secure-coding/no-redos-vulnerable-regex":"error"}},recommended:{plugins:{"secure-coding":exports.plugin},rules:recommendedRules},"recommended-strict":{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(recommendedRules).map(rule=>[rule,"error"]))},strict:{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`secure-coding/${ruleName}`,"error"]))},"owasp-top-10":{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-privilege-escalation":"warn","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-graphql-injection":"error","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-weak-password-recovery":"error","secure-coding/no-improper-type-validation":"error","secure-coding/no-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;exports.rules={get"no-graphql-injection"(){return require("./rules/no-graphql-injection").noGraphqlInjection},get"no-xxe-injection"(){return require("./rules/no-xxe-injection").noXxeInjection},get"no-xpath-injection"(){return require("./rules/no-xpath-injection").noXpathInjection},get"no-ldap-injection"(){return require("./rules/no-ldap-injection").noLdapInjection},get"no-directive-injection"(){return require("./rules/no-directive-injection").noDirectiveInjection},get"no-format-string-injection"(){return require("./rules/no-format-string-injection").noFormatStringInjection},get"no-template-injection"(){return require("./rules/no-template-injection").noTemplateInjection},get"no-sql-injection"(){return require("./rules/no-sql-injection").noSqlInjection},get"no-log-injection"(){return require("./rules/no-log-injection").noLogInjection},get"no-fail-open-auth"(){return require("./rules/no-fail-open-auth").noFailOpenAuth},get"no-homoglyph-identifiers"(){return require("./rules/no-homoglyph-identifiers").noHomoglyphIdentifiers},get"detect-non-literal-regexp"(){return require("./rules/detect-non-literal-regexp").detectNonLiteralRegexp},get"no-redos-vulnerable-regex"(){return require("./rules/no-redos-vulnerable-regex").noRedosVulnerableRegex},get"no-unsafe-regex-construction"(){return require("./rules/no-unsafe-regex-construction").noUnsafeRegexConstruction},get"detect-object-injection"(){return require("./rules/detect-object-injection").detectObjectInjection},get"no-unsafe-deserialization"(){return require("./rules/no-unsafe-deserialization").noUnsafeDeserialization},get"no-insecure-comparison"(){return require("./rules/no-insecure-comparison").noInsecureComparison},get"no-improper-sanitization"(){return require("./rules/no-improper-sanitization").noImproperSanitization},get"no-improper-type-validation"(){return require("./rules/no-improper-type-validation").noImproperTypeValidation},get"no-missing-authentication"(){return require("./rules/no-missing-authentication").noMissingAuthentication},get"no-privilege-escalation"(){return require("./rules/no-privilege-escalation").noPrivilegeEscalation},get"no-weak-password-recovery"(){return require("./rules/no-weak-password-recovery").noWeakPasswordRecovery},get"require-backend-authorization"(){return require("./rules/require-backend-authorization").requireBackendAuthorization},get"no-hardcoded-credentials"(){return require("./rules/no-hardcoded-credentials").noHardcodedCredentials},get"no-sensitive-data-exposure"(){return require("./rules/no-sensitive-data-exposure").noSensitiveDataExposure},get"no-pii-in-logs"(){return require("./rules/no-pii-in-logs").noPiiInLogs},get"no-unlimited-resource-allocation"(){return require("./rules/no-unlimited-resource-allocation").noUnlimitedResourceAllocation},get"no-unchecked-loop-condition"(){return require("./rules/no-unchecked-loop-condition").noUncheckedLoopCondition},get"detect-weak-password-validation"(){return require("./rules/detect-weak-password-validation").detectWeakPasswordValidation},get"no-electron-security-issues"(){return require("./rules/no-electron-security-issues").noElectronSecurityIssues},get"no-hardcoded-session-tokens"(){return require("./rules/no-hardcoded-session-tokens").noHardcodedSessionTokens},get"require-secure-defaults"(){return require("./rules/require-secure-defaults").requireSecureDefaults}};exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"4.0.0"},rules:exports.rules};const recommendedRules={"secure-coding/no-graphql-injection":"warn","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-sql-injection":"error","secure-coding/no-log-injection":"error","secure-coding/no-fail-open-auth":"error","secure-coding/no-homoglyph-identifiers":"error","secure-coding/no-unsafe-deserialization":"warn","secure-coding/no-redos-vulnerable-regex":"error","secure-coding/no-unsafe-regex-construction":"error","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-template-injection":"error","secure-coding/no-improper-sanitization":"error","secure-coding/no-privilege-escalation":"warn","secure-coding/no-weak-password-recovery":"warn","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-unlimited-resource-allocation":"warn"};exports.configs={flagship:{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-hardcoded-credentials":"error","secure-coding/no-redos-vulnerable-regex":"error"}},recommended:{plugins:{"secure-coding":exports.plugin},rules:recommendedRules},"recommended-strict":{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(recommendedRules).map(rule=>[rule,"error"]))},strict:{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`secure-coding/${ruleName}`,"error"]))},"owasp-top-10":{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-privilege-escalation":"warn","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-graphql-injection":"error","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-weak-password-recovery":"error","secure-coding/no-improper-type-validation":"error","secure-coding/no-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectNonLiteralRegexp=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const isRegExpLiteral=node=>{return node.type==="Literal"&&Object.prototype.hasOwnProperty.call(node,"regex")};const REGEXP_PATTERNS=[{pattern:"new RegExp\\(.*\\)",dangerous:true,vulnerability:"redos",safeAlternative:"Pre-defined RegExp constants",example:{bad:"new RegExp(userInput)",good:"const PATTERNS = { email: /^[a-zA-Z0-9]+$/ }; PATTERNS[userChoice]"},effort:"10-15 minutes",riskLevel:"high"},{pattern:"RegExp\\(.*\\)",dangerous:true,vulnerability:"redos",safeAlternative:"Static RegExp literals or validated patterns",example:{bad:"RegExp(userPattern)",good:"const safePattern = userPattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); new RegExp(`^${safePattern}$`)"},effort:"15-20 minutes",riskLevel:"high"},{pattern:"/.*\\*\\*.*|.*\\+\\+.*|.*\\?\\?/",dangerous:true,vulnerability:"redos",safeAlternative:"Avoid nested quantifiers, use atomic groups",example:{bad:"/(a+)+b/",good:"/(?>a+)b/"},effort:"20-30 minutes",riskLevel:"critical"}];exports.detectNonLiteralRegexp=(0,eslint_devkit_2.createRule)({name:"detect-non-literal-regexp",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/detect-non-literal-regexp.md",description:"Detects RegExp(variable), which might allow an attacker to DOS your server with a long-running regular expression",cwe:"CWE-400"},hasSuggestions:true,messages:{regexpReDoS:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"ReDoS vulnerability",cwe:"CWE-400",description:"ReDoS vulnerability detected",severity:"{{riskLevel}}",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),useStaticRegex:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Static Regex",description:"Use pre-defined RegExp constants",severity:"LOW",fix:"const PATTERN = /^[a-z]+$/; // Define at module level",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"}),validateInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Validate Input",description:"Validate and escape user input",severity:"LOW",fix:"Validate input length and characters before RegExp",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),useRegexLibrary:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Safe Library",description:"Use safe-regex library or re2",severity:"LOW",fix:'import { isSafe } from "safe-regex"; if (isSafe(pattern)) ...',documentationLink:"https://github.com/substack/safe-regex"}),addTimeout:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Timeout",description:"Add timeout to regex operations",severity:"LOW",fix:"Use timeout wrapper for regex operations",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),escapeUserInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Escape Input",description:"Escape special regex characters",severity:"LOW",fix:'input.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:false,description:"Allow literal string regex patterns"},additionalPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional RegExp creation patterns to check"},maxPatternLength:{type:"number",default:100,minimum:1,description:"Maximum allowed pattern length for dynamic regex"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:false,additionalPatterns:[],maxPatternLength:100}],create(context){const options=context.options[0]||{};const{allowLiterals=false,maxPatternLength=100}=options;const isLiteralString=node=>{if(node.type==="Literal"&&typeof node.value==="string"){return true}if(node.type==="TemplateLiteral"&&node.expressions.length===0){return true}return false};const hasReDoSPatterns=pattern=>{const nestedQuantifierPatterns=[/\([^)]*[+*]\)[+*]/,/\([^)]*[+*]\)\{[0-9,]+\}/];for(const dangerousPattern of nestedQuantifierPatterns){if(dangerousPattern.test(pattern)){return true}}return false};const extractPattern=node=>{const sourceCode=context.sourceCode;let constructor="RegExp";if(node.type==="NewExpression"&&node.callee.type==="Identifier"){constructor=`new ${node.callee.name}`}const patternNode=node.arguments.length>0?node.arguments[0]:null;const pattern=patternNode?sourceCode.getText(patternNode):"";const isDynamic=patternNode?!isLiteralString(patternNode):false;const length=patternNode&&isLiteralString(patternNode)?String(patternNode.value).length:pattern.length;return{pattern,patternNode,constructor,isDynamic,length}};const detectVulnerability=(pattern,isDynamic)=>{if(isDynamic){for(const vuln of REGEXP_PATTERNS){if(new RegExp(vuln.pattern,"i").test(pattern)){return vuln}}return{pattern:"dynamic",dangerous:true,vulnerability:"redos",safeAlternative:"Pre-defined RegExp constants",example:{bad:pattern,good:"const PATTERNS = { email: /^[a-zA-Z0-9]+$/ }; PATTERNS[type]"},effort:"10-15 minutes",riskLevel:"high"}}if(hasReDoSPatterns(pattern)){return{pattern:"redos-literal",dangerous:true,vulnerability:"redos",safeAlternative:"Restructure regex to avoid nested quantifiers",example:{bad:pattern,good:pattern.replace(/(a+)\+/g,"$1")},effort:"20-30 minutes",riskLevel:"high"}}return null};const generateRefactoringSteps=vulnerability=>{if(vulnerability.pattern==="dynamic"){return[" 1. Create a whitelist of allowed regex patterns"," 2. Use object lookup: PATTERNS[userChoice]"," 3. If dynamic needed: escape input with regex escaping function"," 4. Add pattern length validation"," 5. Consider using a safe regex library"].join("\n")}if(vulnerability.pattern==="redos-literal"){return[" 1. Identify nested quantifiers (*+, ++, ?+)"," 2. Restructure regex to avoid exponential backtracking"," 3. Use atomic groups if supported: (?>...)"," 4. Test regex performance with long inputs"," 5. Consider alternatives like string methods"].join("\n")}return[" 1. Avoid nested quantifiers and backreferences"," 2. Use possessive quantifiers: *+, ++, ?+"," 3. Restructure regex to be more specific"," 4. Test with potentially malicious inputs"," 5. Consider safe-regex library validation"].join("\n")};const determineRiskLevel=(vulnerability,pattern)=>{if(vulnerability.riskLevel==="critical"||hasReDoSPatterns(pattern)){return"CRITICAL"}return"HIGH"};const checkRegExpCall=node=>{const isRegExpCall=node.callee.type==="Identifier"&&node.callee.name==="RegExp";const isNewRegExp=node.type==="NewExpression"&&node.callee.type==="Identifier"&&node.callee.name==="RegExp";if(!isRegExpCall&&!isNewRegExp){return}const{pattern,patternNode,isDynamic,length}=extractPattern(node);if(allowLiterals&&patternNode&&isLiteralString(patternNode)&&length<=maxPatternLength){if(!hasReDoSPatterns(pattern)){return}}const vulnerability=detectVulnerability(pattern,isDynamic);const effectiveVulnerability=vulnerability;if(!effectiveVulnerability){return}const riskLevel=determineRiskLevel(effectiveVulnerability,pattern);const steps=generateRefactoringSteps(effectiveVulnerability);context.report({node,messageId:"regexpReDoS",data:{pattern:pattern.substring(0,30)+(pattern.length>30?"...":""),riskLevel,vulnerability:effectiveVulnerability.vulnerability,safeAlternative:effectiveVulnerability.safeAlternative,steps,effort:effectiveVulnerability.effort},suggest:[{messageId:"useStaticRegex",fix:()=>null},{messageId:"validateInput",fix:()=>null},{messageId:"useRegexLibrary",fix:()=>null},{messageId:"addTimeout",fix:()=>null},{messageId:"escapeUserInput",fix:()=>null}]})};const checkLiteralRegExp=node=>{if(!isRegExpLiteral(node)){return}const pattern=node.regex.pattern;if(hasReDoSPatterns(pattern)){const vulnerability=detectVulnerability(pattern,false);const riskLevel=determineRiskLevel(vulnerability,pattern);const steps=generateRefactoringSteps(vulnerability);context.report({node,messageId:"regexpReDoS",data:{pattern:pattern.substring(0,30)+(pattern.length>30?"...":""),riskLevel,vulnerability:vulnerability.vulnerability,safeAlternative:vulnerability.safeAlternative,steps,effort:vulnerability.effort}})}};return{CallExpression:checkRegExpCall,NewExpression:checkRegExpCall,Literal:checkLiteralRegExp}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectNonLiteralRegexp=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const REGEXP_PATTERNS=[{pattern:"new RegExp\\(.*\\)",dangerous:true,vulnerability:"redos",safeAlternative:"Pre-defined RegExp constants",example:{bad:"new RegExp(userInput)",good:"const PATTERNS = { email: /^[a-zA-Z0-9]+$/ }; PATTERNS[userChoice]"},effort:"10-15 minutes",riskLevel:"high"},{pattern:"RegExp\\(.*\\)",dangerous:true,vulnerability:"redos",safeAlternative:"Static RegExp literals or validated patterns",example:{bad:"RegExp(userPattern)",good:"const safePattern = userPattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); new RegExp(`^${safePattern}$`)"},effort:"15-20 minutes",riskLevel:"high"},{pattern:"/.*\\*\\*.*|.*\\+\\+.*|.*\\?\\?/",dangerous:true,vulnerability:"redos",safeAlternative:"Avoid nested quantifiers, use atomic groups",example:{bad:"/(a+)+b/",good:"/(?>a+)b/"},effort:"20-30 minutes",riskLevel:"critical"}];const CONSTANT_PRESERVING_METHODS=new Set(["join","concat","toUpperCase","toLowerCase","trim","slice","repeat"]);function isBuildTimeConstant(node,sourceCode,depth=0){if(depth>6){return false}switch(node.type){case"Literal":return true;case"TemplateLiteral":return node.expressions.every(expression=>isBuildTimeConstant(expression,sourceCode,depth+1));case"BinaryExpression":return node.operator==="+"&&isBuildTimeConstant(node.left,sourceCode,depth+1)&&isBuildTimeConstant(node.right,sourceCode,depth+1);case"ArrayExpression":return node.elements.every(element=>element!==null&&element.type!=="SpreadElement"&&isBuildTimeConstant(element,sourceCode,depth+1));case"CallExpression":return node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"&&CONSTANT_PRESERVING_METHODS.has(node.callee.property.name)&&isBuildTimeConstant(node.callee.object,sourceCode,depth+1)&&node.arguments.every(argument=>argument.type!=="SpreadElement"&&isBuildTimeConstant(argument,sourceCode,depth+1));case"Identifier":return isConstantBinding(node,sourceCode,depth);default:return false}}function isConstantBinding(node,sourceCode,depth){let variable=null;let scope=sourceCode.getScope(node);while(scope!==null&&variable===null){variable=scope.variables.find(candidate=>candidate.name===node.name)??null;scope=scope.upper}if(variable===null||variable.defs.length!==1){return false}const definition=variable.defs[0];if(definition.type!=="Variable"){return false}if(definition.parent.parent?.type==="ForStatement"){return true}if(definition.parent.kind!=="const"){return false}const init=definition.node.init;return init!==null&&isBuildTimeConstant(init,sourceCode,depth+1)}exports.detectNonLiteralRegexp=(0,eslint_devkit_2.createRule)({name:"detect-non-literal-regexp",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/detect-non-literal-regexp.md",description:"Detects RegExp(variable), which might allow an attacker to DOS your server with a long-running regular expression",cwe:"CWE-400"},hasSuggestions:true,messages:{regexpReDoS:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"ReDoS vulnerability",cwe:"CWE-400",description:"ReDoS vulnerability detected",severity:"{{riskLevel}}",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),useStaticRegex:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Static Regex",description:"Use pre-defined RegExp constants",severity:"LOW",fix:"const PATTERN = /^[a-z]+$/; // Define at module level",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"}),validateInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Validate Input",description:"Validate and escape user input",severity:"LOW",fix:"Validate input length and characters before RegExp",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),useRegexLibrary:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Safe Library",description:"Use safe-regex library or re2",severity:"LOW",fix:'import { isSafe } from "safe-regex"; if (isSafe(pattern)) ...',documentationLink:"https://github.com/substack/safe-regex"}),addTimeout:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Timeout",description:"Add timeout to regex operations",severity:"LOW",fix:"Use timeout wrapper for regex operations",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),escapeUserInput:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Escape Input",description:"Escape special regex characters",severity:"LOW",fix:'input.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:false,description:"Allow literal string regex patterns"},additionalPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional RegExp creation patterns to check"},maxPatternLength:{type:"number",default:100,minimum:1,description:"Maximum allowed pattern length for dynamic regex"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:true,additionalPatterns:[],maxPatternLength:100}],create(context){const options=context.options[0]||{};const{allowLiterals=true,maxPatternLength=100}=options;const isLiteralString=node=>{if(node.type==="Literal"&&typeof node.value==="string"){return true}if(node.type==="TemplateLiteral"&&node.expressions.length===0){return true}return false};const extractPattern=node=>{const sourceCode=context.sourceCode;let constructor="RegExp";if(node.type==="NewExpression"&&node.callee.type==="Identifier"){constructor=`new ${node.callee.name}`}const patternNode=node.arguments.length>0?node.arguments[0]:null;const pattern=patternNode?sourceCode.getText(patternNode):"";const isDynamic=patternNode?!isLiteralString(patternNode):false;const length=patternNode&&isLiteralString(patternNode)?String(patternNode.value).length:pattern.length;return{pattern,patternNode,constructor,isDynamic,length}};const detectVulnerability=(pattern,isDynamic)=>{if(isDynamic){for(const vuln of REGEXP_PATTERNS){if(new RegExp(vuln.pattern,"i").test(pattern)){return vuln}}return{pattern:"dynamic",dangerous:true,vulnerability:"redos",safeAlternative:"Pre-defined RegExp constants",example:{bad:pattern,good:"const PATTERNS = { email: /^[a-zA-Z0-9]+$/ }; PATTERNS[type]"},effort:"10-15 minutes",riskLevel:"high"}}return{pattern:"literal-construction",dangerous:false,vulnerability:"redos",safeAlternative:"Regex literal syntax",example:{bad:`new RegExp(${pattern})`,good:"/pattern/"},effort:"2 minutes",riskLevel:"high"}};const generateRefactoringSteps=vulnerability=>{if(vulnerability.pattern==="dynamic"){return[" 1. Create a whitelist of allowed regex patterns"," 2. Use object lookup: PATTERNS[userChoice]"," 3. If dynamic needed: escape input with regex escaping function"," 4. Add pattern length validation"," 5. Consider using a safe regex library"].join("\n")}if(vulnerability.pattern==="literal-construction"){return[" 1. Replace new RegExp('\u2026') with a /\u2026/ literal"," 2. Keep the flags as literal suffixes: /\u2026/gi"," 3. Escaping differs: a literal needs one backslash, not two"].join("\n")}return[" 1. Avoid nested quantifiers and backreferences"," 2. Use possessive quantifiers: *+, ++, ?+"," 3. Restructure regex to be more specific"," 4. Test with potentially malicious inputs"," 5. Consider safe-regex library validation"].join("\n")};const determineRiskLevel=vulnerability=>{if(vulnerability.riskLevel==="critical"){return"CRITICAL"}return"HIGH"};const checkRegExpCall=node=>{const isRegExpCall=node.callee.type==="Identifier"&&node.callee.name==="RegExp";const isNewRegExp=node.type==="NewExpression"&&node.callee.type==="Identifier"&&node.callee.name==="RegExp";if(!isRegExpCall&&!isNewRegExp){return}const{pattern,patternNode,isDynamic,length}=extractPattern(node);if(!patternNode){return}if(isDynamic){if(isBuildTimeConstant(patternNode,context.sourceCode)){return}}else if(allowLiterals&&length<=maxPatternLength){return}const vulnerability=detectVulnerability(pattern,isDynamic);const riskLevel=determineRiskLevel(vulnerability);const steps=generateRefactoringSteps(vulnerability);context.report({node,messageId:"regexpReDoS",data:{pattern:pattern.substring(0,30)+(pattern.length>30?"...":""),riskLevel,vulnerability:vulnerability.vulnerability,safeAlternative:vulnerability.safeAlternative,steps,effort:vulnerability.effort},suggest:[{messageId:"useStaticRegex",fix:()=>null},{messageId:"validateInput",fix:()=>null},{messageId:"useRegexLibrary",fix:()=>null},{messageId:"addTimeout",fix:()=>null},{messageId:"escapeUserInput",fix:()=>null}]})};return{CallExpression:checkRegExpCall,NewExpression:checkRegExpCall}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectObjectInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const TYPED_ARRAY_CTORS=new Set(["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"]);const OBJECT_INJECTION_PATTERNS=[{pattern:"__proto__",dangerous:true,vulnerability:"prototype-pollution",safeAlternative:"Object.create(null) or Map",example:{bad:'obj[userInput] = value; // if userInput is "__proto__"',good:"const map = new Map(); map.set(userInput, value);"},effort:"15-20 minutes",riskLevel:"critical"},{pattern:"prototype",dangerous:true,vulnerability:"prototype-pollution",safeAlternative:"Avoid prototype manipulation",example:{bad:'obj[userInput] = value; // if userInput is "prototype"',good:"if (!obj.hasOwnProperty(userInput)) obj[userInput] = value;"},effort:"10-15 minutes",riskLevel:"high"},{pattern:"constructor",dangerous:true,vulnerability:"method-injection",safeAlternative:"Validate property names against whitelist",example:{bad:'obj[userInput] = value; // if userInput is "constructor"',good:"const ALLOWED_KEYS = ['name', 'age', 'email']; if (ALLOWED_KEYS.includes(userInput)) obj[userInput] = value;"},effort:"10-15 minutes",riskLevel:"medium"}];exports.detectObjectInjection=(0,eslint_devkit_3.createRule)({name:"detect-object-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/detect-object-injection.md",description:"Detects variable[key] as a left- or right-hand assignment operand",cwe:"CWE-915",confidence:"low"},hasSuggestions:true,messages:{objectInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Object injection",cwe:"CWE-915",description:"Object injection/Prototype pollution (incl. model/tool outputs)",severity:"{{riskLevel}}",fix:"{{safeAlternative}}",documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),useMapInstead:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Map",description:"Use Map instead of plain objects",severity:"LOW",fix:"const map = new Map(); map.set(key, value);",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"}),useHasOwnProperty:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use hasOwnProperty",description:"Check hasOwnProperty to avoid prototype properties",severity:"LOW",fix:"if (obj.hasOwnProperty(key)) { obj[key] = value; }",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty"}),whitelistKeys:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Whitelist Keys",description:"Whitelist allowed property names",severity:"LOW",fix:'const ALLOWED = ["name", "email"]; if (ALLOWED.includes(key)) obj[key] = value; // reject model/tool-supplied unknown keys',documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),useObjectCreate:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Object.create(null)",description:"Create clean objects without prototypes",severity:"LOW",fix:"const obj = Object.create(null);",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create"}),freezePrototypes:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Freeze Prototypes",description:"Freeze Object.prototype to prevent pollution",severity:"LOW",fix:"Object.freeze(Object.prototype);",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze"}),strategyValidate:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Validate Input",description:"Add input validation before property access",severity:"LOW",fix:"Validate key against allowed values before access",documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),strategyWhitelist:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Whitelist Properties",description:"Whitelist allowed property names only",severity:"LOW",fix:"Define allowed keys and validate against them",documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),strategyFreeze:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Freeze Prototypes",description:"Freeze prototypes to prevent pollution",severity:"LOW",fix:"Object.freeze(Object.prototype) at app startup",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:false,description:"Allow bracket notation with literal strings"},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional object methods to check for injection"},dangerousProperties:{type:"array",items:{type:"string"},default:["__proto__","prototype","constructor"],description:"Properties to consider dangerous"},strategy:{type:"string",enum:["validate","whitelist","freeze","auto"],default:"auto",description:"Strategy for fixing object injection (auto = smart detection)"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:false,additionalMethods:[],dangerousProperties:["__proto__","prototype","constructor"],strategy:"auto"}],create(context){const options=context.options[0]||{};const{allowLiterals:_allowLiterals=false,dangerousProperties=["__proto__","prototype","constructor"]}=options;const handledMemberExpressions=new WeakSet;const sourceCode=context.sourceCode;const isInCodemodContext=(()=>{const filename=context.filename;if(/\/codemod[s]?\//i.test(filename))return true;if(/codemod\.[mc]?[jt]sx?$/i.test(filename))return true;const imports=sourceCode.ast.body.filter(n=>n.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration);return imports.some(i=>{const src=String(i.source.value);return src==="@babel/types"||src==="@babel/traverse"||src==="recast"||src==="jscodeshift"||src==="eslint"||src==="estree-walker"||src==="ast-types"||src==="esrap"||src==="unist-util-visit"||src.startsWith("@typescript-eslint/")})})();const isTestFile=(()=>{const f=context.filename;return/\.test\.[mc]?[jt]sx?$/.test(f)||/\.spec\.[mc]?[jt]sx?$/.test(f)||/\/__tests__\//.test(f)||/\/test\//.test(f)||/\.fixture\.[mc]?[jt]sx?$/.test(f)})();const isLiteralString=node=>{return node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"};const hasPrecedingValidation=(propertyNode,node)=>{if(propertyNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const keyName=propertyNode.name;const isIncludesCall=testNode=>{if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&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"&&testNode.arguments.length>0&&testNode.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.arguments[0].name===keyName){return true}if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&testNode.operator==="!"&&testNode.argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isIncludesCall(testNode.argument)}return false};const isHasOwnPropertyCall=testNode=>{if(testNode.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=testNode.callee;const args=testNode.arguments;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name==="call"&&args.length>=2&&args[1].type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&args[1].name===keyName){return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(callee.property.name==="hasOwnProperty"||callee.property.name==="hasOwn")){const keyArg=callee.property.name==="hasOwn"?args[1]:args[0];if(keyArg?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&keyArg.name===keyName){return true}}return false};const isInOperator=testNode=>{return testNode.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&testNode.operator==="in"&&testNode.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.left.name===keyName};const hasValidation=testNode=>{return isIncludesCall(testNode)||isHasOwnPropertyCall(testNode)||isInOperator(testNode)};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=node.parent;let foundFunctionBody=false;while(current&&!foundFunctionBody){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(hasValidation(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=node;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&&hasValidation(stmt.test)&&hasEarlyExit(stmt.consequent)){return true}}}current=current.parent}return false};const hasDisqualifyingLiteralAffix=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||node.operator!=="+"){return false}const bin=node;const literalText=n=>{if(n.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return null;const v=n.value;if(typeof v!=="string"&&typeof v!=="number")return null;const s=String(v);return s.length>0?s:null};const prefix=literalText(bin.left);if(prefix!==null&&!dangerousProperties.some(d=>d.startsWith(prefix))){return true}const suffix=literalText(bin.right);if(suffix!==null&&!dangerousProperties.some(d=>d.endsWith(suffix))){return true}return false};const isDangerousPropertyAccess=propertyNode=>{if(isNumericKey(propertyNode)||hasDisqualifyingLiteralAffix(propertyNode)){return false}if(propertyNode.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=propertyNode.name;if(/^[A-Z][A-Z0-9_]{2,}$/.test(name)){return false}if(/^[a-z]/.test(name)&&/(?:Code|Status|Version|Kind|Mode|Type|Stage|Level|Phase|Step|Flag|Num|Count)$/.test(name)){return false}}if(isLiteralString(propertyNode)){const propName=String(propertyNode.value);if(dangerousProperties.includes(propName)){return true}return false}return true};const isPrototypelessObject=objectNode=>{if(objectNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const varName=objectNode.name;let current=objectNode;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.Program){const statements=current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement?current.body:current.body;for(const stmt of statements){if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration){for(const decl of stmt.declarations){if(decl.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&decl.id.name===varName&&decl.init){if(decl.init.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&decl.init.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&decl.init.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&decl.init.callee.object.name==="Object"&&decl.init.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&decl.init.callee.property.name==="create"&&decl.init.arguments.length>0&&decl.init.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&decl.init.arguments[0].value===null){return true}if(decl.init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&decl.init.elements.length>0&&decl.init.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return true}}}}}}current=current.parent}return false};const extractPropertyAccess=node=>{let object;let property;let propertyNode;let isAssignment=false;if(node.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){object=sourceCode.getText(node.left.object);property=sourceCode.getText(node.left.property);propertyNode=node.left.property;isAssignment=true}else{const memberNode=node;object=sourceCode.getText(memberNode.object);property=sourceCode.getText(memberNode.property);propertyNode=memberNode.property;isAssignment=false}const pattern=OBJECT_INJECTION_PATTERNS.find(p=>new RegExp(p.pattern,"i").test(property)||dangerousProperties.includes(property.replace(/['"]/g,"")))||null;return{object,property,propertyNode,isAssignment,pattern}};const isHighRiskAssignment=node=>{if(node.left.type!=="MemberExpression"){return false}if(!node.left.computed){return false}if(isPrototypelessObject(node.left.object)){return false}if(isTypedArrayObject(node.left.object)){return false}const{propertyNode}=extractPropertyAccess(node);if(isNumericKey(propertyNode)){return false}if(isForInOrObjectKeysKey(propertyNode)){return false}if(hasPrecedingValidation(propertyNode,node)){return false}return isDangerousPropertyAccess(propertyNode)};const isReflectResultAccess=objectNode=>{if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=objectNode.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Reflect"){return true}}if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return isReflectResultAccess(objectNode.expression)}return false};const isHighRiskMemberAccess=node=>{if(!node.computed){return false}if(isReflectResultAccess(node.object)){return false}if(isTypedArrayObject(node.object)){return false}const{propertyNode}=extractPropertyAccess(node);if(isNumericKey(propertyNode)){return false}if(isForInOrObjectKeysKey(propertyNode)){return false}if(hasPrecedingValidation(propertyNode,node)){return false}return isDangerousPropertyAccess(propertyNode)};const isNumericKey=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="number"){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression){const op=node.operator;if(op==="+"||op==="-"||op==="~")return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.UpdateExpression){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const op=node.operator;if(op==="|"||op==="&"||op==="^"||op==="<<"||op===">>"||op===">>>"||op==="*"||op==="/"||op==="%"||op==="-"||op==="**"){return true}if(op==="+"){const bin=node;return isNumericKey(bin.left)&&isNumericKey(bin.right)}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){const cond=node;return isNumericKey(cond.consequent)&&isNumericKey(cond.alternate)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=callee.name;if(name==="Number"||name==="parseInt"||name==="parseFloat")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==="Math"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return true}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return isNumericIdentifier(node)}return false};const numericVarCache=new WeakMap;const numericVarInProgress=new WeakSet;const isNumericIdentifier=node=>{if(isLoopCounterIdentifier(node))return true;const scope=context.sourceCode.getScope(node);const variable=scope.references.find(r=>r.identifier===node)?.resolved;if(!variable||variable.defs.length===0)return false;const cached=numericVarCache.get(variable);if(cached!==void 0)return cached;if(numericVarInProgress.has(variable))return true;numericVarInProgress.add(variable);let result=false;const def=variable.defs[0];const declarator=def.node;if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&declarator.parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration){result=isNumericKey(declarator.init);if(result){for(const ref of variable.references){const written=ref.writeExpr;if(!written||written===declarator.init)continue;if(!isNumericKey(written)){result=false;break}}}}numericVarInProgress.delete(variable);numericVarCache.set(variable,result);return result};const isLoopCounterIdentifier=node=>{const scope=context.sourceCode.getScope(node);const variable=scope.references.find(r=>r.identifier===node)?.resolved;if(!variable||variable.defs.length===0)return false;const def=variable.defs[0];const parent=def.node?.parent;const grand=parent?.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration&&grand?.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement&&grand.init===parent){const init=def.node.init;if(!init)return false;if(init.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof init.value==="number"){return true}}return false};const isForInOrObjectKeysKey=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const scope=context.sourceCode.getScope(node);const variable=scope.references.find(r=>r.identifier===node)?.resolved;if(!variable||variable.defs.length===0)return false;const def=variable.defs[0];const varDecl=def.node?.parent;const loopStmt=varDecl?.parent;if(!varDecl||varDecl.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration)return false;if(loopStmt?.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement&&loopStmt.left===varDecl){return true}if(loopStmt?.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement&&loopStmt.left===varDecl){const right=loopStmt.right;return right.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&right.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!right.callee.computed&&right.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&right.callee.object.name==="Object"&&right.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(right.callee.property.name==="keys"||right.callee.property.name==="entries")}return false};const isTypedArrayObject=objectNode=>{if(objectNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const varName=objectNode.name;let scope=context.sourceCode.getScope(objectNode);while(scope){const variable=scope.variables.find(v=>v.name===varName);if(variable){for(const def of variable.defs){const init=def.node.init;if(init?.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TYPED_ARRAY_CTORS.has(init.callee.name)){return true}}break}if(!scope.upper)break;scope=scope.upper}return false};const determineRiskLevel=(pattern,isAssignment)=>{if(pattern?.riskLevel==="critical"||pattern&&isAssignment){return"CRITICAL"}if(pattern?.riskLevel==="high"||isAssignment){return"HIGH"}return"MEDIUM"};const checkAssignmentExpression=node=>{if(!isHighRiskAssignment(node)){return}let me=node.left;handledMemberExpressions.add(me);while(me.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&me.object.computed){me=me.object;handledMemberExpressions.add(me)}const{object,property,isAssignment,pattern}=extractPropertyAccess(node);const riskLevel=determineRiskLevel(pattern,isAssignment);context.report({node,messageId:"objectInjection",data:{pattern:`${object}[${property}]`,riskLevel,vulnerability:pattern?.vulnerability||"object injection",safeAlternative:pattern?.safeAlternative||"Use Map or property whitelisting"},suggest:[{messageId:"useMapInstead",fix:()=>null},{messageId:"useHasOwnProperty",fix:()=>null},{messageId:"whitelistKeys",fix:()=>null},{messageId:"useObjectCreate",fix:()=>null},{messageId:"freezePrototypes",fix:()=>null}]})};const checkMemberExpression=node=>{if(!isHighRiskMemberAccess(node)){return}if(handledMemberExpressions.has(node)){return}const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.computed&&parent.object===node){return}if(parent&&parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.left===node){return}const{object,property,isAssignment,pattern}=extractPropertyAccess(node);const riskLevel=determineRiskLevel(pattern,isAssignment);context.report({node,messageId:"objectInjection",data:{pattern:`${object}[${property}]`,riskLevel,vulnerability:pattern?.vulnerability||"object injection",safeAlternative:pattern?.safeAlternative||"Use Map or property whitelisting"}})};const checkObjectAssignSpread=node=>{if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callee=node.callee;const objectIsObject=callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Object";const propIsAssign=!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name==="assign";if(!objectIsObject||!propIsAssign)return;if(node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;const sources=node.arguments.slice(1);const anyTaintedSource=sources.some(s=>s.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&s.type!==eslint_devkit_1.AST_NODE_TYPES.Literal);if(!anyTaintedSource)return;context.report({node,messageId:"objectInjection",data:{pattern:"Object.assign(target, untrustedSource)",riskLevel:"HIGH",vulnerability:"object injection via Object.assign spread",safeAlternative:"Validate or whitelist keys before merging: `for (const k of Object.keys(src)) if (!ALLOWED.has(k)) continue;`"}})};return{AssignmentExpression:node=>{if(isInCodemodContext||isTestFile)return;return checkAssignmentExpression(node)},MemberExpression:node=>{if(isInCodemodContext||isTestFile)return;return checkMemberExpression(node)},CallExpression:node=>{if(isInCodemodContext||isTestFile)return;return checkObjectAssignSpread(node)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectObjectInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const fileUsesAstTooling=(0,eslint_devkit_3.createModuleEvidence)({packages:["@babel/types","@babel/traverse","recast","jscodeshift","eslint","estree-walker","ast-types","esrap","unist-util-visit"],scopes:["@typescript-eslint"]});const TYPED_ARRAY_CTORS=new Set(["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"]);const OBJECT_INJECTION_PATTERNS=[{pattern:"__proto__",dangerous:true,vulnerability:"prototype-pollution",safeAlternative:"Object.create(null) or Map",example:{bad:'obj[userInput] = value; // if userInput is "__proto__"',good:"const map = new Map(); map.set(userInput, value);"},effort:"15-20 minutes",riskLevel:"critical"},{pattern:"prototype",dangerous:true,vulnerability:"prototype-pollution",safeAlternative:"Avoid prototype manipulation",example:{bad:'obj[userInput] = value; // if userInput is "prototype"',good:"if (!obj.hasOwnProperty(userInput)) obj[userInput] = value;"},effort:"10-15 minutes",riskLevel:"high"},{pattern:"constructor",dangerous:true,vulnerability:"method-injection",safeAlternative:"Validate property names against whitelist",example:{bad:'obj[userInput] = value; // if userInput is "constructor"',good:"const ALLOWED_KEYS = ['name', 'age', 'email']; if (ALLOWED_KEYS.includes(userInput)) obj[userInput] = value;"},effort:"10-15 minutes",riskLevel:"medium"}];exports.detectObjectInjection=(0,eslint_devkit_3.createRule)({name:"detect-object-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/detect-object-injection.md",description:"Detects variable[key] as a left- or right-hand assignment operand",cwe:"CWE-915",confidence:"low"},hasSuggestions:true,messages:{objectInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Object injection",cwe:"CWE-915",description:"Object injection/Prototype pollution (incl. model/tool outputs)",severity:"{{riskLevel}}",fix:"{{safeAlternative}}",documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),useMapInstead:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Map",description:"Use Map instead of plain objects",severity:"LOW",fix:"const map = new Map(); map.set(key, value);",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map"}),useHasOwnProperty:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use hasOwnProperty",description:"Check hasOwnProperty to avoid prototype properties",severity:"LOW",fix:"if (obj.hasOwnProperty(key)) { obj[key] = value; }",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty"}),whitelistKeys:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Whitelist Keys",description:"Whitelist allowed property names",severity:"LOW",fix:'const ALLOWED = ["name", "email"]; if (ALLOWED.includes(key)) obj[key] = value; // reject model/tool-supplied unknown keys',documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),useObjectCreate:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Object.create(null)",description:"Create clean objects without prototypes",severity:"LOW",fix:"const obj = Object.create(null);",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create"}),freezePrototypes:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Freeze Prototypes",description:"Freeze Object.prototype to prevent pollution",severity:"LOW",fix:"Object.freeze(Object.prototype);",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze"}),strategyValidate:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Validate Input",description:"Add input validation before property access",severity:"LOW",fix:"Validate key against allowed values before access",documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),strategyWhitelist:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Whitelist Properties",description:"Whitelist allowed property names only",severity:"LOW",fix:"Define allowed keys and validate against them",documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),strategyFreeze:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Freeze Prototypes",description:"Freeze prototypes to prevent pollution",severity:"LOW",fix:"Object.freeze(Object.prototype) at app startup",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:false,description:"Allow bracket notation with literal strings"},additionalMethods:{type:"array",items:{type:"string"},default:[],description:"Additional object methods to check for injection"},dangerousProperties:{type:"array",items:{type:"string"},default:["__proto__","prototype","constructor"],description:"Properties to consider dangerous"},strategy:{type:"string",enum:["validate","whitelist","freeze","auto"],default:"auto",description:"Strategy for fixing object injection (auto = smart detection)"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:false,additionalMethods:[],dangerousProperties:["__proto__","prototype","constructor"],strategy:"auto"}],create(context){const options=context.options[0]||{};const{allowLiterals:_allowLiterals=false,dangerousProperties=["__proto__","prototype","constructor"]}=options;const handledMemberExpressions=new WeakSet;const sourceCode=context.sourceCode;const isInCodemodContext=(()=>{const filename=context.filename;if(/\/codemod[s]?\//i.test(filename))return true;if(/codemod\.[mc]?[jt]sx?$/i.test(filename))return true;return fileUsesAstTooling(sourceCode.ast)})();const isTestFile=(()=>{const f=context.filename;return/\.test\.[mc]?[jt]sx?$/.test(f)||/\.spec\.[mc]?[jt]sx?$/.test(f)||/\/__tests__\//.test(f)||/\/test\//.test(f)||/\.fixture\.[mc]?[jt]sx?$/.test(f)})();const isLiteralString=node=>{return node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"};const hasPrecedingValidation=(propertyNode,node)=>{if(propertyNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const keyName=propertyNode.name;const isIncludesCall=testNode=>{if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&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"&&testNode.arguments.length>0&&testNode.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.arguments[0].name===keyName){return true}if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&testNode.operator==="!"&&testNode.argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isIncludesCall(testNode.argument)}return false};const isHasOwnPropertyCall=testNode=>{if(testNode.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=testNode.callee;const args=testNode.arguments;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name==="call"&&args.length>=2&&args[1].type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&args[1].name===keyName){return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(callee.property.name==="hasOwnProperty"||callee.property.name==="hasOwn")){const keyArg=callee.property.name==="hasOwn"?args[1]:args[0];if(keyArg?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&keyArg.name===keyName){return true}}return false};const isInOperator=testNode=>{return testNode.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&testNode.operator==="in"&&testNode.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.left.name===keyName};const hasValidation=testNode=>{return isIncludesCall(testNode)||isHasOwnPropertyCall(testNode)||isInOperator(testNode)};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=node.parent;let foundFunctionBody=false;while(current&&!foundFunctionBody){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(hasValidation(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=node;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&&hasValidation(stmt.test)&&hasEarlyExit(stmt.consequent)){return true}}}current=current.parent}return false};const hasDisqualifyingLiteralAffix=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||node.operator!=="+"){return false}const bin=node;const literalText=n=>{if(n.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return null;const v=n.value;if(typeof v!=="string"&&typeof v!=="number")return null;const s=String(v);return s.length>0?s:null};const prefix=literalText(bin.left);if(prefix!==null&&!dangerousProperties.some(d=>d.startsWith(prefix))){return true}const suffix=literalText(bin.right);if(suffix!==null&&!dangerousProperties.some(d=>d.endsWith(suffix))){return true}return false};const isDangerousPropertyAccess=propertyNode=>{if(isNumericKey(propertyNode)||hasDisqualifyingLiteralAffix(propertyNode)){return false}if(propertyNode.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=propertyNode.name;if(/^[A-Z][A-Z0-9_]{2,}$/.test(name)){return false}if(/^[a-z]/.test(name)&&/(?:Code|Status|Version|Kind|Mode|Type|Stage|Level|Phase|Step|Flag|Num|Count)$/.test(name)){return false}}if(isLiteralString(propertyNode)){const propName=String(propertyNode.value);if(dangerousProperties.includes(propName)){return true}return false}return true};const isPrototypelessObject=objectNode=>{if(objectNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const varName=objectNode.name;let current=objectNode;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.Program){const statements=current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement?current.body:current.body;for(const stmt of statements){if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration){for(const decl of stmt.declarations){if(decl.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&decl.id.name===varName&&decl.init){if(decl.init.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&decl.init.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&decl.init.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&decl.init.callee.object.name==="Object"&&decl.init.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&decl.init.callee.property.name==="create"&&decl.init.arguments.length>0&&decl.init.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&decl.init.arguments[0].value===null){return true}if(decl.init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&decl.init.elements.length>0&&decl.init.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return true}}}}}}current=current.parent}return false};const extractPropertyAccess=node=>{let object;let property;let propertyNode;let isAssignment=false;if(node.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){object=sourceCode.getText(node.left.object);property=sourceCode.getText(node.left.property);propertyNode=node.left.property;isAssignment=true}else{const memberNode=node;object=sourceCode.getText(memberNode.object);property=sourceCode.getText(memberNode.property);propertyNode=memberNode.property;isAssignment=false}const pattern=OBJECT_INJECTION_PATTERNS.find(p=>new RegExp(p.pattern,"i").test(property)||dangerousProperties.includes(property.replace(/['"]/g,"")))||null;return{object,property,propertyNode,isAssignment,pattern}};const isHighRiskAssignment=node=>{if(node.left.type!=="MemberExpression"){return false}if(!node.left.computed){return false}if(isPrototypelessObject(node.left.object)){return false}if(isTypedArrayObject(node.left.object)){return false}const{propertyNode}=extractPropertyAccess(node);if(isNumericKey(propertyNode)){return false}if(isForInOrObjectKeysKey(propertyNode)){return false}if(hasPrecedingValidation(propertyNode,node)){return false}return isDangerousPropertyAccess(propertyNode)};const isReflectResultAccess=objectNode=>{if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=objectNode.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Reflect"){return true}}if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return isReflectResultAccess(objectNode.expression)}return false};const isHighRiskMemberAccess=node=>{if(!node.computed){return false}if(isReflectResultAccess(node.object)){return false}if(isTypedArrayObject(node.object)){return false}const{propertyNode}=extractPropertyAccess(node);if(isNumericKey(propertyNode)){return false}if(isForInOrObjectKeysKey(propertyNode)){return false}if(hasPrecedingValidation(propertyNode,node)){return false}return isDangerousPropertyAccess(propertyNode)};const isNumericKey=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="number"){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression){const op=node.operator;if(op==="+"||op==="-"||op==="~")return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.UpdateExpression){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const op=node.operator;if(op==="|"||op==="&"||op==="^"||op==="<<"||op===">>"||op===">>>"||op==="*"||op==="/"||op==="%"||op==="-"||op==="**"){return true}if(op==="+"){const bin=node;return isNumericKey(bin.left)&&isNumericKey(bin.right)}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){const cond=node;return isNumericKey(cond.consequent)&&isNumericKey(cond.alternate)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=callee.name;if(name==="Number"||name==="parseInt"||name==="parseFloat")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==="Math"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return true}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return isNumericIdentifier(node)}return false};const numericVarCache=new WeakMap;const numericVarInProgress=new WeakSet;const isNumericIdentifier=node=>{if(isLoopCounterIdentifier(node))return true;const scope=context.sourceCode.getScope(node);const variable=scope.references.find(r=>r.identifier===node)?.resolved;if(!variable||variable.defs.length===0)return false;const cached=numericVarCache.get(variable);if(cached!==void 0)return cached;if(numericVarInProgress.has(variable))return true;numericVarInProgress.add(variable);let result=false;const def=variable.defs[0];const declarator=def.node;if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&declarator.parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration){result=isNumericKey(declarator.init);if(result){for(const ref of variable.references){const written=ref.writeExpr;if(!written||written===declarator.init)continue;if(!isNumericKey(written)){result=false;break}}}}numericVarInProgress.delete(variable);numericVarCache.set(variable,result);return result};const isLoopCounterIdentifier=node=>{const scope=context.sourceCode.getScope(node);const variable=scope.references.find(r=>r.identifier===node)?.resolved;if(!variable||variable.defs.length===0)return false;const def=variable.defs[0];const parent=def.node?.parent;const grand=parent?.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration&&grand?.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement&&grand.init===parent){const init=def.node.init;if(!init)return false;if(init.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof init.value==="number"){return true}}return false};const isForInOrObjectKeysKey=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const scope=context.sourceCode.getScope(node);const variable=scope.references.find(r=>r.identifier===node)?.resolved;if(!variable||variable.defs.length===0)return false;const def=variable.defs[0];const varDecl=def.node?.parent;const loopStmt=varDecl?.parent;if(!varDecl||varDecl.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration)return false;if(loopStmt?.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement&&loopStmt.left===varDecl){return true}if(loopStmt?.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement&&loopStmt.left===varDecl){const right=loopStmt.right;return right.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&right.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!right.callee.computed&&right.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&right.callee.object.name==="Object"&&right.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(right.callee.property.name==="keys"||right.callee.property.name==="entries")}return false};const isTypedArrayObject=objectNode=>{if(objectNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const varName=objectNode.name;let scope=context.sourceCode.getScope(objectNode);while(scope){const variable=scope.variables.find(v=>v.name===varName);if(variable){for(const def of variable.defs){const init=def.node.init;if(init?.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TYPED_ARRAY_CTORS.has(init.callee.name)){return true}}break}if(!scope.upper)break;scope=scope.upper}return false};const determineRiskLevel=(pattern,isAssignment)=>{if(pattern?.riskLevel==="critical"||pattern&&isAssignment){return"CRITICAL"}if(pattern?.riskLevel==="high"||isAssignment){return"HIGH"}return"MEDIUM"};const checkAssignmentExpression=node=>{if(!isHighRiskAssignment(node)){return}let me=node.left;handledMemberExpressions.add(me);while(me.object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&me.object.computed){me=me.object;handledMemberExpressions.add(me)}const{object,property,isAssignment,pattern}=extractPropertyAccess(node);const riskLevel=determineRiskLevel(pattern,isAssignment);context.report({node,messageId:"objectInjection",data:{pattern:`${object}[${property}]`,riskLevel,vulnerability:pattern?.vulnerability||"object injection",safeAlternative:pattern?.safeAlternative||"Use Map or property whitelisting"},suggest:[{messageId:"useMapInstead",fix:()=>null},{messageId:"useHasOwnProperty",fix:()=>null},{messageId:"whitelistKeys",fix:()=>null},{messageId:"useObjectCreate",fix:()=>null},{messageId:"freezePrototypes",fix:()=>null}]})};const checkMemberExpression=node=>{if(!isHighRiskMemberAccess(node)){return}if(handledMemberExpressions.has(node)){return}const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.computed&&parent.object===node){return}if(parent&&parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.left===node){return}const{object,property,isAssignment,pattern}=extractPropertyAccess(node);const riskLevel=determineRiskLevel(pattern,isAssignment);context.report({node,messageId:"objectInjection",data:{pattern:`${object}[${property}]`,riskLevel,vulnerability:pattern?.vulnerability||"object injection",safeAlternative:pattern?.safeAlternative||"Use Map or property whitelisting"}})};const checkObjectAssignSpread=node=>{if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callee=node.callee;const objectIsObject=callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Object";const propIsAssign=!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name==="assign";if(!objectIsObject||!propIsAssign)return;if(node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;const sources=node.arguments.slice(1);const anyTaintedSource=sources.some(s=>s.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&s.type!==eslint_devkit_1.AST_NODE_TYPES.Literal);if(!anyTaintedSource)return;context.report({node,messageId:"objectInjection",data:{pattern:"Object.assign(target, untrustedSource)",riskLevel:"HIGH",vulnerability:"object injection via Object.assign spread",safeAlternative:"Validate or whitelist keys before merging: `for (const k of Object.keys(src)) if (!ALLOWED.has(k)) continue;`"}})};return{AssignmentExpression:node=>{if(isInCodemodContext||isTestFile)return;return checkAssignmentExpression(node)},MemberExpression:node=>{if(isInCodemodContext||isTestFile)return;return checkMemberExpression(node)},CallExpression:node=>{if(isInCodemodContext||isTestFile)return;return checkObjectAssignSpread(node)}}}});
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noFailOpenAuth=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const SECURITY_DECISION=new RegExp("^(?:(?:verify|validate|assert|check|ensure|require)(?:Access|AccessToken|Admin|ApiKey|Auth|Authentication|Authorization|Authorized|Authenticated|Claim|Claims|Credential|Credentials|Identity|IdToken|Jwt|Login|Password|Permission|Permissions|Role|Roles|Scope|Scopes|Session|Signature|Token)|(?:is|has|can)(?:Access|Admin|Authenticated|Authorized|Owner|Permission|Permissions|Role|Roles)|authenticate|authorize|introspectToken|decodeAndVerify)$","i");const DENIAL_SIGNAL=/^(?:next|reject|abort|deny|fail|forbid|forbidden|unauthorized|logout|exit|sendStatus|redirect)$/i;const FUNCTION_TYPES=new Set([eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration,eslint_devkit_1.AST_NODE_TYPES.FunctionExpression,eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression]);function memberName(node){return!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.property.name:null}function calleeName(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return callee.name;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return memberName(callee);return null}function isGrant(node){return node?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&Boolean(node.value)}function hasWorkAfter(tryStatement){const parent=tryStatement.parent;if(parent?.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&parent?.type!==eslint_devkit_1.AST_NODE_TYPES.Program){return false}const body=parent.body;return body.indexOf(tryStatement)<body.length-1}exports.noFailOpenAuth=(0,eslint_devkit_1.createRule)({name:"no-fail-open-auth",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-fail-open-auth.md",description:"Detects authentication and authorization checks whose catch block fails open",cwe:"CWE-636",cvss:8.1},messages:{failOpenReturn:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Fail-Open Authorization",cwe:"CWE-636",owasp:"A10:2025",cvss:8.1,description:"Security check fails open \u2014 the catch block returns a truthy verdict, so a verification error grants access",severity:"HIGH",fix:"Return the deny value from the catch block (return false / null) and log the error",documentationLink:"https://cwe.mitre.org/data/definitions/636.html"}),failOpenSwallow:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Swallowed Security Check",cwe:"CWE-636",owasp:"A10:2025",cvss:8.1,description:"Security check fails open \u2014 the catch block swallows the error and execution continues into the code the check was guarding",severity:"HIGH",fix:"Rethrow, return a deny value, or send a 401/403 from the catch block before the guarded work runs",documentationLink:"https://cwe.mitre.org/data/definitions/636.html"})},schema:[{type:"object",properties:{securityDecisions:{type:"array",items:{type:"string"},default:[],description:"Additional call names to treat as authentication/authorization decisions"}},additionalProperties:false}]},defaultOptions:[{securityDecisions:[]}],create(context){const{securityDecisions=[]}=context.options[0]??{};const decisionTries=new WeakSet;const grantingCatches=new WeakSet;const handledScopes=new WeakSet;function enclosingTryBlock(node){let current=node;let parent=current.parent;while(parent){if(FUNCTION_TYPES.has(parent.type))return null;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.TryStatement&&parent.block===current){return parent}current=parent;parent=current.parent}return null}function enclosingHandler(node){let current=node;let parent=current.parent;while(parent){if(FUNCTION_TYPES.has(parent.type))return null;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CatchClause)return parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.TryStatement&&parent.finalizer===current){return parent}current=parent;parent=current.parent}return null}function markHandled(node){const handler=enclosingHandler(node);if(handler!==null)handledScopes.add(handler)}function isDenialSignal(node,name){if(DENIAL_SIGNAL.test(name))return true;if(name!=="status")return false;const code=node.arguments[0];return code?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof code.value==="number"&&code.value>=400}return{CallExpression(node){const name=calleeName(node);if(name===null)return;if(SECURITY_DECISION.test(name)||securityDecisions.includes(name)){const tryStatement=enclosingTryBlock(node);if(tryStatement!==null)decisionTries.add(tryStatement)}if(isDenialSignal(node,name))markHandled(node)},ThrowStatement(node){markHandled(node)},BreakStatement(node){markHandled(node)},ContinueStatement(node){markHandled(node)},ReturnStatement(node){markHandled(node);if(!isGrant(node.argument))return;const handler=enclosingHandler(node);if(handler?.type===eslint_devkit_1.AST_NODE_TYPES.CatchClause){grantingCatches.add(handler)}},"TryStatement:exit"(node){const handler=node.handler;if(handler===null)return;if(!decisionTries.has(node))return;if(grantingCatches.has(handler)){context.report({node:handler,messageId:"failOpenReturn"});return}if(handledScopes.has(handler)||handledScopes.has(node))return;if(!hasWorkAfter(node))return;context.report({node:handler,messageId:"failOpenSwallow"})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noGraphqlInjection=(0,eslint_devkit_1.createRule)({name:"no-graphql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-graphql-injection.md",description:"Detects GraphQL injection vulnerabilities and DoS attacks",cwe:"CWE-89"},hasSuggestions:true,messages:{graphqlInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"GraphQL Injection",cwe:"CWE-89",description:"GraphQL injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/Top10/2025/A05_2025-Injection/"}),introspectionQuery:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Introspection Query",cwe:"CWE-200",description:"Introspection query may leak schema information",severity:"HIGH",fix:"Disable introspection in production",documentationLink:"https://graphql.org/learn/introspection/"}),complexQueryDos:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Complex Query DoS Risk",cwe:"CWE-400",description:"Complex query may cause DoS",severity:"MEDIUM",fix:"Limit query depth and complexity",documentationLink:"https://graphql.org/learn/queries/"}),unsafeVariableInterpolation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Variable Interpolation",cwe:"CWE-89",description:"Unsafe interpolation in GraphQL query",severity:"HIGH",fix:"Use GraphQL variables instead of string interpolation",documentationLink:"https://graphql.org/learn/queries/#variables"}),missingInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Input Validation",cwe:"CWE-20",description:"GraphQL input not validated",severity:"MEDIUM",fix:"Validate all user inputs before GraphQL execution",documentationLink:"https://graphql.org/learn/validation/"}),useQueryBuilder:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Query Builder",description:"Use GraphQL query builders for safe construction",severity:"LOW",fix:"Use graphql-tag or similar libraries",documentationLink:"https://www.npmjs.com/package/graphql-tag"}),disableIntrospection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Disable Introspection",description:"Disable GraphQL introspection in production",severity:"LOW",fix:"Set introspection: false in GraphQL config",documentationLink:"https://www.apollographql.com/docs/apollo-server/security/introspection/"}),limitQueryDepth:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Limit Query Depth",description:"Limit maximum query depth",severity:"LOW",fix:"Use depth limiting plugins or custom validation",documentationLink:"https://www.npmjs.com/package/graphql-depth-limit"}),strategyQueryBuilder:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Query Builder Strategy",description:"Use typed query builders for compile-time safety",severity:"LOW",fix:"Use GraphQL code generation tools",documentationLink:"https://graphql-code-generator.com/"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate all inputs at GraphQL resolver level",severity:"LOW",fix:"Implement custom scalars and input validation",documentationLink:"https://graphql.org/learn/schema/#scalar-types"}),strategyIntrospection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Introspection Strategy",description:"Control introspection access based on environment",severity:"LOW",fix:"Enable introspection only for development/admin users",documentationLink:"https://www.apollographql.com/docs/apollo-server/security/introspection/"})},schema:[{type:"object",properties:{allowIntrospection:{type:"boolean",default:false,description:"Allow introspection queries"},maxQueryDepth:{type:"number",minimum:1,default:10,description:"Maximum query nesting depth before reporting a DoS risk"},trustedGraphqlLibraries:{type:"array",items:{type:"string"},default:["graphql","apollo-server","graphql-tools","graphql-tag"],description:"GraphQL libraries recognised as query builders"},validationFunctions:{type:"array",items:{type:"string"},default:["validate","sanitize","isValid","assertValid"],description:"Function names that count as query validation"},safeTemplateLiteralCallers:{type:"array",items:{type:"string"},default:[],description:"Additional callers where template literals are never GraphQL. Format: object.method or ClassName."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as GraphQL sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{allowIntrospection:false,maxQueryDepth:10,trustedGraphqlLibraries:["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions:["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowIntrospection=false,maxQueryDepth=10,trustedGraphqlLibraries=["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions=["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isGraphqlRelated=node=>{const callee=node.callee;if(callee.type==="Identifier"){return trustedGraphqlLibraries.some(lib=>callee.name.toLowerCase().includes(lib.toLowerCase()))}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){const objectName=callee.object.name;return trustedGraphqlLibraries.some(lib=>objectName.toLowerCase().includes(lib.toLowerCase()))}return false};const BUILTIN_SAFE_MEMBER_CALLERS=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.trace","logger.log","logger.info","logger.warn","logger.error","logger.debug"]);const BUILTIN_SAFE_CONSTRUCTORS=new Set(["URL","Error","TypeError","RangeError"]);const safeMemberCallers=new Set(BUILTIN_SAFE_MEMBER_CALLERS);const safeConstructors=new Set(BUILTIN_SAFE_CONSTRUCTORS);for(const caller of safeTemplateLiteralCallers){if(caller.includes(".")){safeMemberCallers.add(caller)}else{safeConstructors.add(caller)}}const isInSafeCallerContext=node=>{let current=node.parent;while(current){if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){const key=`${callee.object.name}.${callee.property.name}`;if(safeMemberCallers.has(key))return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){if(current.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&safeConstructors.has(current.callee.name)){return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration){break}current=current.parent}return false};const isWordChar=ch=>{const code=ch.charCodeAt(0);return code>=65&&code<=90||code>=97&&code<=122||code>=48&&code<=57||code===95};const isWhitespace=ch=>ch===" "||ch==="\n"||ch===" "||ch==="\r";const GRAPHQL_OP_KEYWORDS=["query","mutation","subscription"];const GRAPHQL_SCHEMA_KEYWORDS=["type","interface","enum","scalar","input"];const isAtLineStart=(text,idx)=>{for(let i=idx-1;i>=0;i--){const ch=text[i];if(ch==="\n")return true;if(!isWhitespace(ch))return false}return true};const isStandaloneSelectionSet=text=>{const trimmed=text.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))return false;let braceDepth=0;for(const ch of trimmed){if(ch==="{"){braceDepth++;if(braceDepth>=2)return true}else if(ch==="}"){braceDepth=Math.max(0,braceDepth-1)}}return false};const findKeywordAtBoundary=(text,keyword,startFrom=0)=>{let pos=startFrom;while(true){const idx=text.indexOf(keyword,pos);if(idx===-1)return-1;const beforeOk=idx===0||!isWordChar(text[idx-1]);const afterIdx=idx+keyword.length;const afterOk=afterIdx>=text.length||!isWordChar(text[afterIdx]);if(beforeOk&&afterOk)return idx;pos=idx+1}};const isGraphqlTemplate=node=>{const staticText=node.quasis.map(q=>(q.value.cooked??q.value.raw).toLowerCase()).join("");for(const keyword of GRAPHQL_OP_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&(staticText[scan]==="{"||staticText[scan]==="(")){return true}}}{let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,"fragment",pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+8;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;const nameStart=scan;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;if(scan===nameStart)continue;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(staticText.slice(scan,scan+2)==="on"&&(scan+2>=staticText.length||!isWordChar(staticText[scan+2]))){return true}}}if(staticText.includes("{"))for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;if(scan>=staticText.length||!isWhitespace(staticText[scan]))continue;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&isWordChar(staticText[scan])){return true}}}return isStandaloneSelectionSet(staticText)};const templateHasIntrospection=node=>{return node.quasis.some(q=>{const text=(q.value.cooked??q.value.raw).toLowerCase();return text.includes("__schema")||text.includes("__type")})};const templateQueryDepth=node=>{let depth=0;let braceCount=0;for(const q of node.quasis){const text=q.value.cooked??q.value.raw;for(const char of text){if(char==="{"){braceCount++;depth=Math.max(depth,braceCount)}else if(char==="}"){braceCount--}}}return depth};const containsGraphqlText=text=>{const lower=text.toLowerCase();for(const keyword of GRAPHQL_OP_KEYWORDS){const idx=findKeywordAtBoundary(lower,keyword);if(idx===-1)continue;if(!isAtLineStart(lower,idx))continue;let scan=idx+keyword.length;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;while(scan<lower.length&&isWordChar(lower[scan]))scan++;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(scan<lower.length&&(lower[scan]==="{"||lower[scan]==="("))return true}const fragIdx=findKeywordAtBoundary(lower,"fragment");if(fragIdx!==-1&&isAtLineStart(lower,fragIdx)){let scan=fragIdx+8;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;const nameStart=scan;while(scan<lower.length&&isWordChar(lower[scan]))scan++;if(scan>nameStart){while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(lower.slice(scan,scan+2)==="on"&&(scan+2>=lower.length||!isWordChar(lower[scan+2])))return true}}if(lower.includes("{"))for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){const idx=findKeywordAtBoundary(lower,keyword);if(idx===-1)continue;if(!isAtLineStart(lower,idx))continue;let scan=idx+keyword.length;if(scan>=lower.length||!isWhitespace(lower[scan]))continue;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(scan<lower.length&&isWordChar(lower[scan]))return true}return isStandaloneSelectionSet(text)};const concatenatedStaticText=node=>{if(node.type==="BinaryExpression"&&node.operator==="+"){return concatenatedStaticText(node.left)+concatenatedStaticText(node.right)}if(node.type==="Literal"&&typeof node.value==="string")return node.value;if(node.type==="TemplateLiteral"){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}return""};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};return{TemplateLiteral(node){if(isInSafeCallerContext(node)){return}if(!isGraphqlTemplate(node)){return}if(!allowIntrospection&&templateHasIntrospection(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(node.expressions.length>0){const allExpressionsSafe=node.expressions.every(expr=>isInputValidated(expr)||safetyChecker.isSafe(expr,context));if(!allExpressionsSafe){context.report({node,messageId:"unsafeVariableInterpolation",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"useQueryBuilder",fix:()=>null}]})}}const depth=templateQueryDepth(node);if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"limitQueryDepth",fix:()=>null}]})}},Literal(node){if(typeof node.value!=="string"){return}const queryText=node.value;if(!containsGraphqlText(queryText)){return}const lowerQuery=queryText.toLowerCase();if(!allowIntrospection&&(lowerQuery.includes("__schema")||lowerQuery.includes("__type"))){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}let depth=0;let bc=0;for(const ch of queryText){if(ch==="{"){bc++;depth=Math.max(depth,bc)}else if(ch==="}"){bc--}}if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}const fullText=concatenatedStaticText(node);if(!containsGraphqlText(fullText)){return}if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"graphqlInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use GraphQL variables or query builders instead of string concatenation"}})},CallExpression(node){if(!isGraphqlRelated(node)){return}const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&["execute","executeQuery","query","mutate","subscribe"].includes(callee.property.name)){for(const arg of node.arguments){if(arg.type==="Identifier"&&!isInputValidated(arg)){if(safetyChecker.isSafe(arg,context)){continue}context.report({node:arg,messageId:"missingInputValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noGraphqlInjection=(0,eslint_devkit_1.createRule)({name:"no-graphql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-graphql-injection.md",description:"Detects GraphQL injection vulnerabilities and DoS attacks",cwe:"CWE-89"},hasSuggestions:true,messages:{graphqlInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"GraphQL Injection",cwe:"CWE-89",description:"GraphQL injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/Top10/2025/A05_2025-Injection/"}),introspectionQuery:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Introspection Query",cwe:"CWE-200",description:"Introspection query may leak schema information",severity:"HIGH",fix:"Disable introspection in production",documentationLink:"https://graphql.org/learn/introspection/"}),complexQueryDos:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Complex Query DoS Risk",cwe:"CWE-400",description:"Complex query may cause DoS",severity:"MEDIUM",fix:"Limit query depth and complexity",documentationLink:"https://graphql.org/learn/queries/"}),unsafeVariableInterpolation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Variable Interpolation",cwe:"CWE-89",description:"Unsafe interpolation in GraphQL query",severity:"HIGH",fix:"Use GraphQL variables instead of string interpolation",documentationLink:"https://graphql.org/learn/queries/#variables"}),missingInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Input Validation",cwe:"CWE-20",description:"GraphQL input not validated",severity:"MEDIUM",fix:"Validate all user inputs before GraphQL execution",documentationLink:"https://graphql.org/learn/validation/"}),useQueryBuilder:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Query Builder",description:"Use GraphQL query builders for safe construction",severity:"LOW",fix:"Use graphql-tag or similar libraries",documentationLink:"https://www.npmjs.com/package/graphql-tag"}),disableIntrospection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Disable Introspection",description:"Disable GraphQL introspection in production",severity:"LOW",fix:"Set introspection: false in GraphQL config",documentationLink:"https://www.apollographql.com/docs/apollo-server/security/introspection/"}),limitQueryDepth:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Limit Query Depth",description:"Limit maximum query depth",severity:"LOW",fix:"Use depth limiting plugins or custom validation",documentationLink:"https://www.npmjs.com/package/graphql-depth-limit"}),strategyQueryBuilder:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Query Builder Strategy",description:"Use typed query builders for compile-time safety",severity:"LOW",fix:"Use GraphQL code generation tools",documentationLink:"https://graphql-code-generator.com/"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate all inputs at GraphQL resolver level",severity:"LOW",fix:"Implement custom scalars and input validation",documentationLink:"https://graphql.org/learn/schema/#scalar-types"}),strategyIntrospection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Introspection Strategy",description:"Control introspection access based on environment",severity:"LOW",fix:"Enable introspection only for development/admin users",documentationLink:"https://www.apollographql.com/docs/apollo-server/security/introspection/"})},schema:[{type:"object",properties:{allowIntrospection:{type:"boolean",default:false,description:"Allow introspection queries"},maxQueryDepth:{type:"number",minimum:1,default:10,description:"Maximum query nesting depth before reporting a DoS risk"},trustedGraphqlLibraries:{type:"array",items:{type:"string"},default:["graphql","apollo-server","graphql-tools","graphql-tag"],description:"GraphQL libraries recognised as query builders"},validationFunctions:{type:"array",items:{type:"string"},default:["validate","sanitize","isValid","assertValid"],description:"Function names that count as query validation"},safeTemplateLiteralCallers:{type:"array",items:{type:"string"},default:[],description:"Additional callers where template literals are never GraphQL. Format: object.method or ClassName."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as GraphQL sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{allowIntrospection:false,maxQueryDepth:10,trustedGraphqlLibraries:["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions:["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowIntrospection=false,maxQueryDepth=10,trustedGraphqlLibraries=["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions=["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isGraphqlRelated=node=>{const callee=node.callee;if(callee.type==="Identifier"){return trustedGraphqlLibraries.some(lib=>callee.name.toLowerCase().includes(lib.toLowerCase()))}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){const objectName=callee.object.name;return trustedGraphqlLibraries.some(lib=>objectName.toLowerCase().includes(lib.toLowerCase()))}return false};const BUILTIN_SAFE_MEMBER_CALLERS=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.trace","logger.log","logger.info","logger.warn","logger.error","logger.debug"]);const BUILTIN_SAFE_CONSTRUCTORS=new Set(["URL","Error","TypeError","RangeError"]);const safeMemberCallers=new Set(BUILTIN_SAFE_MEMBER_CALLERS);const safeConstructors=new Set(BUILTIN_SAFE_CONSTRUCTORS);for(const caller of safeTemplateLiteralCallers){if(caller.includes(".")){safeMemberCallers.add(caller)}else{safeConstructors.add(caller)}}const isInSafeCallerContext=node=>{let current=node.parent;while(current){if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){const key=`${callee.object.name}.${callee.property.name}`;if(safeMemberCallers.has(key))return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){if(current.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&safeConstructors.has(current.callee.name)){return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration){break}current=current.parent}return false};const isWordChar=ch=>{const code=ch.charCodeAt(0);return code>=65&&code<=90||code>=97&&code<=122||code>=48&&code<=57||code===95};const isWhitespace=ch=>ch===" "||ch==="\n"||ch===" "||ch==="\r";const GRAPHQL_OP_KEYWORDS=["query","mutation","subscription"];const GRAPHQL_SCHEMA_KEYWORDS=["type","interface","enum","scalar","input"];const isAtLineStart=(text,idx)=>{for(let i=idx-1;i>=0;i--){const ch=text[i];if(ch==="\n")return true;if(!isWhitespace(ch))return false}return true};const isStandaloneSelectionSet=text=>{const trimmed=text.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))return false;if(/\{\{|\}\}/.test(trimmed))return false;if(/"[^"]*"\s*:/.test(trimmed))return false;let braceDepth=0;for(const ch of trimmed){if(ch==="{"){braceDepth++;if(braceDepth>=2)return true}else if(ch==="}"){braceDepth=Math.max(0,braceDepth-1)}}return false};const findKeywordAtBoundary=(text,keyword,startFrom=0)=>{let pos=startFrom;while(true){const idx=text.indexOf(keyword,pos);if(idx===-1)return-1;const beforeOk=idx===0||!isWordChar(text[idx-1]);const afterIdx=idx+keyword.length;const afterOk=afterIdx>=text.length||!isWordChar(text[afterIdx]);if(beforeOk&&afterOk)return idx;pos=idx+1}};const GRAPHQL_TAG_NAMES=new Set(["gql","graphql"]);const GRAPHQL_SCHEMA_BINDING=/typedef|schema|sdl/i;const hasGraphqlAttribution=node=>{let current=node;while(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){current=current.parent}const parent=current.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){const tag=parent.tag;const tagName=tag.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.name:tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&tag.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.property.name:"";return GRAPHQL_TAG_NAMES.has(tagName.toLowerCase())}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.id.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.key.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isGraphqlRelated(parent)}return false};const isGraphqlTemplate=node=>{const staticText=node.quasis.map(q=>(q.value.cooked??q.value.raw).toLowerCase()).join("");for(const keyword of GRAPHQL_OP_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&(staticText[scan]==="{"||staticText[scan]==="(")){return true}}}{let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,"fragment",pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+8;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;const nameStart=scan;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;if(scan===nameStart)continue;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(staticText.slice(scan,scan+2)==="on"&&(scan+2>=staticText.length||!isWordChar(staticText[scan+2]))){return true}}}if(hasGraphqlAttribution(node)&&staticText.includes("{"))for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;if(scan>=staticText.length||!isWhitespace(staticText[scan]))continue;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&isWordChar(staticText[scan])){return true}}}return isStandaloneSelectionSet(staticText)};const hasIntrospectionField=text=>{const lower=text.toLowerCase();return findKeywordAtBoundary(lower,"__schema")!==-1||findKeywordAtBoundary(lower,"__type")!==-1};const templateHasIntrospection=node=>{return node.quasis.some(q=>hasIntrospectionField(q.value.cooked??q.value.raw))};const templateQueryDepth=node=>{let depth=0;let braceCount=0;for(const q of node.quasis){const text=q.value.cooked??q.value.raw;for(const char of text){if(char==="{"){braceCount++;depth=Math.max(depth,braceCount)}else if(char==="}"){braceCount--}}}return depth};const containsGraphqlText=(text,attributed)=>{const lower=text.toLowerCase();for(const keyword of GRAPHQL_OP_KEYWORDS){const idx=findKeywordAtBoundary(lower,keyword);if(idx===-1)continue;if(!isAtLineStart(lower,idx))continue;let scan=idx+keyword.length;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;while(scan<lower.length&&isWordChar(lower[scan]))scan++;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(scan<lower.length&&(lower[scan]==="{"||lower[scan]==="("))return true}const fragIdx=findKeywordAtBoundary(lower,"fragment");if(fragIdx!==-1&&isAtLineStart(lower,fragIdx)){let scan=fragIdx+8;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;const nameStart=scan;while(scan<lower.length&&isWordChar(lower[scan]))scan++;if(scan>nameStart){while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(lower.slice(scan,scan+2)==="on"&&(scan+2>=lower.length||!isWordChar(lower[scan+2])))return true}}if(attributed&&lower.includes("{"))for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){const idx=findKeywordAtBoundary(lower,keyword);if(idx===-1)continue;if(!isAtLineStart(lower,idx))continue;let scan=idx+keyword.length;if(scan>=lower.length||!isWhitespace(lower[scan]))continue;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(scan<lower.length&&isWordChar(lower[scan]))return true}return isStandaloneSelectionSet(text)};const concatenatedStaticText=node=>{if(node.type==="BinaryExpression"&&node.operator==="+"){return concatenatedStaticText(node.left)+concatenatedStaticText(node.right)}if(node.type==="Literal"&&typeof node.value==="string")return node.value;if(node.type==="TemplateLiteral"){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}return""};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};return{TemplateLiteral(node){if(isInSafeCallerContext(node)){return}if(!isGraphqlTemplate(node)){return}if(!allowIntrospection&&templateHasIntrospection(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(node.expressions.length>0){const allExpressionsSafe=node.expressions.every(expr=>isInputValidated(expr)||safetyChecker.isSafe(expr,context));if(!allExpressionsSafe){context.report({node,messageId:"unsafeVariableInterpolation",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"useQueryBuilder",fix:()=>null}]})}}const depth=templateQueryDepth(node);if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"limitQueryDepth",fix:()=>null}]})}},Literal(node){if(typeof node.value!=="string"){return}const queryText=node.value;if(!containsGraphqlText(queryText,hasGraphqlAttribution(node))){return}if(!allowIntrospection&&hasIntrospectionField(queryText)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}let depth=0;let bc=0;for(const ch of queryText){if(ch==="{"){bc++;depth=Math.max(depth,bc)}else if(ch==="}"){bc--}}if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}const fullText=concatenatedStaticText(node);if(!containsGraphqlText(fullText,hasGraphqlAttribution(node))){return}if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"graphqlInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use GraphQL variables or query builders instead of string concatenation"}})},CallExpression(node){if(!isGraphqlRelated(node)){return}const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&["execute","executeQuery","query","mutate","subscribe"].includes(callee.property.name)){for(const arg of node.arguments){if(arg.type==="Identifier"&&!isInputValidated(arg)){if(safetyChecker.isSafe(arg,context)){continue}context.report({node:arg,messageId:"missingInputValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;exports.isNaturalWordString=isNaturalWordString;exports.looksRandom=looksRandom;exports.isSecretShaped=isSecretShaped;exports.isPlaceholderValue=isPlaceholderValue;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const CREDENTIAL_PATTERNS={apiKey:/^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,jwtToken:/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,oauthToken:/^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,awsAccessKey:/^AKIA[0-9A-Z]{16}$/,databaseString:/^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,commonPassword:/^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,secretKey:/^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/};const CREDENTIAL_VARIABLE_NAMES=new Set(["apikey","api_key","apiKey","secret","secretkey","secret_key","secretKey","clientsecret","client_secret","clientSecret","token","authtoken","auth_token","authToken","accesstoken","access_token","accessToken","refreshtoken","refresh_token","refreshToken","idtoken","id_token","idToken","password","passwd","pass","pwd","privatekey","private_key","privateKey","credentials","creds","authorization","auth","connectionstring","connection_string","connectionString","connectionuri","connectionURI","dburl","db_url","dbUrl","databaseurl","database_url","databaseUrl"]);const WORD_SEPARATORS=new Set(["_","-","."," "]);function shannonEntropy(value){const freq=new Map;for(const ch of value)freq.set(ch,(freq.get(ch)??0)+1);let entropy=0;for(const count of freq.values()){const p=count/value.length;entropy-=p*Math.log2(p)}return entropy}function charClasses(value){const classes={lower:false,upper:false,digit:false,symbol:false};for(const ch of value){if(WORD_SEPARATORS.has(ch))continue;if(ch>="a"&&ch<="z")classes.lower=true;else if(ch>="A"&&ch<="Z")classes.upper=true;else if(ch>="0"&&ch<="9")classes.digit=true;else classes.symbol=true}return classes}function classCount(classes){return Number(classes.lower)+Number(classes.upper)+Number(classes.digit)+Number(classes.symbol)}function isPronounceable(token){const lower=token.toLowerCase();if(!/[aeiouy]/.test(lower))return false;if(/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))return false;return true}function isNaturalWordString(value){if(!/^[A-Za-z][A-Za-z_\-. ]*$/.test(value))return false;const tokens=value.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[^A-Za-z]+/).filter(Boolean);const meaningful=tokens.filter(t=>t.length>=3);if(meaningful.length===0)return false;return meaningful.every(isPronounceable)}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const PLACEHOLDER_WORDS=new Set(["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"]);function isPlaceholderValue(value){const trimmed=value.trim();if(trimmed.length===0)return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>PLACEHOLDER_WORDS.has(token))}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch(error){continue}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(value.length>=32&&CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),strategyEnv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Environment Variable Strategy",description:"Move credentials to environment variables",severity:"MEDIUM",fix:"Store credentials in environment variables (process.env)",documentationLink:"https://12factor.net/config"}),strategyConfig:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Configuration File Strategy",description:"Store credentials in encrypted configuration files",severity:"MEDIUM",fix:"Use encrypted configuration files with proper access controls",documentationLink:"https://owasp.org/www-project-cheat-sheets/cheatsheets/Configuration_Management_Cheat_Sheet.html"}),strategyVault:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Secret Vault Strategy",cwe:"CWE-798",description:"Use dedicated secret management system",severity:"HIGH",fix:"Implement HashiCorp Vault, AWS Secrets Manager, or similar secret vault",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),strategyAuto:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Context-Aware Strategy",description:"Apply context-aware credential management",severity:"MEDIUM",fix:"Choose strategy based on deployment environment and security requirements",documentationLink:"https://owasp.org/www-project-cheat-sheets/cheatsheets/Secrets_Management_Cheat_Sheet.html"})},schema:[{type:"object",properties:{ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:true,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},strategy:{type:"string",enum:["env","config","vault","auto"],default:"auto",description:"Strategy for fixing hardcoded credentials (auto = smart detection)"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:true,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],strategy:"auto",allowPlaceholders:true}],create(context){const options=context.options[0]||{};const{ignorePatterns=[],allowInTests=true,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true}=options;const filename=context.filename;const isTestFile=allowInTests&&(filename.includes(".test.")||filename.includes(".spec.")||filename.includes(".fixture.")||filename.includes(".mock.")||filename.includes("__tests__")||filename.includes("__mocks__")||filename.includes("/test/")||filename.includes("/tests/")||filename.includes("/fixtures/")||filename.includes("/mocks/"));const compiledIgnorePatterns=ignorePatterns.map(pattern=>new RegExp(pattern));const detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};const LABEL_CONTEXT_NAMES=new Set(["type","name","id","placeholder","label","title","role","autocomplete","autoFocus","autocapitalize","inputmode","aria-label","aria-labelledby","aria-describedby","fieldName","fieldType","fieldLabel","inputType","inputName","displayName","columnName","paramName","i18nKey","translationKey","messageKey"]);function isLabelContext(node,parent){if(!parent)return false;if(parent.type==="ObjectExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const n=parent.id.name.toLowerCase();if(LABEL_CONTEXT_NAMES.has(n)||n==="labels"||n.endsWith("label")||n.endsWith("labels")||n.endsWith("name")||n.endsWith("placeholder"))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(LABEL_CONTEXT_NAMES.has(left.property.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&LABEL_CONTEXT_NAMES.has(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(LABEL_CONTEXT_NAMES.has(key.value))return true}const obj=parent.parent;if(obj?.type==="ObjectExpression"){const grand=obj.parent;if(grand)return isLabelContext(node,grand)}}if(parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"){const callee=parent.callee;const methodName=callee.property.name;if(methodName==="setAttribute"||methodName==="getAttribute"){const args=parent.arguments;if(args[1]===node)return true}}if(parent.type==="JSXAttribute")return true;return false}function inferCredentialTypeFromContext(parent){const name=(()=>{if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){return parent.id.name.toLowerCase()}if(parent.type==="Property"){const key=parent.key;if(key.type==="Identifier")return key.name.toLowerCase();return String(key.value).toLowerCase()}if(parent.type==="AssignmentExpression"){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){return left.property.name.toLowerCase()}}return""})();if(/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))return"apikey";return"other"}function isCredentialContext(node,parent){if(!parent)return false;const matches=name=>{const lower=name.toLowerCase();if(lower==="key"||lower==="keys"){return node.type==="Literal"&&typeof node.value==="string"&&looksRandom(node.value)}const singular=lower.endsWith("s")?lower.slice(0,-1):lower;if(CREDENTIAL_VARIABLE_NAMES.has(lower)||CREDENTIAL_VARIABLE_NAMES.has(singular))return true;return lower.endsWith("apikey")||lower.endsWith("apikeys")||lower.endsWith("secret")||lower.endsWith("secrets")||lower.endsWith("token")||lower.endsWith("tokens")||lower.endsWith("password")||lower.endsWith("passwords")||lower.endsWith("passwd")||lower.endsWith("credential")||lower.endsWith("credentials")};if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isCredentialContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){if(matches(parent.id.name))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(matches(left.property.name))return true}if(left.type==="Identifier"){if(matches(left.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&matches(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(matches(key.value))return true}}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator==="||"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&left.object.property.type==="Identifier"&&left.object.property.name==="env"){return}}if(isLabelContext(node,parent)){return}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(node,parent)){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(node,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",data:{credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{isCredential,type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",data:{credentialType:type},fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){if(quasi.value.raw){const{isCredential,type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;exports.isNaturalWordString=isNaturalWordString;exports.looksRandom=looksRandom;exports.isSecretShaped=isSecretShaped;exports.isPlaceholderValue=isPlaceholderValue;exports.isPublishableKeyValue=isPublishableKeyValue;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const CREDENTIAL_PATTERNS={apiKey:/^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,jwtToken:/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,oauthToken:/^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,awsAccessKey:/^AKIA[0-9A-Z]{16}$/,databaseString:/^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,commonPassword:/^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,secretKey:/^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/};const CREDENTIAL_VARIABLE_NAMES=new Set(["apikey","api_key","apiKey","secret","secretkey","secret_key","secretKey","clientsecret","client_secret","clientSecret","token","authtoken","auth_token","authToken","accesstoken","access_token","accessToken","refreshtoken","refresh_token","refreshToken","idtoken","id_token","idToken","password","passwd","pass","pwd","privatekey","private_key","privateKey","credentials","creds","authorization","auth","connectionstring","connection_string","connectionString","connectionuri","connectionURI","dburl","db_url","dbUrl","databaseurl","database_url","databaseUrl"]);const WORD_SEPARATORS=new Set(["_","-","."," "]);function shannonEntropy(value){const freq=new Map;for(const ch of value)freq.set(ch,(freq.get(ch)??0)+1);let entropy=0;for(const count of freq.values()){const p=count/value.length;entropy-=p*Math.log2(p)}return entropy}function charClasses(value){const classes={lower:false,upper:false,digit:false,symbol:false};for(const ch of value){if(WORD_SEPARATORS.has(ch))continue;if(ch>="a"&&ch<="z")classes.lower=true;else if(ch>="A"&&ch<="Z")classes.upper=true;else if(ch>="0"&&ch<="9")classes.digit=true;else classes.symbol=true}return classes}function classCount(classes){return Number(classes.lower)+Number(classes.upper)+Number(classes.digit)+Number(classes.symbol)}function isPronounceable(token){const lower=token.toLowerCase();if(!/[aeiouy]/.test(lower))return false;if(/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))return false;return true}function isNaturalWordString(value){if(!/^[A-Za-z][A-Za-z0-9_\-. ]*$/.test(value))return false;const digits=value.replace(/[^0-9]/g,"").length;if(digits>0&&(digits/value.length>.2||/[0-9]{4,}/.test(value)))return false;const tokens=value.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[^A-Za-z]+/).filter(Boolean);const meaningful=tokens.filter(t=>t.length>=3);if(meaningful.length===0)return false;return meaningful.every(isPronounceable)}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;if(isNaturalWordString(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const PLACEHOLDER_WORDS=new Set(["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"]);function isPlaceholderValue(value){const trimmed=value.trim();if(trimmed.length===0)return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>PLACEHOLDER_WORDS.has(token))}function isPublishableKeyValue(value){if(/^pk_(?:live|test)_[A-Za-z0-9_-]{8,}$/.test(value))return true;if(/^phc_[A-Za-z0-9]{20,}$/.test(value))return true;if(/^https?:\/\/[A-Za-z0-9]+@[A-Za-z0-9.-]+(?::\d+)?\/\d+$/.test(value)){return true}return false}const SECRET_SIDE_VALUE=/^(?:sk|rk)_(?:live|test)_|^sk-[A-Za-z0-9]|^gh[pousr]_|^ph[xs]_|^sntry[su]_|^xox[baprs]-|^AKIA[0-9A-Z]{16}$|^ey[A-Za-z0-9_-]+\.ey|-----BEGIN|^(?:mysql|postgres|mongodb|redis):\/\//;const SECRET_SIDE_SLOT=/secret|private|signing|password|passwd|serviceaccount|serverkey|adminkey|masterkey/;const PUBLISHABLE_VENDORS=[{vendor:"Bugsnag",packages:["bugsnag","bugsnag-js","bugsnag-build-reporter","bugsnag-sourcemaps"],scopes:["@bugsnag"],named:/bugsnag/,slots:/^(?:bugsnag)?(?:notifier)?(?:api)?key$/},{vendor:"Sentry",scopes:["@sentry"],named:/sentry/,slots:/^(?:sentry)?dsn$/},{vendor:"PostHog",packages:["posthog-js","posthog-node"],named:/posthog/,slots:/^(?:posthog)?(?:project)?(?:api)?key$/},{vendor:"Segment",packages:["analytics-node"],scopes:["@segment"],named:/segment/,slots:/^(?:segment)?write(?:key|token)$/},{vendor:"Amplitude",packages:["amplitude-js"],scopes:["@amplitude"],named:/amplitude/,slots:/^(?:amplitude)?(?:api)?key$/},{vendor:"Mixpanel",packages:["mixpanel","mixpanel-browser"],named:/mixpanel/,slots:/^(?:mixpanel)?(?:project)?token$/},{vendor:"Firebase",packages:["firebase"],scopes:["@firebase"],named:/firebase/,slots:/^(?:firebase)?(?:web)?apikey$/}];const VENDOR_PROBES=PUBLISHABLE_VENDORS.map(entry=>({entry,loadsSdk:(0,eslint_devkit_2.createModuleEvidence)({packages:entry.packages,scopes:entry.scopes})}));function slotNameOf(parent){if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){return parent.id.name.toLowerCase()}if(parent.type==="Property"){const key=parent.key;if(key.type==="Identifier")return key.name.toLowerCase();return String(key.value).toLowerCase()}if(parent.type==="AssignmentExpression"){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){return left.property.name.toLowerCase()}}return""}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch(error){continue}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(value.length>=32&&CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),strategyEnv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Environment Variable Strategy",description:"Move credentials to environment variables",severity:"MEDIUM",fix:"Store credentials in environment variables (process.env)",documentationLink:"https://12factor.net/config"}),strategyConfig:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Configuration File Strategy",description:"Store credentials in encrypted configuration files",severity:"MEDIUM",fix:"Use encrypted configuration files with proper access controls",documentationLink:"https://owasp.org/www-project-cheat-sheets/cheatsheets/Configuration_Management_Cheat_Sheet.html"}),strategyVault:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Secret Vault Strategy",cwe:"CWE-798",description:"Use dedicated secret management system",severity:"HIGH",fix:"Implement HashiCorp Vault, AWS Secrets Manager, or similar secret vault",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),strategyAuto:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Context-Aware Strategy",description:"Apply context-aware credential management",severity:"MEDIUM",fix:"Choose strategy based on deployment environment and security requirements",documentationLink:"https://owasp.org/www-project-cheat-sheets/cheatsheets/Secrets_Management_Cheat_Sheet.html"})},schema:[{type:"object",properties:{ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:true,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},strategy:{type:"string",enum:["env","config","vault","auto"],default:"auto",description:"Strategy for fixing hardcoded credentials (auto = smart detection)"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:true,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],strategy:"auto",allowPlaceholders:true}],create(context){const options=context.options[0]||{};const{ignorePatterns=[],allowInTests=true,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true}=options;const filename=context.filename;const isTestFile=allowInTests&&(filename.includes(".test.")||filename.includes(".spec.")||filename.includes(".fixture.")||filename.includes(".mock.")||filename.includes("__tests__")||filename.includes("__mocks__")||filename.includes("/test/")||filename.includes("/tests/")||filename.includes("/fixtures/")||filename.includes("/mocks/"));const compiledIgnorePatterns=ignorePatterns.map(pattern=>new RegExp(pattern));const detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};const LABEL_CONTEXT_NAMES=new Set(["type","name","id","placeholder","label","title","role","autocomplete","autoFocus","autocapitalize","inputmode","aria-label","aria-labelledby","aria-describedby","fieldName","fieldType","fieldLabel","inputType","inputName","displayName","columnName","paramName","i18nKey","translationKey","messageKey"]);function isLabelContext(node,parent){if(!parent)return false;if(parent.type==="ObjectExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const n=parent.id.name.toLowerCase();if(LABEL_CONTEXT_NAMES.has(n)||n==="labels"||n.endsWith("label")||n.endsWith("labels")||n.endsWith("name")||n.endsWith("placeholder"))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(LABEL_CONTEXT_NAMES.has(left.property.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;const keyText=key.type==="Identifier"?key.name:key.type==="Literal"&&typeof key.value==="string"?key.value:null;if(keyText!==null&&node.type==="Literal"&&typeof node.value==="string"){const keyTokens=keyText.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);if(keyTokens.includes(node.value.toUpperCase()))return true}if(key.type==="Identifier"&&LABEL_CONTEXT_NAMES.has(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(LABEL_CONTEXT_NAMES.has(key.value))return true}const obj=parent.parent;if(obj?.type==="ObjectExpression"){const grand=obj.parent;if(grand)return isLabelContext(node,grand)}}if(parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"){const callee=parent.callee;const methodName=callee.property.name;if(methodName==="setAttribute"||methodName==="getAttribute"){const args=parent.arguments;if(args[1]===node)return true}}if(parent.type==="JSXAttribute")return true;return false}function inferCredentialTypeFromContext(parent){const name=slotNameOf(parent);if(/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))return"apikey";return"other"}function isCredentialContext(node,parent){if(!parent)return false;const matches=name=>{const lower=name.toLowerCase();if(lower==="key"||lower==="keys"){return node.type==="Literal"&&typeof node.value==="string"&&looksRandom(node.value)}const singular=lower.endsWith("s")?lower.slice(0,-1):lower;if(CREDENTIAL_VARIABLE_NAMES.has(lower)||CREDENTIAL_VARIABLE_NAMES.has(singular))return true;return lower.endsWith("apikey")||lower.endsWith("apikeys")||lower.endsWith("secret")||lower.endsWith("secrets")||lower.endsWith("token")||lower.endsWith("tokens")||lower.endsWith("password")||lower.endsWith("passwords")||lower.endsWith("passwd")||lower.endsWith("credential")||lower.endsWith("credentials")};if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isCredentialContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){if(matches(parent.id.name))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(matches(left.property.name))return true}if(left.type==="Identifier"){if(matches(left.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&matches(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(matches(key.value))return true}}return false}let loadedVendors=null;function vendorsInFile(){if(loadedVendors===null){const found=new Set;for(const{entry,loadsSdk}of VENDOR_PROBES){if(loadsSdk(context.sourceCode.ast))found.add(entry.vendor)}loadedVendors=found}return loadedVendors}function isPublishableKey(value,parent){if(SECRET_SIDE_VALUE.test(value))return false;if(isPublishableKeyValue(value))return true;const slot=slotNameOf(parent);if(slot===""||SECRET_SIDE_SLOT.test(slot))return false;for(const{entry}of VENDOR_PROBES){if(!entry.named.test(slot)&&!vendorsInFile().has(entry.vendor)){continue}if(entry.slots.test(slot))return true}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator==="||"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&left.object.property.type==="Identifier"&&left.object.property.name==="env"){return}}if(isLabelContext(node,parent)){return}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(node,parent)){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(node,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}if(isPublishableKey(value,parent)){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",data:{credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{isCredential,type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",data:{credentialType:type},fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){if(quasi.value.raw){const{isCredential,type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}}});
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHomoglyphIdentifiers=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const CONFUSABLE_WITH_ASCII=new Map([[1072,"a"],[1074,"b"],[1075,"r"],[1077,"e"],[1082,"k"],[1084,"m"],[1085,"h"],[1086,"o"],[1088,"p"],[1089,"c"],[1091,"y"],[1093,"x"],[1109,"s"],[1110,"i"],[1112,"j"],[1029,"S"],[1030,"I"],[1032,"J"],[1040,"A"],[1042,"B"],[1045,"E"],[1050,"K"],[1052,"M"],[1053,"H"],[1054,"O"],[1056,"P"],[1057,"C"],[1058,"T"],[1059,"Y"],[1061,"X"],[945,"a"],[949,"e"],[953,"i"],[954,"k"],[957,"v"],[959,"o"],[961,"p"],[963,"o"],[964,"t"],[965,"u"],[967,"x"],[913,"A"],[914,"B"],[917,"E"],[918,"Z"],[919,"H"],[921,"I"],[922,"K"],[924,"M"],[925,"N"],[927,"O"],[929,"P"],[932,"T"],[933,"Y"],[935,"X"],[1400,"n"],[1405,"u"],[1413,"o"],[5024,"D"],[5033,"E"],[5034,"A"],[5043,"W"],[5051,"P"],[5056,"G"],[5071,"C"],[5081,"V"],[5086,"S"],[5090,"B"],[448,"l"],[305,"i"],[609,"g"]]);const INVISIBLE=/[\u00ad\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/;function toCodepointLabel(codepoint){return`U+${codepoint.toString(16).toUpperCase().padStart(4,"0")}`}function confusableFor(codepoint){const mapped=CONFUSABLE_WITH_ASCII.get(codepoint);if(mapped!==void 0)return mapped;if(codepoint>=65313&&codepoint<=65338){return String.fromCharCode(codepoint-65313+65)}if(codepoint>=65345&&codepoint<=65370){return String.fromCharCode(codepoint-65345+97)}return null}function homoglyphIn(name){if(!/[A-Za-z]/.test(name))return null;for(let index=0;index<name.length;index++){const codepoint=name.charCodeAt(index);if(codepoint<128)continue;const latin=confusableFor(codepoint);if(latin!==null){return{character:name[index],codepoint,latin}}}return null}function isVisibleAscii(codepoint){return codepoint>=33&&codepoint<=126}function invisibleIn(text){for(let index=0;index<text.length;index++){if(!INVISIBLE.test(text[index]))continue;const before=index>0?text.charCodeAt(index-1):-1;const after=index+1<text.length?text.charCodeAt(index+1):-1;if(!isVisibleAscii(before)&&!isVisibleAscii(after))continue;return{index,codepoint:text.charCodeAt(index)}}return null}exports.noHomoglyphIdentifiers=(0,eslint_devkit_1.createRule)({name:"no-homoglyph-identifiers",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-homoglyph-identifiers.md",description:"Detects homoglyph identifiers and invisible characters that hide what the code actually does",cwe:"CWE-1007",cvss:5.3},messages:{homoglyphIdentifier:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Homoglyph Identifier",cwe:"CWE-1007",cvss:5.3,description:'Identifier "{{name}}" mixes scripts: {{codepoint}} renders as ASCII "{{latin}}" but is a different character',severity:"MEDIUM",fix:"Rewrite the identifier in ASCII, or confirm the binding it resolves to is the one you intended",documentationLink:"https://cwe.mitre.org/data/definitions/1007.html"}),invisibleCharacter:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Invisible Character",cwe:"CWE-1007",cvss:5.3,description:"String contains invisible character {{codepoint}} at index {{index}} - the text is not what it appears to be",severity:"MEDIUM",fix:"Remove the character, or write it as an escape (\\u200B) so it is visible in review",documentationLink:"https://trojansource.codes/"})},schema:[{type:"object",properties:{checkIdentifiers:{type:"boolean",default:true,description:"Check identifier names for script-mixing homoglyphs"},checkStrings:{type:"boolean",default:true,description:"Check string literals and template chunks for invisible characters"}},additionalProperties:false}]},defaultOptions:[{checkIdentifiers:true,checkStrings:true}],create(context){const options=context.options[0]??{};const checkIdentifiers=options.checkIdentifiers??true;const checkStrings=options.checkStrings??true;function checkName(node){if(!checkIdentifiers)return;const found=homoglyphIn(node.name);if(!found)return;context.report({node,messageId:"homoglyphIdentifier",data:{name:node.name,codepoint:toCodepointLabel(found.codepoint),latin:found.latin}})}function checkText(node,text){const found=invisibleIn(text);if(!found)return;context.report({node,messageId:"invisibleCharacter",data:{codepoint:toCodepointLabel(found.codepoint),index:String(found.index)}})}return{Identifier:checkName,PrivateIdentifier:checkName,Literal(node){if(!checkStrings)return;if(typeof node.value!=="string")return;checkText(node,node.raw)},TemplateElement(node){if(!checkStrings)return;checkText(node,node.value.raw)}}}});