eslint-plugin-secure-coding 4.3.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 (35) hide show
  1. package/package.json +9 -3
  2. package/src/index.js +1 -1
  3. package/src/rules/detect-non-literal-regexp/index.js +1 -1
  4. package/src/rules/detect-object-injection/index.js +1 -1
  5. package/src/rules/detect-weak-password-validation/index.js +1 -1
  6. package/src/rules/no-bidi-characters/index.js +1 -1
  7. package/src/rules/no-directive-injection/index.js +1 -1
  8. package/src/rules/no-electron-security-issues/index.js +1 -1
  9. package/src/rules/no-format-string-injection/index.js +1 -1
  10. package/src/rules/no-graphql-injection/index.js +1 -1
  11. package/src/rules/no-hardcoded-credentials/index.js +1 -1
  12. package/src/rules/no-improper-sanitization/index.js +1 -1
  13. package/src/rules/no-improper-type-validation/index.js +1 -1
  14. package/src/rules/no-insecure-comparison/index.js +1 -1
  15. package/src/rules/no-ldap-injection/index.js +1 -1
  16. package/src/rules/no-log-injection/index.js +1 -1
  17. package/src/rules/no-missing-authentication/index.js +1 -1
  18. package/src/rules/no-pii-in-logs/index.js +1 -1
  19. package/src/rules/no-privilege-escalation/index.js +1 -1
  20. package/src/rules/no-redos-vulnerable-regex/index.js +0 -0
  21. package/src/rules/no-sensitive-data-exposure/index.js +1 -1
  22. package/src/rules/no-sql-injection/index.js +1 -1
  23. package/src/rules/no-template-injection/index.js +1 -1
  24. package/src/rules/no-unchecked-loop-condition/index.js +1 -1
  25. package/src/rules/no-unlimited-resource-allocation/index.js +1 -1
  26. package/src/rules/no-unsafe-deserialization/index.js +1 -1
  27. package/src/rules/no-unsafe-regex-construction/index.js +1 -1
  28. package/src/rules/no-weak-password-recovery/index.js +1 -1
  29. package/src/rules/no-xpath-injection/index.js +1 -1
  30. package/src/rules/no-xxe-injection/index.js +1 -1
  31. package/src/rules/require-backend-authorization/index.js +1 -1
  32. package/src/rules/require-secure-defaults/index.js +1 -1
  33. package/src/utils/redos-oracle.js +1 -0
  34. package/src/utils/regexp-intrinsic.js +1 -0
  35. package/src/utils/resolve-reference.js +1 -0
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPrivilegeEscalation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_ROLE_CHECK_PATTERNS=["hasRole","checkRole","isAdmin","isAuthorized","hasPermission","checkPermission","verifyRole","requireRole"];const DEFAULT_USER_INPUT_PATTERNS=[/\breq\.(body|query|params)\b/,/\brequest\.(body|query|params)\b/,/\buserInput\b/,/\binput\b/];function matchesIgnorePattern(text,patterns){return patterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return text.toLowerCase().includes(pattern.toLowerCase())}})}function containsUserInput(node,sourceCode,userInputPatterns){const text=sourceCode.getText(node);return userInputPatterns.some(pattern=>pattern.test(text))}function isInsideRoleCheck(node,sourceCode,roleCheckPatterns){let current=node;while(current){if(current.parent&&current.parent.type==="IfStatement"){const ifStmt=current.parent;const conditionText=sourceCode.getText(ifStmt.test);if(roleCheckPatterns.some(pattern=>conditionText.toLowerCase().includes(pattern.toLowerCase()))){return true}}if(current.parent&&current.parent.type==="ConditionalExpression"){const condExpr=current.parent;const testText=sourceCode.getText(condExpr.test);if(roleCheckPatterns.some(pattern=>testText.toLowerCase().includes(pattern.toLowerCase()))){return true}}if(current.parent&&current.parent.type==="CallExpression"){const callExpr=current.parent;const callee=callExpr.callee;if(callee.type==="Identifier"){const calleeName=callee.name.toLowerCase();if(roleCheckPatterns.some(pattern=>calleeName.includes(pattern.toLowerCase()))){return true}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const propertyName=callee.property.name.toLowerCase();if(roleCheckPatterns.some(pattern=>propertyName.includes(pattern.toLowerCase()))){return true}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}exports.noPrivilegeEscalation=(0,eslint_devkit_2.createRule)({name:"no-privilege-escalation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-privilege-escalation.md",description:"Detects potential privilege escalation vulnerabilities",cwe:"CWE-269",cvss:8.8},hasSuggestions:true,messages:{privilegeEscalation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Privilege Escalation",cwe:"CWE-269",description:"Potential privilege escalation: {{issue}} - user input used without role validation",severity:"HIGH",fix:'Add role check before using user input: if (!hasRole(user, requiredRole)) throw new Error("Unauthorized");',documentationLink:"https://cwe.mitre.org/data/definitions/269.html"}),addRoleCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Role Check",description:"Add role check before privilege operations",severity:"LOW",fix:'if (!hasRole(user, requiredRole)) throw new Error("Unauthorized")',documentationLink:"https://cwe.mitre.org/data/definitions/269.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow privilege escalation patterns in test files"},testFilePattern:{type:"string",default:"\\.(test|spec)\\.(ts|tsx|js|jsx)$",description:"Test file pattern regex string"},roleCheckPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROLE_CHECK_PATTERNS,description:"Role check patterns to recognize"},userInputPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional user input patterns to check (regex strings)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,testFilePattern:"\\.(test|spec)\\.(ts|tsx|js|jsx)$",roleCheckPatterns:DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:[],ignorePatterns:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern="\\.(test|spec)\\.(ts|tsx|js|jsx)$",roleCheckPatterns=DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:additionalUserInputPatterns=[],ignorePatterns=[]}=options;const filename=context.filename;const testFileRegex=new RegExp(testFilePattern);const isTestFile=allowInTests&&testFileRegex.test(filename);const sourceCode=context.sourceCode;const userInputPatterns=[...DEFAULT_USER_INPUT_PATTERNS,...additionalUserInputPatterns.map(pattern=>new RegExp(pattern,"i"))];function checkAssignmentExpression(node){if(isTestFile){return}if(node.left.type==="MemberExpression"&&node.left.property.type==="Identifier"){const propertyName=node.left.property.name.toLowerCase();if(["role","permission","privilege","access","level"].includes(propertyName)){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(containsUserInput(node.right,sourceCode,userInputPatterns)){if(!isInsideRoleCheck(node,sourceCode,roleCheckPatterns)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Role assignment from user input: ${sourceCode.getText(node.left)} = ${sourceCode.getText(node.right)}`},suggest:[{messageId:"addRoleCheck",fix:()=>null}]})}}}}}function checkCallExpression(node){if(isTestFile){return}const callee=node.callee;let isPrivilegeOperation=false;let operationName="";if(callee.type==="Identifier"){const calleeName=callee.name.toLowerCase();if(["setrole","grant","revoke","elevate","promote"].some(op=>calleeName.includes(op))){isPrivilegeOperation=true;operationName=callee.name}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const propertyName=callee.property.name.toLowerCase();if(["setrole","grant","revoke","elevate","promote","updaterole"].some(op=>propertyName.includes(op))){isPrivilegeOperation=true;operationName=propertyName}}if(isPrivilegeOperation){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}for(const arg of node.arguments){if(containsUserInput(arg,sourceCode,userInputPatterns)){if(!isInsideRoleCheck(node,sourceCode,roleCheckPatterns)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Privilege operation (${operationName}) with user input without role validation`},suggest:[{messageId:"addRoleCheck",fix:()=>null}]});return}}}}}function checkObjectExpression(node){if(isTestFile)return;for(const prop of node.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){const keyName=prop.key.name.toLowerCase();if(["role","permission","privilege","access","level"].includes(keyName)){const text=sourceCode.getText(prop);if(matchesIgnorePattern(text,ignorePatterns))continue;if(containsUserInput(prop.value,sourceCode,userInputPatterns)){if(!isInsideRoleCheck(node,sourceCode,roleCheckPatterns)){context.report({node:prop,messageId:"privilegeEscalation",data:{issue:`Role assignment in object from user input: ${sourceCode.getText(prop)}`},suggest:[{messageId:"addRoleCheck",fix:()=>null}]})}}}}}}return{AssignmentExpression:checkAssignmentExpression,CallExpression:checkCallExpression,ObjectExpression:checkObjectExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPrivilegeEscalation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_ROLE_CHECK_PATTERNS=["hasRole","checkRole","isAdmin","isAuthorized","hasPermission","checkPermission","verifyRole","requireRole"];const DEFAULT_USER_INPUT_PATTERNS=[/\breq\.(body|query|params)\b/,/\brequest\.(body|query|params)\b/,/\buserInput\b/];const DEFAULT_PRIVILEGE_PROPERTIES=["role","permission","privilege","access"];const DEFAULT_PRIVILEGE_TERMS=["setRole","updateRole","elevate","grant role","grant permission","grant access","grant privilege","promote user","promote admin","revoke role","revoke permission","revoke access","revoke privilege"];const DEFAULT_BARE_PRIVILEGE_VERBS=["grant","promote","revoke"];function isPrivilegeOperationName(name,privilegeTerms,bareVerbs){if((0,eslint_devkit_1.nameHasAnyWord)(name,privilegeTerms)){return true}const words=(0,eslint_devkit_1.identifierWords)(name);return words.length===1&&bareVerbs.has(words[0])}function assignedPropertyName(member){if(!member.computed&&member.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return member.property.name}if(member.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof member.property.value==="string"){return member.property.value}return null}function forEachNode(root,visit){const pending=[root];while(pending.length>0){const node=pending.pop();visit(node);for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){pending.push(child)}}}}}function containsRoleCheck(root,roleCheckPatterns){let found=false;forEachNode(root,node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(node.name,roleCheckPatterns)){found=true}});return found}function exitsUnconditionally(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||statement.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)}return false}function isAfterRoleGuard(node,roleCheckPatterns){let current=node;while(current.parent){const parent=current.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=parent.body;const index=body.indexOf(current);for(let i=0;i<index;i++){const statement=body[i];if(statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&exitsUnconditionally(statement.consequent)&&containsRoleCheck(statement.test,roleCheckPatterns)){return true}}}current=parent}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}function containsUserInput(node,sourceCode,userInputPatterns){const text=sourceCode.getText(node);return userInputPatterns.some(pattern=>pattern.test(text))}function isInsideRoleCheck(node,roleCheckPatterns){let current=node;while(current){if(current.parent&&current.parent.type==="IfStatement"){const ifStmt=current.parent;if(containsRoleCheck(ifStmt.test,roleCheckPatterns)){return true}}if(current.parent&&current.parent.type==="ConditionalExpression"){const condExpr=current.parent;if(containsRoleCheck(condExpr.test,roleCheckPatterns)){return true}}if(current.parent&&current.parent.type==="CallExpression"){const callExpr=current.parent;const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,roleCheckPatterns)){return true}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.property.name,roleCheckPatterns)){return true}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}exports.noPrivilegeEscalation=(0,eslint_devkit_2.createRule)({name:"no-privilege-escalation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-privilege-escalation.md",description:"Detects potential privilege escalation vulnerabilities",cwe:"CWE-269",cvss:8.8},messages:{privilegeEscalation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Privilege Escalation",cwe:"CWE-269",description:"Potential privilege escalation: {{issue}} - user input used without role validation",severity:"HIGH",fix:'Add role check before using user input: if (!hasRole(user, requiredRole)) throw new Error("Unauthorized");',documentationLink:"https://cwe.mitre.org/data/definitions/269.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow privilege escalation patterns in test files"},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."},roleCheckPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROLE_CHECK_PATTERNS,description:"Role check patterns to recognize"},userInputPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional user input patterns to check (regex strings)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},privilegeProperties:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_PROPERTIES,description:"Property names whose assignment is an authorisation decision, compared case-insensitively as an exact name. Replaces the built-in list."},additionalPrivilegeProperties:{type:"array",items:{type:"string"},default:[],description:"Extra privilege property names, on top of `privilegeProperties`."},privilegeTerms:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_TERMS,description:"Privilege operations, matched as whole words or whole consecutive phrases of a callee name \u2014 never as a substring. Replaces the built-in list."},additionalPrivilegeTerms:{type:"array",items:{type:"string"},default:[],description:"Extra privilege operation terms, on top of `privilegeTerms`."},barePrivilegeVerbs:{type:"array",items:{type:"string"},default:DEFAULT_BARE_PRIVILEGE_VERBS,description:"Verbs that count only when they are the WHOLE callee name, because their ordinary English sense dominates otherwise. Replaces the built-in list."},additionalBarePrivilegeVerbs:{type:"array",items:{type:"string"},default:[],description:"Extra bare privilege verbs, on top of `barePrivilegeVerbs`."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,roleCheckPatterns:DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:[],ignorePatterns:[],privilegeProperties:DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties:[],privilegeTerms:DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms:[],barePrivilegeVerbs:DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,roleCheckPatterns=DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:additionalUserInputPatterns=[],ignorePatterns=[],privilegeProperties=DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties=[],privilegeTerms=DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms=[],barePrivilegeVerbs=DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs=[]}=options;const privilegeProps=new Set([...privilegeProperties,...additionalPrivilegeProperties].map(name=>name.toLowerCase()));const privilegeOperationTerms=[...privilegeTerms,...additionalPrivilegeTerms];const bareVerbs=new Set([...barePrivilegeVerbs,...additionalBarePrivilegeVerbs]);const isPrivilegeOperationCallee=name=>isPrivilegeOperationName(name,privilegeOperationTerms,bareVerbs);const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const userInputPatterns=[...DEFAULT_USER_INPUT_PATTERNS,...(0,eslint_devkit_1.compileUserPatterns)(additionalUserInputPatterns,"i")];function isRoleChecked(node){return isInsideRoleCheck(node,roleCheckPatterns)||isAfterRoleGuard(node,roleCheckPatterns)}function resolvesToUserInput(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);for(const def of reference?.resolved?.defs??[]){let declarator=def.name;while(declarator&&declarator.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){declarator=declarator.parent}if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&containsUserInput(declarator.init,sourceCode,userInputPatterns)){return true}}return false}function isUserControlled(node){return containsUserInput(node,sourceCode,userInputPatterns)||resolvesToUserInput(node)}function checkAssignmentExpression(node){if(isTestFile){return}if(node.left.type==="MemberExpression"){const propertyName=assignedPropertyName(node.left)?.toLowerCase();if(propertyName!==void 0&&privilegeProps.has(propertyName)){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isUserControlled(node.right)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Role assignment from user input: ${sourceCode.getText(node.left)} = ${sourceCode.getText(node.right)}`}})}}}}}function checkCallExpression(node){if(isTestFile){return}const callee=node.callee;let isPrivilegeOperation=false;let operationName="";if(callee.type==="Identifier"){if(isPrivilegeOperationCallee(callee.name)){isPrivilegeOperation=true;operationName=callee.name}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(isPrivilegeOperationCallee(callee.property.name)){isPrivilegeOperation=true;operationName=callee.property.name.toLowerCase()}}if(isPrivilegeOperation){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}for(const arg of node.arguments){if(isUserControlled(arg)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Privilege operation (${operationName}) with user input without role validation`}});return}}}}}function checkObjectExpression(node){if(isTestFile)return;for(const prop of node.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){const keyName=prop.key.name.toLowerCase();if(privilegeProps.has(keyName)){const text=sourceCode.getText(prop);if(matchesIgnorePattern(text,ignorePatterns))continue;if(isUserControlled(prop.value)){if(!isRoleChecked(node)){context.report({node:prop,messageId:"privilegeEscalation",data:{issue:`Role assignment in object from user input: ${sourceCode.getText(prop)}`}})}}}}}}return{AssignmentExpression:checkAssignmentExpression,CallExpression:checkCallExpression,ObjectExpression:checkObjectExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[ _-]{0,2}(?:[a-z0-9]{1,12}[ _-]{0,2})?[:=]\\s*\\S`,"i").test(normalized)})}function literalLabelsValue(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b\\s*[:=]\\s*$`,"i").test(normalized)){return pattern}}return null}const DESCRIPTOR_SEGMENTS=new Set(["msg","message","error","err","label","prompt","hint","description","desc","regex","pattern","placeholder","warning","notice"]);function identifierNamesSecret(name,patterns){const matched=containsSensitiveData(name,patterns);if(!matched)return null;const last=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(-1).join("");return DESCRIPTOR_SEGMENTS.has(last)?null:matched}function memberCarriesSecret(node,patterns){const prop=node.property;const propName=node.computed?prop.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value==="string"?prop.value:null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?identifierNamesSecret(propName,patterns):null;if(fromProp)return fromProp;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(node.object.name,patterns):null}function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}const REDACTION_SUGGESTIONS=[{messageId:"redactData",fix:()=>null},{messageId:"useMasking",fix:()=>null},{messageId:"removeFromLogs",fix:()=>null}];exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},hasSuggestions:true,messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),redactData:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Redact Data",description:"Redact sensitive data before logging",severity:"LOW",fix:"Redact sensitive fields before logging",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),useMasking:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Masking",description:"Use data masking function",severity:"LOW",fix:"maskSensitive(data)",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),removeFromLogs:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Remove From Logs",description:"Remove sensitive data from logs and errors",severity:"LOW",fix:"Filter sensitive data before logging",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},checkApiResponses:{type:"boolean",default:true,description:"Check API responses"}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,checkApiResponses:true}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true}=options||{};function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type==="MemberExpression"){const object=node.callee.object;const property=node.callee.property;if(property.type==="Identifier"){const methodName=property.name.toLowerCase();if(["log","info","warn","error","debug","trace"].includes(methodName)){if(object.type==="Identifier"){const objName=object.name.toLowerCase();if(objName==="console"||objName==="logger"){return true}}}}}else if(node.callee.type==="Identifier"){const words=node.callee.name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);if(words.includes("log")||words.includes("logger")){return true}}return false})();if(isLoggingCall&&checkConsoleLog){for(const arg of node.arguments){if(arg.type==="Literal"&&typeof arg.value==="string"){const text=arg.value;const matchedPattern=literalCarriesSecret(text,sensitivePatterns)?containsSensitiveData(text,sensitivePatterns):null;if(matchedPattern){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:matchedPattern},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type==="BinaryExpression"&&arg.operator==="+"){const side=(arg.left?.type==="Literal"&&typeof arg.left.value==="string"&&literalLabelsValue(arg.left.value,sensitivePatterns)?{node:arg.left,pattern:literalLabelsValue(arg.left.value,sensitivePatterns)}:void 0)??(arg.right?.type==="Identifier"&&identifierNamesSecret(arg.right.name,sensitivePatterns)?{node:arg.right,pattern:identifierNamesSecret(arg.right.name,sensitivePatterns)}:void 0);if(side?.pattern){context.report({node:side.node,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:side.pattern},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const matchedMember=memberCarriesSecret(arg,sensitivePatterns);if(matchedMember){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:matchedMember},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>e.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(e.name,sensitivePatterns):e.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?memberCarriesSecret(e,sensitivePatterns):null).find(m=>Boolean(m));const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const fromText=arg.expressions.length>0&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;const matchedTemplate=fromExpression??fromText;if(matchedTemplate){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:matchedTemplate},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.name){const matchedPattern2=identifierNamesSecret(arg.name,sensitivePatterns);if(matchedPattern2){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:matchedPattern2},suggest:REDACTION_SUGGESTIONS});return}}}}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee&&node.callee.type==="Identifier"&&node.callee.name==="Error"){for(const arg of node.arguments){if(arg.type==="Literal"&&typeof arg.value==="string"){const text=arg.value;const matchedErrPattern=literalCarriesSecret(text,sensitivePatterns)?containsSensitiveData(text,sensitivePatterns):null;if(matchedErrPattern){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"error messages",dataType:matchedErrPattern},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type==="BinaryExpression"&&arg.operator==="+"){if(arg.left&&arg.left.type==="Literal"&&typeof arg.left.value==="string"){const leftText=arg.left.value;const leftMatchedPattern=literalLabelsValue(leftText,sensitivePatterns);if(leftMatchedPattern){context.report({node:arg.left,messageId:"sensitiveDataExposure",data:{context:"error messages",dataType:leftMatchedPattern},suggest:REDACTION_SUGGESTIONS});return}}if(arg.right&&arg.right.type==="Identifier"&&arg.right.name){const rightMatchedPattern=identifierNamesSecret(arg.right.name,sensitivePatterns);if(rightMatchedPattern){context.report({node:arg.right,messageId:"sensitiveDataExposure",data:{context:"error messages",dataType:rightMatchedPattern},suggest:REDACTION_SUGGESTIONS});return}}}}}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[ _-]{0,2}(?:[a-z0-9]{1,12}[ _-]{0,2})?[:=]\\s*\\S`,"i").test(normalized)&&/[:=]\s*\S+\s*$/.test(text)})}function literalLabelsValue(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b\\s*[:=]\\s*$`,"i").test(normalized)){return pattern}}return null}const DESCRIPTOR_SEGMENTS=["msg","message","error","err","label","prompt","hint","description","desc","regex","pattern","placeholder","warning","notice"];function identifierNamesSecret(name,patterns,descriptors){const matched=containsSensitiveData(name,patterns);if(!matched)return null;const last=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(-1).join("");return descriptors.has(last)?null:matched}function memberCarriesSecret(node,patterns,descriptors){const prop=node.property;const propName=node.computed?prop.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value==="string"?prop.value:null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?identifierNamesSecret(propName,patterns,descriptors):null;if(fromProp)return fromProp;if(propName&&VALUE_FREE_PROPERTIES.has(propName))return null;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(node.object.name,patterns,descriptors):null}const VALUE_FREE_PROPERTIES=new Set(["length","size","byteLength","byteOffset"]);function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},descriptorSegments:{type:"array",items:{type:"string"},default:DESCRIPTOR_SEGMENTS,description:"Trailing name segments that describe a secret rather than hold one, so `apiKeyMsg` and `passwordError` are not reported. Compared as the whole FINAL segment of the name, never as a substring. Replaces the built-in list."},additionalDescriptorSegments:{type:"array",items:{type:"string"},default:[],description:"Extra descriptor segments, on top of `descriptorSegments`."}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,descriptorSegments:DESCRIPTOR_SEGMENTS,additionalDescriptorSegments:[]}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true,descriptorSegments=DESCRIPTOR_SEGMENTS,additionalDescriptorSegments=[]}=options||{};const descriptors=new Set([...descriptorSegments,...additionalDescriptorSegments]);const LOGGER_RECEIVERS=new Set(["console","logger","log"]);const LOG_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);function isLoggerReceiver(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return LOGGER_RECEIVERS.has(node.name.toLowerCase())}return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOGGER_RECEIVERS.has(node.property.name.toLowerCase())}function describeExposure(argument){const arg=(0,eslint_devkit_1.unwrapTypeSyntax)(argument);if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"){const pattern=literalCarriesSecret(arg.value,sensitivePatterns)?containsSensitiveData(arg.value,sensitivePatterns):null;return pattern?{node:arg,pattern}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){if(arg.left.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.left.value==="string"){const labelled=literalLabelsValue(arg.left.value,sensitivePatterns);if(labelled)return{node:arg.left,pattern:labelled}}else{const fromLeft=describeExposure(arg.left);if(fromLeft)return fromLeft}return namedValueExposure(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>namedValueExposure(e)).find(m=>Boolean(m));if(fromExpression)return{node:arg,pattern:fromExpression.pattern};const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const fromText=arg.expressions.length>0&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;return fromText?{node:arg,pattern:fromText}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of arg.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const keyName=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"?property.key.value:null;const pattern=keyName?identifierNamesSecret(keyName,sensitivePatterns,descriptors):null;if(!pattern)continue;if((0,eslint_devkit_1.isStaticExpression)({node:property.value,scope:context.sourceCode.getScope(arg)})){continue}return{node:property,pattern}}return null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return describeExposure(arg.consequent)??describeExposure(arg.alternate)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="String"&&arg.arguments.length===1&&arg.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!isShadowed("String",arg)){return describeExposure(arg.arguments[0])}return namedValueExposure(arg)}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function namedValueExposure(node,seen=new Set){const value=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(seen.has(value))return null;seen.add(value);if(value.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return namedValueExposure(value.expression,seen)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const pattern=identifierNamesSecret(value.name,sensitivePatterns,descriptors);if(pattern)return{node:value,pattern};const init=resolveBindingInit(value);const viaBinding=init?namedValueExposure(init,seen):null;return viaBinding?{node:value,pattern:viaBinding.pattern}:null}if(value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const pattern=memberCarriesSecret(value,sensitivePatterns,descriptors);return pattern?{node:value,pattern}:null}return null}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;return variable.references.filter(r=>r.isWrite()).length===1?def.node.init:null}return null}function reportFirstExposure(argumentList,exposureContext){for(const argument of argumentList){const exposure=describeExposure(argument);if(exposure){context.report({node:exposure.node,messageId:"sensitiveDataExposure",data:{context:exposureContext,dataType:exposure.pattern}});return}}}function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;return!node.callee.computed&&property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOG_METHODS.has(property.name.toLowerCase())&&isLoggerReceiver(node.callee.object)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const words=node.callee.name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.includes("log")||words.includes("logger")}return false})();if(isLoggingCall&&checkConsoleLog){reportFirstExposure(node.arguments,"logs")}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Error"){reportFirstExposure(node.arguments,"error messages")}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const SQL_DRIVER_MODULES=new Set(["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite","mysql","mysql2","@planetscale/database","sqlite3","better-sqlite3","node:sqlite","bun:sqlite","@libsql/client","typeorm","@nestjs/typeorm","sequelize","sequelize-typescript","@nestjs/sequelize","knex","objection","drizzle-orm","@prisma/client","prisma","kysely","mssql","oracledb"]);function isSqlDriverSpecifier(specifier){if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return SQL_DRIVER_MODULES.has(root)}function stringLiteralValue(node){if(node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return null}const SQL_SINK_METHODS=new Set(["query","execute"]);const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i];function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}const literal=stringLiteralValue(node);return literal===null?"":literal}function looksLikeSqlStatement(node){const text=staticText(node);return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function isBuiltString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.length>0}return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}const REQUEST_ROOTS=new Set(["req","request","ctx","event"]);const REQUEST_PROPERTIES=new Set(["query","params","body","headers","cookies","url","path"]);function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function singleAssignedInit(variable){const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function attributedSource(node,scope,depth=0){if(depth>5)return null;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return attributedSource(node.left,scope,depth+1)??attributedSource(node.right,scope,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){properties.unshift(root.property.name)}root=root.object}if(root.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_ROOTS.has(root.name)&&properties.some(property=>REQUEST_PROPERTIES.has(property))){return`${root.name}.${properties.join(".")}`}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return null;const init=singleAssignedInit(variable);if(init===null)return null;return attributedSource(init,scope,depth+1)}return null}function effectiveExpression(node,scope){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return node;const variable=resolveVariable(node.name,scope);if(variable===null)return node;const init=singleAssignedInit(variable);return init??node}exports.noSqlInjection=(0,eslint_devkit_1.createRule)({name:"no-sql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sql-injection.md",description:"Prevent SQL injection when a query is built from attacker-controlled input and executed through a driver-agnostic handle",cwe:"CWE-89",cvss:9.8,confidence:"high"},messages:{sqlInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",cwe:"CWE-89",owasp:"A03:2021",cvss:9.8,description:'SQL statement built from "{{source}}" and executed. An attacker controls part of the statement text.',severity:"CRITICAL",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:"Pass the value as a bound parameter (`$1` / `?`) instead of concatenating it into the statement.",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"})},schema:[]},defaultOptions:[],create(context){const pending=[];let importsSqlDriver=false;const noteSpecifier=specifier=>{if(specifier!==null&&isSqlDriverSpecifier(specifier)){importsSqlDriver=true}};return{ImportDeclaration(node){noteSpecifier(node.source.value)},ImportExpression(node){noteSpecifier(stringLiteralValue(node.source))},TSImportEqualsDeclaration(node){if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){noteSpecifier(stringLiteralValue(node.moduleReference.expression))}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){noteSpecifier(stringLiteralValue(node.arguments[0]));return}if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if(node.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(!SQL_SINK_METHODS.has(node.callee.property.name))return;const[firstArgument]=node.arguments;if(firstArgument===void 0||firstArgument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const scope=context.sourceCode.getScope(node);const expression=effectiveExpression(firstArgument,scope);if(!isBuiltString(expression))return;if(!looksLikeSqlStatement(expression))return;const source=attributedSource(expression,scope);if(source===null)return;pending.push({node,source})},"Program:exit"(){if(importsSqlDriver)return;for(const finding of pending){context.report({node:finding.node,messageId:"sqlInjection",data:{source:finding.source}})}}}}});exports.default=exports.noSqlInjection;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NO_SUBSTITUTIONS=new Map;function substitutionFor(node,scope,substitutions){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=resolveVariable(node.name,scope);return variable===null?void 0:substitutions.get(variable)}function hasRawUnattributedPart(node,scope,substitutions){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>{if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawUnattributedPart(part,scope,substitutions)}const bound=substitutionFor(part,scope,substitutions);if(bound!==void 0){return bound.node!==null&&!(0,eslint_devkit_1.isStaticExpression)({node:bound.node,scope:bound.scope})}return!(0,eslint_devkit_1.isStaticExpression)({node:part,scope})})}const SQL_DRIVER_MODULES=new Set(["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite","mysql","mysql2","@planetscale/database","sqlite3","better-sqlite3","node:sqlite","bun:sqlite","@libsql/client","typeorm","@nestjs/typeorm","sequelize","sequelize-typescript","@nestjs/sequelize","knex","objection","drizzle-orm","@prisma/client","prisma","kysely","mssql","oracledb"]);function isSqlDriverSpecifier(specifier){if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return SQL_DRIVER_MODULES.has(root)}function stringLiteralValue(node){if(node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return null}const SQL_SINK_METHODS=["query","execute"];const TRANSPARENT_CALLS=["String"];const QUERY_TEXT_PROPERTIES=["text","sql"];function invokedMethodName(callee,scope){if(!callee.computed){return callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property.name:null}const direct=stringLiteralValue(callee.property);if(direct!==null)return direct;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=resolveVariable(callee.property.name,scope);if(variable===null)return null;const init=singleAssignedInit(variable);return init===null?null:stringLiteralValue(init)}const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i];function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}const literal=stringLiteralValue(node);return literal===null?"":literal}function looksLikeSqlStatement(nodes){const text=nodes.map(staticText).join("");return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function isBuiltString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.length>0}return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}const REQUEST_ROOTS=["req","request","ctx","event"];const REQUEST_PROPERTIES=["query","params","body","headers","cookies","url","path"];function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function singleAssignedInit(variable){const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function isParameterBinding(variable){return variable.defs.some(def=>def.type==="Parameter"&&!bindsADeclaredContract(def))}function bindsADeclaredContract(def){for(let node=def.name;node!==void 0;node=node.parent??void 0){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){continue}const annotation=node.typeAnnotation?.typeAnnotation;if(annotation?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference)return true}return false}function allWritesStatic(variable,scope){const writes=writeExpressions(variable);if(writes.length===0)return false;return writes.every(node=>(0,eslint_devkit_1.isStaticExpression)({node,scope}))}function writeExpressions(variable){const written=[];for(const reference of variable.references){const{writeExpr}=reference;if(reference.isWrite()&&writeExpr!==void 0&&writeExpr!==null){written.push(writeExpr)}}return written}function isLocallyConstructed(variable,scope){if(variable===null)return false;const init=singleAssignedInit(variable);if(init===null)return false;return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_1.isStaticExpression)({node:init,scope})}function isAmbientGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function attributedThroughCall(node,scope,attribution,depth){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.transparentCalls.has(node.callee.name)&&isAmbientGlobal(node.callee.name,scope)){for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=attributedSource(argument,scope,attribution,depth+1);if(found!==null)return found}return null}const inlined=effectiveExpression(node,scope,attribution);if(inlined.nodes.length===1&&inlined.nodes[0]===node)return null;const inner={...attribution,substitutions:inlined.substitutions};for(const candidate of inlined.nodes){const found=attributedSource(candidate,inlined.scope,inner,depth+1);if(found!==null)return found}return null}function attributedSource(node,scope,attribution,depth=0){if(depth>5)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return attributedSource(bare,scope,attribution,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,attribution,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){properties.unshift(root.property.name)}root=root.object}if(root.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.requestRoots.has(root.name)&&properties.some(property=>attribution.requestProperties.has(property))&&!isLocallyConstructed(resolveVariable(root.name,scope),scope)){return`${root.name}.${properties.join(".")}`}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return attributedSource(node.consequent,scope,attribution,depth+1)??attributedSource(node.alternate,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return attributedThroughCall(node,scope,attribution,depth)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return null;const bound=attribution.substitutions.get(variable);if(bound!==void 0){return bound.node===null?null:attributedSource(bound.node,bound.scope,{...attribution,substitutions:NO_SUBSTITUTIONS},depth+1)}const writes=writeExpressions(variable);for(const write of writes){const found=attributedSource(write,scope,attribution,depth+1);if(found!==null)return found}if(attribution.untrustedParameters&&isParameterBinding(variable)&&!allWritesStatic(variable,scope)){return`${node.name} (a caller-supplied parameter)`}return null}return null}function effectiveExpression(node,scope,attribution,depth=0){const unresolved={nodes:[node],scope,substitutions:NO_SUBSTITUTIONS};if(depth>5)return unresolved;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node){return effectiveExpression(bare,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return effectiveExpression(node.argument,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const joined=joinedArrayElements(node,scope);if(joined!==null){return{nodes:joined,scope,substitutions:NO_SUBSTITUTIONS}}return resolveBuilderCall(node,scope,attribution)??unresolved}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=queryTextProperty(node,attribution.queryTextProperties);return text===null?unresolved:effectiveExpression(text,scope,attribution,depth+1)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return unresolved;const variable=resolveVariable(node.name,scope);if(variable===null)return unresolved;const writes=writeExpressions(variable);if(writes.length===0)return unresolved;if(writes.length===1){return effectiveExpression(writes[0],scope,attribution,depth+1)}return{nodes:writes,scope,substitutions:NO_SUBSTITUTIONS}}function resolveBuilderCall(node,scope,attribution){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const impl=resolveLocalFunction(node.callee.name,scope);if(impl===null)return null;const returned=returnedExpression(impl);if(returned===null||returned.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&returned.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return null}const bindings=bindParameters(impl,node.arguments,scope,attribution.sourceCode);if(bindings===null)return null;return{nodes:[returned],scope:attribution.sourceCode.getScope(returned),substitutions:bindings}}function resolveLocalFunction(name,scope){const variable=resolveVariable(name,scope);if(variable===null)return null;const declared=variable.defs.find(def=>def.type==="FunctionName");if(declared!==void 0){return declared.node}const init=singleAssignedInit(variable);if(init!==null&&(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression)){return init}return null}function returnedExpression(impl){if(impl.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return impl.body;const[only]=impl.body.body;if(impl.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument??null}function joinedArrayElements(node,scope){const{callee}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed){return null}if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||callee.property.name!=="join"){return null}let receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(receiver.name,scope);const init=variable===null?null:singleAssignedInit(variable);if(init===null)return null;receiver=init}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;const elements=[];for(const element of receiver.elements){if(element===null||element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){continue}elements.push(element)}return elements}function queryTextProperty(node,names){for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const key=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:stringLiteralValue(property.key);if(key!==null&&names.has(key))return property.value}return null}function bindParameters(impl,args,callerScope,sourceCode){if(args.some(a=>a.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement))return null;if(impl.params.some(p=>p.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier))return null;const bindings=new Map;sourceCode.getDeclaredVariables(impl).filter(variable=>isParameterBinding(variable)).forEach((variable,index)=>{bindings.set(variable,{node:args[index]??null,scope:callerScope})});return bindings}exports.noSqlInjection=(0,eslint_devkit_1.createRule)({name:"no-sql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sql-injection.md",description:"Prevent SQL injection when a query is built from attacker-controlled input and executed through a driver-agnostic handle",cwe:"CWE-89",cvss:9.8,confidence:"high"},messages:{sqlInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",cwe:"CWE-89",owasp:"A03:2021",cvss:9.8,description:'SQL statement built from "{{source}}" and executed. An attacker controls part of the statement text.',severity:"CRITICAL",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:"Pass the value as a bound parameter (`$1` / `?`) instead of concatenating it into the statement.",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"})},schema:[{type:"object",properties:{reportUnattributedInterpolation:{type:"boolean",default:false,description:"Report SQL built by interpolation even when the interpolated value cannot be traced to a request in this file (a property of `this`, a property of a non-request object, a helper return). Parameterise either way. Set false to report only attributable taint."},treatParametersAsUntrusted:{type:"boolean",default:true,description:"Treat a function parameter spliced into statement text as an untrusted inlet \u2014 nothing in this file constrains what a caller passes. Set false to report only values traceable to a request within the linted file."},requestRoots:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Identifier roots that denote an inbound request. Matched exactly."},requestProperties:{type:"array",items:{type:"string"},default:[...REQUEST_PROPERTIES],description:"Request properties that carry caller-supplied data. Matched exactly."},sinkMethods:{type:"array",items:{type:"string"},default:[...SQL_SINK_METHODS],description:"Method names that execute a raw SQL string. Matched exactly against the called member name."},queryTextProperties:{type:"array",items:{type:"string"},default:[...QUERY_TEXT_PROPERTIES],description:"Properties of a driver query-config object that hold the statement text. Matched exactly."},transparentCalls:{type:"array",items:{type:"string"},default:[...TRANSPARENT_CALLS],description:"Ambient global calls that pass their argument through unchanged, so taint survives them. Matched exactly, and only when the file declares no binding of that name."}},additionalProperties:false}]},defaultOptions:[{reportUnattributedInterpolation:false,treatParametersAsUntrusted:true,requestRoots:REQUEST_ROOTS,requestProperties:REQUEST_PROPERTIES,sinkMethods:SQL_SINK_METHODS,transparentCalls:TRANSPARENT_CALLS,queryTextProperties:QUERY_TEXT_PROPERTIES}],create(context,[options={}]){const{reportUnattributedInterpolation=false,treatParametersAsUntrusted=true,requestRoots=REQUEST_ROOTS,requestProperties=REQUEST_PROPERTIES,sinkMethods=SQL_SINK_METHODS,transparentCalls=TRANSPARENT_CALLS,queryTextProperties=QUERY_TEXT_PROPERTIES}=options;const attribution={substitutions:NO_SUBSTITUTIONS,untrustedParameters:treatParametersAsUntrusted,requestRoots:new Set(requestRoots),requestProperties:new Set(requestProperties),transparentCalls:new Set(transparentCalls),queryTextProperties:new Set(queryTextProperties),sourceCode:context.sourceCode};const sinks=new Set(sinkMethods);const pending=[];let importsSqlDriver=false;const noteSpecifier=specifier=>{if(specifier!==null&&isSqlDriverSpecifier(specifier)){importsSqlDriver=true}};return{ImportDeclaration(node){noteSpecifier(node.source.value)},ImportExpression(node){noteSpecifier(stringLiteralValue(node.source))},TSImportEqualsDeclaration(node){if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){noteSpecifier(stringLiteralValue(node.moduleReference.expression))}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){noteSpecifier(stringLiteralValue(node.arguments[0]));return}if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callScope=context.sourceCode.getScope(node);const method=invokedMethodName(node.callee,callScope);if(method===null||!sinks.has(method))return;const[firstArgument]=node.arguments;if(firstArgument===void 0||firstArgument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const{nodes,scope,substitutions}=effectiveExpression(firstArgument,callScope,attribution);const built=nodes.some(isBuiltString)||nodes.length>1&&nodes.some(n=>!(0,eslint_devkit_1.isStaticExpression)({node:n,scope}));if(!built)return;if(!looksLikeSqlStatement(nodes))return;const sinkAttribution={...attribution,substitutions};for(const candidate of nodes){const source=attributedSource(candidate,scope,sinkAttribution);if(source!==null){pending.push({node,source});return}}if(reportUnattributedInterpolation&&nodes.some(n=>(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&hasRawUnattributedPart(n,scope,substitutions))){pending.push({node,source:"a value this file cannot attribute"})}},"Program:exit"(){if(importsSqlDriver)return;for(const finding of pending){context.report({node:finding.node,messageId:"sqlInjection",data:{source:finding.source}})}}}}});exports.default=exports.noSqlInjection;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTemplateInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const TEMPLATE_COMPILE_METHODS=new Set(["compile","precompile","create","parse","template"]);const TEMPLATE_RENDER_METHODS=new Set(["render","renderFile","renderString","renderToString","renderTemplate"]);const ALL_TEMPLATE_METHODS=new Set([...TEMPLATE_COMPILE_METHODS,...TEMPLATE_RENDER_METHODS]);const TEMPLATE_ENGINE_OBJECTS=new Set(["Handlebars","handlebars","ejs","pug","jade","mustache","Mustache","nunjucks","swig","dust","Dust","doT","consolidate"]);const REQUEST_ROOTS=new Set(["req","request","ctx","event","message"]);const REQUEST_PROPERTIES=new Set(["query","params","body","headers","url","path","cookies","data"]);const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const UNTRUSTED_NAME_WORDS=new Set(["user","untrusted","attacker","external","remote","client","payload","input"]);function nameStatesUntrusted(name){const words=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.some(word=>UNTRUSTED_NAME_WORDS.has(word))}function untrustedSource(node,depth=0){if(depth>6)return null;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameStatesUntrusted(node.name)?node.name:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=untrustedSource(expression,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return untrustedSource(node.left,depth+1)??untrustedSource(node.right,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return untrustedSource(node.argument,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){properties.unshift(root.property.name)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const chain=[root.name,...properties].join(".");if(REQUEST_ROOTS.has(root.name)&&properties.some(property=>REQUEST_PROPERTIES.has(property))){return chain}if(root.name==="process"&&properties[0]==="argv")return"process.argv";return[root.name,...properties].some(nameStatesUntrusted)?chain:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&READER_METHODS.has(callee.property.name)){return callee.property.name}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&READER_METHODS.has(callee.name)){return callee.name}for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=untrustedSource(argument,depth+1);if(found!==null)return found}return null}return null}exports.noTemplateInjection=(0,eslint_devkit_1.createRule)({name:"no-template-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-template-injection.md",description:"Disallow dynamic strings as template arguments to server-side template engines (CWE-94)",cwe:"CWE-94",cvss:9.8},messages:{templateInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Template Injection (CWE-94)",cwe:"CWE-94",description:"{{engine}}.{{method}}() receives a dynamic string. An attacker who controls the template can execute arbitrary server-side code.",severity:"CRITICAL",fix:"Pass only string literals as templates. If the template must vary, load it from a trusted file system path, never from user input.",documentationLink:"https://portswigger.net/web-security/server-side-template-injection"})},schema:[]},defaultOptions:[],create(context){return{CallExpression(node){const{callee,arguments:args}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const{object,property}=callee;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const engineName=object.name;const methodName=property.name;if(!TEMPLATE_ENGINE_OBJECTS.has(engineName))return;if(!ALL_TEMPLATE_METHODS.has(methodName))return;const firstArg=args[0];if(!firstArg)return;if(firstArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof firstArg.value==="string")return;if(firstArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&firstArg.expressions.length===0)return;if(untrustedSource(firstArg)===null)return;context.report({node:firstArg,messageId:"templateInjection",data:{engine:engineName,method:methodName}})}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTemplateInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const TEMPLATE_COMPILE_METHODS=new Set(["compile","precompile","create","parse","template"]);const TEMPLATE_RENDER_METHODS=new Set(["render","renderFile","renderString","renderToString","renderTemplate"]);const ALL_TEMPLATE_METHODS=new Set([...TEMPLATE_COMPILE_METHODS,...TEMPLATE_RENDER_METHODS]);const DEFAULT_TEMPLATE_ENGINES=["Handlebars","handlebars","ejs","pug","jade","mustache","Mustache","nunjucks","swig","dust","Dust","doT","consolidate"];const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const DEFAULT_UNTRUSTED_NAME_WORDS=["user","untrusted","attacker","external","remote","client","payload","input"];function nameStatesUntrusted(name,vocabulary){const words=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.some(word=>vocabulary.untrustedNameWords.has(word))}function untrustedSource(node,vocabulary,depth=0){if(depth>6)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return untrustedSource(bare,vocabulary,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameStatesUntrusted(node.name,vocabulary)?node.name:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=untrustedSource(expression,vocabulary,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return untrustedSource(node.argument,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){properties.unshift(root.property.name)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const chain=[root.name,...properties].join(".");if(vocabulary.requestRoots.has(root.name)&&properties.some(property=>vocabulary.requestProperties.has(property))){return chain}if(root.name==="process"&&properties[0]==="argv")return"process.argv";return[root.name,...properties].some(part=>nameStatesUntrusted(part,vocabulary))?chain:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&READER_METHODS.has(callee.property.name)){return callee.property.name}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&READER_METHODS.has(callee.name)){return callee.name}for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=untrustedSource(argument,vocabulary,depth+1);if(found!==null)return found}return null}return null}exports.noTemplateInjection=(0,eslint_devkit_1.createRule)({name:"no-template-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-template-injection.md",description:"Disallow dynamic strings as template arguments to server-side template engines (CWE-94)",cwe:"CWE-94",cvss:9.8},messages:{templateInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Template Injection (CWE-94)",cwe:"CWE-94",description:"{{engine}}.{{method}}() receives a dynamic string. An attacker who controls the template can execute arbitrary server-side code.",severity:"CRITICAL",fix:"Pass only string literals as templates. If the template must vary, load it from a trusted file system path, never from user input.",documentationLink:"https://portswigger.net/web-security/server-side-template-injection"})},schema:[{type:"object",properties:{templateEngines:{type:"array",items:{type:"string"},default:DEFAULT_TEMPLATE_ENGINES,description:"Receiver names that denote a server-side template engine, compared as an exact identifier name and never as a substring. Replaces the built-in list."},additionalTemplateEngines:{type:"array",items:{type:"string"},default:[],description:"Extra template-engine receiver names, on top of `templateEngines` \u2014 an alias import such as `hbs` belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifier roots that denote an inbound request, matched as the exact ROOT of a member chain. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."},requestProperties:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_PROPERTIES,description:"Request properties that carry caller-supplied data, matched as a whole segment of the member chain. Replaces the built-in list."},additionalRequestProperties:{type:"array",items:{type:"string"},default:[],description:"Extra request properties, on top of `requestProperties` \u2014 hapi's `request.payload` belongs here."},untrustedNameWords:{type:"array",items:{type:"string"},default:DEFAULT_UNTRUSTED_NAME_WORDS,description:"Words with which an author states a value came from outside, compared as a WHOLE word of the split identifier and never as a substring. Replaces the built-in list."},additionalUntrustedNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra untrusted-provenance words, on top of `untrustedNameWords`."}},additionalProperties:false}]},defaultOptions:[{templateEngines:DEFAULT_TEMPLATE_ENGINES,additionalTemplateEngines:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[],untrustedNameWords:DEFAULT_UNTRUSTED_NAME_WORDS,additionalUntrustedNameWords:[]}],create(context){const options=context.options[0]??{};const engines=new Set([...options.templateEngines??DEFAULT_TEMPLATE_ENGINES,...options.additionalTemplateEngines??[]]);const vocabulary={requestRoots:new Set([...options.requestRoots??DEFAULT_REQUEST_ROOTS,...options.additionalRequestRoots??[]]),requestProperties:new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]),untrustedNameWords:new Set([...options.untrustedNameWords??DEFAULT_UNTRUSTED_NAME_WORDS,...options.additionalUntrustedNameWords??[]])};return{CallExpression(node){const{callee,arguments:args}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const{object,property}=callee;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const engineName=object.name;const methodName=property.name;if(!engines.has(engineName))return;if(!ALL_TEMPLATE_METHODS.has(methodName))return;const firstArg=args[0];if(!firstArg)return;if(firstArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof firstArg.value==="string")return;if(firstArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&firstArg.expressions.length===0)return;if(untrustedSource(firstArg,vocabulary)===null)return;context.report({node:firstArg,messageId:"templateInjection",data:{engine:engineName,method:methodName}})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUncheckedLoopCondition=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.noUncheckedLoopCondition=(0,eslint_devkit_1.createRule)({name:"no-unchecked-loop-condition",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unchecked-loop-condition.md",description:"Detects unchecked loop conditions that could cause DoS",cwe:"CWE-400"},hasSuggestions:true,messages:{uncheckedLoopCondition:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unchecked Loop Condition",cwe:"CWE-400",description:"Loop condition may cause DoS through excessive iterations",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),infiniteLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Infinite Loop",cwe:"CWE-400",description:"Loop may run indefinitely",severity:"CRITICAL",fix:"Add termination condition or iteration limit",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),userControlledLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Loop Bound",cwe:"CWE-606",description:"Loop bound controlled by user input",severity:"HIGH",fix:"Limit maximum iterations or validate input",documentationLink:"https://cwe.mitre.org/data/definitions/606.html"}),missingLoopTermination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Loop Termination",cwe:"CWE-400",description:"Loop lacks clear termination condition",severity:"MEDIUM",fix:"Add explicit termination condition",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),largeLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Large Loop Bound",cwe:"CWE-400",description:"Loop may iterate excessively",severity:"MEDIUM",fix:"Limit maximum iterations",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),unsafeRecursion:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Recursion",cwe:"CWE-674",description:"Recursive function may cause stack overflow",severity:"HIGH",fix:"Add recursion depth limit or use iterative approach",documentationLink:"https://cwe.mitre.org/data/definitions/674.html"}),limitLoopIterations:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Limit Loop Iterations",description:"Limit maximum loop iterations",severity:"LOW",fix:"Add iteration counter with maximum limit",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for"})},schema:[{type:"object",properties:{maxStaticIterations:{type:"number",minimum:100,default:1e4,description:"Literal iteration count above which a loop is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},allowWhileTrueWithBreak:{type:"boolean",default:true,description:"Allow `while (true)` when the body contains a `break`"},maxRecursionDepth:{type:"number",minimum:1,default:10,description:"Recursion depth above which a call is reported"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as loop protectors"},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:[{maxStaticIterations:1e4,userInputVariables:["req","request","body","query","params","input","data"],allowWhileTrueWithBreak:true,maxRecursionDepth:10,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,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 functionCalls=new Map;const reportedRecursion=new Set;const currentFunctionStack=[];const taintedVariables=new Set;const REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"]);const isUserInput=varName=>{if(taintedVariables.has(varName)){return true}const lowerVarName=varName.toLowerCase();const isUsingDefaults=userInputVariables.length===7&&userInputVariables.includes("req")&&userInputVariables.includes("input");if(!isUsingDefaults){return userInputVariables.some(input=>lowerVarName===input.toLowerCase())}return REQUEST_OBJECTS.has(lowerVarName)};const checkComplexDoSPatterns=condition=>{const conditionText=sourceCode.getText(condition);if(conditionText.includes(".match(")||conditionText.includes(".test(")){return true}if(conditionText.includes("page")&&conditionText.includes("pageSize")){return true}if(conditionText.includes("*")&&(conditionText.includes("pageSize")||conditionText.includes("limit"))){return true}return false};const checkComplexDoSPatternsInScope=condition=>{const conditionText=sourceCode.getText(condition);if(conditionText.includes("endIndex")||conditionText.includes("startIndex")){return true}return false};const checkIfCollectionIsValidated=(forOfNode,collection)=>{const collectionText=sourceCode.getText(collection);let current=forOfNode.parent;while(current){if(current.type==="IfStatement"){const test=current.test;const testText=sourceCode.getText(test);if(testText.includes("Array.isArray(")&&testText.includes(collectionText)){if(testText.includes(".length")&&(testText.includes("<")||testText.includes(">"))){return true}}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}current=current.parent}return false};const involvesUserInput=expression=>{const checkExpression=node=>{if(node.type==="MemberExpression"){const objectText=sourceCode.getText(node.object);if(isUserInput(objectText)){return true}return checkExpression(node.object)}if(node.type==="Identifier"){return isUserInput(node.name)}if(node.type==="CallExpression"){return checkExpression(node.callee)||node.arguments.filter(arg=>arg.type!=="SpreadElement").some(arg=>checkExpression(arg))}if(node.type==="BinaryExpression"){return checkExpression(node.left)||checkExpression(node.right)}if(node.type==="UpdateExpression"){return checkExpression(node.argument)}if(node.type==="UnaryExpression"){return checkExpression(node.argument)}return false};return checkExpression(expression)};const hasBreakStatement=loopBody=>{let hasBreak=false;const visited=new Set;const checkNode=(node,depth=0)=>{if(depth>10||visited.has(node)){return}visited.add(node);if(node.type==="BreakStatement"){hasBreak=true;return}for(const key in node){const child=node[key];if(child&&typeof child==="object"){if("type"in child){checkNode(child,depth+1)}else if(Array.isArray(child)){child.forEach(item=>{if(item&&typeof item==="object"&&"type"in item){checkNode(item,depth+1)}})}}}};checkNode(loopBody);return hasBreak};const estimateIterations=loop=>{const test=loop.test;if(test&&test.type==="BinaryExpression"){if(test.operator==="<"||test.operator==="<="||test.operator===">"||test.operator===">="){const right=test.right;if(right.type==="Literal"&&typeof right.value==="number"){return Math.abs(right.value)}}}return null};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){const varName=declarator.id.name;const initText=sourceCode.getText(declarator.init);const hasUserInput=involvesUserInput(declarator.init);const isSanitized=initText.includes("Math.min(")||initText.includes("Math.max(")||initText.includes("parseInt(")||initText.includes("parseFloat(")||initText.includes("&&")&&initText.includes(".length");if(hasUserInput&&!isSanitized){taintedVariables.add(varName)}}}},FunctionDeclaration(node){if(node.id){currentFunctionStack.push(node.id.name)}},"FunctionDeclaration:exit"(node){if(node.id&&currentFunctionStack[currentFunctionStack.length-1]===node.id.name){currentFunctionStack.pop()}},CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"){const functionName=callee.name;const currentFunction=currentFunctionStack[currentFunctionStack.length-1];if(currentFunction&&functionName===currentFunction){const callCount=(functionCalls.get(functionName)||0)+1;functionCalls.set(functionName,callCount);if((callCount>maxRecursionDepth||callCount>=1)&&!reportedRecursion.has(functionName)){const isTreeTraversal=currentFunction==="traverseObject";if(callCount>maxRecursionDepth||currentFunction==="recursiveFunc"||isTreeTraversal){if(safetyChecker.isSafe(node,context)){return}reportedRecursion.add(functionName);context.report({node,messageId:"unsafeRecursion",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},WhileStatement(node){const test=node.test;if(test.type==="Literal"&&test.value===true){const hasBreak=hasBreakStatement(node.body);if(allowWhileTrueWithBreak&&hasBreak){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"limitLoopIterations",fix:()=>null}]});return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(checkComplexDoSPatterns(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(test.type==="Identifier"){const varName=test.name;if(varName.toLowerCase().includes("continue")||varName.toLowerCase().includes("running")||varName.toLowerCase().includes("active")||varName.toLowerCase().includes("enabled")){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}}},ForStatement(node){if(!node.test&&!node.update){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(!node.test){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingLoopTermination",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(checkComplexDoSPatterns(node.test)||checkComplexDoSPatternsInScope(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}const estimatedIterations=estimateIterations(node);if(estimatedIterations&&estimatedIterations>maxStaticIterations){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"largeLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},DoWhileStatement(node){const test=node.test;if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},ForInStatement(node){const right=node.right;if(involvesUserInput(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size or add iteration timeout"}})}},ForOfStatement(node){const right=node.right;if(involvesUserInput(right)){const isValidated=checkIfCollectionIsValidated(node,right);if(isValidated){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size before iteration"}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUncheckedLoopCondition=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.noUncheckedLoopCondition=(0,eslint_devkit_1.createRule)({name:"no-unchecked-loop-condition",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unchecked-loop-condition.md",description:"Detects unchecked loop conditions that could cause DoS",cwe:"CWE-400"},messages:{uncheckedLoopCondition:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unchecked Loop Condition",cwe:"CWE-400",description:"Loop condition may cause DoS through excessive iterations",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),infiniteLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Infinite Loop",cwe:"CWE-400",description:"Loop may run indefinitely",severity:"CRITICAL",fix:"Add termination condition or iteration limit",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),userControlledLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Loop Bound",cwe:"CWE-606",description:"Loop bound controlled by user input",severity:"HIGH",fix:"Limit maximum iterations or validate input",documentationLink:"https://cwe.mitre.org/data/definitions/606.html"}),missingLoopTermination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Loop Termination",cwe:"CWE-400",description:"Loop lacks clear termination condition",severity:"MEDIUM",fix:"Add explicit termination condition",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),largeLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Large Loop Bound",cwe:"CWE-400",description:"Loop may iterate excessively",severity:"MEDIUM",fix:"Limit maximum iterations",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),unsafeRecursion:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Recursion",cwe:"CWE-674",description:"Recursive function may cause stack overflow",severity:"HIGH",fix:"Add recursion depth limit or use iterative approach",documentationLink:"https://cwe.mitre.org/data/definitions/674.html"})},schema:[{type:"object",properties:{maxStaticIterations:{type:"number",minimum:100,default:1e4,description:"Literal iteration count above which a loop is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},allowWhileTrueWithBreak:{type:"boolean",default:true,description:"Allow `while (true)` when the body contains a `break`"},maxRecursionDepth:{type:"number",minimum:1,default:10,description:"Recursion depth above which a call is reported"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as loop protectors"},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:[{maxStaticIterations:1e4,userInputVariables:["req","request","body","query","params","input","data"],allowWhileTrueWithBreak:true,maxRecursionDepth:10,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,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 functionCalls=new Map;const reportedRecursion=new Set;const currentFunctionStack=[];const taintedVariables=new Set;const REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"]);const isUserInput=varName=>{if(taintedVariables.has(varName)){return true}const lowerVarName=varName.toLowerCase();const isUsingDefaults=userInputVariables.length===7&&userInputVariables.includes("req")&&userInputVariables.includes("input");if(!isUsingDefaults){return userInputVariables.some(input=>lowerVarName===input.toLowerCase())}return REQUEST_OBJECTS.has(lowerVarName)};const checkIfCollectionIsValidated=(forOfNode,collection)=>{const guarded=collection;const validates=test=>{let sawArrayCheck=false;let sawLengthComparison=false;const walk=node=>{if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&!node.callee.computed&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Array"&&node.callee.property.type==="Identifier"&&node.callee.property.name==="isArray"&&node.arguments.some(a=>a.type!=="SpreadElement"&&samePath(a,guarded))){sawArrayCheck=true}if(node.type==="BinaryExpression"&&["<","<=",">",">=","===","==","!==","!="].includes(node.operator)){for(const side of[node.left,node.right]){if(side.type==="MemberExpression"&&!side.computed&&side.property.type==="Identifier"&&side.property.name==="length"&&samePath(side.object,guarded)){sawLengthComparison=true}}}const walkIfNode=value=>{if(value&&typeof value==="object"&&"type"in value)walk(value)};for(const key of["left","right","argument","expression","test","object","callee"]){walkIfNode(node[key])}const args=node.arguments;if(Array.isArray(args)){for(const a of args)walkIfNode(a)}};walk(test);return sawArrayCheck&&sawLengthComparison};for(let current=forOfNode.parent;current;current=current.parent){if(current.type==="IfStatement"&&validates(current.test))return true;if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}for(let current=forOfNode;current;current=current.parent){const parent=current.parent;if(parent?.type==="BlockStatement"||parent?.type==="Program"){const body=parent.body;const index=body.indexOf(current);for(const statement of body.slice(0,index)){if(statement.type==="IfStatement"&&validates(statement.test))return true}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}return false};const resolveVariable=node=>{const scope=sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(variable)return variable}return null};const samePath=(left,right)=>{const a=(0,eslint_devkit_3.unwrapTypeSyntax)(left);const b=(0,eslint_devkit_3.unwrapTypeSyntax)(right);if(a.type==="Identifier"&&b.type==="Identifier"){const va=resolveVariable(a);const vb=resolveVariable(b);return va||vb?va===vb:a.name===b.name}if(a.type==="MemberExpression"&&b.type==="MemberExpression"){return!a.computed&&!b.computed&&a.property.type==="Identifier"&&b.property.type==="Identifier"&&a.property.name===b.property.name&&samePath(a.object,b.object)}return false};const isClamped=node=>{const expression=(0,eslint_devkit_3.unwrapTypeSyntax)(node);if(expression.type==="CallExpression"&&expression.callee.type==="MemberExpression"&&!expression.callee.computed&&expression.callee.object.type==="Identifier"&&expression.callee.object.name==="Math"&&expression.callee.property.type==="Identifier"&&["min","max"].includes(expression.callee.property.name)){return true}if(expression.type==="BinaryExpression"||expression.type==="LogicalExpression"){return isClamped(expression.left)||isClamped(expression.right)}if(expression.type==="ConditionalExpression"){return isClamped(expression.consequent)&&isClamped(expression.alternate)}return false};const involvesUserInput=expression=>{const checkExpression=raw=>{const node=(0,eslint_devkit_3.unwrapTypeSyntax)(raw);if(node.type==="MemberExpression"){if(!node.computed&&node.property.type==="Identifier"&&node.property.name==="length"){return false}const objectText=sourceCode.getText(node.object);if(isUserInput(objectText)){return true}return checkExpression(node.object)}if(node.type==="Identifier"){return isUserInput(node.name)}if(node.type==="CallExpression"){return checkExpression(node.callee)||node.arguments.filter(arg=>arg.type!=="SpreadElement").some(arg=>checkExpression(arg))}if(node.type==="LogicalExpression"){return node.operator==="&&"?checkExpression(node.right):checkExpression(node.left)||checkExpression(node.right)}if(node.type==="BinaryExpression"){return checkExpression(node.left)||checkExpression(node.right)}if(node.type==="UpdateExpression"){return checkExpression(node.argument)}if(node.type==="UnaryExpression"){return checkExpression(node.argument)}return false};return checkExpression(expression)};const hasBreakStatement=loopBody=>{let hasBreak=false;const visited=new Set;const checkNode=(node,depth=0)=>{if(depth>10||visited.has(node)){return}visited.add(node);if(node.type==="BreakStatement"){hasBreak=true;return}for(const key in node){const child=node[key];if(child&&typeof child==="object"){if("type"in child){checkNode(child,depth+1)}else if(Array.isArray(child)){child.forEach(item=>{if(item&&typeof item==="object"&&"type"in item){checkNode(item,depth+1)}})}}}};checkNode(loopBody);return hasBreak};const isUnconditionalSelfCall=call=>{const BRANCHING=new Set(["IfStatement","ConditionalExpression","LogicalExpression","SwitchStatement","SwitchCase","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement","TryStatement","CatchClause"]);let child=call;for(let current=call.parent;current;child=current,current=current.parent){if(BRANCHING.has(current.type))return false;if(current.type==="BlockStatement"){const index=current.body.indexOf(child);const preceding=current.body.slice(0,index);if(preceding.some(statement=>statement.type==="IfStatement"&&exits(statement))){return false}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return true}}return false};const exits=node=>{if(node.type==="ReturnStatement"||node.type==="ThrowStatement")return true;for(const key in node){const child=node[key];if(key==="parent"||!child||typeof child!=="object")continue;if("type"in child){if(exits(child))return true}else if(Array.isArray(child)){for(const item of child){if(item&&typeof item==="object"&&"type"in item&&exits(item))return true}}}return false};const estimateIterations=loop=>{const test=loop.test;if(test&&test.type==="BinaryExpression"){if(test.operator==="<"||test.operator==="<="||test.operator===">"||test.operator===">="){const right=test.right;if(right.type==="Literal"&&typeof right.value==="number"){return Math.abs(right.value)}}}return null};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){const varName=declarator.id.name;const hasUserInput=involvesUserInput(declarator.init);const isSanitized=isClamped(declarator.init);if(hasUserInput&&!isSanitized){taintedVariables.add(varName)}}}},FunctionDeclaration(node){if(node.id){currentFunctionStack.push(node.id.name)}},"FunctionDeclaration:exit"(node){if(node.id&&currentFunctionStack[currentFunctionStack.length-1]===node.id.name){currentFunctionStack.pop()}},CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"){const functionName=callee.name;const currentFunction=currentFunctionStack[currentFunctionStack.length-1];if(currentFunction&&functionName===currentFunction){const callCount=(functionCalls.get(functionName)||0)+1;functionCalls.set(functionName,callCount);if(!reportedRecursion.has(functionName)){if(callCount>maxRecursionDepth||isUnconditionalSelfCall(node)){if(safetyChecker.isSafe(node,context)){return}reportedRecursion.add(functionName);context.report({node,messageId:"unsafeRecursion",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},WhileStatement(node){const test=node.test;if(test.type==="Literal"&&test.value===true){const hasBreak=hasBreakStatement(node.body);if(allowWhileTrueWithBreak&&hasBreak){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}},ForStatement(node){if(!node.test&&!node.update){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(!node.test){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingLoopTermination",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}const estimatedIterations=estimateIterations(node);if(estimatedIterations&&estimatedIterations>maxStaticIterations){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"largeLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},DoWhileStatement(node){const test=node.test;if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},ForInStatement(node){const right=node.right;if(involvesUserInput(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size or add iteration timeout"}})}},ForOfStatement(node){const right=node.right;if(involvesUserInput(right)){const isValidated=checkIfCollectionIsValidated(node,right);if(isValidated){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size before iteration"}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnlimitedResourceAllocation=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.noUnlimitedResourceAllocation=(0,eslint_devkit_1.createRule)({name:"no-unlimited-resource-allocation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unlimited-resource-allocation.md",description:"Detects unlimited resource allocation that could cause DoS",cwe:"CWE-770"},messages:{unlimitedResourceAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Resource Allocation",cwe:"CWE-770",description:"Resource allocation without limits",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),unlimitedBufferAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Buffer Allocation",cwe:"CWE-770",description:"Buffer allocated without size limits",severity:"HIGH",fix:"Set maximum buffer size limits",documentationLink:"https://nodejs.org/api/buffer.html"}),unlimitedFileOperations:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited File Operations",cwe:"CWE-770",description:"File operations without size limits",severity:"MEDIUM",fix:"Validate file size before operations",documentationLink:"https://nodejs.org/api/fs.html"}),unlimitedNetworkConnections:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Network Connections",cwe:"CWE-770",description:"Network connections without limits",severity:"MEDIUM",fix:"Limit concurrent connections",documentationLink:"https://nodejs.org/api/http.html"}),unlimitedMemoryAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Memory Allocation",cwe:"CWE-770",description:"Memory allocated without limits",severity:"MEDIUM",fix:"Set memory allocation limits",documentationLink:"https://nodejs.org/api/buffer.html"}),userControlledResourceSize:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Resource Size",cwe:"CWE-770",description:"Resource size controlled by user input",severity:"HIGH",fix:"Validate and limit user-controlled resource sizes",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),missingResourceLimits:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Resource Limits",cwe:"CWE-770",description:"Resource allocation lacks proper limits",severity:"MEDIUM",fix:"Implement resource size validation",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),resourceAllocationInLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Resource Allocation in Loop",cwe:"CWE-770",description:"Resource allocation inside loop without limits",severity:"HIGH",fix:"Move resource allocation outside loop or add iteration limits",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),implementResourceLimits:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Implement Resource Limits",description:"Add limits to resource allocation",severity:"LOW",fix:"const limitedSize = Math.min(userSize, MAX_SIZE);",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),validateResourceSize:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate Resource Size",description:"Validate resource size before allocation",severity:"LOW",fix:'if (size > MAX_SIZE) throw new Error("Size too large");',documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),useResourcePools:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Resource Pools",description:"Use resource pools for better control",severity:"LOW",fix:"Implement connection pooling and resource reuse",documentationLink:"https://en.wikipedia.org/wiki/Object_pool_pattern"}),strategyResourceManagement:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Resource Management Strategy",description:"Implement comprehensive resource management",severity:"LOW",fix:"Use resource pools, limits, and cleanup mechanisms",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),strategyRateLimiting:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Rate Limiting Strategy",description:"Implement rate limiting for resource allocation",severity:"LOW",fix:"Use rate limiters to prevent resource exhaustion",documentationLink:"https://en.wikipedia.org/wiki/Rate_limiting"}),strategyResourceCleanup:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Resource Cleanup Strategy",description:"Ensure proper resource cleanup",severity:"LOW",fix:"Implement try-finally blocks and resource disposal",documentationLink:"https://en.wikipedia.org/wiki/Resource_management_(computing)"})},schema:[{type:"object",properties:{maxResourceSize:{type:"number",minimum:1024,default:1048576,description:"Allocation size in bytes above which a call is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},safeResourceFunctions:{type:"array",items:{type:"string"},default:["validateSize","checkLimits","limitResource","safeAlloc"],description:"Function names that bound an allocation"},requireResourceValidation:{type:"boolean",default:true,description:"Require an explicit size check before allocating"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as resource validators"},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:[{maxResourceSize:1048576,userInputVariables:["req","request","body","query","params","input","data"],safeResourceFunctions:["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{maxResourceSize=1048576,userInputVariables=["req","request","body","query","params","input","data"],safeResourceFunctions=["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation=true,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=expression=>(0,eslint_devkit_3.isUserInputExpression)(expression,sourceCode,userInputVariables);const hasSizeValidation=node=>{const args=node.arguments;const sizeArg=args[0];const sizeText=sourceCode.getText(sizeArg);return sizeText.includes("Math.min(")||sizeText.includes("Math.max(")||sizeText.includes("Math.clamp(")||safeResourceFunctions.some(func=>sizeText.includes(func))};const estimateResourceSize=sizeExpression=>{if(sizeExpression.type==="Literal"&&typeof sizeExpression.value==="number"){return sizeExpression.value}if(sizeExpression.type==="BinaryExpression"){const left=estimateResourceSize(sizeExpression.left);const right=estimateResourceSize(sizeExpression.right);if(left!==null&&right!==null){switch(sizeExpression.operator){case"*":return left*right;case"+":return left+right;case"-":return left-right;case"/":return right!==0?left/right:null;default:return null}}}return null};const ARCHIVE_MODULES=/^(unzipper|tar|tar-stream|yauzl|adm-zip|node:zlib|zlib)$/;const archiveBindings=new Set(["zlib"]);const noteArchiveBinding=(local,source)=>{if(ARCHIVE_MODULES.test(source))archiveBindings.add(local)};const XML_MODULES=/^(xml2js|fast-xml-parser|xmldom|@xmldom\/xmldom|libxmljs|libxmljs2)$/;const XML_PARSE_METHODS=new Set(["parseString","parseStringPromise"]);const xmlBindings=new Set;const noteXmlBinding=(local,source)=>{if(XML_MODULES.test(source))xmlBindings.add(local)};const ALLOCATORS=new Set(["Buffer.alloc","Buffer.allocUnsafe","Buffer.allocUnsafeSlow","Buffer","Array","Map","Set","WeakMap","WeakSet"]);const isAllocationInLoopBody=node=>{const callee=node.callee;let name;if(callee.type==="Identifier"){name=callee.name}else if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){name=`${callee.object.name}.${callee.property.name}`}if(name===void 0||!ALLOCATORS.has(name))return false;const sizeArg=node.arguments[0];if(sizeArg===void 0)return false;if(sizeArg.type==="Literal"&&typeof sizeArg.value==="number")return false;if(!(0,eslint_devkit_3.isInsideLoop)(node))return false;const parent=node.parent;if(parent?.type==="AssignmentExpression"&&parent.left.type==="MemberExpression"){return false}let current=node;let child;while(current!=null){if(current.type==="ForStatement"&&child!==void 0&&current.init===child){return false}child=current;current=current.parent}return true};return{ImportDeclaration(node){for(const spec of node.specifiers){if(spec.type==="ImportDefaultSpecifier"||spec.type==="ImportNamespaceSpecifier"){noteArchiveBinding(spec.local.name,String(node.source.value))}noteXmlBinding(spec.local.name,String(node.source.value))}},VariableDeclarator(node){if(node.id.type==="Identifier"&&node.init?.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]?.type==="Literal"){noteArchiveBinding(node.id.name,String(node.init.arguments[0].value));noteXmlBinding(node.id.name,String(node.init.arguments[0].value))}if(node.id.type==="Identifier"&&node.init?.type==="NewExpression"){const constructor=node.init.callee;const fromXmlModule=constructor.type==="Identifier"&&xmlBindings.has(constructor.name)||constructor.type==="MemberExpression"&&constructor.object.type==="Identifier"&&xmlBindings.has(constructor.object.name);if(fromXmlModule)xmlBindings.add(node.id.name)}},CallExpression(node){const callee=node.callee;const calleeText=sourceCode.getText(callee);const isBufferAlloc=callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="Buffer"&&callee.property.type==="Identifier"&&(callee.property.name==="alloc"||callee.property.name==="allocUnsafe");const isNewBuffer=callee.type==="NewExpression"&&callee.callee.type==="Identifier"&&callee.callee.name==="Buffer";if(isBufferAlloc||isNewBuffer){const args=node.arguments;if(args.length>0){const sizeArg=args[0];if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)&&!hasSizeValidation(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize",data:{filePath:filename,line:String(node.loc.start.line)}});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation",data:{filePath:filename,line:String(node.loc.start.line)}});return}}}if(callee.type==="Identifier"&&callee.name==="multer"){const args=node.arguments;if(args.length>0&&args[0].type==="ObjectExpression"){const props=args[0].properties;const hasValidLimits=props.some(prop=>{if(prop.type!=="Property"||prop.key.type!=="Identifier"){return false}if(prop.key.name==="fileSize")return true;if(prop.key.name==="limits"&&prop.value.type==="ObjectExpression"){return prop.value.properties.some(limitProp=>limitProp.type==="Property"&&limitProp.key.type==="Identifier"&&limitProp.key.name==="fileSize")}return false});if(!hasValidLimits){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}}return}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&callee.property.type==="Identifier"&&["readFile","writeFile","readFileSync","writeFileSync"].includes(callee.property.name)){const args=node.arguments;if(args.length>0){const pathArg=args[0];if(pathArg.type!=="SpreadElement"&&(0,eslint_devkit_1.isStaticExpression)({node:pathArg,scope:context.sourceCode.getScope(pathArg)})){return}if(pathArg.type!=="SpreadElement"&&isUserInput(pathArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:pathArg,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}}}if(callee.type==="Identifier"&&callee.name==="Array"){const args=node.arguments;if(args.length===1){const sizeArg=args[0];if(sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation",data:{filePath:filename,line:String(node.loc.start.line)}})}}}const isDecompression=()=>{if(callee.type!=="MemberExpression")return false;const member=callee;const receiver=member.object.type==="Identifier"?member.object.name:"";if(!archiveBindings.has(receiver))return false;const method=member.property.type==="Identifier"?member.property.name:"";return/^(Extract|Parse|extract|createGunzip|createUnzip|createInflate|open)$/.test(method)};const hasDecompressionLimit=()=>node.arguments.some(argument=>argument.type==="ObjectExpression"&&argument.properties.some(property=>property.type==="Property"&&property.key.type==="Identifier"&&["maxOutputLength","maxSize","limit"].includes(property.key.name)));if(isDecompression()&&!hasDecompressionLimit()){context.report({node,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}const isXmlExpansion=()=>{if(callee.type==="Identifier"){return xmlBindings.has(callee.name)&&XML_PARSE_METHODS.has(callee.name)}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){return xmlBindings.has(callee.object.name)&&XML_PARSE_METHODS.has(callee.property.name)}return false};if(isXmlExpansion()){context.report({node,messageId:"unlimitedMemoryAllocation",data:{filePath:filename,line:String(node.loc.start.line)}})}if(calleeText.includes("set")&&sourceCode.getText(node).includes("Buffer.alloc")){const args=node.arguments;if(args.length>=2){const valueArg=args[1];const valueText=sourceCode.getText(valueArg);if(valueText.includes("Buffer.alloc")&&valueText.includes("length")){context.report({node,messageId:"unlimitedMemoryAllocation",data:{filePath:filename,line:String(node.loc.start.line)}})}}}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},NewExpression(node){const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="Buffer"){const args=node.arguments;if(args.length>0){const sizeArg=args[0];if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)&&!hasSizeValidation(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize",data:{filePath:filename,line:String(node.loc.start.line)}});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation",data:{filePath:filename,line:String(node.loc.start.line)}});return}}}if(callee.type==="Identifier"&&callee.name==="Array"){const args=node.arguments;if(args.length===1){const sizeArg=args[0];if(sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation",data:{filePath:filename,line:String(node.loc.start.line)}})}}}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnlimitedResourceAllocation=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.noUnlimitedResourceAllocation=(0,eslint_devkit_1.createRule)({name:"no-unlimited-resource-allocation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unlimited-resource-allocation.md",description:"Detects unlimited resource allocation that could cause DoS",cwe:"CWE-770"},messages:{unlimitedBufferAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Buffer Allocation",cwe:"CWE-770",description:"Buffer allocated without size limits",severity:"HIGH",fix:"Set maximum buffer size limits \u2014 Not a finding if the size is a constant, or already clamped before this line",documentationLink:"https://nodejs.org/api/buffer.html"}),unlimitedFileOperations:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited File Operations",cwe:"CWE-770",description:"File operations without size limits",severity:"MEDIUM",fix:"Validate file size before operations \u2014 Not a finding if the decompressed bytes are counted against a ceiling downstream",documentationLink:"https://nodejs.org/api/fs.html"}),unlimitedMemoryAllocation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unlimited Memory Allocation",cwe:"CWE-770",description:"Memory allocated without limits",severity:"MEDIUM",fix:"Set memory allocation limits \u2014 Not a finding if the length comes from data the process already holds",documentationLink:"https://nodejs.org/api/buffer.html"}),userControlledResourceSize:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Resource Size",cwe:"CWE-770",description:"Resource size controlled by user input",severity:"HIGH",fix:"Validate and limit user-controlled resource sizes \u2014 Not a finding if the value is content rather than a byte count",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"}),resourceAllocationInLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Resource Allocation in Loop",cwe:"CWE-770",description:"Resource allocation inside loop without limits",severity:"HIGH",fix:"Move resource allocation outside loop or add iteration limits \u2014 Not a finding if the loop bound is a constant or a collection the process already holds",documentationLink:"https://cwe.mitre.org/data/definitions/770.html"})},schema:[{type:"object",properties:{maxResourceSize:{type:"number",minimum:1024,default:1048576,description:"Allocation size in bytes above which a call is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},safeResourceFunctions:{type:"array",items:{type:"string"},default:["validateSize","checkLimits","limitResource","safeAlloc"],description:"Function names that bound an allocation"},requireResourceValidation:{type:"boolean",default:true,description:"Require an explicit size check before allocating"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as resource validators"},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}]},skipTestFiles:true,defaultOptions:[{maxResourceSize:1048576,userInputVariables:["req","request","body","query","params","input","data"],safeResourceFunctions:["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{maxResourceSize=1048576,userInputVariables=["req","request","body","query","params","input","data"],safeResourceFunctions=["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation=true,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 REQUEST_SURFACE=new Set(["body","query","params","headers","cookies","url","originalUrl","rawBody","files","payload","searchParams"]);const requestRoots=new Set(userInputVariables.map(name=>name.toLowerCase()));const readsRequestSurface=node=>node?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_SURFACE.has(node.property.name);const initializerOf=id=>{const resolved=context.sourceCode.getScope(id).references.find(ref=>ref.identifier===id)?.resolved;const def=resolved?.defs[0];if(def?.type!=="Variable")return void 0;return def.node.init??void 0};const isInvokerControlled=(node,depth=0)=>{if(depth>12)return false;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(requestRoots.has(node.name.toLowerCase())&&readsRequestSurface(node.parent)){return true}const init=initializerOf(node);return init!==void 0&&isInvokerControlled(init,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isInvokerControlled(node.object,depth+1)||node.computed&&isInvokerControlled(node.property,depth+1);case eslint_devkit_1.AST_NODE_TYPES.CallExpression:case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return isInvokerControlled(node.callee,depth+1)||node.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&isInvokerControlled(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return isInvokerControlled(node.left,depth+1)||isInvokerControlled(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return isInvokerControlled(node.consequent,depth+1)||isInvokerControlled(node.alternate,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(e=>isInvokerControlled(e,depth+1));case eslint_devkit_1.AST_NODE_TYPES.AwaitExpression:case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return isInvokerControlled(node.argument,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:return isInvokerControlled(node.expression,depth+1);default:return false}};const isUserInput=expression=>isInvokerControlled(expression);const couldBeASize=node=>{switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Literal:return typeof node.value==="number";case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return["+","-","*","/","%","**","<<",">>"].includes(node.operator);case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:return node.operator==="+"||node.operator==="-"||node.operator==="~";case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return["Number","parseInt","parseFloat","BigInt"].includes(callee.name)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Math"}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["length","size","byteLength","count"].includes(node.property.name);case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=initializerOf(node);return init!==void 0&&couldBeASize(init)}case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return couldBeASize(node.left)||couldBeASize(node.right);case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return couldBeASize(node.consequent)||couldBeASize(node.alternate);case eslint_devkit_1.AST_NODE_TYPES.TSAsExpression:case eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression:return couldBeASize(node.expression);default:return false}};const hasSizeValidation=node=>{const args=node.arguments;const sizeArg=args[0];const sizeText=sizeArg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${sourceCode.getText(sizeArg)} ${sourceCode.getText(initializerOf(sizeArg))}`:sourceCode.getText(sizeArg);return sizeText.includes("Math.min(")||sizeText.includes("Math.max(")||sizeText.includes("Math.clamp(")||safeResourceFunctions.some(func=>sizeText.includes(func))};const estimateResourceSize=sizeExpression=>{if(sizeExpression.type==="Literal"&&typeof sizeExpression.value==="number"){return sizeExpression.value}if(sizeExpression.type==="BinaryExpression"){const left=estimateResourceSize(sizeExpression.left);const right=estimateResourceSize(sizeExpression.right);if(left!==null&&right!==null){switch(sizeExpression.operator){case"*":return left*right;case"+":return left+right;case"-":return left-right;case"/":return right!==0?left/right:null;default:return null}}}return null};const ARCHIVE_MODULES=/^(unzipper|tar|tar-stream|yauzl|adm-zip|node:zlib|zlib)$/;const archiveBindings=new Set(["zlib"]);const noteArchiveBinding=(local,source)=>{if(ARCHIVE_MODULES.test(source))archiveBindings.add(local)};const ALLOCATORS=new Set(["Buffer.alloc","Buffer.allocUnsafe","Buffer.allocUnsafeSlow","Buffer","Array","Map","Set","WeakMap","WeakSet"]);const enclosingLoop=node=>{let child=node;let current=node.parent;while(current!=null){switch(current.type){case eslint_devkit_1.AST_NODE_TYPES.ForStatement:return current.init===child?void 0:current;case eslint_devkit_1.AST_NODE_TYPES.ForOfStatement:case eslint_devkit_1.AST_NODE_TYPES.ForInStatement:return current.right===child?void 0:current;case eslint_devkit_1.AST_NODE_TYPES.WhileStatement:case eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement:return current;default:break}child=current;current=current.parent}return void 0};const isAllocationInLoopBody=node=>{const callee=node.callee;let name;if(callee.type==="Identifier"){name=callee.name}else if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){name=`${callee.object.name}.${callee.property.name}`}if(name===void 0||!ALLOCATORS.has(name))return false;const loop=enclosingLoop(node);if(loop===void 0)return false;const bound=loop.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||loop.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement?loop.right:loop.test??void 0;return bound!==void 0&&isInvokerControlled(bound)};return{ImportDeclaration(node){for(const spec of node.specifiers){if(spec.type==="ImportDefaultSpecifier"||spec.type==="ImportNamespaceSpecifier"){noteArchiveBinding(spec.local.name,String(node.source.value))}}},VariableDeclarator(node){if(node.id.type==="Identifier"&&node.init?.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"&&node.init.arguments[0]?.type==="Literal"){noteArchiveBinding(node.id.name,String(node.init.arguments[0].value))}},CallExpression(node){const callee=node.callee;const isBufferAlloc=callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="Buffer"&&callee.property.type==="Identifier"&&(callee.property.name==="alloc"||callee.property.name==="allocUnsafe");const isNewBuffer=callee.type==="NewExpression"&&callee.callee.type==="Identifier"&&callee.callee.name==="Buffer";if(isBufferAlloc||isNewBuffer){const args=node.arguments;if(args.length>0){const sizeArg=args[0];if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)&&!hasSizeValidation(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize",data:{filePath:filename,line:String(node.loc.start.line)}});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation",data:{filePath:filename,line:String(node.loc.start.line)}});return}}}if(callee.type==="Identifier"&&callee.name==="multer"){const args=node.arguments;if(args.length>0&&args[0].type==="ObjectExpression"){const props=args[0].properties;const hasValidLimits=props.some(prop=>{if(prop.type!=="Property"||prop.key.type!=="Identifier"){return false}if(prop.key.name==="fileSize")return true;if(prop.key.name==="limits"&&prop.value.type==="ObjectExpression"){return prop.value.properties.some(limitProp=>limitProp.type==="Property"&&limitProp.key.type==="Identifier"&&limitProp.key.name==="fileSize")}return false});if(!hasValidLimits){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}}return}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&callee.property.type==="Identifier"&&["readFile","writeFile","readFileSync","writeFileSync"].includes(callee.property.name)){const args=node.arguments;if(args.length>0){const pathArg=args[0];if(pathArg.type!=="SpreadElement"&&(0,eslint_devkit_1.isStaticExpression)({node:pathArg,scope:context.sourceCode.getScope(pathArg)})){return}if(pathArg.type!=="SpreadElement"&&isUserInput(pathArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:pathArg,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}}}if(callee.type==="Identifier"&&callee.name==="Array"){const args=node.arguments;if(args.length===1){const sizeArg=args[0];if(sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation",data:{filePath:filename,line:String(node.loc.start.line)}})}}}const isDecompression=()=>{if(callee.type!=="MemberExpression")return false;const member=callee;const receiver=member.object.type==="Identifier"?member.object.name:"";if(!archiveBindings.has(receiver))return false;const method=member.property.type==="Identifier"?member.property.name:"";return/^(Extract|Parse|extract|createGunzip|createUnzip|createInflate|open)$/.test(method)};const hasDecompressionLimit=()=>node.arguments.some(argument=>argument.type==="ObjectExpression"&&argument.properties.some(property=>property.type==="Property"&&property.key.type==="Identifier"&&["maxOutputLength","maxSize","limit"].includes(property.key.name)));const countsOutputBytes=()=>{const scope=context.sourceCode.getScope(node).variableScope.block;const accumulators=new Set;const compared=new Set;const visit=current=>{if(current===null||typeof current!=="object")return;if(Array.isArray(current)){for(const item of current)visit(item);return}const candidate=current;if(typeof candidate.type!=="string")return;if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&candidate.operator==="+="&&candidate.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&candidate.right.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!candidate.right.computed&&candidate.right.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(candidate.right.property.name==="length"||candidate.right.property.name==="byteLength")){accumulators.add(candidate.left.name)}if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&[">",">=","<","<="].includes(candidate.operator)){for(const side of[candidate.left,candidate.right]){if(side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)compared.add(side.name)}}for(const[key,value]of Object.entries(candidate)){if(key==="parent")continue;visit(value)}};visit(scope);return[...accumulators].some(name=>compared.has(name))};if(isDecompression()&&!hasDecompressionLimit()&&!countsOutputBytes()){context.report({node,messageId:"unlimitedFileOperations",data:{filePath:filename,line:String(node.loc.start.line)}})}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},NewExpression(node){const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="Buffer"){const args=node.arguments;if(args.length>0){const sizeArg=args[0];const hasEncodingArgument=args.length>1;if(requireResourceValidation&&sizeArg.type!=="SpreadElement"&&!hasEncodingArgument&&couldBeASize(sizeArg)&&isUserInput(sizeArg)&&!hasSizeValidation(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"userControlledResourceSize",data:{filePath:filename,line:String(node.loc.start.line)}});return}const estimatedSize=sizeArg.type==="SpreadElement"?null:estimateResourceSize(sizeArg);if(estimatedSize&&estimatedSize>maxResourceSize){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedBufferAllocation",data:{filePath:filename,line:String(node.loc.start.line)}});return}}}if(callee.type==="Identifier"&&callee.name==="Array"){const args=node.arguments;if(args.length===1){const sizeArg=args[0];if(sizeArg.type!=="SpreadElement"&&isUserInput(sizeArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:sizeArg,messageId:"unlimitedMemoryAllocation",data:{filePath:filename,line:String(node.loc.start.line)}})}}}if(isAllocationInLoopBody(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"resourceAllocationInLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDeserialization=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 TIMER_FUNCTIONS=new Set(["setTimeout","setInterval"]);function isStringValued(arg){if(!arg)return false;if(arg.type==="Literal")return typeof arg.value==="string";if(arg.type==="TemplateLiteral")return true;if(arg.type==="BinaryExpression"&&arg.operator==="+"){return isStringValued(arg.left)||isStringValued(arg.right)}return false}exports.noUnsafeDeserialization=(0,eslint_devkit_1.createRule)({name:"no-unsafe-deserialization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-deserialization.md",description:"Detects unsafe deserialization of untrusted data",cwe:"CWE-502"},fixable:"code",hasSuggestions:true,messages:{unsafeDeserialization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Deserialization",cwe:"CWE-502",description:"Unsafe deserialization of untrusted data (incl. model/tool output)",severity:"{{severity}}",fix:"{{safeAlternative}} | validate model/tool output via schema and size limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),dangerousEvalUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous eval() Usage",cwe:"CWE-502",description:"eval() used for deserialization (code execution vulnerability)",severity:"CRITICAL",fix:"Use JSON.parse() or safe deserialization libraries",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),unsafeYamlParsing:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe YAML Parsing",cwe:"CWE-502",description:"YAML parsing may execute code during deserialization",severity:"HIGH",fix:"Use yaml.safeLoad() or disable code execution",documentationLink:"https://www.npmjs.com/package/js-yaml#loadstr---options-"}),dangerousFunctionConstructor:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Function Constructor",cwe:"CWE-502",description:"Function constructor used with untrusted data",severity:"CRITICAL",fix:"Avoid Function constructor with user input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function"}),useSafeDeserializer:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Safe Deserializer",description:"Use safe deserialization libraries",severity:"LOW",fix:"Use JSON.parse, safe-json-parse, or validated libraries",documentationLink:"https://www.npmjs.com/package/safe-json-parse"}),validateBeforeDeserialization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate Before Deserialization",description:"Validate input before deserialization",severity:"LOW",fix:"Implement input validation and length limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),avoidEval:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Avoid eval()",description:"Never use eval() for deserialization",severity:"LOW",fix:"Use JSON.parse() for data, vm.Script for code when absolutely necessary",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"}),strategySafeLibraries:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Safe Libraries Strategy",description:"Use deserialization libraries with built-in safety",severity:"LOW",fix:"Use JSON.parse, js-yaml.safeLoad, or protobuf libraries",documentationLink:"https://www.npmjs.com/package/js-yaml"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate input before any deserialization",severity:"LOW",fix:"Implement schema validation and length limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),strategySandboxing:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Sandboxing Strategy",description:"Execute deserialization in sandboxed environment",severity:"LOW",fix:"Use vm module or worker threads for untrusted deserialization",documentationLink:"https://nodejs.org/api/vm.html"})},schema:[{type:"object",properties:{dangerousFunctions:{type:"array",items:{type:"string"},default:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],description:"Functions that execute or deserialize untrusted input"},safeLibraries:{type:"array",items:{type:"string"},default:["JSON","safe-json-parse","js-yaml.safeLoad","protobuf","msgpack"],description:"Parsers that do not execute their input"},validationFunctions:{type:"array",items:{type:"string"},default:["validateInput","sanitizeData","checkSchema","validateSchema"],description:"Function names that count as input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as safe deserializers"},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:[{dangerousFunctions:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],safeLibraries:["JSON","safe-json-parse","js-yaml.safeLoad","protobuf","msgpack"],validationFunctions:["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{dangerousFunctions=["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions=["validateInput","sanitizeData","checkSchema","validateSchema"],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 validatedVariables=new Set;const untrustedVariables=new Set;const literalPathFileVars=new Set;const isDangerousDeserialization=node=>{const callee=node.callee;if(callee.type==="Identifier"&&dangerousFunctions.includes(callee.name)){if(TIMER_FUNCTIONS.has(callee.name)){return isStringValued(node.arguments[0])}return true}if(callee.type==="MemberExpression"){const memberName=callee.property.type==="Identifier"?callee.property.name:"";const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(callee.object.type==="Super"||callee.object.type==="ThisExpression"){return false}if(TIMER_FUNCTIONS.has(memberName)){return isStringValued(node.arguments[0])}if(objectName==="JSON"&&memberName==="parse"||objectName==="yaml"&&memberName==="safeLoad"){return false}if(dangerousFunctions.includes(memberName)){return true}if(["yaml","js-yaml","node-serialize","serialize-javascript"].includes(objectName.toLowerCase())&&["load","parse","unserialize","deserialize"].includes(memberName)){return true}}if(callee.type==="Identifier"&&callee.name==="require"){const args=node.arguments;if(args.length>0&&args[0].type==="Literal"&&typeof args[0].value==="string"){const moduleName=args[0].value.toLowerCase();if(["node-serialize","serialize-javascript","yaml","js-yaml"].includes(moduleName)){return true}}}return false};const isUntrustedInput=inputNode=>{if(inputNode.type==="BinaryExpression"&&inputNode.operator==="+"){return isUntrustedInput(inputNode.left)||isUntrustedInput(inputNode.right)}if(inputNode.type==="TemplateLiteral"){return inputNode.expressions.some(e=>isUntrustedInput(e))}if(inputNode.type==="AwaitExpression"){return isUntrustedInput(inputNode.argument)}if(inputNode.type==="CallExpression"){const callee=inputNode.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(["text","json","arrayBuffer","formData","blob"].includes(callee.property.name)){return true}if(["readFile","readFileSync"].includes(callee.property.name)){return true}}return inputNode.arguments.some(arg=>arg.type!=="SpreadElement"&&isUntrustedInput(arg))}if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"){return true}}if(inputNode.type==="Identifier"){if(untrustedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;if(func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})){return true}}current=current.parent}}return false};const isInsideDeserializerImplementation=node=>{const DESERIALIZER_NAMES=new Set(["deserialize","unserialize","fromJSON","fromBuffer"]);let current=node.parent;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const fn=current;if("id"in fn&&fn.id?.name&&DESERIALIZER_NAMES.has(fn.id.name))return true;const owner=fn.parent;if(owner?.type==="MethodDefinition"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="Property"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="VariableDeclarator"&&owner.id.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.id.name))return true}current=current.parent}return false};const checkCallExpression=node=>{if((node.type==="NewExpression"||node.type==="CallExpression")&&node.callee.type==="Identifier"&&node.callee.name==="Function"){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg));if(hasUntrustedInput){if(safetyChecker.isSafe(node,context))return;context.report({node,messageId:"dangerousFunctionConstructor",data:{filePath:context.filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Avoid dynamic function creation"}});return}}if(isDangerousDeserialization(node)&&!isInsideDeserializerImplementation(node)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg));if(hasUntrustedInput){const safe=safetyChecker.isSafe(node,context);if(!safe){let messageId="unsafeDeserialization";const calleeText=sourceCode.getText(node.callee);if(calleeText.includes("yaml")||calleeText.includes("YAML")){messageId="unsafeYamlParsing"}if(node.callee.type==="Identifier"&&["eval","setTimeout","setInterval"].includes(node.callee.name)){messageId="dangerousEvalUsage"}context.report({node,messageId,data:{library:calleeText,filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use JSON.parse() or validated safe deserialization libraries"},suggest:messageId==="dangerousEvalUsage"?[{messageId:"useSafeDeserializer",fix:fixer=>{return fixer.replaceText(node,`JSON.parse(${sourceCode.getText(node.arguments[0])})`)}}]:void 0})}}}};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){if(isUntrustedInput(declarator.init)){untrustedVariables.add(declarator.id.name)}if(declarator.init.type==="CallExpression"){const callee=declarator.init.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&callee.property.type==="Identifier"&&["readFile","readFileSync"].includes(callee.property.name)){untrustedVariables.add(declarator.id.name);const pathArg=declarator.init.arguments[0];if(pathArg?.type==="Literal"&&typeof pathArg.value==="string"){literalPathFileVars.add(declarator.id.name)}}}}}},AssignmentExpression(node){if(node.left.type==="Identifier"&&isUntrustedInput(node.right)){untrustedVariables.add(node.left.name)}},CallExpression(node){checkCallExpression(node)},NewExpression(node){checkCallExpression(node)},VariableDeclarator(node){if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(validationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(node.id.name)}if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&node.init.callee.name==="require"){const requireArg=node.init.arguments[0];if(requireArg?.type==="Literal"&&typeof requireArg.value==="string"){const moduleName=requireArg.value;if(["node-serialize","serialize-javascript","js-yaml","yaml"].includes(moduleName)){if(node.id.type==="Identifier"){const variables=sourceCode.getDeclaredVariables(node);for(const variable of variables){for(const reference of variable.references){const refNode=reference.identifier;if(refNode.parent&&refNode.parent.type==="MemberExpression"&&refNode.parent.object===refNode){const memberExpr=refNode.parent;const propertyName=memberExpr.property.type==="Identifier"?memberExpr.property.name:"";if(["unserialize","deserialize","load","parse"].includes(propertyName)){const callExpr=memberExpr.parent;if(callExpr&&callExpr.type==="CallExpression"&&callExpr.callee===memberExpr){if(safetyChecker.isSafe(callExpr,context)){continue}context.report({node:callExpr,messageId:"unsafeDeserialization",data:{filePath:filename,line:String(callExpr.loc?.start.line??0),severity:"CRITICAL",safeAlternative:"Avoid using this library or use safe alternatives"}})}}}}}}}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDeserialization=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 TIMER_FUNCTIONS=new Set(["setTimeout","setInterval"]);const MODULE_SINKS={"js-yaml":new Set(["load","loadAll"]),"node-serialize":new Set(["unserialize"]),funcster:new Set(["deserialize","deepDeserialize"]),v8:new Set(["deserialize"])};const ALWAYS_UNSAFE_MODULES=new Set(["node-serialize","funcster"]);const DEFAULT_SAFE_YAML_SCHEMAS=["JSON_SCHEMA","CORE_SCHEMA","FAILSAFE_SCHEMA"];const DEFAULT_NON_EXECUTING_PACKAGES=["yaml","bson","cbor","msgpackr","@msgpack/msgpack","protobufjs"];function isStringValued(arg){if(!arg)return false;if(arg.type==="Literal")return typeof arg.value==="string";if(arg.type==="TemplateLiteral")return true;if(arg.type==="BinaryExpression"&&arg.operator==="+"){return isStringValued(arg.left)||isStringValued(arg.right)}return false}exports.noUnsafeDeserialization=(0,eslint_devkit_1.createRule)({name:"no-unsafe-deserialization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-deserialization.md",description:"Detects unsafe deserialization of untrusted data",cwe:"CWE-502"},fixable:"code",hasSuggestions:true,messages:{unsafeDeserialization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Deserialization",cwe:"CWE-502",description:"Unsafe deserialization of untrusted data (incl. model/tool output)",severity:"{{severity}}",fix:"{{safeAlternative}} | validate model/tool output via schema and size limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),dangerousEvalUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous eval() Usage",cwe:"CWE-502",description:"eval() used for deserialization (code execution vulnerability)",severity:"CRITICAL",fix:"Use JSON.parse() or safe deserialization libraries",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),unsafeYamlParsing:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe YAML Parsing",cwe:"CWE-502",description:"YAML parsing may execute code during deserialization",severity:"HIGH",fix:"Use yaml.safeLoad() or disable code execution",documentationLink:"https://www.npmjs.com/package/js-yaml#loadstr---options-"}),dangerousFunctionConstructor:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Function Constructor",cwe:"CWE-502",description:"Function constructor used with untrusted data",severity:"CRITICAL",fix:"Avoid Function constructor with user input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function"}),useSafeDeserializer:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Safe Deserializer",description:"Use safe deserialization libraries",severity:"LOW",fix:"Use JSON.parse, safe-json-parse, or validated libraries",documentationLink:"https://www.npmjs.com/package/safe-json-parse"})},schema:[{type:"object",properties:{dangerousFunctions:{type:"array",items:{type:"string"},default:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],description:"Functions that execute or deserialize untrusted input"},validationFunctions:{type:"array",items:{type:"string"},default:["validateInput","sanitizeData","checkSchema","validateSchema"],description:"Function names that count as input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as safe deserializers"},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)"},safeYamlSchemas:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_YAML_SCHEMAS,description:"js-yaml schema exports that make `load` inert, matched against a resolved js-yaml binding. Add DEFAULT_SCHEMA on a repository pinned to js-yaml v4. Replaces the built-in list."},additionalSafeYamlSchemas:{type:"array",items:{type:"string"},default:[],description:"Extra safe js-yaml schema exports, on top of `safeYamlSchemas`."},nonExecutingPackages:{type:"array",items:{type:"string"},default:DEFAULT_NON_EXECUTING_PACKAGES,description:"Packages whose parse entry point cannot execute code or instantiate a payload-named type, matched against a resolved import binding. Replaces the built-in list."},additionalNonExecutingPackages:{type:"array",items:{type:"string"},default:[],description:"Extra non-executing packages, on top of `nonExecutingPackages`."}},additionalProperties:false}]},defaultOptions:[{dangerousFunctions:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions:["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false,safeYamlSchemas:DEFAULT_SAFE_YAML_SCHEMAS,additionalSafeYamlSchemas:[],nonExecutingPackages:DEFAULT_NON_EXECUTING_PACKAGES,additionalNonExecutingPackages:[]}],create(context){const options=context.options[0]||{};const{dangerousFunctions=["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions=["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false,safeYamlSchemas=DEFAULT_SAFE_YAML_SCHEMAS,additionalSafeYamlSchemas=[],nonExecutingPackages=DEFAULT_NON_EXECUTING_PACKAGES,additionalNonExecutingPackages=[]}=options;const safeSchemas=new Set([...safeYamlSchemas,...additionalSafeYamlSchemas]);const inertPackages=new Set([...nonExecutingPackages,...additionalNonExecutingPackages]);const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const validatedVariables=new Set;const untrustedVariables=new Set;const literalPathFileVars=new Set;const pinsSafeYamlSchema=node=>{const optionsArg=node.arguments[1];if(optionsArg?.type!=="ObjectExpression")return false;return optionsArg.properties.some(property=>{if(property.type!=="Property"||property.computed)return false;if(property.key.type!=="Identifier"||property.key.name!=="schema"){return false}const schema=(0,eslint_devkit_1.resolveModuleBinding)(property.value,sourceCode.getScope(property.value));return schema?.module==="js-yaml"&&safeSchemas.has(schema.path.at(-1)??"")})};const isDangerousDeserialization=node=>{const callee=node.callee;const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));if(binding){const sinks=MODULE_SINKS[binding.module];if(sinks&&binding.path.some(segment=>sinks.has(segment))){return!pinsSafeYamlSchema(node)}if(inertPackages.has(binding.module))return false}if(callee.type==="Identifier"&&dangerousFunctions.includes(callee.name)){if(TIMER_FUNCTIONS.has(callee.name)){return isStringValued(node.arguments[0])}return true}if(callee.type==="MemberExpression"){const memberName=callee.property.type==="Identifier"?callee.property.name:"";const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(callee.object.type==="Super"||callee.object.type==="ThisExpression"){return false}if(TIMER_FUNCTIONS.has(memberName)){return isStringValued(node.arguments[0])}if(objectName==="JSON"&&memberName==="parse"||objectName==="yaml"&&memberName==="safeLoad"){return false}if(dangerousFunctions.includes(memberName)){return true}if(["yaml","js-yaml","node-serialize","serialize-javascript"].includes(objectName.toLowerCase())&&["load","parse","unserialize","deserialize"].includes(memberName)){return true}}if(callee.type==="Identifier"&&callee.name==="require"){const args=node.arguments;if(args.length>0&&args[0].type==="Literal"&&typeof args[0].value==="string"){const moduleName=args[0].value.toLowerCase();if(["node-serialize","serialize-javascript","yaml","js-yaml"].includes(moduleName)){return true}}}return false};const isUntrustedInput=inputNode=>{const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(inputNode);if(bare!==inputNode)return isUntrustedInput(bare);if(inputNode.type==="BinaryExpression"&&inputNode.operator==="+"){return isUntrustedInput(inputNode.left)||isUntrustedInput(inputNode.right)}if(inputNode.type==="TemplateLiteral"){return inputNode.expressions.some(e=>isUntrustedInput(e))}if(inputNode.type==="AwaitExpression"){return isUntrustedInput(inputNode.argument)}if(inputNode.type==="CallExpression"){const callee=inputNode.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(["text","json","arrayBuffer","formData","blob"].includes(callee.property.name)){return true}if(["readFile","readFileSync"].includes(callee.property.name)){return true}if(isUntrustedInput(callee.object)){return true}}return inputNode.arguments.some(arg=>arg.type!=="SpreadElement"&&isUntrustedInput(arg))}if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"){return true}}if(inputNode.type==="Identifier"){if(untrustedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;if(func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})){return true}}current=current.parent}}return false};const isInsideDeserializerImplementation=node=>{const DESERIALIZER_NAMES=new Set(["deserialize","unserialize","fromJSON","fromBuffer"]);let current=node.parent;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const fn=current;if("id"in fn&&fn.id?.name&&DESERIALIZER_NAMES.has(fn.id.name))return true;const owner=fn.parent;if(owner?.type==="MethodDefinition"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="Property"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="VariableDeclarator"&&owner.id.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.id.name))return true}current=current.parent}return false};const isAlwaysUnsafeSink=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,sourceCode.getScope(node.callee));return binding!==void 0&&ALWAYS_UNSAFE_MODULES.has(binding.module)};const checkCallExpression=node=>{if((node.type==="NewExpression"||node.type==="CallExpression")&&node.callee.type==="Identifier"&&node.callee.name==="Function"){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg));if(hasUntrustedInput){if(safetyChecker.isSafe(node,context))return;context.report({node,messageId:"dangerousFunctionConstructor",data:{filePath:context.filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Avoid dynamic function creation"}});return}}if(isDangerousDeserialization(node)&&!isInsideDeserializerImplementation(node)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg))||isAlwaysUnsafeSink(node);if(hasUntrustedInput){const safe=safetyChecker.isSafe(node,context);if(!safe){let messageId="unsafeDeserialization";const calleeText=sourceCode.getText(node.callee);if(calleeText.includes("yaml")||calleeText.includes("YAML")){messageId="unsafeYamlParsing"}if(node.callee.type==="Identifier"&&["eval","setTimeout","setInterval"].includes(node.callee.name)){messageId="dangerousEvalUsage"}context.report({node,messageId,data:{library:calleeText,filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use JSON.parse() or validated safe deserialization libraries"},suggest:messageId==="dangerousEvalUsage"?[{messageId:"useSafeDeserializer",fix:fixer=>{return fixer.replaceText(node,`JSON.parse(${sourceCode.getText(node.arguments[0])})`)}}]:void 0})}}}};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){if(isUntrustedInput(declarator.init)){untrustedVariables.add(declarator.id.name)}if(declarator.init.type==="CallExpression"){const callee=declarator.init.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&callee.property.type==="Identifier"&&["readFile","readFileSync"].includes(callee.property.name)){untrustedVariables.add(declarator.id.name);const pathArg=declarator.init.arguments[0];if(pathArg?.type==="Literal"&&typeof pathArg.value==="string"){literalPathFileVars.add(declarator.id.name)}}}}}},AssignmentExpression(node){if(node.left.type==="Identifier"&&isUntrustedInput(node.right)){untrustedVariables.add(node.left.name)}},CallExpression(node){checkCallExpression(node)},NewExpression(node){checkCallExpression(node)},VariableDeclarator(node){if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(validationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(node.id.name)}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeRegexConstruction=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_TRUSTED_ESCAPING_FUNCTIONS=["escapeRegex","escapeRegExp","escapeStringRegexp","regexpEscape","escape","sanitize"];const INLINE_ESCAPE_SUFFIX='.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")';function taintSource(node,depth=0){if(depth>6)return null;if(node.type==="TemplateLiteral"){for(const expression of node.expressions){const found=taintSource(expression,depth+1);if(found!==null)return found}return null}if(node.type==="BinaryExpression"&&node.operator==="+"){return taintSource(node.left,depth+1)??taintSource(node.right,depth+1)}if(node.type==="AwaitExpression"){return taintSource(node.argument,depth+1)}if(node.type==="MemberExpression"){let root=node;const properties=[];while(root.type==="MemberExpression"){if(root.property.type==="Identifier")properties.unshift(root.property.name);root=root.object}if(root.type==="Identifier"){if(REQUEST_ROOTS.has(root.name)&&properties.some(p=>REQUEST_PROPERTIES.has(p))){return`${root.name}.${properties.join(".")}`}if(root.name==="process"&&properties[0]==="argv"){return"process.argv"}}return null}if(node.type==="CallExpression"){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(READER_METHODS.has(callee.property.name)){return callee.property.name}}if(callee.type==="Identifier"&&READER_METHODS.has(callee.name)){return callee.name}for(const arg of node.arguments){if(arg.type==="SpreadElement")continue;const found=taintSource(arg,depth+1);if(found!==null)return found}return null}return null}const REQUEST_ROOTS=new Set(["req","request","ctx","event","message"]);const REQUEST_PROPERTIES=new Set(["query","params","body","headers","url","path","cookies","data"]);const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);function isEscaped(node,trustedFunctions,sourceCode){if(node.type==="CallExpression"&&node.callee.type==="Identifier"){const functionName=node.callee.name;if(trustedFunctions.includes(functionName)){return true}}let current=node;let depth=0;const maxDepth=5;while(depth<maxDepth){const parent=sourceCode.getNodeByRangeIndex?.(current.range[0]-1)||current.parent;if(!parent)break;if(parent.type==="CallExpression"&&parent.callee.type==="Identifier"){const functionName=parent.callee.name;if(trustedFunctions.includes(functionName)){return true}}current=parent;depth++}return false}function isRegexClone(node){if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="source"){return true}if(node.type==="BinaryExpression"&&node.operator==="+"){return isRegexClone(node.left)||isRegexClone(node.right)}return false}function hasDynamicFlags(node){if(node.arguments.length>1){const flagsNode=node.arguments[1];return!(flagsNode.type==="Literal"&&typeof flagsNode.value==="string")}return false}function extractPattern(node,sourceCode,trustedFunctions){const patternNode=node.arguments.length>0?node.arguments[0]:null;if(!patternNode){return{patternNode:null,isUserInput:false,taintedBy:null,isEscaped:false}}const taintedBy=taintSource(patternNode);const isUserInputValue=taintedBy!==null;const allTrustedFunctions=[...new Set([...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS,"RegExp.escape",...trustedFunctions])];const isEscapedValue=isEscaped(patternNode,allTrustedFunctions,sourceCode);return{patternNode,isUserInput:isUserInputValue,taintedBy,isEscaped:isEscapedValue}}exports.noUnsafeRegexConstruction=(0,eslint_devkit_2.createRule)({name:"no-unsafe-regex-construction",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-regex-construction.md",description:"Detects unsafe regex construction patterns (user input without escaping, dynamic flags)",cwe:"CWE-400",cvss:7.5},hasSuggestions:true,messages:{unsafeRegexConstruction:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe regex construction",cwe:"CWE-400",description:"{{issue}}: {{details}}",severity:"HIGH",fix:"{{fix}}",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 User Input",description:"Escape user input for regex",severity:"LOW",fix:'input.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping"}),validatePattern:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Validate Pattern",description:"Validate pattern against whitelist",severity:"LOW",fix:"Validate pattern before creating RegExp",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),useSafeLibrary:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use safe-regex",description:"Use safe-regex library for validation",severity:"LOW",fix:"if (safeRegex(pattern)) { new RegExp(pattern) }",documentationLink:"https://github.com/substack/safe-regex"}),avoidDynamicFlags:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Static Flags",description:"Use static flags instead of dynamic",severity:"LOW",fix:'new RegExp(pattern, "gi") with static flags',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:true,description:"Allow literal string patterns"},trustedEscapingFunctions:{type:"array",items:{type:"string"},default:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],description:"Trusted functions that escape input"},maxPatternLength:{type:"number",default:100,minimum:1,description:"Maximum pattern length for dynamic regex"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:true,trustedEscapingFunctions:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],maxPatternLength:100}],create(context,[options={}]){const{allowLiterals=true,maxPatternLength=100,trustedEscapingFunctions=[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS]}=options;const sourceCode=context.sourceCode;function checkRegExpCall(node){const isRegExpCall=node.type==="CallExpression"&&node.callee.type==="Identifier"&&node.callee.name==="RegExp"||node.type==="NewExpression"&&node.callee.type==="Identifier"&&node.callee.name==="RegExp";if(!isRegExpCall){return}const{patternNode,isUserInput:isUserInputValue,isEscaped:isEscapedValue}=extractPattern(node,sourceCode,trustedEscapingFunctions);if(!patternNode){return}if(patternNode.type==="Literal"&&typeof patternNode.value==="string"){const patternLength=patternNode.value.length;if(patternLength>maxPatternLength){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Pattern too long",details:`Pattern length (${patternLength}) exceeds maximum (${maxPatternLength})`,fix:"Split into smaller patterns or validate length"},suggest:[{messageId:"validatePattern",fix:()=>null}]});return}if(!allowLiterals){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Literal regex pattern",details:"Literal regex patterns should be avoided for security. Use variables instead.",fix:"Use a variable or RegExp constructor with a string variable"},suggest:[{messageId:"validatePattern",fix:()=>null}]});return}}if(isUserInputValue&&!isEscapedValue){const patternText=context.sourceCode.getText(patternNode);context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"User input in regex without escaping",details:"User input in regex pattern can lead to ReDoS or injection attacks",fix:"Escape special characters before using in regex"},suggest:[{messageId:"escapeUserInput",fix:fixer=>fixer.replaceText(patternNode,`(${patternText})${INLINE_ESCAPE_SUFFIX}`)},{messageId:"validatePattern",fix:()=>null},{messageId:"useSafeLibrary",fix:()=>null}]})}if(hasDynamicFlags(node)&&!isRegexClone(patternNode)){context.report({node,messageId:"unsafeRegexConstruction",data:{issue:"Dynamic regex flags",details:"Dynamic flags can lead to unexpected behavior or security issues",fix:"Use static flags instead of dynamic flags"},suggest:[{messageId:"avoidDynamicFlags",fix:()=>null}]})}}return{CallExpression:checkRegExpCall,NewExpression:checkRegExpCall}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeRegexConstruction=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_TRUSTED_ESCAPING_FUNCTIONS=["escapeRegex","escapeRegExp","escapeStringRegexp","regexpEscape"];const INLINE_ESCAPE_SUFFIX='.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")';function taintSource(node,scope,depth=0){if(depth>6)return null;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(unwrapped!==node)return taintSource(unwrapped,scope,depth+1);if(node.type==="TemplateLiteral"){for(const expression of node.expressions){const found=taintSource(expression,scope,depth+1);if(found!==null)return found}return null}if(node.type==="BinaryExpression"&&node.operator==="+"){return taintSource(node.left,scope,depth+1)??taintSource(node.right,scope,depth+1)}if(node.type==="AwaitExpression"){return taintSource(node.argument,scope,depth+1)}if(node.type==="MemberExpression"){let root=node;const properties=[];while(root.type==="MemberExpression"){if(root.property.type==="Identifier")properties.unshift(root.property.name);root=root.object}if(root.type==="Identifier"){if(REQUEST_ROOTS.has(root.name)&&properties.some(p=>REQUEST_PROPERTIES.has(p))&&isInboundRequestBinding(root,scope)){return`${root.name}.${properties.join(".")}`}if(root.name==="process"&&properties[0]==="argv"){return"process.argv"}}return null}if(node.type==="CallExpression"){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(READER_METHODS.has(callee.property.name)){return callee.property.name}}if(callee.type==="Identifier"&&READER_METHODS.has(callee.name)){return callee.name}for(const arg of node.arguments){if(arg.type==="SpreadElement")continue;const found=taintSource(arg,scope,depth+1);if(found!==null)return found}return null}if(node.type==="Identifier"){const variable=lookupVariable(node.name,scope);if(!variable)return null;for(const reference of variable.references){if(!reference.isWrite()||!reference.writeExpr)continue;const found=taintSource(reference.writeExpr,scope,depth+1);if(found!==null)return found}return null}return null}function isInboundRequestBinding(root,scope){const variable=lookupVariable(root.name,scope);if(!variable||variable.defs.length===0)return true;return variable.defs.every(def=>def.type==="Parameter")}function lookupVariable(name,scope){for(let current=scope;current;current=current.upper){const found=current.variables.find(v=>v.name===name);if(found)return found}return void 0}const REQUEST_ROOTS=new Set(["req","request","ctx","event","message"]);const REQUEST_PROPERTIES=new Set(["query","params","body","headers","url","path","cookies","data"]);const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const MEMBER_ESCAPERS=new Set(["escapeRegExp","escapeRegex","escapeStringRegexp","regexpEscape"]);const ESCAPER_PACKAGES=new Set(["escape-string-regexp","lodash.escaperegexp","escape-regexp","regexp.escape"]);function isEscaperPackageBinding(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding&&ESCAPER_PACKAGES.has(binding.module))return true;return binding?.module==="lodash"&&binding.path.at(-1)==="escapeRegExp"}function isRegExpConstructor(callee,scope,depth=0){if(depth>4)return false;if(callee.type!=="Identifier")return false;if(callee.name==="RegExp"){const shadow=lookupVariable("RegExp",scope);return shadow===void 0||shadow.defs.length===0}const variable=lookupVariable(callee.name,scope);if(!variable)return false;const writes=variable.references.filter(ref=>ref.isWrite());return writes.length>0&&writes.every(ref=>{const written=ref.writeExpr;return written!=null&&isRegExpConstructor(written,scope,depth+1)})}function isTrustedMemberEscaper(callee){if(callee.type!=="MemberExpression"||callee.computed)return false;if(callee.property.type!=="Identifier")return false;if(callee.property.name==="escape"&&callee.object.type==="Identifier"&&callee.object.name==="RegExp"){return true}return MEMBER_ESCAPERS.has(callee.property.name)}function isEscaped(node,trustedFunctions,sourceCode,scope){if(node.type==="CallExpression"&&node.callee.type==="Identifier"){const functionName=node.callee.name;if(trustedFunctions.includes(functionName)){return true}}if(node.type==="CallExpression"&&isEscaperPackageBinding(node.callee,scope)){return true}if(node.type==="CallExpression"&&isTrustedMemberEscaper(node.callee)){return true}let current=node;let depth=0;const maxDepth=5;while(depth<maxDepth){const parent=sourceCode.getNodeByRangeIndex?.(current.range[0]-1)||current.parent;if(!parent)break;if(parent.type==="CallExpression"&&parent.callee.type==="Identifier"){const functionName=parent.callee.name;if(trustedFunctions.includes(functionName)){return true}}current=parent;depth++}return false}function isRegexClone(node){if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="source"){return true}if(node.type==="BinaryExpression"&&node.operator==="+"){return isRegexClone(node.left)||isRegexClone(node.right)}return false}function hasDynamicFlags(node){if(node.arguments.length>1){const flagsNode=node.arguments[1];return!(flagsNode.type==="Literal"&&typeof flagsNode.value==="string")}return false}function extractPattern(node,sourceCode,trustedFunctions,scope){const patternNode=node.arguments.length>0?node.arguments[0]:null;if(!patternNode){return{patternNode:null,isUserInput:false,taintedBy:null,isEscaped:false}}const taintedBy=taintSource(patternNode,scope);const isUserInputValue=taintedBy!==null;const allTrustedFunctions=[...new Set([...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS,...trustedFunctions])];const isEscapedValue=isEscaped(patternNode,allTrustedFunctions,sourceCode,scope);return{patternNode,isUserInput:isUserInputValue,taintedBy,isEscaped:isEscapedValue}}exports.noUnsafeRegexConstruction=(0,eslint_devkit_2.createRule)({name:"no-unsafe-regex-construction",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-regex-construction.md",description:"Detects unsafe regex construction patterns (user input without escaping, dynamic flags)",cwe:"CWE-400",cvss:7.5},hasSuggestions:true,messages:{unsafeRegexConstruction:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe regex construction",cwe:"CWE-400",description:"{{issue}}: {{details}}",severity:"HIGH",fix:"{{fix}}",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 User Input",description:"Escape user input for regex",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:true,description:"Allow literal string patterns"},trustedEscapingFunctions:{type:"array",items:{type:"string"},default:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],description:"Trusted functions that escape input"},maxPatternLength:{type:"number",default:100,minimum:1,description:"Maximum pattern length for dynamic regex"}},additionalProperties:false}]},defaultOptions:[{allowLiterals:true,trustedEscapingFunctions:[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS],maxPatternLength:100}],create(context,[options={}]){const{allowLiterals=true,maxPatternLength=100,trustedEscapingFunctions=[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS]}=options;const sourceCode=context.sourceCode;function checkRegExpCall(node){if(!isRegExpConstructor(node.callee,sourceCode.getScope(node))){return}const{patternNode,isUserInput:isUserInputValue,isEscaped:isEscapedValue}=extractPattern(node,sourceCode,trustedEscapingFunctions,sourceCode.getScope(node));if(!patternNode){return}if(patternNode.type==="Literal"&&typeof patternNode.value==="string"){const patternLength=patternNode.value.length;if(patternLength>maxPatternLength){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Pattern too long",details:`Pattern length (${patternLength}) exceeds maximum (${maxPatternLength})`,fix:"Split into smaller patterns or validate length"}});return}if(!allowLiterals){context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"Literal regex pattern",details:"Literal regex patterns should be avoided for security. Use variables instead.",fix:"Use a variable or RegExp constructor with a string variable"}});return}}if(isUserInputValue&&!isEscapedValue){const patternText=context.sourceCode.getText(patternNode);context.report({node:patternNode,messageId:"unsafeRegexConstruction",data:{issue:"User input in regex without escaping",details:"User input in regex pattern can lead to ReDoS or injection attacks",fix:"Escape special characters before using in regex"},suggest:[{messageId:"escapeUserInput",fix:fixer=>fixer.replaceText(patternNode,`(${patternText})${INLINE_ESCAPE_SUFFIX}`)}]})}if(hasDynamicFlags(node)&&!isRegexClone(patternNode)){context.report({node,messageId:"unsafeRegexConstruction",data:{issue:"Dynamic regex flags",details:"Dynamic flags can lead to unexpected behavior or security issues",fix:"Use static flags instead of dynamic flags"}})}}return{CallExpression:checkRegExpCall,NewExpression:checkRegExpCall}}});