eslint-plugin-secure-coding 4.2.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +39 -0
  2. package/package.json +9 -3
  3. package/src/index.js +1 -1
  4. package/src/rules/detect-non-literal-regexp/index.js +1 -1
  5. package/src/rules/detect-object-injection/index.js +1 -1
  6. package/src/rules/detect-weak-password-validation/index.js +1 -1
  7. package/src/rules/no-bidi-characters/index.js +1 -1
  8. package/src/rules/no-directive-injection/index.js +1 -1
  9. package/src/rules/no-electron-security-issues/index.js +1 -1
  10. package/src/rules/no-format-string-injection/index.js +1 -1
  11. package/src/rules/no-graphql-injection/index.js +1 -1
  12. package/src/rules/no-hardcoded-credentials/index.js +1 -1
  13. package/src/rules/no-improper-sanitization/index.js +1 -1
  14. package/src/rules/no-improper-type-validation/index.js +1 -1
  15. package/src/rules/no-insecure-comparison/index.js +1 -1
  16. package/src/rules/no-ldap-injection/index.js +1 -1
  17. package/src/rules/no-log-injection/index.js +1 -1
  18. package/src/rules/no-missing-authentication/index.js +1 -1
  19. package/src/rules/no-pii-in-logs/index.js +1 -1
  20. package/src/rules/no-privilege-escalation/index.js +1 -1
  21. package/src/rules/no-redos-vulnerable-regex/index.js +0 -0
  22. package/src/rules/no-sensitive-data-exposure/index.js +1 -1
  23. package/src/rules/no-sql-injection/index.js +1 -1
  24. package/src/rules/no-template-injection/index.js +1 -1
  25. package/src/rules/no-unchecked-loop-condition/index.js +1 -1
  26. package/src/rules/no-unlimited-resource-allocation/index.js +1 -1
  27. package/src/rules/no-unsafe-deserialization/index.js +1 -1
  28. package/src/rules/no-unsafe-regex-construction/index.js +1 -1
  29. package/src/rules/no-weak-password-recovery/index.js +1 -1
  30. package/src/rules/no-xpath-injection/index.js +1 -1
  31. package/src/rules/no-xxe-injection/index.js +1 -1
  32. package/src/rules/require-backend-authorization/index.js +1 -1
  33. package/src/rules/require-secure-defaults/index.js +1 -1
  34. package/src/utils/redos-oracle.js +1 -0
  35. package/src/utils/regexp-intrinsic.js +1 -0
  36. package/src/utils/resolve-reference.js +1 -0
package/README.md CHANGED
@@ -29,6 +29,45 @@ This plugin provides General secure coding practices and OWASP compliance for Ja
29
29
 
30
30
  **Interlace** fosters **strength through integration**. Instead of stacking isolated rules, we **interlace** security directly into your workflow to create a resilient fabric of code. We believe tools should **guide rather than gatekeep**, providing educational feedback that strengthens the developer with every interaction.
31
31
 
32
+ <!-- AUTO-GENERATED:DOCTRINE:START - Do not edit manually -->
33
+
34
+ ## Why these rules are quiet
35
+
36
+ **Noise creates apathy, and apathy is not a security posture.** A linter that reports
37
+ a thousand things a week gets switched off in a month, and the real finding goes with
38
+ it. So every rule here is built to be worth reading: we would rather miss a finding
39
+ than spend your attention on one that was never real.
40
+
41
+ That is a trade, and it is made deliberately. It costs recall, and we measure what it
42
+ costs rather than assuming it is free.
43
+
44
+ ## How the rules decide
45
+
46
+ **Evidence, not names.** A rule fires on what the code *does*, resolved through the
47
+ AST and ESLint's own scope analysis — not on an identifier that happens to contain
48
+ `query`, a method called `setItem`, or a file whose path contains `key`. Every one of
49
+ those was a real false positive in this ecosystem, found by reading our own output on
50
+ open-source projects and fixed with a test that fails on the unfixed rule.
51
+
52
+ Where a rule has known false-positive shapes, its page carries a **Not a finding**
53
+ section: what it deliberately stays quiet on, and what to check first when it fires
54
+ and you disagree.
55
+
56
+ ## What you get
57
+
58
+ The rules below. Security rules carry a CWE mapping and, where one is assigned, a
59
+ CVSS score; every rule carries a fix on its message — in prose for a human and as
60
+ structured JSON for an agent. Install it, enable
61
+ `recommended`, and read the findings. If one of them is wrong,
62
+ [open an issue](https://github.com/ofri-peretz/eslint/issues) — a false positive is a
63
+ bug here, not a tuning exercise for you.
64
+
65
+ How that is measured, on which projects, and where it falls short:
66
+ [benchmark methodology](https://github.com/ofri-peretz/eslint/blob/main/BENCHMARK-METHODOLOGY.md)
67
+ and [results](https://github.com/ofri-peretz/eslint/blob/main/BENCHMARK-RESULTS.md).
68
+
69
+ <!-- AUTO-GENERATED:DOCTRINE:END -->
70
+
32
71
  ## Getting Started
33
72
 
34
73
  - To check out the [guide](https://eslint.interlace.tools/docs/security/plugin-secure-coding?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding), visit [eslint.interlace.tools](https://eslint.interlace.tools/?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding). 📚
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-secure-coding",
3
- "version": "4.2.0",
3
+ "version": "5.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",
@@ -78,15 +78,21 @@
78
78
  "node": ">=18.0.0"
79
79
  },
80
80
  "dependencies": {
81
- "@interlace/eslint-devkit": "^1.15.0",
81
+ "@interlace/eslint-devkit": "^1.16.1",
82
82
  "scslre": "^0.3.0",
83
83
  "@eslint-community/regexpp": "^4.10.0"
84
84
  },
85
85
  "peerDependencies": {
86
- "eslint": "^8.40.0 || ^9.0.0 || ^10.0.0"
86
+ "eslint": "^8.40.0 || ^9.0.0 || ^10.0.0",
87
+ "recheck": "^4.5.0"
87
88
  },
88
89
  "funding": {
89
90
  "type": "github",
90
91
  "url": "git+https://github.com/ofri-peretz/eslint.git"
92
+ },
93
+ "peerDependenciesMeta": {
94
+ "recheck": {
95
+ "optional": true
96
+ }
91
97
  }
92
98
  }
package/src/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"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},get"no-bidi-characters"(){return require("./rules/no-bidi-characters").noBidiCharacters}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-secure-coding",exports.rules);exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"4.2.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
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"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},get"no-bidi-characters"(){return require("./rules/no-bidi-characters").noBidiCharacters}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-secure-coding",exports.rules);exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"5.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 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
+ "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_intrinsic_1=require("../../utils/regexp-intrinsic");const CONSTANT_PRESERVING_METHODS=new Set(["join","concat","toUpperCase","toLowerCase","trim","slice","repeat"]);function isStringRawTag(node,sourceCode){return node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="raw"&&node.object.type==="Identifier"&&node.object.name==="String"&&(0,regexp_intrinsic_1.isEnvironmentGlobal)(node.object.name,sourceCode.getScope(node.object))}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"TaggedTemplateExpression":return isStringRawTag(node.tag,sourceCode)&&node.quasi.expressions.every(expression=>isBuildTimeConstant(expression,sourceCode,depth+1));case"Identifier":return isConstantBinding(node,sourceCode,depth);case"TSAsExpression":case"TSTypeAssertion":return isBuildTimeConstant(node.expression,sourceCode,depth+1);case"ObjectExpression":return node.properties.every(property=>property.type==="Property"&&!property.computed&&isBuildTimeConstant(property.value,sourceCode,depth+1));case"MemberExpression":return isConstantTableLookup(node,sourceCode,depth);default:return false}}function isConstantTableLookup(node,sourceCode,depth){const value=resolveLookup(node,sourceCode,depth);return value!==null&&isBuildTimeConstant(value,sourceCode,depth+1)}function withoutTypeAnnotation(node){let current=node;while(current.type==="TSAsExpression"||current.type==="TSTypeAssertion"){current=current.expression}return current}function resolveLookup(node,sourceCode,depth){if(depth>6||node.computed||node.property.type!=="Identifier"){return null}const table=node.object.type==="Identifier"?constObjectBinding(node.object,sourceCode):node.object.type==="MemberExpression"?resolveLookup(node.object,sourceCode,depth+1):null;if(table===null){return null}const unwrapped=withoutTypeAnnotation(table);if(unwrapped.type!=="ObjectExpression"){return null}const name=node.property.name;const match=unwrapped.properties.find(property=>property.type==="Property"&&!property.computed&&property.key.type==="Identifier"&&property.key.name===name);return match!==void 0&&match.type==="Property"?match.value:null}function constObjectBinding(node,sourceCode){const variable=(0,regexp_intrinsic_1.resolveVariable)(node.name,sourceCode.getScope(node));if(variable===null||variable.defs.length!==1){return null}const definition=variable.defs[0];if(definition.type!=="Variable"||definition.parent.kind!=="const"||definition.node.init===null){return null}return isMutatedThroughAnyReference(variable)?null:definition.node.init}function isMutatedThroughAnyReference(variable){return variable.references.some(reference=>{let current=reference.identifier;let parent=current.parent;while(parent?.type==="MemberExpression"&&parent.object===current){current=parent;parent=parent.parent}if(current===reference.identifier){return false}return parent?.type==="AssignmentExpression"&&parent.left===current||parent?.type==="UpdateExpression"&&parent.argument===current||parent?.type==="UnaryExpression"&&parent.operator==="delete"&&parent.argument===current})}function isConstantBinding(node,sourceCode,depth){const variable=(0,regexp_intrinsic_1.resolveVariable)(node.name,sourceCode.getScope(node));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}const init=definition.node.init;if(init===null){const loop=definition.parent.parent;return loop?.type==="ForOfStatement"&&loop.left===definition.parent&&isBuildTimeConstant(loop.right,sourceCode,depth+1)}if(!isBuildTimeConstant(init,sourceCode,depth+1)){return false}return variable.references.every(reference=>{if(!reference.isWrite()){return true}const written=reference.writeExpr;if(!written){return false}return written===init||isBuildTimeConstant(written,sourceCode,depth+1)})}function isRegExpClone(node,sourceCode){const[patternArg]=node.arguments;if(patternArg?.type!=="MemberExpression"||patternArg.computed||patternArg.property.type!=="Identifier"||patternArg.property.name!=="source"){return false}const receiver=patternArg.object;if(receiver.type!=="Identifier"){return false}const variable=(0,regexp_intrinsic_1.resolveVariable)(receiver.name,sourceCode.getScope(receiver));const def=variable?.defs.length===1?variable.defs[0]:null;if(!def||def.type!=="Variable"||def.node.type!=="VariableDeclarator"){return false}const init=def.node.init;if(!init){return false}return init.type==="Literal"&&"regex"in init||(init.type==="NewExpression"||init.type==="CallExpression")&&(0,regexp_intrinsic_1.isRegExpConstructor)(init.callee,sourceCode)}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"},messages:{runtimeDecidedPattern:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.WARNING,issueName:"Regex pattern decided at runtime",cwe:"CWE-400",description:"Pattern decided at runtime, not visible here. Backtracking: no-redos-vulnerable-regex. Untrusted input: no-unsafe-regex-construction",severity:"{{riskLevel}}",fix:"{{safeAlternative}} \u2014 Not a finding when the pattern is a module constant, a closed-set lookup, or escaped before construction",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:true,description:"Allow literal string regex patterns \u2014 `new RegExp('^[a-z]+$')`. A rule named \"non-literal\" reporting a literal by default contradicted its own contract. Set false to prefer `/\u2026/` literal syntax; measured effect on the 30-fixture corpus: +6 findings, all on safe/ files."},maxPatternLength:{type:"number",default:100,minimum:1,description:"Maximum allowed pattern length for dynamic regex"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowLiterals:true,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 isNeutralised=patternNode2=>{const escaped=n=>{if(n.type!=="CallExpression")return false;const callee=n.callee;if(callee.type!=="MemberExpression"||callee.computed||callee.property.type!=="Identifier"||callee.property.name!=="replace"){return false}const search=n.arguments[0];if(search===void 0||search.type!=="Literal")return false;const re=search.regex;return re!==void 0&&/\[[^\]]*[.*+?^${}()|][^\]]*\]/.test(re.pattern)};if(escaped(patternNode2))return true;if(patternNode2.type==="Identifier"){const v=context.sourceCode.getScope(patternNode2).references.find(r=>r.identifier===patternNode2)?.resolved;if(v&&v.defs.length===1&&v.defs[0].type==="Variable"){if(v.references.filter(r=>r.isWrite()).length>1)return false;const init=v.defs[0].node.init;if(init&&escaped(init))return true;if(init?.type==="MemberExpression"&&init.computed){const obj=init.object;if(obj.type==="Identifier"){const ov=context.sourceCode.getScope(obj).references.find(r=>r.identifier===obj)?.resolved;const oinit=ov&&ov.defs.length===1&&ov.defs[0].type==="Variable"?ov.defs[0].node.init:void 0;if(oinit?.type==="ObjectExpression"||oinit?.type==="ArrayExpression"){return true}}}}}return false};const patternNode=node.arguments.length>0?node.arguments[0]:null;const pattern=patternNode?sourceCode.getText(patternNode):"";const isDynamic=patternNode?!(0,eslint_devkit_1.isStaticExpression)({node:patternNode,scope:context.sourceCode.getScope(patternNode)})&&!isNeutralised(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){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")}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")};const RISK_LEVEL="HIGH";const checkRegExpCall=node=>{if(isRegExpClone(node,context.sourceCode)){return}if(!(0,regexp_intrinsic_1.isRegExpConstructor)(node.callee,context.sourceCode)){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=RISK_LEVEL;const steps=generateRefactoringSteps(vulnerability);context.report({node,messageId:"runtimeDecidedPattern",data:{pattern:pattern.substring(0,30)+(pattern.length>30?"...":""),riskLevel,vulnerability:vulnerability.vulnerability,safeAlternative:vulnerability.safeAlternative,steps,effort:vulnerability.effort}})};return{CallExpression:node=>checkRegExpCall((0,regexp_intrinsic_1.asDirectConstruction)(node,context.sourceCode)),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 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 openCopyLoops=[];const armedLoops=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}if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.computed&&keyComesFromConstAllowlist(node.left.property,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 constObjectLiteralOf=(name,from)=>{for(let scope=sourceCode.getScope(from);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===name);if(!variable)continue;if(variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="Variable"||def.parent?.kind!=="const")return null;if(variable.references.some(ref=>ref.isWrite()&&ref.identifier!==def.name)){return null}const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression?init:null}return null};const isReadFromConstObjectLiteral=node=>node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&constObjectLiteralOf(node.object.name,node)!==null;const keyComesFromConstAllowlist=(property,from)=>{if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let scope=sourceCode.getScope(from);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===property.name);if(!variable)continue;if(variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable"||def.parent?.kind!=="const")return false;if(variable.references.some(ref=>ref.isWrite()&&ref.identifier!==def.name)){return false}const init=def.node.init;if(init?.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||!init.computed||init.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const source=constObjectLiteralOf(init.object.name,init);if(!source)return false;return source.properties.every(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&p.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof p.value.value==="string")}return false};const checkMemberExpression=node=>{if(!isHighRiskMemberAccess(node)){return}if(isReadFromConstObjectLiteral(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;`"}})};const checkPrototypePollutingCopyLoop=node=>{if(isInCodemodContext||isTestFile)return;const keyName=node.left.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration?node.left.declarations[0]?.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.left.declarations[0].id.name:void 0:node.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.left.name:void 0;if(!keyName)return;if(node.right.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const sourceName=node.right.name;let isParameter=false;for(let scope=context.sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===sourceName);if(!variable)continue;isParameter=variable.defs.some(def=>def.type==="Parameter");break}if(!isParameter)return;const bodyText=context.sourceCode.getTokens(node.body).map(token=>token.value).join("");if(/hasOwnProperty|hasOwn|__proto__|constructor|prototype|includes\(|allowlist|whitelist|Object\.keys/.test(bodyText)){return}armedLoops.add(node);openCopyLoops.push({keyName,reported:false})};const reportCopyLoopWrite=node=>{if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||!node.left.computed||node.left.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const propertyName=node.left.property.name;const loop=openCopyLoops.find(open=>open.keyName===propertyName&&!open.reported);if(!loop)return false;loop.reported=true;context.report({node,messageId:"objectInjection",data:{riskLevel:"HIGH",safeAlternative:'Guard the key before assigning: `if (k === "__proto__" || k === "constructor" || k === "prototype") continue;` \u2014 or copy with Object.create(null) / structuredClone.'}});return true};return{ForInStatement:checkPrototypePollutingCopyLoop,"ForInStatement:exit":node=>{if(armedLoops.has(node))openCopyLoops.pop()},AssignmentExpression:node=>{if(isInCodemodContext||isTestFile)return;if(reportCopyLoopWrite(node))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 resolve_reference_1=require("../../utils/resolve-reference");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",riskLevel:"critical"},{pattern:"prototype",dangerous:true,vulnerability:"prototype-pollution",safeAlternative:"Avoid prototype manipulation",riskLevel:"high"},{pattern:"constructor",dangerous:true,vulnerability:"method-injection",safeAlternative:"Validate property names against whitelist",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"},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}} \u2014 Not a finding when the key is a numeric index, a module constant, or guarded by Object.hasOwn / an allowlist",documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),massAssignment:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Mass assignment",cwe:"CWE-915",description:"Every key of an untrusted object is copied onto this target, so the caller chooses which field is written \u2014 including one they should not control, such as isAdmin",severity:"HIGH",fix:"Copy an explicit allowlist of assignable fields instead of the caller's keys \u2014 Not a finding when the iterated object is module-built, or the body checks each key against an allowlist",documentationLink:"https://cwe.mitre.org/data/definitions/915.html"}),globalPrototypeWrite:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Global prototype pollution",cwe:"CWE-1321",description:"Assignment writes THROUGH {{step}}, so the property lands on Object.prototype and every object in the process inherits it",severity:"CRITICAL",fix:"Guard with Object.hasOwn, or build the target with Object.create(null) / a Map \u2014 Not a finding when the path is fixed at build time, or __proto__ / constructor / prototype are rejected first",documentationLink:"https://portswigger.net/web-security/prototype-pollution"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:false,description:"Allow bracket notation with literal strings"},dangerousProperties:{type:"array",items:{type:"string"},default:["__proto__","prototype","constructor"],description:"Property NAMES treated as dangerous where the name is visible in the source \u2014 `obj['__proto__'] = v`. It cannot apply to a dynamic key (`obj[k] = v`), because there is no name to compare, and it does not gate the CWE-1321 traversal check, which is a fact about the language rather than a vocabulary. Set it to [] to stop reporting literal dangerous-property writes."}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowLiterals:false,dangerousProperties:["__proto__","prototype","constructor"]}],create(context){const options=context.options[0]||{};const{allowLiterals:_allowLiterals=false,dangerousProperties=["__proto__","prototype","constructor"]}=options;const handledMemberExpressions=new WeakSet;const openCopyLoops=[];const armedLoops=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 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=>{return 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};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=>{if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&testNode.operator==="!"){return hasValidation(testNode.argument)}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 NUMERIC_RENDERING_CHARS=/[0-9NI]/;const hasNumericOperandInConcatenation=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||node.operator!=="+"||dangerousProperties.some(name=>NUMERIC_RENDERING_CHARS.test(name))){return false}const anyNumericOperand=operand=>{if(operand.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&operand.operator==="+"){const chain=operand;return anyNumericOperand(chain.left)||anyNumericOperand(chain.right)}return isNumericKey(operand)};const bin=node;return anyNumericOperand(bin.left)||anyNumericOperand(bin.right)};const hasVisibleNonConstantInitialiser=node=>{const scope=sourceCode.getScope(node);const variable=(0,resolve_reference_1.resolvedReference)(scope,node);if(!variable||variable.defs.length!==1){return false}const def=variable.defs[0];if(def.type!=="Variable"){return false}const init=def.node.init;if(!init){return false}return!(0,eslint_devkit_2.isStaticExpression)({node:init,scope:sourceCode.getScope(init)})};const chainRoot=node=>{let cur=node;while(cur.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression)cur=cur.object;return cur.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?cur:null};const isLocallyConstructed=id=>{const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(id),id);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const init=def.node.init;if(!init)return false;return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_2.isStaticExpression)({node:init,scope:sourceCode.getScope(init)})};const REQUEST_ROOTS=new Set(["req","request","ctx","context","event"]);const isUntrustedExpression=node=>{const root=chainRoot(node);if(root===null)return false;if(!REQUEST_ROOTS.has(root.name))return false;return!isLocallyConstructed(root)};const isSymbolKey=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="Symbol"){return true}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(node),node);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const init=def.node.init;if(init?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=init.callee;return callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.name==="Symbol"||callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Symbol"};const isImportedBinding=node=>{const root=chainRoot(node);if(root===null)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(root),root);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type==="ImportBinding"){return true}if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="require"};const isDangerousPropertyAccess=propertyNode=>{if(isSymbolKey(propertyNode))return false;if(isImportedBinding(propertyNode))return false;{const root=chainRoot(propertyNode);if(root!==null&&isLocallyConstructed(root))return false}if(isNumericKey(propertyNode)||hasDisqualifyingLiteralAffix(propertyNode)||hasNumericOperandInConcatenation(propertyNode)){return false}if(propertyNode.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!hasVisibleNonConstantInitialiser(propertyNode)){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 stepName=m=>{if(!m.computed&&m.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return m.property.name;if(m.computed&&m.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof m.property.value==="string"){return m.property.value}return null};const globalPrototypeWrite=node=>{if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const steps=[];let cur=node.left.object;while(cur.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const name=stepName(cur);if(name===null)return null;steps.unshift(name);cur=cur.object}if(steps.includes("__proto__"))return"__proto__";for(let i=0;i<steps.length-1;i++){if(steps[i]==="constructor"&&steps[i+1]==="prototype")return"constructor.prototype"}return null};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=(0,resolve_reference_1.resolvedReference)(scope,node);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=(0,resolve_reference_1.resolvedReference)(scope,node);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 ELEMENT_FIRST_ITERATORS=new Set(["forEach","map","filter","find","findLast","some","every","flatMap"]);const isObjectKeysCallbackKey=(fn,name)=>{if(fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return false}const first=fn.params[0];const bindsName=first?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&first.name===name||first?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&first.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&first.elements[0].name===name;if(!bindsName)return false;const call=fn.parent;if(call?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||call.arguments[0]!==fn||call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||call.callee.computed||call.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!ELEMENT_FIRST_ITERATORS.has(call.callee.property.name)){return false}const source=call.callee.object;return source.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&source.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!source.callee.computed&&source.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&source.callee.object.name==="Object"&&source.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(source.callee.property.name==="keys"||source.callee.property.name==="entries")};const isForInOrObjectKeysKey=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const scope=context.sourceCode.getScope(node);const variable=(0,resolve_reference_1.resolvedReference)(scope,node);if(!variable||variable.defs.length===0)return false;const def=variable.defs[0];if(def.type==="Parameter"){return isObjectKeysCallbackKey(def.node,node.name)}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.set.get(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=>{const step=globalPrototypeWrite(node);if(step!==null){for(let m=node.left;m.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression;m=m.object){handledMemberExpressions.add(m)}context.report({node,messageId:"globalPrototypeWrite",data:{step}});return}if(!isHighRiskAssignment(node)){return}if(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.left.computed&&keyComesFromConstAllowlist(node.left.property,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"}})};const constObjectLiteralOf=(name,from)=>{for(let scope=sourceCode.getScope(from);scope;scope=scope.upper){const variable=scope.set.get(name);if(!variable)continue;if(variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="Variable"||def.parent?.kind!=="const")return null;if(variable.references.some(ref=>ref.isWrite()&&ref.identifier!==def.name)){return null}const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression?init:null}return null};const isReadFromConstObjectLiteral=node=>node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&constObjectLiteralOf(node.object.name,node)!==null;const keyComesFromConstAllowlist=(property,from)=>{if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let scope=sourceCode.getScope(from);scope;scope=scope.upper){const variable=scope.set.get(property.name);if(!variable)continue;if(variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable"||def.parent?.kind!=="const")return false;if(variable.references.some(ref=>ref.isWrite()&&ref.identifier!==def.name)){return false}const init=def.node.init;if(init?.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||!init.computed||init.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const source=constObjectLiteralOf(init.object.name,init);if(!source)return false;return source.properties.every(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&p.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof p.value.value==="string")}return false};const isInvokedRead=node=>{const parent=node.parent;if(parent===void 0)return false;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee===node){return true}if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator||parent.init!==node||parent.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const variable=context.sourceCode.getDeclaredVariables(parent).find(candidate=>candidate.name===parent.id.name);return variable?.references.some(reference=>{const referenceParent=reference.identifier.parent;return referenceParent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&referenceParent.callee===reference.identifier})??false};const isWriteTarget=node=>{let current=node;let parent=current.parent;while(parent!==void 0){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.left===current){return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.UpdateExpression&&parent.argument===current){return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&parent.operator==="delete"){return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}return false}return false};const checkMemberExpression=node=>{if(!isWriteTarget(node)&&!isInvokedRead(node)){return}if(!isHighRiskMemberAccess(node)){return}if(isReadFromConstObjectLiteral(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;`"}})};const checkMassAssignmentLoop=node=>{if(isInCodemodContext)return;const iterated=node.right;if(iterated.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return;const callee=iterated.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed||callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||callee.object.name!=="Object"||callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!["keys","entries"].includes(callee.property.name)){return}const source=iterated.arguments[0];if(source===void 0||!isUntrustedExpression(source))return;if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration)return;const bound=node.left.declarations[0]?.id;const keyName=bound?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?bound.name:bound?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&bound.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?bound.elements[0].name:null;if(keyName===null)return;const body=sourceCode.getText(node.body);if(/\b(includes|has|hasOwn|hasOwnProperty|indexOf)\s*\(/.test(body))return;let reported=false;const walk=n=>{if(reported)return;if(n.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&n.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&n.left.computed&&n.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&n.left.property.name===keyName){reported=true;context.report({node:n,messageId:"massAssignment",data:{key:keyName}});return}for(const key of Object.keys(n)){const child=n[key];if(key==="parent"||child===null||typeof child!=="object")continue;for(const c of Array.isArray(child)?child:[child]){if(c&&typeof c.type==="string")walk(c)}}};walk(node.body)};const isCopyLoopSourceOpaque=source=>{if(isUntrustedExpression(source))return true;if(source.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(source),source);if(!variable)return false;if(variable.defs.some(def2=>def2.type==="Parameter"))return true;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const def=variable.defs[0];if(!def||def.type!=="Variable")return false;const init=def.node.init;return init?isUntrustedExpression(init):false};const checkPrototypePollutingCopyLoop=node=>{if(isInCodemodContext)return;const keyName=node.left.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration?node.left.declarations[0]?.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.left.declarations[0].id.name:void 0:node.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.left.name:void 0;if(!keyName)return;if(!isCopyLoopSourceOpaque(node.right))return;const bodyText=context.sourceCode.getTokens(node.body).map(token=>token.value).join("");if(/hasOwnProperty|hasOwn|__proto__|constructor|prototype|includes\(|allowlist|whitelist|Object\.keys/.test(bodyText)){return}armedLoops.add(node);openCopyLoops.push({keyName,reported:false})};const reportCopyLoopWrite=node=>{if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||!node.left.computed||node.left.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const propertyName=node.left.property.name;const loop=openCopyLoops.find(open=>open.keyName===propertyName&&!open.reported);if(!loop)return false;loop.reported=true;context.report({node,messageId:"objectInjection",data:{riskLevel:"HIGH",safeAlternative:'Guard the key before assigning: `if (k === "__proto__" || k === "constructor" || k === "prototype") continue;` \u2014 or copy with Object.create(null) / structuredClone.'}});return true};return{ForOfStatement:checkMassAssignmentLoop,ForInStatement:checkPrototypePollutingCopyLoop,"ForInStatement:exit":node=>{if(armedLoops.has(node))openCopyLoops.pop()},AssignmentExpression:node=>{if(isInCodemodContext)return;if(reportCopyLoopWrite(node))return;return checkAssignmentExpression(node)},MemberExpression:node=>{if(isInCodemodContext)return;return checkMemberExpression(node)},CallExpression:node=>{if(isInCodemodContext)return;return checkObjectAssignSpread(node)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectWeakPasswordValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.detectWeakPasswordValidation=(0,eslint_devkit_1.createRule)({name:"detect-weak-password-validation",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/detect-weak-password-validation.md",description:"Identify weak password requirements",cwe:"CWE-521",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak Password Validation",cwe:"CWE-521",description:"Password length requirement is too weak (less than 8 characters)",severity:"CRITICAL",fix:"Require at least 12 characters with complexity requirements",documentationLink:"https://cwe.mitre.org/data/definitions/521.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}return{BinaryExpression(node){if([">=",">","==","==="].includes(node.operator)){if(node.left.type==="MemberExpression"&&node.left.property.type==="Identifier"&&node.left.property.name==="length"){if(node.right.type==="Literal"&&typeof node.right.value==="number"&&node.right.value<8){if(node.left.object.type==="Identifier"){const varName=node.left.object.name.toLowerCase();if(varName.includes("password")||varName.includes("pwd")||varName.includes("pass")){report(node)}}}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectWeakPasswordValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NIST_MINIMUM_LENGTH=8;const SMALLEST_MEANINGFUL_MINIMUM=2;const PASSWORD_WORDS=["password","passphrase","passwd","pwd","pass"];function enforcedMinimum(operator,threshold){switch(operator){case">=":case"<":case"===":case"==":return threshold;case">":case"<=":return threshold+1;default:return null}}function resolveThreshold(node,sourceCode){if(node.type==="Literal"&&typeof node.value==="number"){return node.value}if(node.type!=="Identifier"){return null}for(let scope=sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(candidate=>candidate.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const definition=variable.defs[0];if(definition.type!=="Variable"||definition.parent.kind!=="const")return null;const init=definition.node.init;return init?.type==="Literal"&&typeof init.value==="number"?init.value:null}return null}function measuresPasswordLength(node){const access=node.type==="ChainExpression"?node.expression:node;if(access.type!=="MemberExpression"||access.computed||access.property.type!=="Identifier"||access.property.name!=="length"){return false}return namesPassword(access.object)}function namesPassword(node,depth=0){if(depth>4){return false}if(node.type==="Identifier"){return(0,eslint_devkit_1.nameHasAnyWord)(node.name,PASSWORD_WORDS)}if(node.type==="ChainExpression"){return namesPassword(node.expression,depth+1)}if(node.type==="CallExpression"){return node.callee.type==="MemberExpression"&&!node.callee.computed&&namesPassword(node.callee.object,depth+1)}if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"){return(0,eslint_devkit_1.nameHasAnyWord)(node.property.name,PASSWORD_WORDS)}return false}exports.detectWeakPasswordValidation=(0,eslint_devkit_1.createRule)({name:"detect-weak-password-validation",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/detect-weak-password-validation.md",description:"Identify weak password requirements",cwe:"CWE-521",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak Password Validation",cwe:"CWE-521",description:"Password length requirement is too weak (less than 8 characters)",severity:"CRITICAL",fix:"Require at least 12 characters with complexity requirements",documentationLink:"https://cwe.mitre.org/data/definitions/521.html"})},schema:[]},defaultOptions:[],create(context){return{BinaryExpression(node){if(!measuresPasswordLength(node.left)){return}const threshold=resolveThreshold(node.right,context.sourceCode);if(threshold===null){return}const minimum=enforcedMinimum(node.operator,threshold);if(minimum===null){return}if(minimum<SMALLEST_MEANINGFUL_MINIMUM||minimum>=NIST_MINIMUM_LENGTH){return}context.report({node,messageId:"violationDetected"})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noBidiCharacters=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const BIDI_CHARACTERS=new Map([["\u202A","U+202A LEFT-TO-RIGHT EMBEDDING"],["\u202B","U+202B RIGHT-TO-LEFT EMBEDDING"],["\u202C","U+202C POP DIRECTIONAL FORMATTING"],["\u202D","U+202D LEFT-TO-RIGHT OVERRIDE"],["\u202E","U+202E RIGHT-TO-LEFT OVERRIDE"],["\u2066","U+2066 LEFT-TO-RIGHT ISOLATE"],["\u2067","U+2067 RIGHT-TO-LEFT ISOLATE"],["\u2068","U+2068 FIRST STRONG ISOLATE"],["\u2069","U+2069 POP DIRECTIONAL ISOLATE"]]);const DIRECTIONAL_MARKS=new Map([["\u200E","U+200E LEFT-TO-RIGHT MARK"],["\u200F","U+200F RIGHT-TO-LEFT MARK"]]);const codePointFromLabel=label=>{const match=/^U\+([0-9a-fA-F]{4,6})$/.exec(label.trim());if(!match)return void 0;const codePoint=Number.parseInt(match[1],16);if(codePoint>1114111)return void 0;return String.fromCodePoint(codePoint)};exports.noBidiCharacters=(0,eslint_devkit_1.createRule)({name:"no-bidi-characters",meta:{type:"problem",docs:{url:"https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-bidi-characters",description:"Disallows Unicode bidirectional control characters, which let source render differently than it compiles (Trojan Source, CWE-1007)",cwe:"CWE-1007",cvss:8.8},hasSuggestions:true,messages:{bidiCharacter:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Bidirectional control character \u2014 Trojan Source (CWE-1007)",cwe:"CWE-1007",description:"{{characterName}} found in source. Bidi controls change how code is DISPLAYED without changing how it is COMPILED, so a reviewer can approve one program while the compiler builds another.",severity:"HIGH",fix:"Remove the character. If the string genuinely needs bidirectional text, use the escape sequence (\\u202E) so it is visible in review.",documentationLink:"https://trojansource.codes/"}),removeBidiCharacter:"Remove {{characterName}}"},schema:[{type:"object",properties:{additionalCharacters:{type:"array",items:{type:"string"}},allowDirectionalMarks:{type:"boolean",default:false}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options={}]){const{additionalCharacters=[],allowDirectionalMarks=false}=options;const dangerous=new Map(BIDI_CHARACTERS);if(!allowDirectionalMarks){for(const[char,name]of DIRECTIONAL_MARKS)dangerous.set(char,name)}for(const label of additionalCharacters){const char=codePointFromLabel(label);if(char)dangerous.set(char,label.trim())}return{Program(node){const{sourceCode}=context;const text=sourceCode.getText();for(let index=0;index<text.length;){const codePoint=text.codePointAt(index);const width=codePoint>65535?2:1;const characterName=dangerous.get(text.slice(index,index+width));if(!characterName){index+=width;continue}const range=[index,index+width];context.report({node,loc:{start:sourceCode.getLocFromIndex(index),end:sourceCode.getLocFromIndex(index+width)},messageId:"bidiCharacter",data:{characterName},suggest:[{messageId:"removeBidiCharacter",data:{characterName},fix:fixer=>fixer.removeRange(range)}]});index+=width}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noBidiCharacters=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const BIDI_CHARACTERS=new Map([["\u202A","U+202A LEFT-TO-RIGHT EMBEDDING"],["\u202B","U+202B RIGHT-TO-LEFT EMBEDDING"],["\u202C","U+202C POP DIRECTIONAL FORMATTING"],["\u202D","U+202D LEFT-TO-RIGHT OVERRIDE"],["\u202E","U+202E RIGHT-TO-LEFT OVERRIDE"],["\u2066","U+2066 LEFT-TO-RIGHT ISOLATE"],["\u2067","U+2067 RIGHT-TO-LEFT ISOLATE"],["\u2068","U+2068 FIRST STRONG ISOLATE"],["\u2069","U+2069 POP DIRECTIONAL ISOLATE"]]);const DIRECTIONAL_MARKS=new Map([["\u200E","U+200E LEFT-TO-RIGHT MARK"],["\u200F","U+200F RIGHT-TO-LEFT MARK"]]);const codePointFromLabel=label=>{const match=/^U\+([0-9a-fA-F]{4,6})$/.exec(label.trim());if(!match)return void 0;const codePoint=Number.parseInt(match[1],16);if(codePoint>1114111)return void 0;return String.fromCodePoint(codePoint)};exports.noBidiCharacters=(0,eslint_devkit_1.createRule)({name:"no-bidi-characters",meta:{type:"problem",docs:{url:"https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-bidi-characters",description:"Disallows Unicode bidirectional control characters, which let source render differently than it compiles (Trojan Source, CWE-1007)",cwe:"CWE-1007",cvss:5.3},hasSuggestions:true,messages:{bidiCharacter:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Bidirectional control character \u2014 Trojan Source (CWE-1007)",cwe:"CWE-1007",description:"{{characterName}} found in source. Bidi controls change how code is DISPLAYED without changing how it is COMPILED, so a reviewer can approve one program while the compiler builds another.",severity:"HIGH",fix:"Remove the character. If the string genuinely needs bidirectional text, use the escape sequence (\\u202E) so it is visible in review.",documentationLink:"https://trojansource.codes/"}),removeBidiCharacter:"Remove {{characterName}}"},schema:[{type:"object",properties:{additionalCharacters:{type:"array",items:{type:"string"},default:[]},allowDirectionalMarks:{type:"boolean",default:false}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options={}]){const{additionalCharacters=[],allowDirectionalMarks=false}=options;const dangerous=new Map(BIDI_CHARACTERS);if(!allowDirectionalMarks){for(const[char,name]of DIRECTIONAL_MARKS)dangerous.set(char,name)}for(const label of additionalCharacters){const char=codePointFromLabel(label);if(char)dangerous.set(char,label.trim())}return{Program(node){const{sourceCode}=context;const text=sourceCode.getText();for(let index=0;index<text.length;){const codePoint=text.codePointAt(index);const width=codePoint>65535?2:1;const characterName=dangerous.get(text.slice(index,index+width));if(!characterName){index+=width;continue}const range=[index,index+width];context.report({node,loc:{start:sourceCode.getLocFromIndex(index),end:sourceCode.getLocFromIndex(index+width)},messageId:"bidiCharacter",data:{characterName},suggest:[{messageId:"removeBidiCharacter",data:{characterName},fix:fixer=>fixer.removeRange(range)}]});index+=width}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDirectiveInjection=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 DANGEROUS_TAGS=new Set(["script","iframe","object","embed","base"]);const DANGEROUS_ATTRS=new Set(["srcdoc","formaction","xlink:href"]);const TAG_OPTIONS=new Set(["ADD_TAGS","ALLOWED_TAGS"]);const ATTR_OPTIONS=new Set(["ADD_ATTR","ALLOWED_ATTR"]);function staticStringArray(node){if(node.type!=="ArrayExpression")return null;const out=[];for(const element of node.elements){if(element?.type==="Literal"&&typeof element.value==="string"){out.push(element.value)}}return out}function findUnsafeSanitizerConfig(node){const callee=node.callee;if(callee.type!=="MemberExpression")return null;if(callee.property.type!=="Identifier"||callee.property.name!=="sanitize")return null;if(callee.object.type!=="Identifier")return null;if(!callee.object.name.toLowerCase().includes("purify"))return null;const config=node.arguments[1];if(!config||config.type!=="ObjectExpression")return null;for(const property of config.properties){if(property.type!=="Property")continue;if(property.computed)continue;const option=property.key.type==="Identifier"?property.key.name:property.key.type==="Literal"&&typeof property.key.value==="string"?property.key.value:null;if(option===null)continue;if(property.shorthand)continue;const values=staticStringArray(property.value);if(!values)continue;if(TAG_OPTIONS.has(option)){const bad=values.find(v=>DANGEROUS_TAGS.has(v.toLowerCase()));if(bad)return{node:property,option,allowed:`<${bad}>`}}if(ATTR_OPTIONS.has(option)){const bad=values.find(v=>v.toLowerCase().startsWith("on")||DANGEROUS_ATTRS.has(v.toLowerCase()));if(bad)return{node:property,option,allowed:`the "${bad}" attribute`}}}return null}exports.noDirectiveInjection=(0,eslint_devkit_1.createRule)({name:"no-directive-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-directive-injection.md",description:"Detects directive injection vulnerabilities in templates",cwe:"CWE-96"},messages:{directiveInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Directive Injection",cwe:"CWE-96",description:"User input injected into directive or template",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeDirectiveName:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Directive Name",cwe:"CWE-96",description:"Directive name controlled by user input",severity:"CRITICAL",fix:"Use hardcoded directive names or validate against whitelist",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dynamicDirectiveCreation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dynamic Directive Creation",cwe:"CWE-96",description:"Dynamic creation of directives from user input",severity:"HIGH",fix:"Validate directive names against trusted list",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),templateInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Template Injection",cwe:"CWE-96",description:"User input injected into template content",severity:"HIGH",fix:"Sanitize template input or use safe rendering",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeComponentBinding:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Component Binding",cwe:"CWE-96",description:"Dynamic component binding with user input",severity:"HIGH",fix:"Use component whitelist or validate component names",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),userControlledTemplate:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Template",cwe:"CWE-96",description:"Template content controlled by user input",severity:"CRITICAL",fix:"Sanitize template input before compilation",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dangerousInnerHTML:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous innerHTML",cwe:"CWE-96",description:"innerHTML set with user-controlled content",severity:"HIGH",fix:"Use textContent or sanitize HTML content",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML"}),untrustedDirectiveSource:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Untrusted Directive Source",cwe:"CWE-96",description:"Directive loaded from untrusted source",severity:"MEDIUM",fix:"Load directives from trusted, verified sources",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),useTrustedDirectives:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Trusted Directives",description:"Use only trusted, verified directives",severity:"LOW",fix:"Maintain whitelist of allowed directives",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeSanitizerConfig:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Sanitizer configured to allow {{allowed}}",cwe:"CWE-96",description:"DOMPurify was configured with {{option}} re-enabling {{allowed}}, which is exactly what the sanitizer removes by default. The call returns markup that can execute script, so the sanitization provides no protection.",severity:"HIGH",fix:"Drop {{allowed}} from {{option}}. If the markup genuinely needs it, render it outside the sanitized region rather than widening the allow-list.",documentationLink:"https://github.com/cure53/DOMPurify#can-i-configure-dompurify"}),sanitizeTemplateInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Sanitize Template Input",description:"Sanitize user input before template processing",severity:"LOW",fix:"Use DOMPurify or equivalent sanitization",documentationLink:"https://github.com/cure53/DOMPurify"}),validateDirectiveNames:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate Directive Names",description:"Validate directive names against whitelist",severity:"LOW",fix:"Check directive names before dynamic creation",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),strategyTemplateSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Template Sanitization Strategy",description:"Implement template input sanitization",severity:"LOW",fix:"Sanitize all user input before template processing",documentationLink:"https://owasp.org/www-community/xss-filter-evasion-cheatsheet"}),strategyContentSecurity:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Content Security Strategy",description:"Use CSP to restrict directive execution",severity:"LOW",fix:"Implement strict CSP with script-src restrictions",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate all template inputs",severity:"LOW",fix:"Use schema validation for template inputs",documentationLink:"https://joi.dev/"})},schema:[{type:"object",properties:{trustedDirectives:{type:"array",items:{type:"string"},default:["ngIf","ngFor","ngClass","v-if","v-for","v-bind","v-on"],description:"Template directives treated as safe"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},frameworks:{type:"array",items:{type:"string"},default:["angular","vue","react","svelte"],description:"Template frameworks to analyse"},allowDynamicInComponents:{type:"boolean",default:false,description:"Allow dynamic directives inside component code"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as template 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:[{trustedDirectives:["ngIf","ngFor","ngClass","v-if","v-for","v-bind","v-on"],userInputVariables:["req","request","body","query","params","input","data","userInput"],frameworks:["angular","vue","react","svelte"],allowDynamicInComponents:false,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{userInputVariables=["req","request","body","query","params","input","data","userInput"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isUserInput=varName=>{return userInputVariables.some(input=>varName.includes(input))||varName.startsWith("user")};return{JSXAttribute(node){const attrName=node.name;const attrValue=node.value;if(attrName.type==="JSXIdentifier"&&attrName.name==="dangerouslySetInnerHTML"){if(attrValue&&attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;const expressionText=sourceCode.getText(expression);if(userInputVariables.some(input=>expressionText.includes(input))){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}const isNamespaceDirective=attrName.type==="JSXNamespacedName"&&(attrName.namespace.name==="v"||attrName.namespace.name==="ng")||attrName.type==="JSXIdentifier"&&(attrName.name.startsWith("ng:")||attrName.name.startsWith("v:"));if(isNamespaceDirective&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(expression.type==="Identifier"&&isUserInput(expression.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"directiveInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded directive values or validate user input"}})}}}if(attrName.type==="JSXIdentifier"){const attrNameStr=attrName.name;if(attrNameStr==="is"&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(expression.type==="Identifier"&&isUserInput(expression.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"unsafeComponentBinding",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},AssignmentExpression(node){const left=node.left;const right=node.right;if(left.type==="MemberExpression"&&left.property.type==="Identifier"&&left.property.name==="innerHTML"){const isSanitizedValue=right.type==="CallExpression"&&right.callee.type==="MemberExpression"&&right.callee.property.type==="Identifier"&&right.callee.property.name==="sanitize"&&findUnsafeSanitizerConfig(right)===null;if(isSanitizedValue){return}const rightText=sourceCode.getText(right);if(userInputVariables.some(input=>rightText.includes(input))){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;const unsafeConfig=findUnsafeSanitizerConfig(node);if(unsafeConfig){context.report({node:unsafeConfig.node,messageId:"unsafeSanitizerConfig",data:{option:unsafeConfig.option,allowed:unsafeConfig.allowed}})}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const methodName=callee.property.name;const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(["compile","template","$compile","$interpolate"].includes(methodName)||objectName==="Handlebars"&&methodName==="compile"||objectName==="_"&&methodName==="template"||objectName==="ejs"&&methodName==="render"||objectName==="pug"&&methodName==="render"||objectName==="mustache"&&methodName==="render"){const args=node.arguments;if(args.length>0){const templateArg=args[0];if(templateArg.type==="Identifier"&&isUserInput(templateArg.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:templateArg,messageId:"userControlledTemplate",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}if(objectName==="Vue"&&methodName==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(directiveName.type==="Identifier"&&isUserInput(directiveName.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"unsafeDirectiveName",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}if(callee.type==="Identifier"&&callee.name==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(directiveName.type==="Identifier"&&isUserInput(directiveName.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"dynamicDirectiveCreation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},TemplateLiteral(node){let current=node;let isInDangerousContext=false;while(current){if(current.type==="JSXExpressionContainer"){if(current.parent?.type==="JSXAttribute"&&current.parent.name.type==="JSXIdentifier"&&current.parent.name.name==="dangerouslySetInnerHTML"){isInDangerousContext=true;break}}else if(current.type==="AssignmentExpression"){const left=current.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"&&left.property.name==="innerHTML"){isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext){const hasUserInput=node.expressions.some(expr=>expr.type==="Identifier"&&isUserInput(expr.name)||expr.type==="MemberExpression"&&expr.object.type==="Identifier"&&isUserInput(expr.object.name));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"templateInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Sanitize template input before insertion"}})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDirectiveInjection=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 DANGEROUS_TAGS=new Set(["script","iframe","object","embed","base"]);const DANGEROUS_ATTRS=new Set(["srcdoc","formaction","xlink:href"]);const TAG_OPTIONS=new Set(["ADD_TAGS","ALLOWED_TAGS"]);const ATTR_OPTIONS=new Set(["ADD_ATTR","ALLOWED_ATTR"]);function staticStringArray(node){if(node.type!=="ArrayExpression")return null;const out=[];for(const element of node.elements){if(element?.type==="Literal"&&typeof element.value==="string"){out.push(element.value)}}return out}function findUnsafeSanitizerConfig(node){const callee=node.callee;if(callee.type!=="MemberExpression")return null;if(callee.property.type!=="Identifier"||callee.property.name!=="sanitize")return null;if(callee.object.type!=="Identifier")return null;if(!callee.object.name.toLowerCase().includes("purify"))return null;const config=node.arguments[1];if(!config||config.type!=="ObjectExpression")return null;for(const property of config.properties){if(property.type!=="Property")continue;if(property.computed)continue;const option=property.key.type==="Identifier"?property.key.name:property.key.type==="Literal"&&typeof property.key.value==="string"?property.key.value:null;if(option===null)continue;if(property.shorthand)continue;const values=staticStringArray(property.value);if(!values)continue;if(TAG_OPTIONS.has(option)){const bad=values.find(v=>DANGEROUS_TAGS.has(v.toLowerCase()));if(bad)return{node:property,option,allowed:`<${bad}>`}}if(ATTR_OPTIONS.has(option)){const bad=values.find(v=>v.toLowerCase().startsWith("on")||DANGEROUS_ATTRS.has(v.toLowerCase()));if(bad)return{node:property,option,allowed:`the "${bad}" attribute`}}}return null}exports.noDirectiveInjection=(0,eslint_devkit_1.createRule)({name:"no-directive-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-directive-injection.md",description:"Detects directive injection vulnerabilities in templates",cwe:"CWE-96"},messages:{directiveInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Directive Injection",cwe:"CWE-96",description:"User input injected into directive or template",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeDirectiveName:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Directive Name",cwe:"CWE-96",description:"Directive name controlled by user input",severity:"CRITICAL",fix:"Use hardcoded directive names or validate against whitelist",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dynamicDirectiveCreation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dynamic Directive Creation",cwe:"CWE-96",description:"Dynamic creation of directives from user input",severity:"HIGH",fix:"Validate directive names against trusted list",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),templateInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Template Injection",cwe:"CWE-96",description:"User input injected into template content",severity:"HIGH",fix:"Sanitize template input or use safe rendering",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeComponentBinding:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Component Binding",cwe:"CWE-96",description:"Dynamic component binding with user input",severity:"HIGH",fix:"Use component whitelist or validate component names",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),userControlledTemplate:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Template",cwe:"CWE-96",description:"Template content controlled by user input",severity:"CRITICAL",fix:"Sanitize template input before compilation",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dangerousInnerHTML:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous innerHTML",cwe:"CWE-96",description:"innerHTML set with user-controlled content",severity:"HIGH",fix:"Use textContent or sanitize HTML content",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML"}),unsafeSanitizerConfig:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Sanitizer configured to allow {{allowed}}",cwe:"CWE-96",description:"DOMPurify was configured with {{option}} re-enabling {{allowed}}, which is exactly what the sanitizer removes by default. The call returns markup that can execute script, so the sanitization provides no protection.",severity:"HIGH",fix:"Drop {{allowed}} from {{option}}. If the markup genuinely needs it, render it outside the sanitized region rather than widening the allow-list.",documentationLink:"https://github.com/cure53/DOMPurify#can-i-configure-dompurify"})},schema:[{type:"object",properties:{userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as template 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:[{userInputVariables:["req","request","body","query","params","input","data","userInput"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{userInputVariables=["req","request","body","query","params","input","data","userInput"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const declaredUserInput=new Set(userInputVariables.map(name=>name.toLowerCase()));const namesUserInput=varName=>declaredUserInput.has(varName.toLowerCase());const memberChainNames=node=>{const names=[];let current=node;while(current.type==="MemberExpression"){if(!current.computed&&current.property.type==="Identifier"){names.push(current.property.name)}current=current.object}if(current.type==="Identifier")names.push(current.name);return names};const resolvesToUserInput=(node,seen)=>{if(seen.has(node.name))return false;seen.add(node.name);let scope=sourceCode.getScope(node);while(scope){const variable=scope.variables.find(v=>v.name===node.name);if(variable){return variable.references.some(reference=>reference.writeExpr!==void 0&&reference.writeExpr!==null&&isUserInputExpression(reference.writeExpr,seen))}scope=scope.upper}return false};const isUnattributedParameter=raw=>{const node=(0,eslint_devkit_1.unwrapTypeSyntax)(raw);if(node.type!=="Identifier")return false;let scope=sourceCode.getScope(node);while(scope){const variable=scope.variables.find(v=>v.name===node.name);if(variable){return variable.defs.some(def=>def.type==="Parameter")}scope=scope.upper}return false};function isUserInputExpression(raw,seen=new Set){const node=(0,eslint_devkit_1.unwrapTypeSyntax)(raw);switch(node.type){case"Identifier":return namesUserInput(node.name)||resolvesToUserInput(node,seen);case"MemberExpression":return memberChainNames(node).some(namesUserInput);case"TemplateLiteral":return node.expressions.some(expr=>isUserInputExpression(expr,seen));case"BinaryExpression":return isUserInputExpression(node.left,seen)||isUserInputExpression(node.right,seen);case"ConditionalExpression":return isUserInputExpression(node.consequent,seen)||isUserInputExpression(node.alternate,seen);case"LogicalExpression":return isUserInputExpression(node.left,seen)||isUserInputExpression(node.right,seen);case"ObjectExpression":return node.properties.some(property=>property.type==="Property"&&isUserInputExpression(property.value,seen));default:return false}}return{JSXAttribute(node){const attrName=node.name;const attrValue=node.value;if(attrName.type==="JSXIdentifier"&&attrName.name==="dangerouslySetInnerHTML"){if(attrValue&&attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(isUserInputExpression(expression)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}const isNamespaceDirective=attrName.type==="JSXNamespacedName"&&(attrName.namespace.name==="v"||attrName.namespace.name==="ng")||attrName.type==="JSXIdentifier"&&(attrName.name.startsWith("ng:")||attrName.name.startsWith("v:"));if(isNamespaceDirective&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(isUserInputExpression(expression)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"directiveInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded directive values or validate user input"}})}}}if(attrName.type==="JSXIdentifier"){const attrNameStr=attrName.name;if(attrNameStr==="is"&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(isUserInputExpression(expression)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"unsafeComponentBinding",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},AssignmentExpression(node){const left=node.left;const right=node.right;if(left.type==="MemberExpression"&&left.property.type==="Identifier"&&left.property.name==="innerHTML"){const isSanitizedValue=right.type==="CallExpression"&&right.callee.type==="MemberExpression"&&right.callee.property.type==="Identifier"&&right.callee.property.name==="sanitize"&&findUnsafeSanitizerConfig(right)===null;if(isSanitizedValue){return}if(isUserInputExpression(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;const unsafeConfig=findUnsafeSanitizerConfig(node);if(unsafeConfig){context.report({node:unsafeConfig.node,messageId:"unsafeSanitizerConfig",data:{option:unsafeConfig.option,allowed:unsafeConfig.allowed}})}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const methodName=callee.property.name;const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(["compile","template","$compile","$interpolate"].includes(methodName)||objectName==="Handlebars"&&methodName==="compile"||objectName==="_"&&methodName==="template"||objectName==="ejs"&&methodName==="render"||objectName==="pug"&&methodName==="render"||objectName==="mustache"&&methodName==="render"){const args=node.arguments;if(args.length>0){const templateArg=args[0];if(isUserInputExpression(templateArg)||isUnattributedParameter(templateArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:templateArg,messageId:"userControlledTemplate",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}if(objectName==="Vue"&&methodName==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(isUserInputExpression(directiveName)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"unsafeDirectiveName",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}if(callee.type==="Identifier"&&callee.name==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(isUserInputExpression(directiveName)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"dynamicDirectiveCreation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},TemplateLiteral(node){let current=node;let isInDangerousContext=false;while(current){if(current.type==="JSXExpressionContainer"){if(current.parent?.type==="JSXAttribute"&&current.parent.name.type==="JSXIdentifier"&&current.parent.name.name==="dangerouslySetInnerHTML"){if(current.expression&&isUserInputExpression(current.expression))return;isInDangerousContext=true;break}}else if(current.type==="AssignmentExpression"){const left=current.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"&&left.property.name==="innerHTML"){if(current.right&&isUserInputExpression(current.right))return;isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext){const hasUserInput=node.expressions.some(expr=>isUserInputExpression(expr));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"templateInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Sanitize template input before insertion"}})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noElectronSecurityIssues=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.noElectronSecurityIssues=(0,eslint_devkit_1.createRule)({name:"no-electron-security-issues",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-electron-security-issues.md",description:"Detects Electron security vulnerabilities and insecure configurations",cwe:"CWE-16"},messages:{electronSecurityIssue:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Electron Security Issue",cwe:"CWE-16",description:"Electron security vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://electronjs.org/docs/tutorial/security"}),nodeIntegrationEnabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Node Integration Enabled",cwe:"CWE-16",description:"nodeIntegration enabled allows Node.js access in renderer",severity:"CRITICAL",fix:"Set nodeIntegration: false and use secure preload scripts",documentationLink:"https://electronjs.org/docs/tutorial/security#2-do-not-enable-nodejs-integration-for-remote-content"}),contextIsolationDisabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Context Isolation Disabled",cwe:"CWE-16",description:"contextIsolation disabled removes security boundary",severity:"CRITICAL",fix:"Enable contextIsolation and use preload scripts",documentationLink:"https://electronjs.org/docs/tutorial/context-isolation"}),webSecurityDisabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Web Security Disabled",cwe:"CWE-16",description:"webSecurity disabled removes CORS and security protections",severity:"HIGH",fix:"Keep webSecurity enabled",documentationLink:"https://electronjs.org/docs/tutorial/security#6-define-a-content-security-policy"}),insecureContentEnabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insecure Content Enabled",cwe:"CWE-16",description:"allowRunningInsecureContent allows mixed content",severity:"MEDIUM",fix:"Set allowRunningInsecureContent: false",documentationLink:"https://electronjs.org/docs/tutorial/security#5-do-not-disable-websecurity"}),unsafePreloadScript:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Preload Script",cwe:"CWE-16",description:"Preload script may expose sensitive APIs",severity:"HIGH",fix:"Use minimal, secure preload scripts",documentationLink:"https://electronjs.org/docs/tutorial/security#3-enable-context-isolation-for-remote-content"}),directNodeAccess:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Direct Node Access",cwe:"CWE-16",description:"Direct access to Node.js APIs in renderer process",severity:"HIGH",fix:"Access Node.js APIs only through secure IPC channels",documentationLink:"https://electronjs.org/docs/tutorial/security#3-enable-context-isolation-for-remote-content"}),insecureIpcPattern:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insecure IPC Pattern",cwe:"CWE-16",description:"IPC communication lacks proper validation",severity:"MEDIUM",fix:"Validate IPC messages and restrict channels",documentationLink:"https://electronjs.org/docs/tutorial/security#7-do-not-use-the-ipc-transport-for-sensitive-data"}),missingSandbox:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Sandbox",cwe:"CWE-16",description:"BrowserWindow not sandboxed",severity:"MEDIUM",fix:"Enable sandbox for untrusted content",documentationLink:"https://electronjs.org/docs/tutorial/sandbox"}),enableSecurityFeatures:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Enable Security Features",description:"Enable Electron security features",severity:"LOW",fix:"Set contextIsolation: true, nodeIntegration: false",documentationLink:"https://electronjs.org/docs/tutorial/security"}),useContextIsolation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Context Isolation",description:"Use context isolation for security",severity:"LOW",fix:"Enable contextIsolation in BrowserWindow options",documentationLink:"https://electronjs.org/docs/tutorial/context-isolation"}),securePreloadScripts:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Secure Preload Scripts",description:"Use secure preload scripts",severity:"LOW",fix:"Limit APIs exposed in preload scripts",documentationLink:"https://electronjs.org/docs/tutorial/security#3-enable-context-isolation-for-remote-content"}),strategySecureDefaults:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Secure Defaults Strategy",description:"Use secure defaults for Electron applications",severity:"LOW",fix:"Start with secure configuration and relax only when necessary",documentationLink:"https://electronjs.org/docs/tutorial/security"}),strategyProcessSeparation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Process Separation Strategy",description:"Separate main and renderer processes properly",severity:"LOW",fix:"Keep Node.js APIs in main process, use IPC for communication",documentationLink:"https://electronjs.org/docs/tutorial/application-architecture"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate all inputs in Electron applications",severity:"LOW",fix:"Validate IPC messages and user inputs",documentationLink:"https://electronjs.org/docs/tutorial/security#7-do-not-use-the-ipc-transport-for-sensitive-data"})},schema:[{type:"object",properties:{allowInDev:{type:"boolean",default:false,description:"Allow insecure settings in development"},safePreloadPatterns:{type:"array",items:{type:"string"},default:["contextBridge","ipcRenderer"],description:"Preload-script APIs treated as safe"},allowedIpcChannels:{type:"array",items:{type:"string"},default:[],description:"IPC channel names allowed without validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as safe"},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:[{allowInDev:false,safePreloadPatterns:["contextBridge","ipcRenderer"],allowedIpcChannels:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowedIpcChannels=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isBrowserWindowCreation=node=>{return node.callee.type==="Identifier"&&node.callee.name==="BrowserWindow"};const checkBrowserWindowOptions=optionsNode=>{for(const prop of optionsNode.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){const key=prop.key.name;const value=prop.value;if(["nodeIntegration","contextIsolation","webSecurity","allowRunningInsecureContent","sandbox"].includes(key)){if(value.type==="Literal"){const isInsecure=key==="nodeIntegration"&&value.value===true||key==="contextIsolation"&&value.value===false||key==="webSecurity"&&value.value===false||key==="allowRunningInsecureContent"&&value.value===true||key==="sandbox"&&value.value===false;if(isInsecure){if(safetyChecker.isSafe(prop,context)){continue}const messageId=key==="nodeIntegration"?"nodeIntegrationEnabled":key==="contextIsolation"?"contextIsolationDisabled":key==="webSecurity"?"webSecurityDisabled":key==="allowRunningInsecureContent"?"insecureContentEnabled":"missingSandbox";context.report({node:prop,messageId,data:{filePath:filename,line:String(prop.loc?.start.line??0)}})}}}}}};const isIpcCall=node=>{const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&["ipcMain","ipcRenderer"].includes(callee.object.name)&&callee.property.type==="Identifier"){return["send","invoke","handle","on","once"].includes(callee.property.name)}return false};const checkIpcCall=node=>{const args=node.arguments;if(args.length===0){return}const channelArg=args[0];if(channelArg.type==="Literal"&&typeof channelArg.value==="string"){const channel=channelArg.value;if(allowedIpcChannels.length>0&&!allowedIpcChannels.includes(channel)){if(safetyChecker.isSafe(node,context)){return}context.report({node:channelArg,messageId:"insecureIpcPattern",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}};const isRendererFile=()=>{const segments=filename.toLowerCase().split(/[\\/]/).filter(Boolean);if(segments.length===0)return false;const base=segments[segments.length-1].replace(/\.[cm]?[jt]sx?$/,"");const dirs=segments.slice(0,-1);return base==="renderer"||base==="preload"||base.startsWith("renderer.")||base.startsWith("preload.")||dirs.includes("renderer")||dirs.includes("preload")||dirs.includes("ui")||dirs.includes("view")||dirs.includes("views")};const isNodeApiCall=node=>{const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="require"){const arg=node.arguments[0];if(arg?.type==="Literal"&&typeof arg.value==="string"){const moduleName=arg.value;return["fs","child_process","os","path","crypto","http","https"].includes(moduleName)}}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&["process","global","__dirname","__filename"].includes(callee.object.name)){return true}return false};return{NewExpression(node){try{if(isBrowserWindowCreation(node)){const args=node.arguments;if(args.length>0&&args[0]?.type==="ObjectExpression"){checkBrowserWindowOptions(args[0])}}}catch{return}},CallExpression(node){try{if(isIpcCall(node)){checkIpcCall(node)}if(isRendererFile()&&isNodeApiCall(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"directNodeAccess",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}catch{return}},AssignmentExpression(node){try{if(node.left.type==="MemberExpression"&&node.left.property.type==="Identifier"&&node.left.property.name==="preload"){if(node.right.type==="Literal"&&typeof node.right.value==="string"){const preloadPath=node.right.value;if(preloadPath.includes("node_modules")||preloadPath.includes("http")||preloadPath.includes("remote")){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.right,messageId:"unsafePreloadScript",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}catch{return}},Property(node){try{if(node.key.type==="Identifier"&&node.key.name==="webPreferences"){if(node.value.type==="ObjectExpression"){checkBrowserWindowOptions(node.value)}}}catch{return}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noElectronSecurityIssues=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 fileUsesElectron=(0,eslint_devkit_1.createModuleEvidence)({packages:["electron"],scopes:["@electron"],prefixes:["electron-"]});const INSECURE_WEB_PREFERENCES=new Map([["nodeIntegration",{insecureValue:true,messageId:"nodeIntegrationEnabled"}],["nodeIntegrationInWorker",{insecureValue:true,messageId:"nodeIntegrationEnabled"}],["nodeIntegrationInSubFrames",{insecureValue:true,messageId:"nodeIntegrationEnabled"}],["contextIsolation",{insecureValue:false,messageId:"contextIsolationDisabled"}],["webSecurity",{insecureValue:false,messageId:"webSecurityDisabled"}],["allowRunningInsecureContent",{insecureValue:true,messageId:"insecureContentEnabled"}],["allowDisplayingInsecureContent",{insecureValue:true,messageId:"insecureContentEnabled"}],["sandbox",{insecureValue:false,messageId:"missingSandbox"}],["enableRemoteModule",{insecureValue:true,messageId:"legacyElectronFeature"}],["webviewTag",{insecureValue:true,messageId:"legacyElectronFeature"}]]);const REMOTE_SPECIFIER=/^(?:[a-z][a-z0-9+.-]*:)?\/\//i;function isOffProjectPreload(preloadPath){if(REMOTE_SPECIFIER.test(preloadPath)&&!/^file:/i.test(preloadPath)){return true}return preloadPath.split(/[\\/]/).includes("node_modules")}function propertyName(property){if(property.type!=="Property"||property.computed)return null;if(property.key.type==="Identifier")return property.key.name;if(property.key.type==="Literal"&&typeof property.key.value==="string"){return property.key.value}return null}exports.noElectronSecurityIssues=(0,eslint_devkit_1.createRule)({name:"no-electron-security-issues",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-electron-security-issues.md",description:"Detects Electron security vulnerabilities and insecure configurations",cwe:"CWE-16"},messages:{nodeIntegrationEnabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Node Integration Enabled",cwe:"CWE-16",description:"nodeIntegration enabled allows Node.js access in renderer",severity:"CRITICAL",fix:"Set nodeIntegration: false and use secure preload scripts",documentationLink:"https://electronjs.org/docs/tutorial/security#2-do-not-enable-nodejs-integration-for-remote-content"}),contextIsolationDisabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Context Isolation Disabled",cwe:"CWE-16",description:"contextIsolation disabled removes security boundary",severity:"CRITICAL",fix:"Enable contextIsolation and use preload scripts",documentationLink:"https://electronjs.org/docs/tutorial/context-isolation"}),webSecurityDisabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Web Security Disabled",cwe:"CWE-16",description:"webSecurity disabled removes CORS and security protections",severity:"HIGH",fix:"Keep webSecurity enabled",documentationLink:"https://electronjs.org/docs/tutorial/security#6-define-a-content-security-policy"}),insecureContentEnabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insecure Content Enabled",cwe:"CWE-16",description:"allowRunningInsecureContent allows mixed content",severity:"MEDIUM",fix:"Set allowRunningInsecureContent: false",documentationLink:"https://electronjs.org/docs/tutorial/security#5-do-not-disable-websecurity"}),unsafePreloadScript:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Preload Script",cwe:"CWE-16",description:"Preload script may expose sensitive APIs",severity:"HIGH",fix:"Use minimal, secure preload scripts",documentationLink:"https://electronjs.org/docs/tutorial/security#3-enable-context-isolation-for-remote-content"}),directNodeAccess:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Direct Node Access",cwe:"CWE-16",description:"Direct access to Node.js APIs in renderer process",severity:"HIGH",fix:"Access Node.js APIs only through secure IPC channels",documentationLink:"https://electronjs.org/docs/tutorial/security#3-enable-context-isolation-for-remote-content"}),insecureIpcPattern:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insecure IPC Pattern",cwe:"CWE-16",description:"IPC communication lacks proper validation",severity:"MEDIUM",fix:"Validate IPC messages and restrict channels",documentationLink:"https://electronjs.org/docs/tutorial/security#7-do-not-use-the-ipc-transport-for-sensitive-data"}),missingSandbox:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Sandbox",cwe:"CWE-16",description:"BrowserWindow not sandboxed",severity:"MEDIUM",fix:"Enable sandbox for untrusted content",documentationLink:"https://electronjs.org/docs/tutorial/sandbox"}),legacyElectronFeature:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Legacy Electron Feature Enabled ({{option}})",cwe:"CWE-16",description:"{{option}} is enabled in webPreferences. It widens what renderer content can reach past the context bridge: enableRemoteModule gives the renderer synchronous access to main-process objects, and webviewTag re-enables <webview>, whose own options a compromised page can rewrite. Both are off by default in current Electron because of it.",severity:"HIGH",fix:"Remove {{option}} (or set it to false) and expose the specific capability through contextBridge backed by an ipcMain handler.",documentationLink:"https://electronjs.org/docs/latest/tutorial/security#12-verify-webview-options-before-creation"})},schema:[{type:"object",properties:{allowedIpcChannels:{type:"array",items:{type:"string"},default:[],description:"IPC channel names allowed without validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as safe"},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:[{allowedIpcChannels:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowedIpcChannels=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const filename=context.filename;const usesElectron=fileUsesElectron(context.sourceCode.ast);const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isBrowserWindowCreation=node=>{return node.callee.type==="Identifier"&&node.callee.name==="BrowserWindow"};const checkBrowserWindowOptions=optionsNode=>{for(const prop of optionsNode.properties){const key=propertyName(prop);if(key===null)continue;const setting=INSECURE_WEB_PREFERENCES.get(key);if(!setting)continue;const value=prop.value;if(value.type!=="Literal"||value.value!==setting.insecureValue)continue;if(safetyChecker.isSafe(prop,context)){continue}context.report({node:prop,messageId:setting.messageId,data:{filePath:filename,line:String(prop.loc?.start.line??0),option:key}})}};const isIpcCall=node=>{const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&["ipcMain","ipcRenderer"].includes(callee.object.name)&&callee.property.type==="Identifier"){return["send","invoke","handle","on","once"].includes(callee.property.name)}return false};const checkIpcCall=node=>{const args=node.arguments;if(args.length===0){return}const channelArg=args[0];if(channelArg.type==="Literal"&&typeof channelArg.value==="string"){const channel=channelArg.value;if(allowedIpcChannels.length>0&&!allowedIpcChannels.includes(channel)){if(safetyChecker.isSafe(node,context)){return}context.report({node:channelArg,messageId:"insecureIpcPattern",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}};const isRendererFile=()=>{const segments=filename.toLowerCase().split(/[\\/]/).filter(Boolean);if(segments.length===0)return false;const base=segments[segments.length-1].replace(/\.[cm]?[jt]sx?$/,"");const dirs=segments.slice(0,-1);return base==="renderer"||base==="preload"||base.startsWith("renderer.")||base.startsWith("preload.")||dirs.includes("renderer")||dirs.includes("preload")};const isNodeApiCall=node=>{const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="require"){const arg=node.arguments[0];if(arg?.type==="Literal"&&typeof arg.value==="string"){const moduleName=arg.value;return["fs","child_process","os","path","crypto","http","https"].includes(moduleName)}}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&["process","global","__dirname","__filename"].includes(callee.object.name)){return true}return false};return{NewExpression(node){try{if(isBrowserWindowCreation(node)){const args=node.arguments;if(args.length>0&&args[0]?.type==="ObjectExpression"){checkBrowserWindowOptions(args[0])}}}catch{return}},CallExpression(node){try{if(isIpcCall(node)){checkIpcCall(node)}if(isRendererFile()&&usesElectron&&isNodeApiCall(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"directNodeAccess",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}catch{return}},AssignmentExpression(node){try{if(node.left.type==="MemberExpression"&&node.left.property.type==="Identifier"&&node.left.property.name==="preload"){if(node.right.type==="Literal"&&typeof node.right.value==="string"){const preloadPath=node.right.value;if(isOffProjectPreload(preloadPath)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.right,messageId:"unsafePreloadScript",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}catch{return}},Property(node){try{if(propertyName(node)==="webPreferences"){if(node.value.type==="ObjectExpression"){checkBrowserWindowOptions(node.value)}}}catch{return}}}}});