eslint-plugin-secure-coding 5.4.17 → 5.5.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 (38) hide show
  1. package/README.md +26 -0
  2. package/package.json +5 -2
  3. package/src/index.js +1 -1
  4. package/src/rules/detect-non-literal-regexp/index.js +1 -1
  5. package/src/rules/detect-object-injection/index.js +1 -1
  6. package/src/rules/detect-weak-password-validation/index.js +1 -1
  7. package/src/rules/no-bidi-characters/index.js +1 -1
  8. package/src/rules/no-directive-injection/index.js +1 -1
  9. package/src/rules/no-disabled-template-escaping/index.js +1 -0
  10. package/src/rules/no-electron-security-issues/index.js +1 -1
  11. package/src/rules/no-fail-open-auth/index.js +1 -1
  12. package/src/rules/no-format-string-injection/index.js +1 -1
  13. package/src/rules/no-graphql-injection/index.js +1 -1
  14. package/src/rules/no-hardcoded-credentials/index.js +1 -1
  15. package/src/rules/no-hardcoded-session-tokens/index.js +1 -1
  16. package/src/rules/no-homoglyph-identifiers/index.js +1 -1
  17. package/src/rules/no-improper-sanitization/index.js +1 -1
  18. package/src/rules/no-improper-type-validation/index.js +1 -1
  19. package/src/rules/no-insecure-comparison/index.js +1 -1
  20. package/src/rules/no-invisible-characters/index.js +1 -0
  21. package/src/rules/no-ldap-injection/index.js +1 -1
  22. package/src/rules/no-log-injection/index.js +1 -1
  23. package/src/rules/no-missing-authentication/index.js +1 -1
  24. package/src/rules/no-pii-in-logs/index.js +1 -1
  25. package/src/rules/no-privilege-escalation/index.js +1 -1
  26. package/src/rules/no-redos-vulnerable-regex/index.js +1 -1
  27. package/src/rules/no-sensitive-data-exposure/index.js +1 -1
  28. package/src/rules/no-sql-injection/index.js +1 -1
  29. package/src/rules/no-template-injection/index.js +1 -1
  30. package/src/rules/no-unchecked-loop-condition/index.js +1 -1
  31. package/src/rules/no-unlimited-resource-allocation/index.js +1 -1
  32. package/src/rules/no-unsafe-deserialization/index.js +1 -1
  33. package/src/rules/no-unsafe-regex-construction/index.js +1 -1
  34. package/src/rules/no-weak-password-recovery/index.js +1 -1
  35. package/src/rules/no-xpath-injection/index.js +1 -1
  36. package/src/rules/no-xxe-injection/index.js +1 -1
  37. package/src/rules/require-backend-authorization/index.js +1 -1
  38. package/src/rules/require-secure-defaults/index.js +1 -1
@@ -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 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.LogicalExpression){return node.operator==="&&"?untrustedSource(node.right,vocabulary,depth+1):untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return untrustedSource(node.consequent,vocabulary,depth+1)??untrustedSource(node.alternate,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){const segment=(0,eslint_devkit_1.propertyName)(root);if(segment!==null){properties.unshift(segment)}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&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),READER_METHODS)){return(0,eslint_devkit_1.propertyName)(callee)}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}=callee;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const methodName=(0,eslint_devkit_1.propertyName)(callee);if(methodName===null)return;const engineName=object.name;if(!engines.has(engineName))return;if(!ALL_TEMPLATE_METHODS.has(methodName))return;const firstArg=args[0];if(!firstArg)return;if(untrustedSource(firstArg,vocabulary)===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.LogicalExpression){return node.operator==="&&"?untrustedSource(node.right,vocabulary,depth+1):untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return untrustedSource(node.consequent,vocabulary,depth+1)??untrustedSource(node.alternate,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){const segment=(0,eslint_devkit_1.propertyName)(root);if(segment!==null){properties.unshift(segment)}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&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),READER_METHODS)){return(0,eslint_devkit_1.propertyName)(callee)}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:{interop:{runtimes:["eslint","oxlint"]},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:[]}],createOnce(context){let engines;let vocabulary;return{before(){const options=context.options[0]??{};engines=new Set([...options.templateEngines??DEFAULT_TEMPLATE_ENGINES,...options.additionalTemplateEngines??[]]);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??[]])}},CallExpression(node){const{callee,arguments:args}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const{object}=callee;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const methodName=(0,eslint_devkit_1.propertyName)(callee);if(methodName===null)return;const engineName=object.name;if(!engines.has(engineName))return;if(!ALL_TEMPLATE_METHODS.has(methodName))return;const firstArg=args[0];if(!firstArg)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"},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.object.type==="Identifier"&&node.callee.object.name==="Array"&&(0,eslint_devkit_1.propertyName)(node.callee)==="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"&&(0,eslint_devkit_1.propertyName)(side)==="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(0,eslint_devkit_1.propertyName)(a)===(0,eslint_devkit_1.propertyName)(b)&&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((0,eslint_devkit_1.propertyName)(node)==="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 hasLoopExit=loopBody=>{let found=false;const innerLabels=new Set;const walk=(node,insideNestedBreakable)=>{if(found)return;switch(node.type){case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return;case"BreakStatement":if(node.label===null){if(!insideNestedBreakable)found=true}else if(!innerLabels.has(node.label.name)){found=true}return;case"ReturnStatement":case"ThrowStatement":found=true;return;default:break}if(node.type==="LabeledStatement")innerLabels.add(node.label.name);const breakable=insideNestedBreakable||node.type==="ForStatement"||node.type==="ForInStatement"||node.type==="ForOfStatement"||node.type==="WhileStatement"||node.type==="DoWhileStatement"||node.type==="SwitchStatement";for(const key of Object.keys(node)){if(key==="parent")continue;const child=node[key];if(child===null||typeof child!=="object")continue;if(Array.isArray(child)){for(const item of child){if(item!==null&&typeof item==="object"&&"type"in item){walk(item,breakable)}}}else if("type"in child){walk(child,breakable)}}};walk(loopBody,false);return found};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}if(allowWhileTrueWithBreak&&hasLoopExit(node.body)){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
+ "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:{interop:{runtimes:["eslint","oxlint"]},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}],createOnce(context){let maxStaticIterations;let userInputVariables;let allowWhileTrueWithBreak;let maxRecursionDepth;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;let functionCalls;let reportedRecursion;let currentFunctionStack;let taintedVariables;let REQUEST_OBJECTS;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.object.type==="Identifier"&&node.callee.object.name==="Array"&&(0,eslint_devkit_1.propertyName)(node.callee)==="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"&&(0,eslint_devkit_1.propertyName)(side)==="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(0,eslint_devkit_1.propertyName)(a)===(0,eslint_devkit_1.propertyName)(b)&&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((0,eslint_devkit_1.propertyName)(node)==="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 hasLoopExit=loopBody=>{let found=false;const innerLabels=new Set;const walk=(node,insideNestedBreakable)=>{if(found)return;switch(node.type){case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return;case"BreakStatement":if(node.label===null){if(!insideNestedBreakable)found=true}else if(!innerLabels.has(node.label.name)){found=true}return;case"ReturnStatement":case"ThrowStatement":found=true;return;default:break}if(node.type==="LabeledStatement")innerLabels.add(node.label.name);const breakable=insideNestedBreakable||node.type==="ForStatement"||node.type==="ForInStatement"||node.type==="ForOfStatement"||node.type==="WhileStatement"||node.type==="DoWhileStatement"||node.type==="SwitchStatement";for(const key of Object.keys(node)){if(key==="parent")continue;const child=node[key];if(child===null||typeof child!=="object")continue;if(Array.isArray(child)){for(const item of child){if(item!==null&&typeof item==="object"&&"type"in item){walk(item,breakable)}}}else if("type"in child){walk(child,breakable)}}};walk(loopBody,false);return found};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{before(){const options=context.options[0]||{};({maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});functionCalls=new Map;reportedRecursion=new Set;currentFunctionStack=[];taintedVariables=new Set;REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"])},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}if(allowWhileTrueWithBreak&&hasLoopExit(node.body)){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");const DEFAULT_SIZE_PROPERTIES=["length","size","byteLength","count"];const DEFAULT_LIMIT_OPTION_NAMES=["maxOutputLength","maxSize","limit"];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:{sizeProperties:{type:"array",items:{type:"string"},default:[...DEFAULT_SIZE_PROPERTIES],description:"Property names that carry a magnitude. Replaces the default."},limitOptionNames:{type:"array",items:{type:"string"},default:[...DEFAULT_LIMIT_OPTION_NAMES],description:"Option keys a library accepts to cap an operation. Replaces the default."},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 sizeProperties=new Set(options.sizeProperties??DEFAULT_SIZE_PROPERTIES);const limitOptionNames=new Set(options.limitOptionNames??DEFAULT_LIMIT_OPTION_NAMES);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&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),REQUEST_SURFACE);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(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),sizeProperties);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;const member=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="Identifier"){name=callee.name}else if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&member!==null){name=`${callee.object.name}.${member}`}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"&&((0,eslint_devkit_1.propertyName)(callee)==="alloc"||(0,eslint_devkit_1.propertyName)(callee)==="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"&&["readFile","writeFile","readFileSync","writeFileSync"].includes((0,eslint_devkit_1.propertyName)(callee)??"")){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=(0,eslint_devkit_1.propertyName)(member)??"";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"&&limitOptionNames.has(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&&((0,eslint_devkit_1.propertyName)(candidate.right)==="length"||(0,eslint_devkit_1.propertyName)(candidate.right)==="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
+ "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");const DEFAULT_SIZE_PROPERTIES=["length","size","byteLength","count"];const DEFAULT_LIMIT_OPTION_NAMES=["maxOutputLength","maxSize","limit"];exports.noUnlimitedResourceAllocation=(0,eslint_devkit_1.createRule)({name:"no-unlimited-resource-allocation",meta:{interop:{runtimes:["eslint","oxlint"]},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:{sizeProperties:{type:"array",items:{type:"string"},default:[...DEFAULT_SIZE_PROPERTIES],description:"Property names that carry a magnitude. Replaces the default."},limitOptionNames:{type:"array",items:{type:"string"},default:[...DEFAULT_LIMIT_OPTION_NAMES],description:"Option keys a library accepts to cap an operation. Replaces the default."},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}],createOnce(context){let sizeProperties;let limitOptionNames;let maxResourceSize;let userInputVariables;let safeResourceFunctions;let requireResourceValidation;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;let REQUEST_SURFACE;let requestRoots;const ARCHIVE_MODULES=/^(unzipper|tar|tar-stream|yauzl|adm-zip|node:zlib|zlib)$/;let archiveBindings;let ALLOCATORS;const readsRequestSurface=node=>node?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),REQUEST_SURFACE);const 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(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),sizeProperties);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 noteArchiveBinding=(local,source)=>{if(ARCHIVE_MODULES.test(source))archiveBindings.add(local)};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;const member=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="Identifier"){name=callee.name}else if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&member!==null){name=`${callee.object.name}.${member}`}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{before(){const options=context.options[0]||{};sizeProperties=new Set(options.sizeProperties??DEFAULT_SIZE_PROPERTIES);limitOptionNames=new Set(options.limitOptionNames??DEFAULT_LIMIT_OPTION_NAMES);({maxResourceSize=1048576,userInputVariables=["req","request","body","query","params","input","data"],safeResourceFunctions=["validateSize","checkLimits","limitResource","safeAlloc"],requireResourceValidation=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});REQUEST_SURFACE=new Set(["body","query","params","headers","cookies","url","originalUrl","rawBody","files","payload","searchParams"]);requestRoots=new Set(userInputVariables.map(name=>name.toLowerCase()));archiveBindings=new Set(["zlib"]);ALLOCATORS=new Set(["Buffer.alloc","Buffer.allocUnsafe","Buffer.allocUnsafeSlow","Buffer","Array","Map","Set","WeakMap","WeakSet"])},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"&&((0,eslint_devkit_1.propertyName)(callee)==="alloc"||(0,eslint_devkit_1.propertyName)(callee)==="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"&&["readFile","writeFile","readFileSync","writeFileSync"].includes((0,eslint_devkit_1.propertyName)(callee)??"")){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=(0,eslint_devkit_1.propertyName)(member)??"";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"&&limitOptionNames.has(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&&((0,eslint_devkit_1.propertyName)(candidate.right)==="length"||(0,eslint_devkit_1.propertyName)(candidate.right)==="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 node_fs_1=require("node:fs");const node_path_1=require("node:path");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 GLOBAL_ONLY_SINKS=new Set(["eval","Function"]);function isLocallyBoundIn(identifier,sourceCode){for(let scope=sourceCode.getScope(identifier);scope!==null;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(variable!==void 0)return variable.defs.length>0}return false}const GLOBAL_OBJECTS=new Set(["window","globalThis","global","self"]);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 majorCache=new Map;function declaredMajorFrom(startDir,pkg){const cacheKey=`${startDir}\0${pkg}`;const cached=majorCache.get(cacheKey);if(cached!==void 0)return cached;let dir=startDir;let found=0;for(let depth=0;depth<12;depth++){try{const manifest=JSON.parse((0,node_fs_1.readFileSync)((0,node_path_1.join)(dir,"package.json"),"utf8"));const range=manifest.dependencies?.[pkg]??manifest.devDependencies?.[pkg]??manifest.peerDependencies?.[pkg];if(typeof range==="string"){const digits=/(\d+)/.exec(range);if(digits!==null)found=Number(digits[1]);break}}catch{}const parent=(0,node_path_1.dirname)(dir);if(parent===dir)break;dir=parent}majorCache.set(cacheKey,found);return found}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))){if(binding.module==="js-yaml"&&declaredMajorFrom((0,node_path_1.dirname)(context.filename),"js-yaml")>=4){return false}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])}if(!isGlobalBinding(callee))return false;return true}if(callee.type==="MemberExpression"){const memberName=(0,eslint_devkit_1.propertyName)(callee)??"";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(GLOBAL_ONLY_SINKS.has(memberName)){if(!GLOBAL_OBJECTS.has(objectName))return false;const object=callee.object;return object.type==="Identifier"&&!isLocallyBoundIn(object,sourceCode)}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"&&(0,eslint_devkit_1.propertyName)(callee)!==null){if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["text","json","arrayBuffer","formData","blob"])){return true}if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["readFile","readFileSync"])){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 isGlobalBinding=identifier=>{let scope=sourceCode.getScope(identifier);while(scope){const found=scope.variables.find(v=>v.name===identifier.name);if(found)return found.defs.length===0;scope=scope.upper}return true};const checkCallExpression=node=>{if((node.type==="NewExpression"||node.type==="CallExpression")&&node.callee.type==="Identifier"&&node.callee.name==="Function"&&isGlobalBinding(node.callee)){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"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["readFile","readFileSync"])){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
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDeserialization=void 0;const node_fs_1=require("node:fs");const node_path_1=require("node:path");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 GLOBAL_ONLY_SINKS=new Set(["eval","Function"]);function isLocallyBoundIn(identifier,sourceCode){for(let scope=sourceCode.getScope(identifier);scope!==null;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(variable!==void 0)return variable.defs.length>0}return false}const GLOBAL_OBJECTS=new Set(["window","globalThis","global","self"]);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 majorCache=new Map;function declaredMajorFrom(startDir,pkg){const cacheKey=`${startDir}\0${pkg}`;const cached=majorCache.get(cacheKey);if(cached!==void 0)return cached;let dir=startDir;let found=0;for(let depth=0;depth<12;depth++){try{const manifest=JSON.parse((0,node_fs_1.readFileSync)((0,node_path_1.join)(dir,"package.json"),"utf8"));const range=manifest.dependencies?.[pkg]??manifest.devDependencies?.[pkg]??manifest.peerDependencies?.[pkg];if(typeof range==="string"){const digits=/(\d+)/.exec(range);if(digits!==null)found=Number(digits[1]);break}}catch{}const parent=(0,node_path_1.dirname)(dir);if(parent===dir)break;dir=parent}majorCache.set(cacheKey,found);return found}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:{interop:{runtimes:["eslint","oxlint"]},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:[]}],createOnce(context){let dangerousFunctions;let validationFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let safeYamlSchemas;let additionalSafeYamlSchemas;let nonExecutingPackages;let additionalNonExecutingPackages;let safeSchemas;let inertPackages;let sourceCode;let filename;let safetyChecker;let validatedVariables;let untrustedVariables;let literalPathFileVars;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))){if(binding.module==="js-yaml"&&declaredMajorFrom((0,node_path_1.dirname)(context.filename),"js-yaml")>=4){return false}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])}if(!isGlobalBinding(callee))return false;return true}if(callee.type==="MemberExpression"){const memberName=(0,eslint_devkit_1.propertyName)(callee)??"";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(GLOBAL_ONLY_SINKS.has(memberName)){if(!GLOBAL_OBJECTS.has(objectName))return false;const object=callee.object;return object.type==="Identifier"&&!isLocallyBoundIn(object,sourceCode)}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"&&(0,eslint_devkit_1.propertyName)(callee)!==null){if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["text","json","arrayBuffer","formData","blob"])){return true}if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["readFile","readFileSync"])){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 isGlobalBinding=identifier=>{let scope=sourceCode.getScope(identifier);while(scope){const found=scope.variables.find(v=>v.name===identifier.name);if(found)return found.defs.length===0;scope=scope.upper}return true};const checkCallExpression=node=>{if((node.type==="NewExpression"||node.type==="CallExpression")&&node.callee.type==="Identifier"&&node.callee.name==="Function"&&isGlobalBinding(node.callee)){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{before(){const options=context.options[0]||{};({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);safeSchemas=new Set([...safeYamlSchemas,...additionalSafeYamlSchemas]);inertPackages=new Set([...nonExecutingPackages,...additionalNonExecutingPackages]);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});validatedVariables=new Set;untrustedVariables=new Set;literalPathFileVars=new Set},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"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["readFile","readFileSync"])){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"];const INLINE_ESCAPE_SUFFIX='.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\\\$&")';function taintSource(node,scope,requestRoots,depth=0){if(depth>6)return null;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(unwrapped!==node)return taintSource(unwrapped,scope,requestRoots,depth+1);if(node.type==="TemplateLiteral"){for(const expression of node.expressions){const found=taintSource(expression,scope,requestRoots,depth+1);if(found!==null)return found}return null}if(node.type==="BinaryExpression"&&node.operator==="+"){return taintSource(node.left,scope,requestRoots,depth+1)??taintSource(node.right,scope,requestRoots,depth+1)}if(node.type==="AwaitExpression"){return taintSource(node.argument,scope,requestRoots,depth+1)}if(node.type==="MemberExpression"){let root=node;const properties=[];while(root.type==="MemberExpression"){const link=(0,eslint_devkit_1.propertyName)(root);if(link!==null)properties.unshift(link);root=root.object}if(root.type==="Identifier"){if(requestRoots.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"){const reader=(0,eslint_devkit_1.propertyName)(callee);if(reader!==null&&READER_METHODS.has(reader)){return reader}}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,requestRoots,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,requestRoots,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 DEFAULT_REQUEST_ROOT_NAMES=["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")return false;if((0,eslint_devkit_1.propertyName)(callee)===null)return false;if((0,eslint_devkit_1.propertyName)(callee)==="escape"&&callee.object.type==="Identifier"&&callee.object.name==="RegExp"){return true}return(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),MEMBER_ESCAPERS)}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"&&(0,eslint_devkit_1.propertyName)(node)==="source"){return true}if(node.type==="BinaryExpression"&&node.operator==="+"){return isRegexClone(node.left)||isRegexClone(node.right)}return false}function isSameObjectPair(pattern,flags){const root=node=>node.type==="MemberExpression"&&!node.computed&&node.object.type==="Identifier"&&node.property.type==="Identifier"?node.object.name:null;const a=root(pattern);return a!==null&&a===root(flags)}function hasDynamicFlags(node){if(node.arguments.length>1){const flagsNode=node.arguments[1];return!((0,eslint_devkit_1.staticString)(flagsNode)!==null)}return false}function extractPattern(node,sourceCode,trustedFunctions,scope,requestRoots){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,requestRoots);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:{requestRootNames:{type:"array",items:{type:"string"},default:[...DEFAULT_REQUEST_ROOT_NAMES],description:"Identifier names that select a candidate inbound request. Replaces the default."},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;const requestRoots=new Set(options.requestRootNames??DEFAULT_REQUEST_ROOT_NAMES);function checkRegExpCall(node){if(!isRegExpConstructor(node.callee,sourceCode.getScope(node))){return}const{patternNode,isUserInput:isUserInputValue,isEscaped:isEscapedValue}=extractPattern(node,sourceCode,trustedEscapingFunctions,sourceCode.getScope(node),requestRoots);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)&&!isSameObjectPair(patternNode,node.arguments[1])){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}}});
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,requestRoots,depth=0){if(depth>6)return null;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(unwrapped!==node)return taintSource(unwrapped,scope,requestRoots,depth+1);if(node.type==="TemplateLiteral"){for(const expression of node.expressions){const found=taintSource(expression,scope,requestRoots,depth+1);if(found!==null)return found}return null}if(node.type==="BinaryExpression"&&node.operator==="+"){return taintSource(node.left,scope,requestRoots,depth+1)??taintSource(node.right,scope,requestRoots,depth+1)}if(node.type==="AwaitExpression"){return taintSource(node.argument,scope,requestRoots,depth+1)}if(node.type==="MemberExpression"){let root=node;const properties=[];while(root.type==="MemberExpression"){const link=(0,eslint_devkit_1.propertyName)(root);if(link!==null)properties.unshift(link);root=root.object}if(root.type==="Identifier"){if(requestRoots.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"){const reader=(0,eslint_devkit_1.propertyName)(callee);if(reader!==null&&READER_METHODS.has(reader)){return reader}}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,requestRoots,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,requestRoots,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 DEFAULT_REQUEST_ROOT_NAMES=["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")return false;if((0,eslint_devkit_1.propertyName)(callee)===null)return false;if((0,eslint_devkit_1.propertyName)(callee)==="escape"&&callee.object.type==="Identifier"&&callee.object.name==="RegExp"){return true}return(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),MEMBER_ESCAPERS)}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"&&(0,eslint_devkit_1.propertyName)(node)==="source"){return true}if(node.type==="BinaryExpression"&&node.operator==="+"){return isRegexClone(node.left)||isRegexClone(node.right)}return false}function isSameObjectPair(pattern,flags){const root=node=>node.type==="MemberExpression"&&!node.computed&&node.object.type==="Identifier"&&node.property.type==="Identifier"?node.object.name:null;const a=root(pattern);return a!==null&&a===root(flags)}function hasDynamicFlags(node){if(node.arguments.length>1){const flagsNode=node.arguments[1];return!((0,eslint_devkit_1.staticString)(flagsNode)!==null)}return false}function extractPattern(node,sourceCode,trustedFunctions,scope,requestRoots){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,requestRoots);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:{interop:{runtimes:["eslint","oxlint"]},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:{requestRootNames:{type:"array",items:{type:"string"},default:[...DEFAULT_REQUEST_ROOT_NAMES],description:"Identifier names that select a candidate inbound request. Replaces the default."},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}],createOnce(context,currentOptions){let allowLiterals;let maxPatternLength;let trustedEscapingFunctions;let sourceCode;let requestRoots;function checkRegExpCall(node){if(!isRegExpConstructor(node.callee,sourceCode.getScope(node))){return}const{patternNode,isUserInput:isUserInputValue,isEscaped:isEscapedValue}=extractPattern(node,sourceCode,trustedEscapingFunctions,sourceCode.getScope(node),requestRoots);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)&&!isSameObjectPair(patternNode,node.arguments[1])){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{before(){const[options={}]=currentOptions();({allowLiterals=true,maxPatternLength=100,trustedEscapingFunctions=[...DEFAULT_TRUSTED_ESCAPING_FUNCTIONS]}=options);sourceCode=context.sourceCode;requestRoots=new Set(options.requestRootNames??DEFAULT_REQUEST_ROOT_NAMES)},CallExpression:checkRegExpCall,NewExpression:checkRegExpCall}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakPasswordRecovery=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 CREDENTIAL_GENERATORS=new Set(["randomBytes","randomUUID","randomInt","getRandomValues","nanoid","uuidv4"]);exports.noWeakPasswordRecovery=(0,eslint_devkit_1.createRule)({name:"no-weak-password-recovery",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-weak-password-recovery.md",description:"Detects weak password recovery mechanisms",cwe:"CWE-640"},messages:{missingRateLimit:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Rate Limit",cwe:"CWE-640",description:"Password recovery attempts not rate limited",severity:"HIGH",fix:"Implement rate limiting on recovery requests",documentationLink:"https://owasp.org/www-community/attacks/Brute_force_attack"}),predictableRecoveryToken:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Predictable Recovery Token",cwe:"CWE-640",description:"Recovery token can be predicted or guessed",severity:"CRITICAL",fix:"Use cryptographically secure random tokens",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),insufficientTokenEntropy:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insufficient Token Entropy",cwe:"CWE-640",description:"Recovery token has insufficient randomness",severity:"HIGH",fix:"Use at least 128-bit entropy for tokens",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),missingTokenExpiration:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Token Expiration",cwe:"CWE-640",description:"Recovery tokens never expire",severity:"HIGH",fix:"Implement token expiration (15-60 minutes)",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),recoveryLoggingSensitiveData:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Recovery Logging Sensitive Data",cwe:"CWE-640",description:"Logging sensitive data during password recovery",severity:"MEDIUM",fix:"Never log passwords, tokens, or sensitive recovery data",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"})},schema:[{type:"object",properties:{secureTokenFunctions:{type:"array",items:{type:"string"},default:["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],description:"Functions that generate cryptographically secure tokens"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as secure"},trustedAnnotations:{type:"array",items:{type:"string"},default:["secure-recovery","rate-limited"],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:[{secureTokenFunctions:["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers:[],trustedAnnotations:["secure-recovery","rate-limited"],strictMode:false}],create(context){const options=context.options[0]||{};const{secureTokenFunctions=["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers=[],trustedAnnotations=["secure-recovery","rate-limited"],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isRecoveryRelated=text=>{const lowerText=text.toLowerCase();const passwordKeywords=["password","pwd"];const recoveryKeywords=["reset","recover","forgot","restore"];const hasPasswordKeyword=passwordKeywords.some(keyword=>lowerText.includes(keyword));const hasRecoveryKeyword=recoveryKeywords.some(keyword=>lowerText.includes(keyword));if(hasPasswordKeyword&&hasRecoveryKeyword){return true}const strongRecoveryPatterns=["resetpassword","passwordreset","forgotpassword","passwordrecovery","recoverytoken","password_reset","forgot_password","reset_password","passwordforgot","recoverpassword"];return strongRecoveryPatterns.some(pattern=>lowerText.includes(pattern))};const isSecureTokenGeneration=callExpression=>{const callText=sourceCode.getText(callExpression);return secureTokenFunctions.some(func=>callText.includes(func))};const looksLikeTokenValue=callExpression=>!callExpression.arguments.some(arg=>arg.type==="ArrowFunctionExpression"||arg.type==="FunctionExpression");const usesPredictableSource=callExpression=>{const text=sourceCode.getText(callExpression);return/\bMath\s*(?:\.\s*random|\[\s*['"]random['"]\s*\])\s*\(/.test(text)||/\bDate\s*(?:\.\s*now|\[\s*['"]now['"]\s*\])\s*\(/.test(text)||/new\s+Date\s*\([^)]*\)\s*(?:\.\s*getTime|\[\s*['"]getTime['"]\s*\])\s*\(/.test(text)||/\buuid\s*(?:\.\s*v1|\[\s*['"]v1['"]\s*\])\s*\(/.test(text)||/\bv1\s*\(\s*\)/.test(text)};const isCredentialName=name=>/token|otp|code|secret|nonce|magiclink/i.test(name);const handlesRecoveryCredential=functionNode=>{const walk=scope=>{for(const reference of scope.references){if(CREDENTIAL_GENERATORS.has(reference.identifier.name)){return true}}for(const variable of scope.variables){for(const definition of variable.defs){if(definition.type==="Variable"&&definition.node.init?.type==="CallExpression"){const{callee}=definition.node.init;const calleeName=callee.type==="Identifier"?callee.name:callee.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(callee):null;if(calleeName!==null&&CREDENTIAL_GENERATORS.has(calleeName)){return true}}}if(!isCredentialName(variable.name)){continue}if(variable.defs.some(definition=>definition.type==="Parameter"||definition.type==="Variable"&&definition.node.init!==null)){return true}}return scope.childScopes.some(child=>walk(child))};return walk(sourceCode.getScope(functionNode.body))};const isDeclarationOnly=fn=>fn.body.body.length===1&&fn.body.body[0]?.type==="ReturnStatement";const hasTokenExpiration=functionNode=>{const functionText=sourceCode.getText(functionNode).toLowerCase();return functionText.includes("expire")||functionText.includes("ttl")||functionText.includes("timeout")||functionText.includes("lifetime")};return{VariableDeclarator(node){if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name.toLowerCase();if(isRecoveryRelated(varName)){const initText=sourceCode.getText(node.init);if(node.init.type==="CallExpression"){if(looksLikeTokenValue(node.init)&&!isSecureTokenGeneration(node.init)&&usesPredictableSource(node.init)){if(safetyChecker.isSafe(node,context)||node.parent&&safetyChecker.isSafe(node.parent,context)){return}context.report({node:node.init,messageId:"predictableRecoveryToken",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(node.init.type==="BinaryExpression"){if(usesPredictableSource(node.init)||initText.includes("timestamp")){if(safetyChecker.isSafe(node,context)||node.parent&&safetyChecker.isSafe(node.parent,context)){return}context.report({node:node.init,messageId:"insufficientTokenEntropy",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},FunctionDeclaration(node){if(!node.id){return}const functionName=node.id.name;const functionText=sourceCode.getText(node).toLowerCase();if(isRecoveryRelated(functionName)&&!isDeclarationOnly(node)&&handlesRecoveryCredential(node)){if(!hasTokenExpiration(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.id,messageId:"missingTokenExpiration",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}if(!functionText.includes("limit")&&!functionText.includes("rate")){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.id,messageId:"missingRateLimit",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&(callee.object.name==="console"||callee.object.name==="logger")&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["log","info","warn","error"])||callee.type==="Identifier"&&callee.name==="logger"){const args=node.arguments;for(const arg of args){if(arg.type==="Literal"){continue}const argText=sourceCode.getText(arg).toLowerCase();if(isRecoveryRelated(argText)&&(argText.includes("token")||argText.includes("password")||argText.includes("reset")||argText.includes("code"))){if(safetyChecker.isSafe(node,context)){continue}context.report({node:arg,messageId:"recoveryLoggingSensitiveData",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakPasswordRecovery=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 CREDENTIAL_GENERATORS=new Set(["randomBytes","randomUUID","randomInt","getRandomValues","nanoid","uuidv4"]);exports.noWeakPasswordRecovery=(0,eslint_devkit_1.createRule)({name:"no-weak-password-recovery",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-weak-password-recovery.md",description:"Detects weak password recovery mechanisms",cwe:"CWE-640"},messages:{missingRateLimit:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Rate Limit",cwe:"CWE-640",description:"Password recovery attempts not rate limited",severity:"HIGH",fix:"Implement rate limiting on recovery requests",documentationLink:"https://owasp.org/www-community/attacks/Brute_force_attack"}),predictableRecoveryToken:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Predictable Recovery Token",cwe:"CWE-640",description:"Recovery token can be predicted or guessed",severity:"CRITICAL",fix:"Use cryptographically secure random tokens",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),insufficientTokenEntropy:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insufficient Token Entropy",cwe:"CWE-640",description:"Recovery token has insufficient randomness",severity:"HIGH",fix:"Use at least 128-bit entropy for tokens",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),missingTokenExpiration:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Token Expiration",cwe:"CWE-640",description:"Recovery tokens never expire",severity:"HIGH",fix:"Implement token expiration (15-60 minutes)",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"}),recoveryLoggingSensitiveData:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Recovery Logging Sensitive Data",cwe:"CWE-640",description:"Logging sensitive data during password recovery",severity:"MEDIUM",fix:"Never log passwords, tokens, or sensitive recovery data",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"})},schema:[{type:"object",properties:{secureTokenFunctions:{type:"array",items:{type:"string"},default:["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],description:"Functions that generate cryptographically secure tokens"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as secure"},trustedAnnotations:{type:"array",items:{type:"string"},default:["secure-recovery","rate-limited"],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:[{secureTokenFunctions:["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers:[],trustedAnnotations:["secure-recovery","rate-limited"],strictMode:false}],createOnce(context){let secureTokenFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;const isRecoveryRelated=text=>{const lowerText=text.toLowerCase();const passwordKeywords=["password","pwd"];const recoveryKeywords=["reset","recover","forgot","restore"];const hasPasswordKeyword=passwordKeywords.some(keyword=>lowerText.includes(keyword));const hasRecoveryKeyword=recoveryKeywords.some(keyword=>lowerText.includes(keyword));if(hasPasswordKeyword&&hasRecoveryKeyword){return true}const strongRecoveryPatterns=["resetpassword","passwordreset","forgotpassword","passwordrecovery","recoverytoken","password_reset","forgot_password","reset_password","passwordforgot","recoverpassword"];return strongRecoveryPatterns.some(pattern=>lowerText.includes(pattern))};const isSecureTokenGeneration=callExpression=>{const callText=sourceCode.getText(callExpression);return secureTokenFunctions.some(func=>callText.includes(func))};const looksLikeTokenValue=callExpression=>!callExpression.arguments.some(arg=>arg.type==="ArrowFunctionExpression"||arg.type==="FunctionExpression");const usesPredictableSource=callExpression=>{const text=sourceCode.getText(callExpression);return/\bMath\s*(?:\.\s*random|\[\s*['"]random['"]\s*\])\s*\(/.test(text)||/\bDate\s*(?:\.\s*now|\[\s*['"]now['"]\s*\])\s*\(/.test(text)||/new\s+Date\s*\([^)]*\)\s*(?:\.\s*getTime|\[\s*['"]getTime['"]\s*\])\s*\(/.test(text)||/\buuid\s*(?:\.\s*v1|\[\s*['"]v1['"]\s*\])\s*\(/.test(text)||/\bv1\s*\(\s*\)/.test(text)};const isCredentialName=name=>/token|otp|code|secret|nonce|magiclink/i.test(name);const handlesRecoveryCredential=functionNode=>{const walk=scope=>{for(const reference of scope.references){if(CREDENTIAL_GENERATORS.has(reference.identifier.name)){return true}}for(const variable of scope.variables){for(const definition of variable.defs){if(definition.type==="Variable"&&definition.node.init?.type==="CallExpression"){const{callee}=definition.node.init;const calleeName=callee.type==="Identifier"?callee.name:callee.type==="MemberExpression"?(0,eslint_devkit_1.propertyName)(callee):null;if(calleeName!==null&&CREDENTIAL_GENERATORS.has(calleeName)){return true}}}if(!isCredentialName(variable.name)){continue}if(variable.defs.some(definition=>definition.type==="Parameter"||definition.type==="Variable"&&definition.node.init!==null)){return true}}return scope.childScopes.some(child=>walk(child))};return walk(sourceCode.getScope(functionNode.body))};const isDeclarationOnly=fn=>fn.body.body.length===1&&fn.body.body[0]?.type==="ReturnStatement";const hasTokenExpiration=functionNode=>{const functionText=sourceCode.getText(functionNode).toLowerCase();return functionText.includes("expire")||functionText.includes("ttl")||functionText.includes("timeout")||functionText.includes("lifetime")};return{before(){const options=context.options[0]||{};({secureTokenFunctions=["crypto.randomBytes","crypto.randomUUID","randomBytes","generateSecureToken"],trustedSanitizers=[],trustedAnnotations=["secure-recovery","rate-limited"],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode})},VariableDeclarator(node){if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name.toLowerCase();if(isRecoveryRelated(varName)){const initText=sourceCode.getText(node.init);if(node.init.type==="CallExpression"){if(looksLikeTokenValue(node.init)&&!isSecureTokenGeneration(node.init)&&usesPredictableSource(node.init)){if(safetyChecker.isSafe(node,context)||node.parent&&safetyChecker.isSafe(node.parent,context)){return}context.report({node:node.init,messageId:"predictableRecoveryToken",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(node.init.type==="BinaryExpression"){if(usesPredictableSource(node.init)||initText.includes("timestamp")){if(safetyChecker.isSafe(node,context)||node.parent&&safetyChecker.isSafe(node.parent,context)){return}context.report({node:node.init,messageId:"insufficientTokenEntropy",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},FunctionDeclaration(node){if(!node.id){return}const functionName=node.id.name;const functionText=sourceCode.getText(node).toLowerCase();if(isRecoveryRelated(functionName)&&!isDeclarationOnly(node)&&handlesRecoveryCredential(node)){if(!hasTokenExpiration(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.id,messageId:"missingTokenExpiration",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}if(!functionText.includes("limit")&&!functionText.includes("rate")){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.id,messageId:"missingRateLimit",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&(callee.object.name==="console"||callee.object.name==="logger")&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["log","info","warn","error"])||callee.type==="Identifier"&&callee.name==="logger"){const args=node.arguments;for(const arg of args){if(arg.type==="Literal"){continue}const argText=sourceCode.getText(arg).toLowerCase();if(isRecoveryRelated(argText)&&(argText.includes("token")||argText.includes("password")||argText.includes("reset")||argText.includes("code"))){if(safetyChecker.isSafe(node,context)){continue}context.report({node:arg,messageId:"recoveryLoggingSensitiveData",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXpathInjection=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");function literalTextOf(node){if(node.type==="Literal")return typeof node.value==="string"?node.value:"";if(node.type==="TemplateLiteral")return node.quasis.map(q=>q.value.raw).join(" ");if(node.type==="BinaryExpression"&&node.operator==="+"){return`${literalTextOf(node.left)} ${literalTextOf(node.right)}`}return""}const XPATH_AXIS="ancestor-or-self|ancestor|attribute|child|descendant-or-self|descendant|following-sibling|following|namespace|parent|preceding-sibling|preceding|self";const XPATH_SYNTAX=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\/\\*(?![\\w.*/-])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function looksLikeXpath(text){return XPATH_SYNTAX.test(text.replace(/:\/\//g," "))}const XPATH_SYNTAX_UNAMBIGUOUS=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function isWildcardOnlyXpath(text){const cleaned=text.replace(/:\/\//g," ");return XPATH_SYNTAX.test(cleaned)&&!XPATH_SYNTAX_UNAMBIGUOUS.test(cleaned)}const DEFAULT_XPATH_PACKAGES=["xpath","xmldom-xpath","xpath.js","libxmljs","libxmljs2","@xmldom/xmldom"];function isXpathModuleExport(node,scope,xpathPackages){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,scope);return binding!==void 0&&xpathPackages.has(binding.module)}exports.noXpathInjection=(0,eslint_devkit_1.createRule)({name:"no-xpath-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-xpath-injection.md",description:"Detects XPath injection vulnerabilities",cwe:"CWE-643"},messages:{xpathInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XPath Injection",cwe:"CWE-643",description:"XPath injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"}),unsafeXpathConcatenation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XPath Concatenation",cwe:"CWE-643",description:"Unsafe string concatenation in XPath expression",severity:"HIGH",fix:"Use parameterized XPath or escape user input",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),unvalidatedXpathInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unvalidated XPath Input",cwe:"CWE-643",description:"XPath query uses unvalidated user input",severity:"MEDIUM",fix:"Validate and sanitize XPath input before use",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),dangerousXpathExpression:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous XPath Expression",cwe:"CWE-643",description:"XPath expression allows dangerous operations",severity:"MEDIUM",fix:"Restrict XPath to safe patterns and validate expressions",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"})},schema:[{type:"object",properties:{reportDangerousConstructs:{type:"boolean",default:false,description:"Also report constant XPath containing ordinary axis syntax (//, text(), .., /*). These are not vulnerabilities; a constant expression has nothing to inject into. Off by default because it reported essentially every XPath in existence at CVSS 9.8."},xpathFunctions:{type:"array",items:{type:"string"},default:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],description:"XPath evaluation methods treated as query sinks"},safeXpathConstructors:{type:"array",items:{type:"string"},default:["buildXPath","createXPath","safeXPath","xpathBuilder"],description:"Builders that produce a parameterized XPath expression"},xpathValidationFunctions:{type:"array",items:{type:"string"},default:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],description:"Function names that escape or validate XPath input"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as XPath sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},xpathPackages:{type:"array",items:{type:"string"},default:DEFAULT_XPATH_PACKAGES,description:"Module specifiers whose exports evaluate an XPath expression, matched against a resolved import binding. Replaces the built-in list."},additionalXpathPackages:{type:"array",items:{type:"string"},default:[],description:"Extra XPath package specifiers, on top of `xpathPackages`."}},additionalProperties:false}]},defaultOptions:[{xpathPackages:DEFAULT_XPATH_PACKAGES,additionalXpathPackages:[],xpathFunctions:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],safeXpathConstructors:["buildXPath","createXPath","safeXPath","xpathBuilder"],xpathValidationFunctions:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers:[],trustedAnnotations:["@xpath-safe"],strictMode:false}],create(context){const options=context.options[0]||{};const{reportDangerousConstructs=false,xpathPackages=DEFAULT_XPATH_PACKAGES,additionalXpathPackages=[],xpathFunctions=["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],xpathValidationFunctions=["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const xpathPackageSet=new Set([...xpathPackages,...additionalXpathPackages]);const sourceCode=context.sourceCode;const filename=context.filename;let moduleEvaluatesXpath=false;const wildcardPending=[];const DOM_XPATH_MEMBERS=new Set(["evaluate","selectNodes","selectSingleNode","createExpression"]);const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const validatedVariables=new Set;function everyUseAvoidsSink(node){const declarator=node.parent;if(declarator?.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator||declarator.init!==node||declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const[variable]=context.sourceCode.getDeclaredVariables(declarator);const reads=variable.references.filter(ref=>ref.isRead());if(reads.length===0)return false;return reads.every(ref=>!reachesXpathSink(ref.identifier))}function isXpathSinkCall(call){const callee=call.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),xpathFunctions)}function reachesXpathSink(node){const parent=node.parent;if(!parent)return false;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===node){return isXpathSinkCall(parent)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const declared=parent.id;const resolved=sourceCode.getScope(node).references.find(r=>r.identifier.name===declared.name)?.resolved;return(resolved?.references??[]).some(ref=>{const refParent=ref.identifier.parent;return refParent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&refParent.arguments[0]===ref.identifier&&isXpathSinkCall(refParent)})}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return reachesXpathSink(parent)}return false}const isXpathOperation=node=>{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),xpathFunctions)){if((0,eslint_devkit_1.propertyName)(callee)!=="select"){return true}const receiver=callee.object;return receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/xpath|xpth/i.test(receiver.name)||receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&/xpath/i.test((0,eslint_devkit_1.propertyName)(receiver)??"")}if(callee.type==="Identifier"&&xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)){return true}return false};const containsDangerousXpath=xpathText=>{if(!reportDangerousConstructs)return false;const dangerousPatterns=[/\.\./,/\/\*/,/\[.*\*\]/,/\/\//,/text\(\)/,/comment\(\)/,/processing-instruction\(\)/];return dangerousPatterns.some(pattern=>pattern.test(xpathText))};const isUntrustedXpathInput=inputNode=>{if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(inputNode.object),["query","body","params","param"])){return true}if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}}if(inputNode.type!=="Identifier"){return false}const varName=inputNode.name.toLowerCase();if(["req","request","query","params","input","user","search"].some(keyword=>varName.includes(keyword))){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;return func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})}current=current.parent}return false};const isXpathInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&xpathValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const hasSafeAnnotationOnStatement=node=>{let current=node;while(current){if(current.type==="VariableDeclaration"||current.type==="ExpressionStatement"||current.type==="FunctionDeclaration"){const comments=sourceCode.getCommentsBefore(current);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@xpath-safe")){return true}}}current=current.parent}return false};const declarationReachesSink=declarator=>{const name=declarator.id.name;for(let scope=context.sourceCode.getScope(declarator.id);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===name);if(variable){return variable.references.some(ref=>reachesXpathSink(ref.identifier))}}return false};return{CallExpression(node){if(!isXpathOperation(node)){return}const args=node.arguments;if(args.length===0){return}const xpathArg=args[0];const staticText=xpathArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?null:(0,eslint_devkit_1.staticString)(xpathArg);if(staticText!==null){const xpathText=staticText;if(containsDangerousXpath(xpathText)){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(xpathArg.type==="Identifier"){if(isUntrustedXpathInput(xpathArg)&&!isXpathInputValidated(xpathArg)&&!(xpathArg.type==="Identifier"&&validatedVariables.has(xpathArg.name))){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||safetyChecker.isSafe(xpathArg,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"unvalidatedXpathInput",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},ImportDeclaration(node){if(xpathPackageSet.has(String(node.source.value))){moduleEvaluatesXpath=true}},MemberExpression(node){const member=(0,eslint_devkit_1.propertyName)(node);if(member!==null&&DOM_XPATH_MEMBERS.has(member)){moduleEvaluatesXpath=true}},"Program:exit"(){if(!moduleEvaluatesXpath)return;for(const pending of wildcardPending){context.report({node:pending,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(pending.loc.start.line)}})}},TemplateLiteral(node){const staticText=literalTextOf(node);if(/https?:\/\//.test(staticText)||/^\s*\/api\//.test(staticText)){return}if(/^\s*\/home\//.test(staticText)||/^\s*\/usr\//.test(staticText)||/^\s*\/tmp\//.test(staticText)){return}if(/\[data-[\w-]+/.test(staticText)||/\[class=/.test(staticText)||/\[id=/.test(staticText)){return}if(/\?.*=/.test(staticText)&&!/\[@/.test(staticText)){return}if(!looksLikeXpath(staticText)){return}const wildcardOnly=isWildcardOnlyXpath(staticText);if(node.expressions.length>0){const hasUntrustedInterpolation=node.expressions.some(expr=>isUntrustedXpathInput(expr)&&!isXpathInputValidated(expr)&&!(expr.type==="Identifier"&&validatedVariables.has(expr.name)));if(hasUntrustedInterpolation){if(hasSafeAnnotationOnStatement(node)){return}if(wildcardOnly){wildcardPending.push(node);return}context.report({node,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}if(containsDangerousXpath(staticText)&&reachesXpathSink(node)){if(hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}if(!looksLikeXpath(literalTextOf(node))){return}const isInnerConcat=node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.parent.operator==="+";if(isInnerConcat){return}const operands=[];(function flatten(n){if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&n.operator==="+"){flatten(n.left);flatten(n.right);return}operands.push(n)})(node);const unvalidated=operand=>!isXpathInputValidated(operand)&&!(operand.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&validatedVariables.has(operand.name));const hasUntrusted=operands.some(operand=>isUntrustedXpathInput(operand)&&unvalidated(operand));const dynamicAtSink=reachesXpathSink(node)&&operands.some(operand=>!(0,eslint_devkit_1.isStaticExpression)({node:operand,scope:context.sourceCode.getScope(operand)})&&unvalidated(operand));if((hasUntrusted||dynamicAtSink)&&!everyUseAvoidsSink(node)){if(safetyChecker.isSafe(node,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"xpathInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use parameterized XPath construction with input validation"}})}},VariableDeclarator(node){const declLine=String(node.loc?.start.line??0);if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(xpathValidationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("xpath")&&!varNameLower.includes("query")&&!varNameLower.includes("path")){return}if(node.init.type==="Literal"&&typeof node.init.value==="string"){if(looksLikeXpath(node.init.value)&&containsDangerousXpath(node.init.value)){if(safetyChecker.isSafe(node.init,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:node.init,messageId:"dangerousXpathExpression",data:{filePath:filename,line:declLine}})}}else if(isUntrustedXpathInput(node.init)&&declarationReachesSink(node)&&!isUntrustedXpathInput(node.id)){context.report({node:node.init,messageId:"xpathInjection",data:{filePath:filename,line:declLine,severity:"MEDIUM",safeAlternative:"Use safe XPath construction methods"}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXpathInjection=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");function literalTextOf(node){if(node.type==="Literal")return typeof node.value==="string"?node.value:"";if(node.type==="TemplateLiteral")return node.quasis.map(q=>q.value.raw).join(" ");if(node.type==="BinaryExpression"&&node.operator==="+"){return`${literalTextOf(node.left)} ${literalTextOf(node.right)}`}return""}const XPATH_AXIS="ancestor-or-self|ancestor|attribute|child|descendant-or-self|descendant|following-sibling|following|namespace|parent|preceding-sibling|preceding|self";const XPATH_SYNTAX=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\/\\*(?![\\w.*/-])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function looksLikeXpath(text){return XPATH_SYNTAX.test(text.replace(/:\/\//g," "))}const XPATH_SYNTAX_UNAMBIGUOUS=new RegExp(`\\/\\/(?=[A-Za-z_*@.])|\\[@(?=[A-Za-z_*])|\\b(?:${XPATH_AXIS})::|\\btext\\(\\)|\\bnode\\(\\)|\\bcontains\\(|\\bstarts-with\\(|\\blocal-name\\(|\\bposition\\(\\)|\\/[A-Za-z_*][\\w.-]*\\[`);function isWildcardOnlyXpath(text){const cleaned=text.replace(/:\/\//g," ");return XPATH_SYNTAX.test(cleaned)&&!XPATH_SYNTAX_UNAMBIGUOUS.test(cleaned)}const DEFAULT_XPATH_PACKAGES=["xpath","xmldom-xpath","xpath.js","libxmljs","libxmljs2","@xmldom/xmldom"];function isXpathModuleExport(node,scope,xpathPackages){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,scope);return binding!==void 0&&xpathPackages.has(binding.module)}exports.noXpathInjection=(0,eslint_devkit_1.createRule)({name:"no-xpath-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-xpath-injection.md",description:"Detects XPath injection vulnerabilities",cwe:"CWE-643"},messages:{xpathInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XPath Injection",cwe:"CWE-643",description:"XPath injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"}),unsafeXpathConcatenation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XPath Concatenation",cwe:"CWE-643",description:"Unsafe string concatenation in XPath expression",severity:"HIGH",fix:"Use parameterized XPath or escape user input",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),unvalidatedXpathInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unvalidated XPath Input",cwe:"CWE-643",description:"XPath query uses unvalidated user input",severity:"MEDIUM",fix:"Validate and sanitize XPath input before use",documentationLink:"https://owasp.org/www-community/attacks/XPATH_Injection"}),dangerousXpathExpression:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous XPath Expression",cwe:"CWE-643",description:"XPath expression allows dangerous operations",severity:"MEDIUM",fix:"Restrict XPath to safe patterns and validate expressions",documentationLink:"https://cwe.mitre.org/data/definitions/643.html"})},schema:[{type:"object",properties:{reportDangerousConstructs:{type:"boolean",default:false,description:"Also report constant XPath containing ordinary axis syntax (//, text(), .., /*). These are not vulnerabilities; a constant expression has nothing to inject into. Off by default because it reported essentially every XPath in existence at CVSS 9.8."},xpathFunctions:{type:"array",items:{type:"string"},default:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],description:"XPath evaluation methods treated as query sinks"},safeXpathConstructors:{type:"array",items:{type:"string"},default:["buildXPath","createXPath","safeXPath","xpathBuilder"],description:"Builders that produce a parameterized XPath expression"},xpathValidationFunctions:{type:"array",items:{type:"string"},default:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],description:"Function names that escape or validate XPath input"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as XPath sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},xpathPackages:{type:"array",items:{type:"string"},default:DEFAULT_XPATH_PACKAGES,description:"Module specifiers whose exports evaluate an XPath expression, matched against a resolved import binding. Replaces the built-in list."},additionalXpathPackages:{type:"array",items:{type:"string"},default:[],description:"Extra XPath package specifiers, on top of `xpathPackages`."}},additionalProperties:false}]},defaultOptions:[{xpathPackages:DEFAULT_XPATH_PACKAGES,additionalXpathPackages:[],xpathFunctions:["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],safeXpathConstructors:["buildXPath","createXPath","safeXPath","xpathBuilder"],xpathValidationFunctions:["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers:[],trustedAnnotations:["@xpath-safe"],strictMode:false}],createOnce(context){let reportDangerousConstructs;let xpathPackages;let additionalXpathPackages;let xpathFunctions;let xpathValidationFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let xpathPackageSet;let sourceCode;let filename;let moduleEvaluatesXpath;let wildcardPending;let DOM_XPATH_MEMBERS;let safetyChecker;let validatedVariables;function everyUseAvoidsSink(node){const declarator=node.parent;if(declarator?.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator||declarator.init!==node||declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const[variable]=context.sourceCode.getDeclaredVariables(declarator);const reads=variable.references.filter(ref=>ref.isRead());if(reads.length===0)return false;return reads.every(ref=>!reachesXpathSink(ref.identifier))}function isXpathSinkCall(call){const callee=call.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),xpathFunctions)}function reachesXpathSink(node){const parent=node.parent;if(!parent)return false;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===node){return isXpathSinkCall(parent)}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const declared=parent.id;const resolved=sourceCode.getScope(node).references.find(r=>r.identifier.name===declared.name)?.resolved;return(resolved?.references??[]).some(ref=>{const refParent=ref.identifier.parent;return refParent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&refParent.arguments[0]===ref.identifier&&isXpathSinkCall(refParent)})}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return reachesXpathSink(parent)}return false}const isXpathOperation=node=>{const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),xpathFunctions)){if((0,eslint_devkit_1.propertyName)(callee)!=="select"){return true}const receiver=callee.object;return receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&/xpath|xpth/i.test(receiver.name)||receiver.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&/xpath/i.test((0,eslint_devkit_1.propertyName)(receiver)??"")}if(callee.type==="Identifier"&&xpathFunctions.includes(callee.name)&&isXpathModuleExport(callee,sourceCode.getScope(callee),xpathPackageSet)){return true}return false};const containsDangerousXpath=xpathText=>{if(!reportDangerousConstructs)return false;const dangerousPatterns=[/\.\./,/\/\*/,/\[.*\*\]/,/\/\//,/text\(\)/,/comment\(\)/,/processing-instruction\(\)/];return dangerousPatterns.some(pattern=>pattern.test(xpathText))};const isUntrustedXpathInput=inputNode=>{if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(inputNode.object),["query","body","params","param"])){return true}if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}}if(inputNode.type!=="Identifier"){return false}const varName=inputNode.name.toLowerCase();if(["req","request","query","params","input","user","search"].some(keyword=>varName.includes(keyword))){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;return func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})}current=current.parent}return false};const isXpathInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&xpathValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const hasSafeAnnotationOnStatement=node=>{let current=node;while(current){if(current.type==="VariableDeclaration"||current.type==="ExpressionStatement"||current.type==="FunctionDeclaration"){const comments=sourceCode.getCommentsBefore(current);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@xpath-safe")){return true}}}current=current.parent}return false};const declarationReachesSink=declarator=>{const name=declarator.id.name;for(let scope=context.sourceCode.getScope(declarator.id);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===name);if(variable){return variable.references.some(ref=>reachesXpathSink(ref.identifier))}}return false};return{before(){const options=context.options[0]||{};({reportDangerousConstructs=false,xpathPackages=DEFAULT_XPATH_PACKAGES,additionalXpathPackages=[],xpathFunctions=["evaluate","selectSingleNode","selectNodes","xpath","select","select1"],xpathValidationFunctions=["validateXPath","escapeXPath","sanitizeXPath","cleanXPath"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);xpathPackageSet=new Set([...xpathPackages,...additionalXpathPackages]);sourceCode=context.sourceCode;filename=context.filename;moduleEvaluatesXpath=false;wildcardPending=[];DOM_XPATH_MEMBERS=new Set(["evaluate","selectNodes","selectSingleNode","createExpression"]);safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});validatedVariables=new Set},CallExpression(node){if(!isXpathOperation(node)){return}const args=node.arguments;if(args.length===0){return}const xpathArg=args[0];const staticText=xpathArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?null:(0,eslint_devkit_1.staticString)(xpathArg);if(staticText!==null){const xpathText=staticText;if(containsDangerousXpath(xpathText)){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(xpathArg.type==="Identifier"){if(isUntrustedXpathInput(xpathArg)&&!isXpathInputValidated(xpathArg)&&!(xpathArg.type==="Identifier"&&validatedVariables.has(xpathArg.name))){if((0,eslint_devkit_3.hasSafeAnnotation)(xpathArg,context,trustedAnnotations)||safetyChecker.isSafe(xpathArg,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:xpathArg,messageId:"unvalidatedXpathInput",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},ImportDeclaration(node){if(xpathPackageSet.has(String(node.source.value))){moduleEvaluatesXpath=true}},MemberExpression(node){const member=(0,eslint_devkit_1.propertyName)(node);if(member!==null&&DOM_XPATH_MEMBERS.has(member)){moduleEvaluatesXpath=true}},"Program:exit"(){if(!moduleEvaluatesXpath)return;for(const pending of wildcardPending){context.report({node:pending,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(pending.loc.start.line)}})}},TemplateLiteral(node){const staticText=literalTextOf(node);if(/https?:\/\//.test(staticText)||/^\s*\/api\//.test(staticText)){return}if(/^\s*\/home\//.test(staticText)||/^\s*\/usr\//.test(staticText)||/^\s*\/tmp\//.test(staticText)){return}if(/\[data-[\w-]+/.test(staticText)||/\[class=/.test(staticText)||/\[id=/.test(staticText)){return}if(/\?.*=/.test(staticText)&&!/\[@/.test(staticText)){return}if(!looksLikeXpath(staticText)){return}const wildcardOnly=isWildcardOnlyXpath(staticText);if(node.expressions.length>0){const hasUntrustedInterpolation=node.expressions.some(expr=>isUntrustedXpathInput(expr)&&!isXpathInputValidated(expr)&&!(expr.type==="Identifier"&&validatedVariables.has(expr.name)));if(hasUntrustedInterpolation){if(hasSafeAnnotationOnStatement(node)){return}if(wildcardOnly){wildcardPending.push(node);return}context.report({node,messageId:"unsafeXpathConcatenation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}if(containsDangerousXpath(staticText)&&reachesXpathSink(node)){if(hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"dangerousXpathExpression",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}if(!looksLikeXpath(literalTextOf(node))){return}const isInnerConcat=node.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.parent.operator==="+";if(isInnerConcat){return}const operands=[];(function flatten(n){if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&n.operator==="+"){flatten(n.left);flatten(n.right);return}operands.push(n)})(node);const unvalidated=operand=>!isXpathInputValidated(operand)&&!(operand.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&validatedVariables.has(operand.name));const hasUntrusted=operands.some(operand=>isUntrustedXpathInput(operand)&&unvalidated(operand));const dynamicAtSink=reachesXpathSink(node)&&operands.some(operand=>!(0,eslint_devkit_1.isStaticExpression)({node:operand,scope:context.sourceCode.getScope(operand)})&&unvalidated(operand));if((hasUntrusted||dynamicAtSink)&&!everyUseAvoidsSink(node)){if(safetyChecker.isSafe(node,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node,messageId:"xpathInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use parameterized XPath construction with input validation"}})}},VariableDeclarator(node){const declLine=String(node.loc?.start.line??0);if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(xpathValidationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("xpath")&&!varNameLower.includes("query")&&!varNameLower.includes("path")){return}if(node.init.type==="Literal"&&typeof node.init.value==="string"){if(looksLikeXpath(node.init.value)&&containsDangerousXpath(node.init.value)){if(safetyChecker.isSafe(node.init,context)||hasSafeAnnotationOnStatement(node)){return}context.report({node:node.init,messageId:"dangerousXpathExpression",data:{filePath:filename,line:declLine}})}}else if(isUntrustedXpathInput(node.init)&&declarationReachesSink(node)&&!isUntrustedXpathInput(node.id)){context.report({node:node.init,messageId:"xpathInjection",data:{filePath:filename,line:declLine,severity:"MEDIUM",safeAlternative:"Use safe XPath construction methods"}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXxeInjection=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 DEFAULT_SAFE_PARSER_OPTIONS=["noent","resolveExternals","expandEntityReferences","entityResolver","processEntities","dtdload"];const DEFAULT_XML_VALIDATION_FUNCTIONS=["validateXml","sanitizeXml","cleanXml","parseXmlSafe"];const DEFAULT_XML_MODULES=["libxmljs","libxmljs2","xml2js","xml2json","fast-xml-parser","@xmldom/xmldom","xmldom","node-expat"];const PROVEN_NO_EXTERNAL_ENTITIES=["xml2js","fast-xml-parser","@xmldom/xmldom","xmldom"];const DEFAULT_XML_PARSE_METHODS=["parseFromString","parseString","parseStringPromise","parseXml","parseXmlAsync","parseXmlString","parseXML"];const DEFAULT_DANGEROUS_PARSER_OPTIONS=["resolveExternals","expandEntityReferences","noent","processEntities","dtdload"];const optionKey=prop=>{if(prop.type!==eslint_devkit_3.AST_NODE_TYPES.Property||prop.computed)return void 0;if(prop.key.type===eslint_devkit_3.AST_NODE_TYPES.Identifier)return prop.key.name;return(0,eslint_devkit_1.staticString)(prop.key)??void 0};const hasDangerousParserOptions=(optionsNode,dangerousKeys)=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!dangerousKeys.has(key))continue;const{value}=prop;if(value.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&value.value===true)return true}return false};const containsDangerousEntities=xmlText=>{return/<!ENTITY/i.test(xmlText)&&/SYSTEM\s+["']/i.test(xmlText)};exports.noXxeInjection=(0,eslint_devkit_1.createRule)({name:"no-xxe-injection",meta:{type:"problem",docs:{description:"Detect XML External Entity (XXE) injection vulnerabilities",url:"https://cwe.mitre.org/data/definitions/611.html",cwe:"CWE-611",cvss:9.1},messages:{xxeInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XXE Injection",cwe:"CWE-611",description:"XML contains dangerous entity declarations",severity:"CRITICAL",fix:"Remove SYSTEM/PUBLIC entity declarations or use safe XML parser",documentationLink:"https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"}),unsafeXmlParser:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XML Parser",cwe:"CWE-611",description:"Using unsafe XML parser without secure configuration",severity:"HIGH",fix:"Use libxmljs with noent: false or xmldom with entityResolver: null",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"}),externalEntityEnabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"External Entity Processing",cwe:"CWE-611",description:"External entity processing is enabled",severity:"CRITICAL",fix:"Disable external entity processing",documentationLink:"https://cwe.mitre.org/data/definitions/611.html"}),untrustedXmlSource:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Untrusted XML Source",cwe:"CWE-611",description:"XML from untrusted source without validation",severity:"HIGH",fix:"Validate and sanitize XML input before parsing",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{safeParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_PARSER_OPTIONS,description:"Parser option keys whose disabled value proves entity expansion is off"},xmlValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_XML_VALIDATION_FUNCTIONS,description:"Function names that count as XML input validation"},xmlModules:{type:"array",items:{type:"string"},default:DEFAULT_XML_MODULES,description:"Module specifiers this rule treats as XML parsers, matched against a resolved import binding. Replaces the built-in list."},additionalXmlModules:{type:"array",items:{type:"string"},default:[],description:"Extra XML package specifiers, on top of `xmlModules`."},xmlParseMethods:{type:"array",items:{type:"string"},default:DEFAULT_XML_PARSE_METHODS,description:"Method names that only ever parse XML, matched as an exact method name whatever the receiver. Replaces the built-in list."},additionalXmlParseMethods:{type:"array",items:{type:"string"},default:[],description:"Extra XML-only parse method names, on top of `xmlParseMethods`."},dangerousParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_DANGEROUS_PARSER_OPTIONS,description:"Parser option keys whose `true` value turns entity expansion ON. Replaces the built-in list."},entityIncapableModules:{type:"array",items:{type:"string"},default:PROVEN_NO_EXTERNAL_ENTITIES,description:"Packages proven unable to resolve an external entity, and therefore never reported for parsing untrusted input. Replaces the built-in list."},additionalDangerousParserOptions:{type:"array",items:{type:"string"},default:[],description:"Extra entity-expansion option keys, on top of `dangerousParserOptions`."}},additionalProperties:false}]},defaultOptions:[{safeParserOptions:DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions:DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules:DEFAULT_XML_MODULES,additionalXmlModules:[],xmlParseMethods:DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods:[],dangerousParserOptions:DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions:[],entityIncapableModules:PROVEN_NO_EXTERNAL_ENTITIES}],create(context,[options]){const{safeParserOptions=DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions=DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules=DEFAULT_XML_MODULES,additionalXmlModules=[],xmlParseMethods=DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods=[],dangerousParserOptions=DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions=[],entityIncapableModules=PROVEN_NO_EXTERNAL_ENTITIES}=options;const xmlPackages=new Set([...xmlModules,...additionalXmlModules]);const incapablePackages=new Set(entityIncapableModules);const parseMethods=new Set([...xmlParseMethods,...additionalXmlParseMethods]);const dangerousKeys=new Set([...dangerousParserOptions,...additionalDangerousParserOptions]);const filename=context.filename;const sourceCode=context.sourceCode;const isHtmlParse=node=>{const mime=node.arguments[1];return mime!==void 0&&mime.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&typeof mime.value==="string"&&mime.value.toLowerCase().startsWith("text/html")};const reportData=node=>({filePath:filename,line:String(node.loc.start.line)});const resolvesToXmlModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&xmlPackages.has(binding.module)};const resolvesToEntityIncapableModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&incapablePackages.has(binding.module)};const constructionSite=callee=>{if(callee.type!==eslint_devkit_3.AST_NODE_TYPES.MemberExpression)return void 0;const receiver=callee.object;if(receiver.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression)return receiver;if(receiver.type!==eslint_devkit_3.AST_NODE_TYPES.Identifier)return void 0;const variable=sourceCode.getScope(receiver).references.find(reference=>reference.identifier===receiver)?.resolved;const definition=variable?.defs[0];if(definition?.type!=="Variable")return void 0;if(variable.references.filter(reference=>reference.isWrite()).length!==1){return void 0}return definition.node.init?.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression?definition.node.init:void 0};const isXmlParsingCall=node=>{const callee=node.callee;if(callee.type===eslint_devkit_3.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),parseMethods)){return true}if(hasDangerousParserOptions(node.arguments[1],dangerousKeys))return true;if(resolvesToXmlModule(callee))return true;const construction=constructionSite(callee);return construction!==void 0&&resolvesToXmlModule(construction.callee)};const hasSecureParserOptions=optionsNode=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!safeParserOptions.includes(key))continue;const{value}=prop;if(value.type!==eslint_devkit_3.AST_NODE_TYPES.Literal)continue;if(value.value===false||value.value===null)return true}return false};const isXmlInputValidated=xmlSource=>{let current=xmlSource;while(current){if(current.type===eslint_devkit_3.AST_NODE_TYPES.CallExpression&&current.callee.type===eslint_devkit_3.AST_NODE_TYPES.Identifier&&xmlValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const isTrustedXmlSource=xmlSource=>(0,eslint_devkit_1.isStaticExpression)({node:xmlSource,scope:sourceCode.getScope(xmlSource)});return{CallExpression(node){if(!isXmlParsingCall(node))return;const xmlInput=node.arguments[0];if(!xmlInput)return;if(isHtmlParse(node))return;const callOptions=node.arguments[1];const construction=constructionSite(node.callee);const constructionOptions=construction?.arguments[0];if(hasDangerousParserOptions(callOptions,dangerousKeys)){context.report({node:callOptions,messageId:"externalEntityEnabled",data:reportData(node)});return}if(hasDangerousParserOptions(constructionOptions,dangerousKeys)){context.report({node:node.callee,messageId:"unsafeXmlParser",data:reportData(node)});return}if(hasSecureParserOptions(callOptions)||hasSecureParserOptions(constructionOptions)){return}if(isTrustedXmlSource(xmlInput)||isXmlInputValidated(xmlInput))return;if(resolvesToEntityIncapableModule(node.callee)||construction!==void 0&&resolvesToEntityIncapableModule(construction.callee)){return}context.report({node:xmlInput,messageId:"untrustedXmlSource",data:reportData(node)})},Literal(node){if(typeof node.value==="string"&&containsDangerousEntities(node.value)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}},TemplateElement(node){if(containsDangerousEntities(node.value.raw)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noXxeInjection=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 DEFAULT_SAFE_PARSER_OPTIONS=["noent","resolveExternals","expandEntityReferences","entityResolver","processEntities","dtdload"];const DEFAULT_XML_VALIDATION_FUNCTIONS=["validateXml","sanitizeXml","cleanXml","parseXmlSafe"];const DEFAULT_XML_MODULES=["libxmljs","libxmljs2","xml2js","xml2json","fast-xml-parser","@xmldom/xmldom","xmldom","node-expat"];const PROVEN_NO_EXTERNAL_ENTITIES=["xml2js","fast-xml-parser","@xmldom/xmldom","xmldom"];const DEFAULT_XML_PARSE_METHODS=["parseFromString","parseString","parseStringPromise","parseXml","parseXmlAsync","parseXmlString","parseXML"];const DEFAULT_DANGEROUS_PARSER_OPTIONS=["resolveExternals","expandEntityReferences","noent","processEntities","dtdload"];const optionKey=prop=>{if(prop.type!==eslint_devkit_3.AST_NODE_TYPES.Property||prop.computed)return void 0;if(prop.key.type===eslint_devkit_3.AST_NODE_TYPES.Identifier)return prop.key.name;return(0,eslint_devkit_1.staticString)(prop.key)??void 0};const hasDangerousParserOptions=(optionsNode,dangerousKeys)=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!dangerousKeys.has(key))continue;const{value}=prop;if(value.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&value.value===true)return true}return false};const containsDangerousEntities=xmlText=>{return/<!ENTITY/i.test(xmlText)&&/SYSTEM\s+["']/i.test(xmlText)};exports.noXxeInjection=(0,eslint_devkit_1.createRule)({name:"no-xxe-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{description:"Detect XML External Entity (XXE) injection vulnerabilities",url:"https://cwe.mitre.org/data/definitions/611.html",cwe:"CWE-611",cvss:9.1},messages:{xxeInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"XXE Injection",cwe:"CWE-611",description:"XML contains dangerous entity declarations",severity:"CRITICAL",fix:"Remove SYSTEM/PUBLIC entity declarations or use safe XML parser",documentationLink:"https://owasp.org/www-community/vulnerabilities/XML_External_Entity_(XXE)_Processing"}),unsafeXmlParser:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe XML Parser",cwe:"CWE-611",description:"Using unsafe XML parser without secure configuration",severity:"HIGH",fix:"Use libxmljs with noent: false or xmldom with entityResolver: null",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"}),externalEntityEnabled:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"External Entity Processing",cwe:"CWE-611",description:"External entity processing is enabled",severity:"CRITICAL",fix:"Disable external entity processing",documentationLink:"https://cwe.mitre.org/data/definitions/611.html"}),untrustedXmlSource:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Untrusted XML Source",cwe:"CWE-611",description:"XML from untrusted source without validation",severity:"HIGH",fix:"Validate and sanitize XML input before parsing",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{safeParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_PARSER_OPTIONS,description:"Parser option keys whose disabled value proves entity expansion is off"},xmlValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_XML_VALIDATION_FUNCTIONS,description:"Function names that count as XML input validation"},xmlModules:{type:"array",items:{type:"string"},default:DEFAULT_XML_MODULES,description:"Module specifiers this rule treats as XML parsers, matched against a resolved import binding. Replaces the built-in list."},additionalXmlModules:{type:"array",items:{type:"string"},default:[],description:"Extra XML package specifiers, on top of `xmlModules`."},xmlParseMethods:{type:"array",items:{type:"string"},default:DEFAULT_XML_PARSE_METHODS,description:"Method names that only ever parse XML, matched as an exact method name whatever the receiver. Replaces the built-in list."},additionalXmlParseMethods:{type:"array",items:{type:"string"},default:[],description:"Extra XML-only parse method names, on top of `xmlParseMethods`."},dangerousParserOptions:{type:"array",items:{type:"string"},default:DEFAULT_DANGEROUS_PARSER_OPTIONS,description:"Parser option keys whose `true` value turns entity expansion ON. Replaces the built-in list."},entityIncapableModules:{type:"array",items:{type:"string"},default:PROVEN_NO_EXTERNAL_ENTITIES,description:"Packages proven unable to resolve an external entity, and therefore never reported for parsing untrusted input. Replaces the built-in list."},additionalDangerousParserOptions:{type:"array",items:{type:"string"},default:[],description:"Extra entity-expansion option keys, on top of `dangerousParserOptions`."}},additionalProperties:false}]},defaultOptions:[{safeParserOptions:DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions:DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules:DEFAULT_XML_MODULES,additionalXmlModules:[],xmlParseMethods:DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods:[],dangerousParserOptions:DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions:[],entityIncapableModules:PROVEN_NO_EXTERNAL_ENTITIES}],createOnce(context,currentOptions){let safeParserOptions;let xmlValidationFunctions;let xmlModules;let additionalXmlModules;let xmlParseMethods;let additionalXmlParseMethods;let dangerousParserOptions;let additionalDangerousParserOptions;let entityIncapableModules;let xmlPackages;let incapablePackages;let parseMethods;let dangerousKeys;let filename;let sourceCode;const isHtmlParse=node=>{const mime=node.arguments[1];return mime!==void 0&&mime.type===eslint_devkit_3.AST_NODE_TYPES.Literal&&typeof mime.value==="string"&&mime.value.toLowerCase().startsWith("text/html")};const reportData=node=>({filePath:filename,line:String(node.loc.start.line)});const resolvesToXmlModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&xmlPackages.has(binding.module)};const resolvesToEntityIncapableModule=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,sourceCode.getScope(node));return binding!==void 0&&incapablePackages.has(binding.module)};const constructionSite=callee=>{if(callee.type!==eslint_devkit_3.AST_NODE_TYPES.MemberExpression)return void 0;const receiver=callee.object;if(receiver.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression)return receiver;if(receiver.type!==eslint_devkit_3.AST_NODE_TYPES.Identifier)return void 0;const variable=sourceCode.getScope(receiver).references.find(reference=>reference.identifier===receiver)?.resolved;const definition=variable?.defs[0];if(definition?.type!=="Variable")return void 0;if(variable.references.filter(reference=>reference.isWrite()).length!==1){return void 0}return definition.node.init?.type===eslint_devkit_3.AST_NODE_TYPES.NewExpression?definition.node.init:void 0};const isXmlParsingCall=node=>{const callee=node.callee;if(callee.type===eslint_devkit_3.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),parseMethods)){return true}if(hasDangerousParserOptions(node.arguments[1],dangerousKeys))return true;if(resolvesToXmlModule(callee))return true;const construction=constructionSite(callee);return construction!==void 0&&resolvesToXmlModule(construction.callee)};const hasSecureParserOptions=optionsNode=>{if(optionsNode?.type!==eslint_devkit_3.AST_NODE_TYPES.ObjectExpression)return false;for(const prop of optionsNode.properties){const key=optionKey(prop);if(key===void 0||!safeParserOptions.includes(key))continue;const{value}=prop;if(value.type!==eslint_devkit_3.AST_NODE_TYPES.Literal)continue;if(value.value===false||value.value===null)return true}return false};const isXmlInputValidated=xmlSource=>{let current=xmlSource;while(current){if(current.type===eslint_devkit_3.AST_NODE_TYPES.CallExpression&&current.callee.type===eslint_devkit_3.AST_NODE_TYPES.Identifier&&xmlValidationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};const isTrustedXmlSource=xmlSource=>(0,eslint_devkit_1.isStaticExpression)({node:xmlSource,scope:sourceCode.getScope(xmlSource)});return{before(){const[options]=currentOptions();({safeParserOptions=DEFAULT_SAFE_PARSER_OPTIONS,xmlValidationFunctions=DEFAULT_XML_VALIDATION_FUNCTIONS,xmlModules=DEFAULT_XML_MODULES,additionalXmlModules=[],xmlParseMethods=DEFAULT_XML_PARSE_METHODS,additionalXmlParseMethods=[],dangerousParserOptions=DEFAULT_DANGEROUS_PARSER_OPTIONS,additionalDangerousParserOptions=[],entityIncapableModules=PROVEN_NO_EXTERNAL_ENTITIES}=options);xmlPackages=new Set([...xmlModules,...additionalXmlModules]);incapablePackages=new Set(entityIncapableModules);parseMethods=new Set([...xmlParseMethods,...additionalXmlParseMethods]);dangerousKeys=new Set([...dangerousParserOptions,...additionalDangerousParserOptions]);filename=context.filename;sourceCode=context.sourceCode},CallExpression(node){if(!isXmlParsingCall(node))return;const xmlInput=node.arguments[0];if(!xmlInput)return;if(isHtmlParse(node))return;const callOptions=node.arguments[1];const construction=constructionSite(node.callee);const constructionOptions=construction?.arguments[0];if(hasDangerousParserOptions(callOptions,dangerousKeys)){context.report({node:callOptions,messageId:"externalEntityEnabled",data:reportData(node)});return}if(hasDangerousParserOptions(constructionOptions,dangerousKeys)){context.report({node:node.callee,messageId:"unsafeXmlParser",data:reportData(node)});return}if(hasSecureParserOptions(callOptions)||hasSecureParserOptions(constructionOptions)){return}if(isTrustedXmlSource(xmlInput)||isXmlInputValidated(xmlInput))return;if(resolvesToEntityIncapableModule(node.callee)||construction!==void 0&&resolvesToEntityIncapableModule(construction.callee)){return}context.report({node:xmlInput,messageId:"untrustedXmlSource",data:reportData(node)})},Literal(node){if(typeof node.value==="string"&&containsDangerousEntities(node.value)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}},TemplateElement(node){if(containsDangerousEntities(node.value.raw)){context.report({node,messageId:"xxeInjection",data:reportData(node)})}}}}});