eslint-plugin-secure-coding 5.6.0 → 5.6.2

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 (31) hide show
  1. package/package.json +1 -1
  2. package/src/index.js +1 -1
  3. package/src/rules/detect-non-literal-regexp/index.js +1 -1
  4. package/src/rules/detect-object-injection/index.js +1 -1
  5. package/src/rules/no-directive-injection/index.js +1 -1
  6. package/src/rules/no-disabled-template-escaping/index.js +1 -1
  7. package/src/rules/no-electron-security-issues/index.js +1 -1
  8. package/src/rules/no-fail-open-auth/index.js +1 -1
  9. package/src/rules/no-format-string-injection/index.js +1 -1
  10. package/src/rules/no-graphql-injection/index.js +1 -1
  11. package/src/rules/no-hardcoded-session-tokens/index.js +1 -1
  12. package/src/rules/no-homoglyph-identifiers/index.js +1 -1
  13. package/src/rules/no-improper-sanitization/index.js +1 -1
  14. package/src/rules/no-improper-type-validation/index.js +1 -1
  15. package/src/rules/no-insecure-comparison/index.js +1 -1
  16. package/src/rules/no-ldap-injection/index.js +1 -1
  17. package/src/rules/no-log-injection/index.js +1 -1
  18. package/src/rules/no-missing-authentication/index.js +1 -1
  19. package/src/rules/no-pii-in-logs/index.js +1 -1
  20. package/src/rules/no-privilege-escalation/index.js +1 -1
  21. package/src/rules/no-redos-vulnerable-regex/index.js +1 -1
  22. package/src/rules/no-sensitive-data-exposure/index.js +1 -1
  23. package/src/rules/no-sql-injection/index.js +1 -1
  24. package/src/rules/no-unchecked-loop-condition/index.js +1 -1
  25. package/src/rules/no-unlimited-resource-allocation/index.js +1 -1
  26. package/src/rules/no-unsafe-deserialization/index.js +1 -1
  27. package/src/rules/no-unsafe-regex-construction/index.js +1 -1
  28. package/src/rules/no-weak-password-recovery/index.js +1 -1
  29. package/src/rules/no-xpath-injection/index.js +1 -1
  30. package/src/rules/no-xxe-injection/index.js +1 -1
  31. package/src/rules/require-secure-defaults/index.js +1 -1
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noFormatStringInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_USER_INPUT_ALIASES=["user","userinput","userdata","userparam","userparams","usermessage","usertemplate","userformat","uservar"];exports.noFormatStringInjection=(0,eslint_devkit_1.createRule)({name:"no-format-string-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-format-string-injection.md",description:"Detects format string injection vulnerabilities",cwe:"CWE-134"},fixable:"code",hasSuggestions:true,messages:{formatStringInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Format String Injection",cwe:"CWE-134",description:"Format string controlled by user input",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),userControlledFormatString:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Format String",cwe:"CWE-134",description:"Format string parameter comes from user input",severity:"CRITICAL",fix:"Use hardcoded format strings or validate user formats",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),missingFormatValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Format Validation",cwe:"CWE-134",description:"Format string not validated before use",severity:"HIGH",fix:"Validate format strings against allowed patterns",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),escapeFormatString:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Escape Format String",description:"Escape format specifiers in user input",severity:"LOW",fix:"Replace % with %% in user input",documentationLink:"https://nodejs.org/api/util.html#utilformatformat-args"})},schema:[{type:"object",properties:{formatFunctions:{type:"array",items:{type:"string"},default:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],description:"Functions whose first argument is a format string"},formatSpecifiers:{type:"array",items:{type:"string"},default:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],description:"Format specifiers recognised in a format string"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},userInputAliases:{type:"array",items:{type:"string"},default:DEFAULT_USER_INPUT_ALIASES,description:"The user-input name family recognised on top of `userInputVariables`, compared case-insensitively as a whole name or a whole dotted segment \u2014 never as a substring. Replaces the built-in list."},additionalUserInputAliases:{type:"array",items:{type:"string"},default:[],description:"Extra user-input aliases, on top of `userInputAliases`."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as format string sanitizers"}},additionalProperties:false}]},defaultOptions:[{formatFunctions:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],formatSpecifiers:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],userInputVariables:["req","request","body","query","params","input","data","userInput"],userInputAliases:DEFAULT_USER_INPUT_ALIASES,additionalUserInputAliases:[],trustedSanitizers:["validateFormat","sanitizeFormat","escapeFormat","cleanFormat","sanitizeFormatString","validate","sanitize","escape","clean"]}],createOnce(context){let options;let formatSpecifiers;let userInputVariables;let userInputAliases;let additionalUserInputAliases;let trustedSanitizers;let filename;let reportedTemplates;let safetyChecker;let declaredUserInput;let validatedVariables;let dangerousVariables;const isUserInput=varName=>declaredUserInput.has(varName.toLowerCase());const isUserInputPath=path=>path.split(".").some(segment=>isUserInput(segment));const isUserInputNode=rawNode=>{const node=(0,eslint_devkit_1.unwrapTypeSyntax)(rawNode);if(node.type==="ConditionalExpression"){return isUserInputNode(node.consequent)||isUserInputNode(node.alternate)}if(node.type==="LogicalExpression"){return isUserInputNode(node.left)||isUserInputNode(node.right)}if(node.type==="Identifier"){return isUserInput(node.name)||dangerousVariables.has(node.name)}if(node.type==="MemberExpression"){if(node.object.type==="MemberExpression"&&node.object.object.type==="Identifier"&&node.object.object.name==="req"&&["query","body","params","param"].includes((0,eslint_devkit_1.propertyName)(node.object)??"")){return true}if(node.object.type==="Identifier"&&node.object.name==="req"){return true}const fullName=getMemberExpressionName(node);return isUserInputPath(fullName)}return false};const getMemberExpressionName=node=>{const own=(0,eslint_devkit_1.propertyName)(node);if(node.object.type==="Identifier"){if(own!==null){return`${node.object.name}.${own}`}}else if(node.object.type==="MemberExpression"){const objectName=getMemberExpressionName(node.object);if(own!==null){return`${objectName}.${own}`}}return""};const containsFormatSpecifiers=text=>{return formatSpecifiers.some(specifier=>text.includes(specifier))};const isConsoleMethod=node=>{const callee=node.callee;return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="console"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["log","error","warn","info","debug"])};const isFormatFunctionCall=node=>{const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="util"&&(0,eslint_devkit_1.propertyName)(callee)==="format"){return true}if(callee.type==="Identifier"&&(0,eslint_devkit_1.isModuleBinding)(callee,context.sourceCode.getScope(callee),"util",["format"])){return true}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="console"&&["log","error","warn","info","debug"].includes((0,eslint_devkit_1.propertyName)(callee)??"")){return true}if(callee.type==="Identifier"&&["sprintf","printf","vsprintf"].includes(callee.name)){return true}return false};const isStaticFormatString=fmtNode=>(0,eslint_devkit_1.isStaticExpression)({node:fmtNode,scope:context.sourceCode.getScope(fmtNode)});const isInputValidated=inputNode=>{if(inputNode.type==="Identifier"&&validatedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&trustedSanitizers.includes(current.callee.name)){return true}current=current.parent}return false};function containsFormatSpecifiersInExpression(expr){const left=(0,eslint_devkit_1.staticString)(expr.left);if(left!==null&&containsFormatSpecifiers(left)){return true}const right=(0,eslint_devkit_1.staticString)(expr.right);if(right!==null&&containsFormatSpecifiers(right)){return true}if(expr.left.type==="BinaryExpression"&&containsFormatSpecifiersInExpression(expr.left)){return true}if(expr.right.type==="BinaryExpression"&&containsFormatSpecifiersInExpression(expr.right)){return true}return false}function hasUserInputInExpression(expr){if(isUserInputNode(expr.left)){return true}if(isUserInputNode(expr.right)){return true}if(expr.left.type==="BinaryExpression"&&hasUserInputInExpression(expr.left)){return true}if(expr.right.type==="BinaryExpression"&&hasUserInputInExpression(expr.right)){return true}return false}return{before(){const defaultOptions={formatFunctions:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],formatSpecifiers:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],userInputVariables:["req","request","body","query","params","input","data","userInput"],userInputAliases:DEFAULT_USER_INPUT_ALIASES,additionalUserInputAliases:[],trustedSanitizers:["validateFormat","sanitizeFormat","escapeFormat","cleanFormat","sanitizeFormatString","validate","sanitize","escape","clean"]};options={...defaultOptions,...context.options[0]};({formatSpecifiers,userInputVariables,userInputAliases,additionalUserInputAliases,trustedSanitizers}=options);filename=context.filename;reportedTemplates=new WeakSet;safetyChecker={isSafe:(safeNode,ruleCtx)=>{const comments=ruleCtx.sourceCode.getCommentsBefore(safeNode);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@safe-format")){return true}}if(safeNode.type==="CallExpression"){const firstArg=safeNode.arguments[0];if(firstArg.type==="Identifier"&&validatedVariables.has(firstArg.name)){return true}}return false}};declaredUserInput=new Set([...userInputVariables,...userInputAliases,...additionalUserInputAliases].map(name=>name.toLowerCase()));validatedVariables=new Set;dangerousVariables=new Set},CallExpression:function(node){if(!isFormatFunctionCall(node)){return}const args=node.arguments;if(args.length===0){return}const formatArg=args[0];const isFormatFromUserInput=isUserInputNode(formatArg)||formatArg.type==="BinaryExpression"&&hasUserInputInExpression(formatArg);const consoleSubstitutes=isConsoleMethod(node)&&args.length>1;if(isFormatFromUserInput&&(!isConsoleMethod(node)||consoleSubstitutes)){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"userControlledFormatString",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(formatArg.type==="TemplateLiteral"){const hasUserInput=formatArg.expressions.some(expr=>isUserInputNode(expr));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded format strings or validate template input"}});return}}else if(formatArg.type==="BinaryExpression"&&formatArg.operator==="+"){const hasUserInput=hasUserInputInExpression(formatArg);if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Separate user input from format strings"}});return}}const fmtArg=args[0];const isFormatSafe=isInputValidated(fmtArg);if(!isFormatSafe){let hasUserInputInArgs=false;let hasSpecifiersInFormat=false;for(let i=1;i<args.length;i++){const arg=args[i];if(isUserInputNode(arg)&&!isInputValidated(arg)){hasUserInputInArgs=true;break}}const firstArg=args[0];if(firstArg.type==="Identifier"){const varName=firstArg.name.toLowerCase();if(varName.includes("format")||varName.includes("template")||varName.includes("pattern")){hasSpecifiersInFormat=true}}if(hasSpecifiersInFormat&&hasUserInputInArgs&&!isStaticFormatString(firstArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingFormatValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"escapeFormatString",fix:fixer=>{const arg=node.arguments.find(a=>isUserInputNode(a));return fixer.insertTextAfter(arg,'.replace(/%/g, "%%")')}}]})}}},TemplateLiteral:function(node){let templateCurrent=node;let isFormatString=false;while(templateCurrent){if(templateCurrent.type==="CallExpression"&&isFormatFunctionCall(templateCurrent)){const args=templateCurrent.arguments;if(args.length>0&&args[0]===node){isFormatString=true;break}}templateCurrent=templateCurrent.parent}if(isFormatString){return}const hasUserInput=node.expressions.some(expr=>isUserInputNode(expr));if(hasUserInput){let assignCurrent=node;let isAssignedToVariable=false;while(assignCurrent){if(assignCurrent.type==="VariableDeclarator"){isAssignedToVariable=true;break}assignCurrent=assignCurrent.parent}const carriesFormatSpecifier=node.quasis.some(quasi=>{const raw=quasi.value.raw;return options.formatSpecifiers.some(spec=>raw.includes(spec))});if(isAssignedToVariable&&carriesFormatSpecifier){if(safetyChecker.isSafe(node,context)||reportedTemplates.has(node)){return}context.report({node,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Extract user input from template and validate separately"}})}}},'VariableDeclarator[id.type!="Identifier"]':function(node){if(!node.init||!isUserInputNode(node.init))return;for(const variable of context.sourceCode.getDeclaredVariables(node)){dangerousVariables.add(variable.name)}},AssignmentExpression:function(node){if(node.left.type!=="Identifier")return;if(isUserInputNode(node.right)){dangerousVariables.add(node.left.name)}},VariableDeclarator:function(node){if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&trustedSanitizers.includes(node.init.callee.name)){validatedVariables.add(varName)}if(isUserInputNode(node.init)||node.init.type==="BinaryExpression"&&hasUserInputInExpression(node.init)||node.init.type==="TemplateLiteral"&&node.init.expressions.some(expr=>isUserInputNode(expr))){dangerousVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("format")&&!varNameLower.includes("template")&&!varNameLower.includes("fmt")&&!varNameLower.includes("str")){return}if(node.init.type==="TemplateLiteral"){const hasSpecifiers=node.init.quasis.some(quasi=>containsFormatSpecifiers(quasi.value.raw));const hasUserInput=node.init.expressions.some(expr=>isUserInputNode(expr));if(hasSpecifiers&&hasUserInput){reportedTemplates.add(node.init);if(safetyChecker.isSafe(node,context)){return}context.report({node:node.init,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Separate format string from user data"}})}}if(node.init.type==="BinaryExpression"&&node.init.operator==="+"){const hasSpecifiers=containsFormatSpecifiersInExpression(node.init);const hasUserInput=hasUserInputInExpression(node.init);if(hasSpecifiers&&hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.init,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Separate format string from user data"}})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noFormatStringInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_USER_INPUT_ALIASES=["user","userinput","userdata","userparam","userparams","usermessage","usertemplate","userformat","uservar"];exports.noFormatStringInjection=(0,eslint_devkit_1.createRule)({name:"no-format-string-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-format-string-injection.md",description:"Detects format string injection vulnerabilities",cwe:"CWE-134"},fixable:"code",hasSuggestions:true,messages:{formatStringInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Format String Injection",cwe:"CWE-134",description:"Format string controlled by user input",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),userControlledFormatString:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Format String",cwe:"CWE-134",description:"Format string parameter comes from user input",severity:"CRITICAL",fix:"Use hardcoded format strings or validate user formats",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),missingFormatValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Format Validation",cwe:"CWE-134",description:"Format string not validated before use",severity:"HIGH",fix:"Validate format strings against allowed patterns",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),escapeFormatString:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Escape Format String",description:"Escape format specifiers in user input",severity:"LOW",fix:"Replace % with %% in user input",documentationLink:"https://nodejs.org/api/util.html#utilformatformat-args"})},schema:[{type:"object",properties:{formatFunctions:{type:"array",items:{type:"string"},default:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],description:"Functions whose first argument is a format string"},formatSpecifiers:{type:"array",items:{type:"string"},default:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],description:"Format specifiers recognised in a format string"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},userInputAliases:{type:"array",items:{type:"string"},default:DEFAULT_USER_INPUT_ALIASES,description:"The user-input name family recognised on top of `userInputVariables`, compared case-insensitively as a whole name or a whole dotted segment \u2014 never as a substring. Replaces the built-in list."},additionalUserInputAliases:{type:"array",items:{type:"string"},default:[],description:"Extra user-input aliases, on top of `userInputAliases`."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as format string sanitizers"}},additionalProperties:false}]},defaultOptions:[{formatFunctions:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],formatSpecifiers:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],userInputVariables:["req","request","body","query","params","input","data","userInput"],userInputAliases:DEFAULT_USER_INPUT_ALIASES,additionalUserInputAliases:[],trustedSanitizers:["validateFormat","sanitizeFormat","escapeFormat","cleanFormat","sanitizeFormatString","validate","sanitize","escape","clean"]}],createOnce(context){let options;let formatSpecifiers;let userInputVariables;let userInputAliases;let additionalUserInputAliases;let trustedSanitizers;let filename;let reportedTemplates;let safetyChecker;let declaredUserInput;let validatedVariables;let dangerousVariables;const isUserInput=varName=>declaredUserInput.has(varName.toLowerCase());const isUserInputPath=path=>path.split(".").some(segment=>isUserInput(segment));const isUserInputNode=rawNode=>{const node=(0,eslint_devkit_1.unwrapTypeSyntax)(rawNode);if(node.type==="ConditionalExpression"){return isUserInputNode(node.consequent)||isUserInputNode(node.alternate)}if(node.type==="LogicalExpression"){return isUserInputNode(node.left)||isUserInputNode(node.right)}if(node.type==="Identifier"){return isUserInput(node.name)||dangerousVariables.has(node.name)}if(node.type==="MemberExpression"){if(node.object.type==="MemberExpression"&&node.object.object.type==="Identifier"&&node.object.object.name==="req"&&["query","body","params","param"].includes((0,eslint_devkit_1.propertyName)(node.object)??"")){return true}if(node.object.type==="Identifier"&&node.object.name==="req"){return true}const fullName=getMemberExpressionName(node);return isUserInputPath(fullName)}return false};const getMemberExpressionName=node=>{const own=(0,eslint_devkit_1.propertyName)(node);if(node.object.type==="Identifier"){if(own!==null){return`${node.object.name}.${own}`}}else if(node.object.type==="MemberExpression"){const objectName=getMemberExpressionName(node.object);if(own!==null){return`${objectName}.${own}`}}return""};const containsFormatSpecifiers=text=>{return formatSpecifiers.some(specifier=>text.includes(specifier))};const isConsoleMethod=node=>{const callee=node.callee;return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="console"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["log","error","warn","info","debug"])};const isFormatFunctionCall=node=>{const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="util"&&(0,eslint_devkit_1.propertyName)(callee)==="format"){return true}if(callee.type==="Identifier"&&(0,eslint_devkit_1.isModuleBinding)(callee,context.sourceCode.getScope(callee),"util",["format"])){return true}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="console"&&["log","error","warn","info","debug"].includes((0,eslint_devkit_1.propertyName)(callee)??"")){return true}if(callee.type==="Identifier"&&["sprintf","printf","vsprintf"].includes(callee.name)){return true}return false};const isStaticFormatString=fmtNode=>(0,eslint_devkit_1.isStaticExpression)({node:fmtNode,scope:context.sourceCode.getScope(fmtNode)});const isInputValidated=inputNode=>{if(inputNode.type==="Identifier"&&validatedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&trustedSanitizers.includes(current.callee.name)){return true}current=current.parent}return false};function containsFormatSpecifiersInExpression(expr){const left=(0,eslint_devkit_1.staticString)(expr.left);if(left!==null&&containsFormatSpecifiers(left)){return true}const right=(0,eslint_devkit_1.staticString)(expr.right);if(right!==null&&containsFormatSpecifiers(right)){return true}if(expr.left.type==="BinaryExpression"&&containsFormatSpecifiersInExpression(expr.left)){return true}if(expr.right.type==="BinaryExpression"&&containsFormatSpecifiersInExpression(expr.right)){return true}return false}function hasUserInputInExpression(expr){if(isUserInputNode(expr.left)){return true}if(isUserInputNode(expr.right)){return true}if(expr.left.type==="BinaryExpression"&&hasUserInputInExpression(expr.left)){return true}if(expr.right.type==="BinaryExpression"&&hasUserInputInExpression(expr.right)){return true}return false}return{before(){const defaultOptions={formatFunctions:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],formatSpecifiers:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],userInputVariables:["req","request","body","query","params","input","data","userInput"],userInputAliases:DEFAULT_USER_INPUT_ALIASES,additionalUserInputAliases:[],trustedSanitizers:["validateFormat","sanitizeFormat","escapeFormat","cleanFormat","sanitizeFormatString","validate","sanitize","escape","clean"]};options={...defaultOptions,...context.options[0]};({formatSpecifiers,userInputVariables,userInputAliases,additionalUserInputAliases,trustedSanitizers}=options);filename=context.filename;reportedTemplates=new WeakSet;safetyChecker={isSafe:(safeNode,ruleCtx)=>{const comments=ruleCtx.sourceCode.getCommentsBefore(safeNode);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@safe-format")){return true}}if(safeNode.type==="CallExpression"){const firstArg=safeNode.arguments[0];if(firstArg.type==="Identifier"&&validatedVariables.has(firstArg.name)){return true}}return false}};declaredUserInput=new Set([...userInputVariables,...userInputAliases,...additionalUserInputAliases].map(name=>name.toLowerCase()));validatedVariables=new Set;dangerousVariables=new Set},CallExpression:function(node){if(!isFormatFunctionCall(node)){return}const args=node.arguments;if(args.length===0){return}const formatArg=args[0];const isFormatFromUserInput=isUserInputNode(formatArg)||formatArg.type==="BinaryExpression"&&hasUserInputInExpression(formatArg);const consoleSubstitutes=isConsoleMethod(node)&&args.length>1;if(isFormatFromUserInput&&(!isConsoleMethod(node)||consoleSubstitutes)){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"userControlledFormatString",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(formatArg.type==="TemplateLiteral"){const hasUserInput=formatArg.expressions.some(expr=>isUserInputNode(expr));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded format strings or validate template input"}});return}}else if(formatArg.type==="BinaryExpression"&&formatArg.operator==="+"){const hasUserInput=hasUserInputInExpression(formatArg);if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Separate user input from format strings"}});return}}let hasUserInputInArgs=false;let hasSpecifiersInFormat=false;for(let i=1;i<args.length;i++){const arg=args[i];if(isUserInputNode(arg)&&!isInputValidated(arg)){hasUserInputInArgs=true;break}}const firstArg=args[0];if(firstArg.type==="Identifier"){const varName=firstArg.name.toLowerCase();if(varName.includes("format")||varName.includes("template")||varName.includes("pattern")){hasSpecifiersInFormat=true}}if(hasSpecifiersInFormat&&hasUserInputInArgs&&!isStaticFormatString(firstArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingFormatValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"escapeFormatString",fix:fixer=>{const arg=node.arguments.find(a=>isUserInputNode(a));return fixer.insertTextAfter(arg,'.replace(/%/g, "%%")')}}]})}},TemplateLiteral:function(node){let templateCurrent=node;let isFormatString=false;while(templateCurrent){if(templateCurrent.type==="CallExpression"&&isFormatFunctionCall(templateCurrent)){const args=templateCurrent.arguments;if(args[0]===node){isFormatString=true;break}}templateCurrent=templateCurrent.parent}if(isFormatString){return}const hasUserInput=node.expressions.some(expr=>isUserInputNode(expr));if(hasUserInput){let assignCurrent=node;let isAssignedToVariable=false;while(assignCurrent){if(assignCurrent.type==="VariableDeclarator"){isAssignedToVariable=true;break}assignCurrent=assignCurrent.parent}const carriesFormatSpecifier=node.quasis.some(quasi=>{const raw=quasi.value.raw;return options.formatSpecifiers.some(spec=>raw.includes(spec))});if(isAssignedToVariable&&carriesFormatSpecifier){if(safetyChecker.isSafe(node,context)||reportedTemplates.has(node)){return}context.report({node,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Extract user input from template and validate separately"}})}}},'VariableDeclarator[id.type!="Identifier"]':function(node){if(!node.init||!isUserInputNode(node.init))return;for(const variable of context.sourceCode.getDeclaredVariables(node)){dangerousVariables.add(variable.name)}},AssignmentExpression:function(node){if(node.left.type!=="Identifier")return;if(isUserInputNode(node.right)){dangerousVariables.add(node.left.name)}},VariableDeclarator:function(node){if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&trustedSanitizers.includes(node.init.callee.name)){validatedVariables.add(varName)}if(isUserInputNode(node.init)||node.init.type==="BinaryExpression"&&hasUserInputInExpression(node.init)||node.init.type==="TemplateLiteral"&&node.init.expressions.some(expr=>isUserInputNode(expr))){dangerousVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("format")&&!varNameLower.includes("template")&&!varNameLower.includes("fmt")&&!varNameLower.includes("str")){return}if(node.init.type==="TemplateLiteral"){const hasSpecifiers=node.init.quasis.some(quasi=>containsFormatSpecifiers(quasi.value.raw));const hasUserInput=node.init.expressions.some(expr=>isUserInputNode(expr));if(hasSpecifiers&&hasUserInput){reportedTemplates.add(node.init);if(safetyChecker.isSafe(node,context)){return}context.report({node:node.init,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Separate format string from user data"}})}}if(node.init.type==="BinaryExpression"&&node.init.operator==="+"){const hasSpecifiers=containsFormatSpecifiersInExpression(node.init);const hasUserInput=hasUserInputInExpression(node.init);if(hasSpecifiers&&hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.init,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Separate format string from user data"}})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const resolve_reference_1=require("../../utils/resolve-reference");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noGraphqlInjection=(0,eslint_devkit_1.createRule)({name:"no-graphql-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-graphql-injection.md",description:"Detects GraphQL injection vulnerabilities and DoS attacks",cwe:"CWE-89"},messages:{graphqlInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"GraphQL Injection",cwe:"CWE-89",description:"GraphQL injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/Top10/2025/A05_2025-Injection/"}),introspectionQuery:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Introspection Query",cwe:"CWE-200",description:"Introspection query may leak schema information",severity:"HIGH",fix:"Disable introspection in production",documentationLink:"https://graphql.org/learn/introspection/"}),complexQueryDos:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Complex Query DoS Risk",cwe:"CWE-400",description:"Complex query may cause DoS",severity:"MEDIUM",fix:"Limit query depth and complexity",documentationLink:"https://graphql.org/learn/queries/"}),unsafeVariableInterpolation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Variable Interpolation",cwe:"CWE-89",description:"Unsafe interpolation in GraphQL query",severity:"HIGH",fix:"Use GraphQL variables instead of string interpolation",documentationLink:"https://graphql.org/learn/queries/#variables"}),missingInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Input Validation",cwe:"CWE-20",description:"GraphQL input not validated",severity:"MEDIUM",fix:"Validate all user inputs before GraphQL execution",documentationLink:"https://graphql.org/learn/validation/"})},schema:[{type:"object",properties:{allowIntrospection:{type:"boolean",default:false,description:"Allow introspection queries"},maxQueryDepth:{type:"number",minimum:1,default:10,description:"Maximum query nesting depth before reporting a DoS risk"},trustedGraphqlLibraries:{type:"array",items:{type:"string"},default:["graphql","apollo-server","graphql-tools","graphql-tag"],description:"GraphQL libraries recognised as query builders"},validationFunctions:{type:"array",items:{type:"string"},default:["validate","sanitize","isValid","assertValid"],description:"Function names that count as query validation"},safeTemplateLiteralCallers:{type:"array",items:{type:"string"},default:[],description:"Additional callers where template literals are never GraphQL. Format: object.method or ClassName."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as GraphQL sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{allowIntrospection:false,maxQueryDepth:10,trustedGraphqlLibraries:["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions:["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let allowIntrospection;let maxQueryDepth;let trustedGraphqlLibraries;let validationFunctions;let safeTemplateLiteralCallers;let trustedSanitizers;let trustedAnnotations;let strictMode;let filename;let sourceCode;let safetyChecker;let safeMemberCallers;let safeConstructors;let GRAPHQL_OP_KEYWORDS;let GRAPHQL_SCHEMA_KEYWORDS;let GRAPHQL_TAG_NAMES;const GRAPHQL_SCHEMA_BINDING=/typedef|schema|sdl/i;const isGraphqlRelated=node=>{const callee=node.callee;if(callee.type==="Identifier"){return trustedGraphqlLibraries.some(lib=>callee.name.toLowerCase().includes(lib.toLowerCase()))}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){const objectName=callee.object.name;return trustedGraphqlLibraries.some(lib=>objectName.toLowerCase().includes(lib.toLowerCase()))}return false};const isInSafeCallerContext=node=>{let current=node.parent;while(current){if(current.type==="CallExpression"){const callee=current.callee;const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&method!==null){const key=`${callee.object.name}.${method}`;if(safeMemberCallers.has(key))return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){if(current.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&safeConstructors.has(current.callee.name)){return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration){break}current=current.parent}return false};const isWordChar=ch=>{const code=ch.charCodeAt(0);return code>=65&&code<=90||code>=97&&code<=122||code>=48&&code<=57||code===95};const isWhitespace=ch=>ch===" "||ch==="\n"||ch===" "||ch==="\r";const isAtLineStart=(text,idx)=>{for(let i=idx-1;i>=0;i--){const ch=text[i];if(ch==="\n")return true;if(!isWhitespace(ch))return false}return true};const isStandaloneSelectionSet=text=>{const trimmed=text.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))return false;if(/\{\{|\}\}/.test(trimmed))return false;if(/"[^"]*"\s*:/.test(trimmed))return false;let braceDepth=0;for(const ch of trimmed){if(ch==="{"){braceDepth++;if(braceDepth>=2)return true}else if(ch==="}"){braceDepth=Math.max(0,braceDepth-1)}}return false};const findKeywordAtBoundary=(text,keyword,startFrom=0)=>{let pos=startFrom;while(true){const idx=text.indexOf(keyword,pos);if(idx===-1)return-1;const beforeOk=idx===0||!isWordChar(text[idx-1]);const afterIdx=idx+keyword.length;const afterOk=afterIdx>=text.length||!isWordChar(text[afterIdx]);if(beforeOk&&afterOk)return idx;pos=idx+1}};const hasGraphqlAttribution=node=>{let current=node;while(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){current=current.parent}const parent=current.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){const tag=parent.tag;const tagName=tag.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.name:tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(tag)??"":"";return GRAPHQL_TAG_NAMES.has(tagName.toLowerCase())}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.id.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.key.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isGraphqlRelated(parent)}return false};const isGraphqlTemplate=node=>{const staticText=node.quasis.map(q=>(q.value.cooked??q.value.raw).toLowerCase()).join("");for(const keyword of GRAPHQL_OP_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&staticText[scan]==="("){return true}if(scan<staticText.length&&staticText[scan]==="{"){let probe=scan+1;while(probe<staticText.length&&isWhitespace(staticText[probe]))probe++;if(probe<staticText.length&&isWordChar(staticText[probe])){return true}continue}}}{let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,"fragment",pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+8;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;const nameStart=scan;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;if(scan===nameStart)continue;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(staticText.slice(scan,scan+2)==="on"&&(scan+2>=staticText.length||!isWordChar(staticText[scan+2]))){return true}}}if(hasGraphqlAttribution(node)&&staticText.includes("{"))for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;if(scan>=staticText.length||!isWhitespace(staticText[scan]))continue;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&isWordChar(staticText[scan])){return true}}}return isStandaloneSelectionSet(staticText)};const isGraphqlComposition=expr=>{if(expr.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(expr),expr);if(variable===null||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1){return false}const init=def.node.init;if(init===null)return false;const literal=init.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression?init.expression:init;return literal.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&isGraphqlTemplate(literal)};const hasIntrospectionField=text=>{const lower=text.toLowerCase();return findKeywordAtBoundary(lower,"__schema")!==-1||findKeywordAtBoundary(lower,"__type")!==-1};const templateHasIntrospection=node=>{return node.quasis.some(q=>hasIntrospectionField(q.value.cooked??q.value.raw))};const templateQueryDepth=node=>{let depth=0;let braceCount=0;for(const q of node.quasis){const text=q.value.cooked??q.value.raw;for(const char of text){if(char==="{"){braceCount++;depth=Math.max(depth,braceCount)}else if(char==="}"){braceCount--}}}return depth};const containsGraphqlText=(text,attributed)=>{const lower=text.toLowerCase();for(const keyword of GRAPHQL_OP_KEYWORDS){const idx=findKeywordAtBoundary(lower,keyword);if(idx===-1)continue;if(!isAtLineStart(lower,idx))continue;let scan=idx+keyword.length;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;while(scan<lower.length&&isWordChar(lower[scan]))scan++;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(scan<lower.length&&lower[scan]==="(")return true;if(scan<lower.length&&lower[scan]==="{"){if(attributed)return true;let probe=scan+1;while(probe<lower.length&&isWhitespace(lower[probe]))probe++;if(probe<lower.length&&isWordChar(lower[probe]))return true}}const fragIdx=findKeywordAtBoundary(lower,"fragment");if(fragIdx!==-1&&isAtLineStart(lower,fragIdx)){let scan=fragIdx+8;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;const nameStart=scan;while(scan<lower.length&&isWordChar(lower[scan]))scan++;if(scan>nameStart){while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(lower.slice(scan,scan+2)==="on"&&(scan+2>=lower.length||!isWordChar(lower[scan+2])))return true}}if(attributed&&lower.includes("{"))for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){const idx=findKeywordAtBoundary(lower,keyword);if(idx===-1)continue;if(!isAtLineStart(lower,idx))continue;let scan=idx+keyword.length;if(scan>=lower.length||!isWhitespace(lower[scan]))continue;while(scan<lower.length&&isWhitespace(lower[scan]))scan++;if(scan<lower.length&&isWordChar(lower[scan]))return true}return isStandaloneSelectionSet(text)};const concatenatedStaticText=node=>{if(node.type==="BinaryExpression"&&node.operator==="+"){return concatenatedStaticText(node.left)+concatenatedStaticText(node.right)}if(node.type==="TemplateLiteral"){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}return(0,eslint_devkit_1.staticString)(node)??""};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};return{before(){const options=context.options[0]||{};({allowIntrospection=false,maxQueryDepth=10,trustedGraphqlLibraries=["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions=["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);filename=context.filename;sourceCode=context.sourceCode;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const BUILTIN_SAFE_MEMBER_CALLERS=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.trace","logger.log","logger.info","logger.warn","logger.error","logger.debug"]);const BUILTIN_SAFE_CONSTRUCTORS=new Set(["URL","Error","TypeError","RangeError"]);safeMemberCallers=new Set(BUILTIN_SAFE_MEMBER_CALLERS);safeConstructors=new Set(BUILTIN_SAFE_CONSTRUCTORS);for(const caller of safeTemplateLiteralCallers){if(caller.includes(".")){safeMemberCallers.add(caller)}else{safeConstructors.add(caller)}}GRAPHQL_OP_KEYWORDS=["query","mutation","subscription"];GRAPHQL_SCHEMA_KEYWORDS=["type","interface","enum","scalar","input"];GRAPHQL_TAG_NAMES=new Set(["gql","graphql"])},TemplateLiteral(node){if(isInSafeCallerContext(node)){return}if(!isGraphqlTemplate(node)){return}if(!allowIntrospection&&templateHasIntrospection(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(node.expressions.length>0){const allExpressionsSafe=node.expressions.every(expr=>isGraphqlComposition(expr)||isInputValidated(expr)||safetyChecker.isSafe(expr,context));if(!allExpressionsSafe){context.report({node,messageId:"unsafeVariableInterpolation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}const depth=templateQueryDepth(node);if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},Literal(node){const queryText=(0,eslint_devkit_1.staticString)(node);if(queryText===null)return;if(!containsGraphqlText(queryText,hasGraphqlAttribution(node))){return}if(!allowIntrospection&&hasIntrospectionField(queryText)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}let depth=0;let bc=0;for(const ch of queryText){if(ch==="{"){bc++;depth=Math.max(depth,bc)}else if(ch==="}"){bc--}}if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}const fullText=concatenatedStaticText(node);if(!containsGraphqlText(fullText,hasGraphqlAttribution(node))){return}if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"graphqlInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use GraphQL variables or query builders instead of string concatenation"}})},CallExpression(node){if(!isGraphqlRelated(node)){return}const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["execute","executeQuery","query","mutate","subscribe"])){for(const arg of node.arguments){if(arg.type==="Identifier"&&!isInputValidated(arg)){if(safetyChecker.isSafe(arg,context)){continue}context.report({node:arg,messageId:"missingInputValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const resolve_reference_1=require("../../utils/resolve-reference");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noGraphqlInjection=(0,eslint_devkit_1.createRule)({name:"no-graphql-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-graphql-injection.md",description:"Detects GraphQL injection vulnerabilities and DoS attacks",cwe:"CWE-89"},messages:{graphqlInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"GraphQL Injection",cwe:"CWE-89",description:"GraphQL injection vulnerability detected",severity:"CRITICAL",fix:"Use GraphQL variables or query builders instead of string concatenation",documentationLink:"https://owasp.org/Top10/2025/A05_2025-Injection/"}),introspectionQuery:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Introspection Query",cwe:"CWE-200",description:"Introspection query may leak schema information",severity:"HIGH",fix:"Disable introspection in production",documentationLink:"https://graphql.org/learn/introspection/"}),complexQueryDos:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Complex Query DoS Risk",cwe:"CWE-400",description:"Complex query may cause DoS",severity:"MEDIUM",fix:"Limit query depth and complexity",documentationLink:"https://graphql.org/learn/queries/"}),unsafeVariableInterpolation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Variable Interpolation",cwe:"CWE-89",description:"Unsafe interpolation in GraphQL query",severity:"HIGH",fix:"Use GraphQL variables instead of string interpolation",documentationLink:"https://graphql.org/learn/queries/#variables"}),missingInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Input Validation",cwe:"CWE-20",description:"GraphQL input not validated",severity:"MEDIUM",fix:"Validate all user inputs before GraphQL execution",documentationLink:"https://graphql.org/learn/validation/"})},schema:[{type:"object",properties:{allowIntrospection:{type:"boolean",default:false,description:"Allow introspection queries"},maxQueryDepth:{type:"number",minimum:1,default:10,description:"Maximum query nesting depth before reporting a DoS risk"},trustedGraphqlLibraries:{type:"array",items:{type:"string"},default:["graphql","apollo-server","graphql-tools","graphql-tag"],description:"GraphQL libraries recognised as query builders"},validationFunctions:{type:"array",items:{type:"string"},default:["validate","sanitize","isValid","assertValid"],description:"Function names that count as query validation"},safeTemplateLiteralCallers:{type:"array",items:{type:"string"},default:[],description:"Additional callers where template literals are never GraphQL. Format: object.method or ClassName."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as GraphQL sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{allowIntrospection:false,maxQueryDepth:10,trustedGraphqlLibraries:["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions:["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let allowIntrospection;let maxQueryDepth;let trustedGraphqlLibraries;let validationFunctions;let safeTemplateLiteralCallers;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let safetyChecker;let safeMemberCallers;let safeConstructors;let GRAPHQL_OP_KEYWORDS;let GRAPHQL_SCHEMA_KEYWORDS;let GRAPHQL_TAG_NAMES;const GRAPHQL_SCHEMA_BINDING=/typedef|schema|sdl/i;const isGraphqlRelated=node=>{const callee=node.callee;if(callee.type==="Identifier"){return trustedGraphqlLibraries.some(lib=>callee.name.toLowerCase().includes(lib.toLowerCase()))}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){const objectName=callee.object.name;return trustedGraphqlLibraries.some(lib=>objectName.toLowerCase().includes(lib.toLowerCase()))}return false};const isInSafeCallerContext=node=>{let current=node.parent;while(current){if(current.type==="CallExpression"){const callee=current.callee;const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&method!==null){const key=`${callee.object.name}.${method}`;if(safeMemberCallers.has(key))return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){if(current.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&safeConstructors.has(current.callee.name)){return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){break}current=current.parent}return false};const isWordChar=ch=>/\w/.test(ch);const isWhitespace=ch=>/\s/.test(ch);const skip=(text,from,accept)=>{let at=from;while(accept(text.charAt(at)))at++;return at};const isAtLineStart=(text,idx)=>{for(let i=idx-1;i>=0;i--){const ch=text[i];if(ch==="\n")return true;if(!isWhitespace(ch))return false}return true};const maxBraceDepth=text=>{let depth=0;let open=0;for(const ch of text){if(ch==="{"){open++;depth=Math.max(depth,open)}else if(ch==="}"){open--}}return depth};const isStandaloneSelectionSet=text=>{const trimmed=text.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))return false;if(/\{\{|\}\}/.test(trimmed))return false;if(/"[^"]*"\s*:/.test(trimmed))return false;return maxBraceDepth(trimmed)>=2};const findKeywordAtBoundary=(text,keyword,startFrom=0)=>{let pos=startFrom;while(true){const idx=text.indexOf(keyword,pos);if(idx===-1)return-1;const beforeOk=idx===0||!isWordChar(text[idx-1]);const afterOk=!isWordChar(text.charAt(idx+keyword.length));if(beforeOk&&afterOk)return idx;pos=idx+1}};const keywordEndsAtLineStart=(text,keyword)=>{const ends=[];for(let idx=findKeywordAtBoundary(text,keyword);idx!==-1;idx=findKeywordAtBoundary(text,keyword,idx+1)){if(isAtLineStart(text,idx))ends.push(idx+keyword.length)}return ends};const hasGraphqlAttribution=node=>{let current=node;while(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){current=current.parent}const parent=current.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){const tag=parent.tag;const tagName=tag.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.name:tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(tag)??"":"";return GRAPHQL_TAG_NAMES.has(tagName.toLowerCase())}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.id.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.key.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isGraphqlRelated(parent)}return false};const templateText=node=>node.quasis.map(q=>q.value.cooked??q.value.raw).join("");const isGraphqlTemplate=node=>containsGraphqlText(templateText(node),hasGraphqlAttribution(node));const isGraphqlComposition=expr=>{const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(expr),expr);if(variable===null||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1){return false}const init=def.node.init;if(init===null)return false;const literal=init.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression?init.expression:init;const text=literal.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?templateText(literal):(0,eslint_devkit_1.staticString)(literal);return text!==null&&containsGraphqlText(text,hasGraphqlAttribution(literal))};const hasIntrospectionField=text=>{const lower=text.toLowerCase();return findKeywordAtBoundary(lower,"__schema")!==-1||findKeywordAtBoundary(lower,"__type")!==-1};const containsGraphqlText=(text,attributed)=>{const lower=text.toLowerCase();for(const keyword of GRAPHQL_OP_KEYWORDS){for(const end of keywordEndsAtLineStart(lower,keyword)){const afterName=skip(lower,skip(lower,skip(lower,end,isWhitespace),isWordChar),isWhitespace);const next=lower.charAt(afterName);if(next==="(")return true;if(next==="{"&&(attributed||isWordChar(lower.charAt(skip(lower,afterName+1,isWhitespace))))){return true}}}for(const end of keywordEndsAtLineStart(lower,"fragment")){const on=skip(lower,skip(lower,skip(lower,end,isWhitespace),isWordChar),isWhitespace);if(lower.startsWith("on",on)&&!isWordChar(lower.charAt(on+2))){return true}}if(attributed&&lower.includes("{")){for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){for(const end of keywordEndsAtLineStart(lower,keyword)){if(isWordChar(lower.charAt(skip(lower,end,isWhitespace)))){return true}}}}return isStandaloneSelectionSet(text)};const concatenatedStaticText=node=>{if(node.type==="BinaryExpression"&&node.operator==="+"){return concatenatedStaticText(node.left)+concatenatedStaticText(node.right)}if(node.type==="TemplateLiteral"){return templateText(node)}return(0,eslint_devkit_1.staticString)(node)??""};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};return{before(){const options=context.options[0]||{};({allowIntrospection=false,maxQueryDepth=10,trustedGraphqlLibraries=["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions=["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const BUILTIN_SAFE_MEMBER_CALLERS=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.trace","logger.log","logger.info","logger.warn","logger.error","logger.debug"]);const BUILTIN_SAFE_CONSTRUCTORS=new Set(["URL","Error","TypeError","RangeError"]);safeMemberCallers=new Set(BUILTIN_SAFE_MEMBER_CALLERS);safeConstructors=new Set(BUILTIN_SAFE_CONSTRUCTORS);for(const caller of safeTemplateLiteralCallers){if(caller.includes(".")){safeMemberCallers.add(caller)}else{safeConstructors.add(caller)}}GRAPHQL_OP_KEYWORDS=["query","mutation","subscription"];GRAPHQL_SCHEMA_KEYWORDS=["type","interface","enum","scalar","input"];GRAPHQL_TAG_NAMES=new Set(["gql","graphql"])},TemplateLiteral(node){if(isInSafeCallerContext(node)){return}if(!isGraphqlTemplate(node)){return}if(!allowIntrospection&&node.quasis.some(q=>hasIntrospectionField(q.value.cooked??q.value.raw))){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery"});return}const allExpressionsSafe=node.expressions.every(expr=>isGraphqlComposition(expr)||isInputValidated(expr)||safetyChecker.isSafe(expr,context));if(!allExpressionsSafe){context.report({node,messageId:"unsafeVariableInterpolation"})}if(maxBraceDepth(templateText(node))>maxQueryDepth){context.report({node,messageId:"complexQueryDos"})}},Literal(node){const queryText=(0,eslint_devkit_1.staticString)(node);if(queryText===null)return;if(!containsGraphqlText(queryText,hasGraphqlAttribution(node))){return}if(!allowIntrospection&&hasIntrospectionField(queryText)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery"})}if(maxBraceDepth(queryText)>maxQueryDepth){context.report({node,messageId:"complexQueryDos"})}},BinaryExpression(node){const fullText=concatenatedStaticText(node);if(!containsGraphqlText(fullText,hasGraphqlAttribution(node))){return}if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"graphqlInjection"})},CallExpression(node){if(!isGraphqlRelated(node)){return}const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["execute","executeQuery","query","mutate","subscribe"])){for(const arg of node.arguments){if(arg.type==="Identifier"&&!isInputValidated(arg)){if(safetyChecker.isSafe(arg,context)){continue}context.report({node:arg,messageId:"missingInputValidation"})}}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedSessionTokens=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_SESSION_WORDS=["session","token"];exports.noHardcodedSessionTokens=(0,eslint_devkit_1.createRule)({name:"no-hardcoded-session-tokens",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-hardcoded-session-tokens.md",description:"Detect hardcoded session/JWT tokens",cwe:"CWE-798",cvss:9.8},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hardcoded Token",cwe:"CWE-798",description:"Hardcoded session or JWT token detected - credentials at risk",severity:"CRITICAL",fix:"Use environment variables or secure credential management",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"})},schema:[{type:"object",properties:{sessionWords:{type:"array",items:{type:"string"},default:[...DEFAULT_SESSION_WORDS],description:"Variable-name substrings that mark a literal as a session credential. Replaces the default."}},additionalProperties:false}]},defaultOptions:[{sessionWords:[...DEFAULT_SESSION_WORDS]}],createOnce(context){let sessionWords;function report(node){context.report({node,messageId:"violationDetected"})}return{before(){sessionWords=(context.options[0]?.sessionWords??DEFAULT_SESSION_WORDS).map(word=>word.toLowerCase())},Literal(node){if(typeof node.value!=="string")return;if(node.value.startsWith("eyJ")&&node.value.length>50&&(node.value.match(/\./g)||[]).length>=2){report(node)}if(node.value.startsWith("Bearer ")&&node.value.length>20){report(node)}const parent=node.parent;if(parent?.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name.toLowerCase();if(sessionWords.some(word=>varName.includes(word))&&node.value.length>=16&&/^[a-zA-Z0-9]+$/.test(node.value)){report(node)}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedSessionTokens=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_SESSION_WORDS=["session","token"];exports.noHardcodedSessionTokens=(0,eslint_devkit_1.createRule)({name:"no-hardcoded-session-tokens",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-hardcoded-session-tokens.md",description:"Detect hardcoded session/JWT tokens",cwe:"CWE-798",cvss:9.8},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hardcoded Token",cwe:"CWE-798",description:"Hardcoded session or JWT token detected - credentials at risk",severity:"CRITICAL",fix:"Use environment variables or secure credential management",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"})},schema:[{type:"object",properties:{sessionWords:{type:"array",items:{type:"string"},default:[...DEFAULT_SESSION_WORDS],description:"Variable-name substrings that mark a literal as a session credential. Replaces the default."}},additionalProperties:false}]},defaultOptions:[{sessionWords:[...DEFAULT_SESSION_WORDS]}],createOnce(context){let sessionWords;function report(node){context.report({node,messageId:"violationDetected"})}return{before(){sessionWords=(context.options[0]?.sessionWords??DEFAULT_SESSION_WORDS).map(word=>word.toLowerCase())},Literal(node){if(typeof node.value!=="string")return;if(node.value.startsWith("eyJ")&&node.value.length>50&&(node.value.match(/\./g)||[]).length>=2){report(node)}if(node.value.startsWith("Bearer ")&&node.value.length>20){report(node)}const parent=node.parent;if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name.toLowerCase();if(sessionWords.some(word=>varName.includes(word))&&node.value.length>=16&&/^[a-zA-Z0-9]+$/.test(node.value)){report(node)}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHomoglyphIdentifiers=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const CONFUSABLE_WITH_ASCII=new Map([[1072,"a"],[1074,"b"],[1075,"r"],[1077,"e"],[1082,"k"],[1084,"m"],[1085,"h"],[1086,"o"],[1088,"p"],[1089,"c"],[1091,"y"],[1093,"x"],[1109,"s"],[1110,"i"],[1112,"j"],[1029,"S"],[1030,"I"],[1032,"J"],[1040,"A"],[1042,"B"],[1045,"E"],[1050,"K"],[1052,"M"],[1053,"H"],[1054,"O"],[1056,"P"],[1057,"C"],[1058,"T"],[1059,"Y"],[1061,"X"],[945,"a"],[949,"e"],[953,"i"],[954,"k"],[957,"v"],[959,"o"],[961,"p"],[963,"o"],[964,"t"],[965,"u"],[967,"x"],[913,"A"],[914,"B"],[917,"E"],[918,"Z"],[919,"H"],[921,"I"],[922,"K"],[924,"M"],[925,"N"],[927,"O"],[929,"P"],[932,"T"],[933,"Y"],[935,"X"],[1400,"n"],[1405,"u"],[1413,"o"],[5024,"D"],[5033,"E"],[5034,"A"],[5043,"W"],[5051,"P"],[5056,"G"],[5071,"C"],[5081,"V"],[5086,"S"],[5090,"B"],[448,"l"],[305,"i"],[609,"g"]]);const INVISIBLE=/[\u00ad\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/;function toCodepointLabel(codepoint){return`U+${codepoint.toString(16).toUpperCase().padStart(4,"0")}`}function confusableFor(codepoint){const mapped=CONFUSABLE_WITH_ASCII.get(codepoint);if(mapped!==void 0)return mapped;if(codepoint>=65313&&codepoint<=65338){return String.fromCharCode(codepoint-65313+65)}if(codepoint>=65345&&codepoint<=65370){return String.fromCharCode(codepoint-65345+97)}return null}function homoglyphIn(name){if(!/[A-Za-z]/.test(name))return null;for(let index=0;index<name.length;index++){const codepoint=name.charCodeAt(index);if(codepoint<128)continue;const latin=confusableFor(codepoint);if(latin!==null){return{character:name[index],codepoint,latin}}}return null}function isVisibleAscii(codepoint){return codepoint>=33&&codepoint<=126}function invisibleIn(text){for(let index=0;index<text.length;index++){if(!INVISIBLE.test(text[index]))continue;const before=index>0?text.charCodeAt(index-1):-1;const after=index+1<text.length?text.charCodeAt(index+1):-1;if(!isVisibleAscii(before)&&!isVisibleAscii(after))continue;return{index,codepoint:text.charCodeAt(index)}}return null}exports.noHomoglyphIdentifiers=(0,eslint_devkit_1.createRule)({name:"no-homoglyph-identifiers",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-homoglyph-identifiers.md",description:"Detects homoglyph identifiers and invisible characters that hide what the code actually does",cwe:"CWE-1007",cvss:5.3},messages:{homoglyphIdentifier:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Homoglyph Identifier",cwe:"CWE-1007",cvss:5.3,description:'Identifier "{{name}}" mixes scripts: {{codepoint}} renders as ASCII "{{latin}}" but is a different character',severity:"MEDIUM",fix:"Rewrite the identifier in ASCII, or confirm the binding it resolves to is the one you intended",documentationLink:"https://cwe.mitre.org/data/definitions/1007.html"}),invisibleCharacter:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Invisible Character",cwe:"CWE-1007",cvss:5.3,description:"String contains invisible character {{codepoint}} at index {{index}} - the text is not what it appears to be",severity:"MEDIUM",fix:"Remove the character, or write it as an escape (\\u200B) so it is visible in review",documentationLink:"https://trojansource.codes/"})},schema:[{type:"object",properties:{checkIdentifiers:{type:"boolean",default:true,description:"Check identifier names for script-mixing homoglyphs"},checkStrings:{type:"boolean",default:true,description:"Check string literals and template chunks for invisible characters"}},additionalProperties:false}]},defaultOptions:[{checkIdentifiers:true,checkStrings:true}],createOnce(context){let checkIdentifiers;let checkStrings;function checkName(node){if(!checkIdentifiers)return;const found=homoglyphIn(node.name);if(!found)return;context.report({node,messageId:"homoglyphIdentifier",data:{name:node.name,codepoint:toCodepointLabel(found.codepoint),latin:found.latin}})}function checkText(node,text){const found=invisibleIn(text);if(!found)return;context.report({node,messageId:"invisibleCharacter",data:{codepoint:toCodepointLabel(found.codepoint),index:String(found.index)}})}return{before(){const options=context.options[0]??{};checkIdentifiers=options.checkIdentifiers??true;checkStrings=options.checkStrings??true},Identifier:checkName,PrivateIdentifier:checkName,Literal(node){if(!checkStrings)return;if(typeof node.value!=="string")return;checkText(node,node.raw)},TemplateElement(node){if(!checkStrings)return;checkText(node,node.value.raw)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHomoglyphIdentifiers=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const CONFUSABLE_WITH_ASCII=new Map([[1072,"a"],[1074,"b"],[1075,"r"],[1077,"e"],[1082,"k"],[1084,"m"],[1085,"h"],[1086,"o"],[1088,"p"],[1089,"c"],[1091,"y"],[1093,"x"],[1109,"s"],[1110,"i"],[1112,"j"],[1029,"S"],[1030,"I"],[1032,"J"],[1040,"A"],[1042,"B"],[1045,"E"],[1050,"K"],[1052,"M"],[1053,"H"],[1054,"O"],[1056,"P"],[1057,"C"],[1058,"T"],[1059,"Y"],[1061,"X"],[945,"a"],[949,"e"],[953,"i"],[954,"k"],[957,"v"],[959,"o"],[961,"p"],[963,"o"],[964,"t"],[965,"u"],[967,"x"],[913,"A"],[914,"B"],[917,"E"],[918,"Z"],[919,"H"],[921,"I"],[922,"K"],[924,"M"],[925,"N"],[927,"O"],[929,"P"],[932,"T"],[933,"Y"],[935,"X"],[1400,"n"],[1405,"u"],[1413,"o"],[5024,"D"],[5033,"E"],[5034,"A"],[5043,"W"],[5051,"P"],[5056,"G"],[5071,"C"],[5081,"V"],[5086,"S"],[5090,"B"],[448,"l"],[305,"i"],[609,"g"]]);const INVISIBLE=/[\u00ad\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/;function toCodepointLabel(codepoint){return`U+${codepoint.toString(16).toUpperCase().padStart(4,"0")}`}function confusableFor(codepoint){const mapped=CONFUSABLE_WITH_ASCII.get(codepoint);if(mapped!==void 0)return mapped;if(codepoint>=65313&&codepoint<=65338){return String.fromCharCode(codepoint-65313+65)}if(codepoint>=65345&&codepoint<=65370){return String.fromCharCode(codepoint-65345+97)}return null}function homoglyphIn(name){if(!/[A-Za-z]/.test(name))return null;for(let index=0;index<name.length;index++){const codepoint=name.charCodeAt(index);if(codepoint<128)continue;const latin=confusableFor(codepoint);if(latin!==null){return{character:name[index],codepoint,latin}}}return null}function isVisibleAscii(codepoint){return codepoint>=33&&codepoint<=126}function invisibleIn(text){for(let index=0;index<text.length;index++){if(!INVISIBLE.test(text[index]))continue;const before=text.charCodeAt(index-1);const after=text.charCodeAt(index+1);if(!isVisibleAscii(before)&&!isVisibleAscii(after))continue;return{index,codepoint:text.charCodeAt(index)}}return null}exports.noHomoglyphIdentifiers=(0,eslint_devkit_1.createRule)({name:"no-homoglyph-identifiers",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-homoglyph-identifiers.md",description:"Detects homoglyph identifiers and invisible characters that hide what the code actually does",cwe:"CWE-1007",cvss:5.3},messages:{homoglyphIdentifier:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Homoglyph Identifier",cwe:"CWE-1007",cvss:5.3,description:'Identifier "{{name}}" mixes scripts: {{codepoint}} renders as ASCII "{{latin}}" but is a different character',severity:"MEDIUM",fix:"Rewrite the identifier in ASCII, or confirm the binding it resolves to is the one you intended",documentationLink:"https://cwe.mitre.org/data/definitions/1007.html"}),invisibleCharacter:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Invisible Character",cwe:"CWE-1007",cvss:5.3,description:"String contains invisible character {{codepoint}} at index {{index}} - the text is not what it appears to be",severity:"MEDIUM",fix:"Remove the character, or write it as an escape (\\u200B) so it is visible in review",documentationLink:"https://trojansource.codes/"})},schema:[{type:"object",properties:{checkIdentifiers:{type:"boolean",default:true,description:"Check identifier names for script-mixing homoglyphs"},checkStrings:{type:"boolean",default:true,description:"Check string literals and template chunks for invisible characters"}},additionalProperties:false}]},defaultOptions:[{checkIdentifiers:true,checkStrings:true}],createOnce(context){let checkIdentifiers;let checkStrings;function checkName(node){if(!checkIdentifiers)return;const found=homoglyphIn(node.name);if(!found)return;context.report({node,messageId:"homoglyphIdentifier",data:{name:node.name,codepoint:toCodepointLabel(found.codepoint),latin:found.latin}})}function checkText(node,text){const found=invisibleIn(text);if(!found)return;context.report({node,messageId:"invisibleCharacter",data:{codepoint:toCodepointLabel(found.codepoint),index:String(found.index)}})}return{before(){const options=context.options[0]??{};checkIdentifiers=options.checkIdentifiers??true;checkStrings=options.checkStrings??true},Identifier:checkName,PrivateIdentifier:checkName,Literal(node){if(!checkStrings)return;checkText(node,node.raw)},TemplateElement(node){if(!checkStrings)return;checkText(node,node.value.raw)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noImproperSanitization=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.noImproperSanitization=(0,eslint_devkit_1.createRule)({name:"no-improper-sanitization",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-improper-sanitization.md",description:"Detects improper sanitization of user input",cwe:"CWE-116"},messages:{insufficientXssProtection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insufficient XSS Protection",cwe:"CWE-79",description:"XSS protection is incomplete or missing",severity:"HIGH",fix:"Use comprehensive XSS prevention or trusted sanitization library",documentationLink:"https://owasp.org/www-community/attacks/xss/"}),incompleteHtmlEscaping:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Incomplete HTML Escaping",cwe:"CWE-116",description:"HTML escaping misses dangerous characters",severity:"MEDIUM",fix:`Escape all HTML special characters: & < > " '`,documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"}),unsafeReplaceSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unescaped Markup In Output",cwe:"CWE-116",description:"A string reaching this sink carries unescaped markup",severity:"MEDIUM",fix:"Escape the value before it reaches the sink, or send it as text rather than markup",documentationLink:"https://cwe.mitre.org/data/definitions/116.html"})},schema:[{type:"object",properties:{safeSanitizers:{type:"array",items:{type:"string"},default:["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],description:"Sanitizer calls treated as sufficient"},dangerousChars:{type:"array",items:{type:"string"},default:["<",">",'"',"'","&"],description:"Characters a sanitizer is expected to handle"},contexts:{type:"array",items:{type:"string"},default:["html","url","sql","command","javascript","css"],description:"Output contexts checked for a context-appropriate sanitizer"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{safeSanitizers:["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],dangerousChars:["<",">",'"',"'","&"],contexts:["html","url","sql","command","javascript","css"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let safeSanitizers;let dangerousChars;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;const ENTITY=/&(?:amp|lt|gt|quot|apos|#x[0-9a-f]+|#\d+);/i;const isSafeSanitizer=callText=>{return safeSanitizers.some(sanitizer=>callText.includes(sanitizer))};const isReplaceCall=node=>node?.type==="CallExpression"&&node.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node.callee)==="replace";const isMidChain=node=>{const parent=node.parent;const grandparent=parent?.parent;return isReplaceCall(grandparent)&&grandparent.callee===parent};const staticPattern=node=>{if(node?.type!=="Literal")return void 0;const withRegex=node;if(withRegex.regex)return withRegex.regex.pattern;return typeof node.value==="string"?node.value:void 0};const staticReplacement=node=>{if(node?.type==="Literal"){return typeof node.value==="string"?node.value:void 0}if(node?.type==="TemplateLiteral"&&node.expressions.length===0){return node.quasis.map(quasi=>quasi.value.cooked).join("")}return void 0};const replaceChain=terminal=>{const pairs=[];let current=terminal;while(isReplaceCall(current)){pairs.push({pattern:staticPattern(current.arguments[0]),replacement:staticReplacement(current.arguments[1])});current=current.callee.object}return pairs};const isIncompleteReplaceSanitization=callExpression=>{const pairs=replaceChain(callExpression);const escapesTagChar=pairs.some(pair=>(pair.pattern==="<"||pair.pattern===">")&&pair.replacement!==void 0&&ENTITY.test(pair.replacement));if(!escapesTagChar)return false;const replacements=pairs.map(pair=>pair.replacement??"").join("");const hasQuoteEscaping=/&quot;|&#x27;|&#0?39;|&apos;/i.test(replacements);const hasAmpersandEscaping=/&amp;/.test(replacements);return!(hasQuoteEscaping&&hasAmpersandEscaping)};const needsContextEncoding=outputNode=>{let current=outputNode;while(current){const text=sourceCode.getText(current).toLowerCase();if(text.includes("innerhtml")||text.includes("outerhtml")){return"html"}if(text.includes("href")||text.includes("src")||text.includes("url")){return"url"}if(text.includes("sql")||text.includes("query")||text.includes("execute")){return"sql"}if(text.includes("exec")||text.includes("spawn")||text.includes("command")){return"command"}current=current.parent}return null};return{before(){const options=context.options[0]||{};({safeSanitizers=["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],dangerousChars=["<",">",'"',"'","&"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode})},CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="replace"){if(isMidChain(node)){return}if(isIncompleteReplaceSanitization(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"incompleteHtmlEscaping",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},AssignmentExpression(node){const left=node.left;const right=node.right;if(left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const sink=((0,eslint_devkit_1.propertyName)(left)??"").toLowerCase();if(["innerhtml","outerhtml","innertext","textcontent"].includes(sink)){const encodingContext=needsContextEncoding(node);if(encodingContext==="html"&&sink==="innerhtml"){const rightText=sourceCode.getText(right);if(!isSafeSanitizer(rightText)){const hasUserInput=rightText.includes("req.")||rightText.includes("body")||rightText.includes("query")||rightText.includes("input");if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"insufficientXssProtection",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}},Literal(node){if(typeof node.value!=="string"){return}const directParent=node.parent;if(directParent?.type==="AssignmentExpression"&&directParent.right===node&&directParent.left.type==="MemberExpression"){const left=directParent.left;if(["innerHTML","outerHTML"].includes((0,eslint_devkit_1.propertyName)(left)??"")){const literalValue=node.value;const hasDangerousMarkup=/<script[\s>]|<\/script>|\son\w+\s*=|javascript:/i.test(literalValue);if(!hasDangerousMarkup){return}}}const text=node.value;let current=node;let isInDangerousContext=false;while(current){if(current.type==="AssignmentExpression"){const left=current.left;if(left.type==="MemberExpression"&&["innerHTML","outerHTML"].includes((0,eslint_devkit_1.propertyName)(left)??"")){isInDangerousContext=true;break}}else if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["write","send","json"])){isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext){const enclosingArgument=literal=>{let current2=literal;let parent=current2.parent;for(;;){if(parent?.type==="BinaryExpression"&&parent.operator==="+"){current2=parent}else if(parent?.type==="ArrayExpression"){current2=parent}else if(parent?.type==="Property"||parent?.type==="ObjectExpression"&&current2.type==="Property"){current2=parent}else if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression||parent?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion){current2=parent}else if(parent?.type==="MemberExpression"&&parent.object===current2&&(0,eslint_devkit_1.propertyName)(parent)==="join"){current2=parent}else if(parent?.type==="CallExpression"&&parent.callee===current2){current2=parent}else{break}parent=current2.parent}if(parent?.type==="CallExpression"&&parent.arguments.includes(current2)){return current2}return void 0};const sanitizerNames=new Set([...safeSanitizers,...trustedSanitizers,"escapeHtml","escapeHTML","htmlEscape"]);const calleeName=callee=>{if(callee.type==="Identifier")return callee.name;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){return`${callee.object.name}.${callee.property.name}`}return void 0};const isSafeText=expr=>{if(expr.type==="Literal"){if(expr.value===null||typeof expr.value==="number"||typeof expr.value==="boolean"||typeof expr.value==="bigint"){return true}return typeof expr.value==="string"}if(expr.type==="TemplateLiteral")return expr.expressions.length===0;if(expr.type==="BinaryExpression"&&expr.operator==="+"){return isSafeText(expr.left)&&isSafeText(expr.right)}if(expr.type==="ObjectExpression"){return expr.properties.every(property=>property.type==="Property"&&isSafeText(property.value))}if(expr.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion){return isSafeText(expr.expression)}if(expr.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return expr.elements.every(element=>element===null||isSafeText(element))}if(expr.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(expr)==="length"){return true}if(expr.type==="CallExpression"){const callee=expr.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="join"&&callee.object.type==="ArrayExpression"){return callee.object.elements.every(element=>element!==null&&isSafeText(element))}const name=calleeName(callee);return name!==void 0&&sanitizerNames.has(name)}return false};const argument=enclosingArgument(node);const isBareLiteral=argument!==void 0&&isSafeText(argument);const hasDangerousMarkup=/<script[\s>]|<\/script>|\son\w+\s*=|javascript:/i.test(text);if(isBareLiteral&&!hasDangerousMarkup){return}const hasDangerousChars=dangerousChars.some(char=>text.includes(char));const hasEscaping=text.includes("&lt;")||text.includes("&gt;")||text.includes("&quot;")||text.includes("&#x27;")||text.includes("&amp;");if(hasDangerousChars&&!hasEscaping){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unsafeReplaceSanitization",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noImproperSanitization=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.noImproperSanitization=(0,eslint_devkit_1.createRule)({name:"no-improper-sanitization",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-improper-sanitization.md",description:"Detects improper sanitization of user input",cwe:"CWE-116"},messages:{insufficientXssProtection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Insufficient XSS Protection",cwe:"CWE-79",description:"XSS protection is incomplete or missing",severity:"HIGH",fix:"Use comprehensive XSS prevention or trusted sanitization library",documentationLink:"https://owasp.org/www-community/attacks/xss/"}),incompleteHtmlEscaping:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Incomplete HTML Escaping",cwe:"CWE-116",description:"HTML escaping misses dangerous characters",severity:"MEDIUM",fix:`Escape all HTML special characters: & < > " '`,documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"}),unsafeReplaceSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unescaped Markup In Output",cwe:"CWE-116",description:"A string reaching this sink carries unescaped markup",severity:"MEDIUM",fix:"Escape the value before it reaches the sink, or send it as text rather than markup",documentationLink:"https://cwe.mitre.org/data/definitions/116.html"})},schema:[{type:"object",properties:{safeSanitizers:{type:"array",items:{type:"string"},default:["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],description:"Sanitizer calls treated as sufficient"},dangerousChars:{type:"array",items:{type:"string"},default:["<",">",'"',"'","&"],description:"Characters a sanitizer is expected to handle"},contexts:{type:"array",items:{type:"string"},default:["html","url","sql","command","javascript","css"],description:"Output contexts checked for a context-appropriate sanitizer"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{safeSanitizers:["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],dangerousChars:["<",">",'"',"'","&"],contexts:["html","url","sql","command","javascript","css"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let safeSanitizers;let dangerousChars;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;const ENTITY=/&(?:amp|lt|gt|quot|apos|#x[0-9a-f]+|#\d+);/i;const isSafeSanitizer=callText=>{return safeSanitizers.some(sanitizer=>callText.includes(sanitizer))};const isReplaceCall=node=>node?.type==="CallExpression"&&node.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node.callee)==="replace";const isMidChain=node=>{const parent=node.parent;const grandparent=parent?.parent;return isReplaceCall(grandparent)&&grandparent.callee===parent};const staticPattern=node=>{if(node?.type!=="Literal")return void 0;const withRegex=node;if(withRegex.regex)return withRegex.regex.pattern;return typeof node.value==="string"?node.value:void 0};const staticReplacement=node=>{if(node?.type==="Literal"){return typeof node.value==="string"?node.value:void 0}if(node?.type==="TemplateLiteral"&&node.expressions.length===0){return node.quasis.map(quasi=>quasi.value.cooked).join("")}return void 0};const replaceChain=terminal=>{const pairs=[];let current=terminal;while(isReplaceCall(current)){pairs.push({pattern:staticPattern(current.arguments[0]),replacement:staticReplacement(current.arguments[1])});current=current.callee.object}return pairs};const isIncompleteReplaceSanitization=callExpression=>{const pairs=replaceChain(callExpression);const escapesTagChar=pairs.some(pair=>(pair.pattern==="<"||pair.pattern===">")&&pair.replacement!==void 0&&ENTITY.test(pair.replacement));if(!escapesTagChar)return false;const replacements=pairs.map(pair=>pair.replacement??"").join("");const hasQuoteEscaping=/&quot;|&#x27;|&#0?39;|&apos;/i.test(replacements);const hasAmpersandEscaping=/&amp;/.test(replacements);return!(hasQuoteEscaping&&hasAmpersandEscaping)};return{before(){const options=context.options[0]||{};({safeSanitizers=["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],dangerousChars=["<",">",'"',"'","&"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode})},CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="replace"){if(isMidChain(node)){return}if(isIncompleteReplaceSanitization(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"incompleteHtmlEscaping",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},AssignmentExpression(node){const left=node.left;const right=node.right;if(left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const sink=((0,eslint_devkit_1.propertyName)(left)??"").toLowerCase();if(sink==="innerhtml"||sink==="outerhtml"){const rightText=sourceCode.getText(right);if(!isSafeSanitizer(rightText)){const hasUserInput=rightText.includes("req.")||rightText.includes("body")||rightText.includes("query")||rightText.includes("input");if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"insufficientXssProtection",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},Literal(node){if(typeof node.value!=="string"){return}const directParent=node.parent;if(directParent.type==="AssignmentExpression"&&directParent.left.type==="MemberExpression"){const left=directParent.left;if(["innerHTML","outerHTML"].includes((0,eslint_devkit_1.propertyName)(left)??"")){const literalValue=node.value;const hasDangerousMarkup=/<script[\s>]|<\/script>|\son\w+\s*=|javascript:/i.test(literalValue);if(!hasDangerousMarkup){return}}}const text=node.value;let current=node;let isInDangerousContext=false;while(current){if(current.type==="AssignmentExpression"){const left=current.left;if(left.type==="MemberExpression"&&["innerHTML","outerHTML"].includes((0,eslint_devkit_1.propertyName)(left)??"")){isInDangerousContext=true;break}}else if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["write","send","json"])){isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext){const enclosingArgument=literal=>{let current2=literal;let parent=current2.parent;for(;;){if(parent.type==="BinaryExpression"&&parent.operator==="+"){current2=parent}else if(parent.type==="ArrayExpression"){current2=parent}else if(parent.type==="Property"||parent.type==="ObjectExpression"){current2=parent}else if(parent.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion){current2=parent}else if(parent.type==="MemberExpression"&&parent.object===current2&&(0,eslint_devkit_1.propertyName)(parent)==="join"){current2=parent}else if(parent.type==="CallExpression"&&parent.callee===current2){current2=parent}else{break}parent=current2.parent}if(parent.type==="CallExpression"&&parent.arguments.includes(current2)){return current2}return void 0};const sanitizerNames=new Set([...safeSanitizers,...trustedSanitizers,"escapeHtml","escapeHTML","htmlEscape"]);const calleeName=callee=>{if(callee.type==="Identifier")return callee.name;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){return`${callee.object.name}.${callee.property.name}`}return void 0};const isSafeText=expr=>{if(expr.type==="Literal"){if(expr.value===null||typeof expr.value==="number"||typeof expr.value==="boolean"||typeof expr.value==="bigint"){return true}return typeof expr.value==="string"}if(expr.type==="TemplateLiteral")return expr.expressions.length===0;if(expr.type==="UnaryExpression")return true;if(expr.type==="BinaryExpression"){return expr.operator!=="+"||isSafeText(expr.left)&&isSafeText(expr.right)}if(expr.type==="ObjectExpression"){return expr.properties.every(property=>property.type==="Property"&&isSafeText(property.value))}if(expr.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression||expr.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion){return isSafeText(expr.expression)}if(expr.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return expr.elements.every(element=>element===null||isSafeText(element))}if(expr.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(expr)==="length"){return true}if(expr.type==="CallExpression"){const callee=expr.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="join"&&callee.object.type==="ArrayExpression"){return isSafeText(callee.object)}const name=calleeName(callee);return name!==void 0&&sanitizerNames.has(name)}return false};const argument=enclosingArgument(node);const isBareLiteral=argument!==void 0&&isSafeText(argument);const hasDangerousMarkup=/<script[\s>]|<\/script>|\son\w+\s*=|javascript:/i.test(text);if(isBareLiteral&&!hasDangerousMarkup){return}const hasDangerousChars=dangerousChars.some(char=>text.includes(char));const hasEscaping=text.includes("&lt;")||text.includes("&gt;")||text.includes("&quot;")||text.includes("&#x27;")||text.includes("&amp;");if(hasDangerousChars&&!hasEscaping){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unsafeReplaceSanitization",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noImproperTypeValidation=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 unwrapTypeOnly(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion||current.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression){current=current.expression}return current}exports.noImproperTypeValidation=(0,eslint_devkit_1.createRule)({name:"no-improper-type-validation",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-improper-type-validation.md",description:"Detects improper type validation in user input handling",cwe:"CWE-1287"},messages:{unsafeTypeofCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe typeof Check",cwe:"CWE-1287",description:"typeof x === 'object' also matches null and arrays",severity:"MEDIUM",fix:'Use value != null && typeof value === "object" && !Array.isArray(value) \u2014 Not a finding if the value is already known non-null on this path',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof"}),unsafeInstanceofUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe instanceof Usage",cwe:"CWE-1287",description:"instanceof may fail across contexts",severity:"LOW",fix:"Use Array.isArray() or typeof checks \u2014 Not a finding if the value never crosses a realm boundary (no vm, iframe, or worker)",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof"}),looseEqualityTypeCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Loose Equality Type Check",cwe:"CWE-1287",description:"Loose equality may cause type confusion",severity:"LOW",fix:"Use strict equality (===) for type checking \u2014 Not a finding if both operands are already the same primitive type",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"}),unreliableConstructorCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unreliable Constructor Check",cwe:"CWE-1287",description:"constructor.name can be spoofed",severity:"MEDIUM",fix:"Use Object.prototype.toString.call() or duck typing \u2014 Not a finding if the value never came from parsed input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor"})},schema:[{type:"object",properties:{allowInstanceofSameRealm:{type:"boolean",default:true,description:"Allow instanceof for same-realm objects"},checkLooseEquality:{type:"boolean",default:true,description:"Report loose == / != between operands of unprovable type. Set false to keep only the structural typeof/instanceof/constructor arms."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as type 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:[{allowInstanceofSameRealm:true,checkLooseEquality:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let allowInstanceofSameRealm;let checkLooseEquality;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let filename;let safetyChecker;const isNullish=node=>node.type==="Literal"&&node.raw==="null"||node.type==="Identifier"&&node.name==="undefined";const sameExpression=(a,b)=>{a=unwrapTypeOnly(a);b=unwrapTypeOnly(b);if(a.type!==b.type)return false;if(a.type==="Identifier"&&b.type==="Identifier")return a.name===b.name;if(a.type==="ThisExpression")return true;if(a.type==="MemberExpression"&&b.type==="MemberExpression"){if(a.computed!==b.computed)return false;return sameExpression(a.object,b.object)&&sameExpression(a.property,b.property)}if(a.type==="Literal"&&b.type==="Literal")return a.raw===b.raw;return false};const hasNullGuard=(node,operand)=>{const excludesNullish=(expression,negated2)=>{if(sameExpression(expression,operand))return!negated2;if(expression.type==="UnaryExpression"&&expression.operator==="!"){return sameExpression(expression.argument,operand)&&negated2}if(expression.type!=="BinaryExpression")return false;if(expression.operator==="instanceof")return!negated2&&sameExpression(expression.left,operand);const wanted=negated2?["===","=="]:["!==","!="];if(!wanted.includes(expression.operator))return false;const strict=expression.operator.length===3;const excludesNull=side=>isNullish(side)&&(!strict||side.type==="Literal");if(excludesNull(expression.right))return sameExpression(expression.left,operand);if(excludesNull(expression.left))return sameExpression(expression.right,operand);return false};const negated=node.operator==="!=="||node.operator==="!=";const combinator=negated?"||":"&&";const guards=expression=>{if(expression.type==="LogicalExpression"&&expression.operator===combinator){return guards(expression.left)||guards(expression.right)}return excludesNullish(expression,negated)};let chain=node;while(chain.parent?.type==="LogicalExpression"&&chain.parent.operator===combinator){chain=chain.parent}return chain!==node&&guards(chain)};const primitiveTypeOf=(node,seen=new Set)=>{if(node.type==="Literal"){if(typeof node.value==="string")return"string";if(typeof node.value==="number")return"number";return void 0}if(node.type==="TemplateLiteral")return"string";if(node.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node)==="length"){return"number"}if(node.type==="CallExpression"&&node.callee.type==="Identifier"){if(node.callee.name==="String")return"string";if(node.callee.name==="Number"||node.callee.name==="parseInt")return"number"}if(node.type!=="Identifier")return void 0;if(seen.has(node.name))return void 0;seen.add(node.name);for(let scope=sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr);if(writes.length===0)return void 0;const types=writes.map(ref=>primitiveTypeOf(ref.writeExpr,seen));return types.every(type=>type!==void 0&&type===types[0])?types[0]:void 0}return void 0};const typeofObjectOperand=node=>{if(!["===","!==","==","!="].includes(node.operator))return void 0;const{left,right}=node;if(left.type==="UnaryExpression"&&left.operator==="typeof"&&right.type==="Literal"&&right.value==="object"){return left.argument}return void 0};const report=(node,messageId)=>{if(safetyChecker.isSafe(node,context))return;context.report({node,messageId,data:{filePath:filename,line:String(node.loc.start.line)}})};return{before(){const options=context.options[0]||{};({allowInstanceofSameRealm=true,checkLooseEquality=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode})},BinaryExpression(node){const operand=typeofObjectOperand(node);if(operand){if(!hasNullGuard(node,operand))report(node.left,"unsafeTypeofCheck");return}if(node.operator==="instanceof"&&!allowInstanceofSameRealm){report(node,"unsafeInstanceofUsage");return}if(checkLooseEquality&&(node.operator==="=="||node.operator==="!=")){if(isNullish(node.left)||isNullish(node.right))return;const leftType=primitiveTypeOf(node.left);if(leftType!==void 0&&leftType===primitiveTypeOf(node.right))return;report(node,"looseEqualityTypeCheck")}},MemberExpression(node){if((0,eslint_devkit_1.propertyName)(node)!=="name")return;const inner=node.object;if(inner.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(inner)!=="constructor"){return}if(node.parent?.type!=="BinaryExpression")return;report(node,"unreliableConstructorCheck")}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noImproperTypeValidation=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 unwrapTypeOnly(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion||current.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression){current=current.expression}return current}exports.noImproperTypeValidation=(0,eslint_devkit_1.createRule)({name:"no-improper-type-validation",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-improper-type-validation.md",description:"Detects improper type validation in user input handling",cwe:"CWE-1287"},messages:{unsafeTypeofCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe typeof Check",cwe:"CWE-1287",description:"typeof x === 'object' also matches null and arrays",severity:"MEDIUM",fix:'Use value != null && typeof value === "object" && !Array.isArray(value) \u2014 Not a finding if the value is already known non-null on this path',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof"}),unsafeInstanceofUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe instanceof Usage",cwe:"CWE-1287",description:"instanceof may fail across contexts",severity:"LOW",fix:"Use Array.isArray() or typeof checks \u2014 Not a finding if the value never crosses a realm boundary (no vm, iframe, or worker)",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof"}),looseEqualityTypeCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Loose Equality Type Check",cwe:"CWE-1287",description:"Loose equality may cause type confusion",severity:"LOW",fix:"Use strict equality (===) for type checking \u2014 Not a finding if both operands are already the same primitive type",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"}),unreliableConstructorCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unreliable Constructor Check",cwe:"CWE-1287",description:"constructor.name can be spoofed",severity:"MEDIUM",fix:"Use Object.prototype.toString.call() or duck typing \u2014 Not a finding if the value never came from parsed input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor"})},schema:[{type:"object",properties:{allowInstanceofSameRealm:{type:"boolean",default:true,description:"Allow instanceof for same-realm objects"},checkLooseEquality:{type:"boolean",default:true,description:"Report loose == / != between operands of unprovable type. Set false to keep only the structural typeof/instanceof/constructor arms."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as type 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:[{allowInstanceofSameRealm:true,checkLooseEquality:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let allowInstanceofSameRealm;let checkLooseEquality;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let safetyChecker;const isNullish=node=>node.type==="Literal"&&node.raw==="null"||node.type==="Identifier"&&node.name==="undefined";const sameExpression=(a,b)=>{a=unwrapTypeOnly(a);b=unwrapTypeOnly(b);if(a.type!==b.type)return false;if(a.type==="Identifier"&&b.type==="Identifier")return a.name===b.name;if(a.type==="ThisExpression")return true;if(a.type==="MemberExpression"&&b.type==="MemberExpression"){if(a.computed!==b.computed)return false;return sameExpression(a.object,b.object)&&sameExpression(a.property,b.property)}if(a.type==="Literal"&&b.type==="Literal")return a.raw===b.raw;return false};const hasNullGuard=(node,operand)=>{const excludesNullish=(expression,negated2)=>{if(sameExpression(expression,operand))return!negated2;if(expression.type==="UnaryExpression"&&expression.operator==="!"){return sameExpression(expression.argument,operand)&&negated2}if(expression.type!=="BinaryExpression")return false;if(expression.operator==="instanceof")return!negated2&&sameExpression(expression.left,operand);const wanted=negated2?["===","=="]:["!==","!="];if(!wanted.includes(expression.operator))return false;const strict=expression.operator.length===3;const excludesNull=side=>isNullish(side)&&(!strict||side.type==="Literal");if(excludesNull(expression.right))return sameExpression(expression.left,operand);if(excludesNull(expression.left))return sameExpression(expression.right,operand);return false};const negated=node.operator==="!=="||node.operator==="!=";const combinator=negated?"||":"&&";const guards=expression=>{if(expression.type==="LogicalExpression"&&expression.operator===combinator){return guards(expression.left)||guards(expression.right)}return excludesNullish(expression,negated)};let chain=node;while(chain.parent?.type==="LogicalExpression"&&chain.parent.operator===combinator){chain=chain.parent}return guards(chain)};const primitiveTypeOf=(node,seen=new Set)=>{if(node.type==="Literal"){if(typeof node.value==="string")return"string";if(typeof node.value==="number")return"number";return void 0}if(node.type==="TemplateLiteral")return"string";if(node.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node)==="length"){return"number"}if(node.type==="CallExpression"&&node.callee.type==="Identifier"){if(node.callee.name==="String")return"string";if(node.callee.name==="Number"||node.callee.name==="parseInt")return"number"}if(node.type!=="Identifier")return void 0;if(seen.has(node.name))return void 0;seen.add(node.name);for(let scope=sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr);if(writes.length===0)return void 0;const types=writes.map(ref=>primitiveTypeOf(ref.writeExpr,seen));return types.every(type=>type!==void 0&&type===types[0])?types[0]:void 0}return void 0};const typeofObjectOperand=node=>{if(!["===","!==","==","!="].includes(node.operator))return void 0;const{left,right}=node;if(left.type==="UnaryExpression"&&left.operator==="typeof"&&right.type==="Literal"&&right.value==="object"){return left.argument}return void 0};const report=(node,messageId)=>{if(safetyChecker.isSafe(node,context))return;context.report({node,messageId})};return{before(){const options=context.options[0]||{};({allowInstanceofSameRealm=true,checkLooseEquality=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode})},BinaryExpression(node){const operand=typeofObjectOperand(node);if(operand){if(!hasNullGuard(node,operand))report(node.left,"unsafeTypeofCheck");return}if(node.operator==="instanceof"&&!allowInstanceofSameRealm){report(node,"unsafeInstanceofUsage");return}if(checkLooseEquality&&(node.operator==="=="||node.operator==="!=")){if(isNullish(node.left)||isNullish(node.right))return;const leftType=primitiveTypeOf(node.left);if(leftType!==void 0&&leftType===primitiveTypeOf(node.right))return;report(node,"looseEqualityTypeCheck")}},MemberExpression(node){if((0,eslint_devkit_1.propertyName)(node)!=="name")return;const inner=node.object;if(inner.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(inner)!=="constructor"){return}if(node.parent.type!=="BinaryExpression")return;report(node,"unreliableConstructorCheck")}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureComparison=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const fileUsesAstTooling=(0,eslint_devkit_2.createModuleEvidence)({packages:["@babel/types","@babel/traverse","@babel/generator","@babel/parser","recast","jscodeshift","estree-walker","unist-util-visit","@typescript-eslint/utils","@typescript-eslint/typescript-estree","typescript","ts-morph","eslint"]});exports.noInsecureComparison=(0,eslint_devkit_2.createRule)({name:"no-insecure-comparison",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-insecure-comparison.md",description:"Detects insecure comparison operators (==, !=) that can lead to type coercion vulnerabilities",cwe:"CWE-697",cvss:5.3},hasSuggestions:true,messages:{insecureComparison:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure Comparison",cwe:"CWE-697",description:"Insecure comparison operator ({{operator}}) detected - can lead to type coercion vulnerabilities",severity:"HIGH",fix:"Use strict equality ({{strictOperator}}) instead: {{example}} \u2014 Not a finding if the comparison is against null, which tests null and undefined together on purpose",documentationLink:"https://cwe.mitre.org/data/definitions/697.html"}),useStrictEquality:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Strict Equality",description:"Use strict equality operator",severity:"LOW",fix:"Replace == with === and != with !== \u2014 Not a finding if the comparison is the idiomatic `x == null` nullish test",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality"}),useTimingSafeEqual:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use A Constant-Time Comparison",description:"Compare secrets in constant time, not with an operator that short-circuits",severity:"LOW",fix:"Rewrite as crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)) \u2014 Not a finding if neither side is a secret the caller can guess one character at a time",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"}),timingUnsafeComparison:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Timing Attack Risk",cwe:"CWE-208",description:"Secret comparison with {{operator}} can leak timing information",severity:"HIGH",fix:"Use crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)) \u2014 Not a finding if the compared value is public, such as an id or a status",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow insecure comparison in test files"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},reportLooseEquality:{type:"boolean",default:true,description:"Report `==` between non-secret operands. Turn off to keep only the secret-comparison findings and leave generic type coercion to eqeqeq."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,ignorePatterns:[],reportLooseEquality:true}],createOnce(context,currentOptions){let allowInTests;let ignorePatterns;let reportLooseEquality;let isTestFile;let sourceCode;let isCodemodFile;function matchesIgnorePattern(text,patterns){return patterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return text.toLowerCase().includes(pattern.toLowerCase())}})}function isNullLiteral(node){return node.type==="Literal"&&node.raw==="null"}function isStringTyped(node,seen=new Set){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return typeof node.value==="string";if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral)return true;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(seen.has(node.name))return false;seen.add(node.name);for(let scope=sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length===0)return false;return writes.every(ref=>{const written=ref.writeExpr;return written!=null&&isStringTyped(written,seen)})}return false}function checkBinaryExpression(node){if(isTestFile){return}if(isCodemodFile){return}const secretKeywords=new Set(["secret","secrets","token","tokens","password","passwd","pwd","apikey","api_key","secretkey","secret_key","privatekey","private_key","signature","hmac","digest","checksum","nonce","otp","passwordhash","password_hash","hashedpassword","hashed_password","credential","credentials"]);const nameSegments=name=>{const parts=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean).map(p=>p.toLowerCase());const pairs=[];for(let i=0;i+1<parts.length;i+=1){pairs.push(parts[i]+parts[i+1],`${parts[i]}_${parts[i+1]}`)}return[...parts,...pairs,parts.join(""),parts.join("_"),name.toLowerCase()]};const scopeAtNode=sourceCode.getScope(node);const destructuringKeys=(pattern,target)=>{const keys=[];const walkPattern=n=>{if(n.type==="ObjectPattern"){for(const property of n.properties){if(property.type!=="Property")continue;if(property.value===target&&!property.computed&&property.key.type==="Identifier"){keys.push(property.key.name)}walkPattern(property.value)}}else if(n.type==="ArrayPattern"){for(const element of n.elements)if(element)walkPattern(element)}else if(n.type==="AssignmentPattern"){walkPattern(n.left)}};walkPattern(pattern);return keys};const namesIn=expr=>{const out=[];const visited=new Set;const walk=n=>{if(visited.has(n))return;visited.add(n);if(n.type==="Identifier"){out.push(n.name);resolveIdentifier(n)}else if(n.type==="MemberExpression"){walk(n.object);const key=(0,eslint_devkit_1.propertyName)(n);if(key!==null)out.push(key);else walk(n.property)}else if(n.type==="CallExpression"){walk(n.callee)}else if(n.type==="ConditionalExpression"){walk(n.consequent);walk(n.alternate)}else if(n.type==="TSAsExpression"||n.type==="TSSatisfiesExpression"||n.type==="TSNonNullExpression"){walk(n.expression)}};function resolveIdentifier(identifier){for(let scope=scopeAtNode;scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite());const isObjectDestructured=variable.defs.some(def=>def.type==="Variable"&&def.node.id.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern);if(!isObjectDestructured&&writes.length===1&&writes[0].writeExpr){walk(writes[0].writeExpr)}for(const def of variable.defs){if(def.type!=="Variable")continue;out.push(...destructuringKeys(def.node.id,def.name))}return}}walk(expr);return out};const isPotentialSecret=expr=>namesIn(expr).flatMap(nameSegments).some(segment=>secretKeywords.has(segment));if((node.operator==="==="||node.operator==="!==")&&(isPotentialSecret(node.left)||isPotentialSecret(node.right))){const isLengthComparison=expr=>{return expr.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(expr)==="length"};if(isLengthComparison(node.left)||isLengthComparison(node.right)){return}const isNonSecretLiteral=expr=>expr.type===eslint_devkit_1.AST_NODE_TYPES.Literal||expr.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&expr.expressions.length===0||expr.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&expr.argument.type===eslint_devkit_1.AST_NODE_TYPES.Literal||expr.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&expr.name==="undefined";if(isNonSecretLiteral(node.left)||isNonSecretLiteral(node.right)){return}const leftText=sourceCode.getText(node.left);const rightText=sourceCode.getText(node.right);const example=`crypto.timingSafeEqual(Buffer.from(${leftText}), Buffer.from(${rightText}))`;context.report({node,messageId:"timingUnsafeComparison",data:{operator:node.operator,strictOperator:node.operator,example},suggest:[{messageId:"useTimingSafeEqual",fix:fixer=>fixer.replaceText(node,example)}]});return}if(node.operator==="=="||node.operator==="!="){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isNullLiteral(node.left)||isNullLiteral(node.right)){return}if(isStringTyped(node.left)&&isStringTyped(node.right)){return}const comparesSecret=isPotentialSecret(node.left)||isPotentialSecret(node.right);if(!reportLooseEquality&&!comparesSecret){return}const strictOperator=node.operator==="=="?"===":"!==";const leftText=sourceCode.getText(node.left);const rightText=sourceCode.getText(node.right);const example=`${leftText} ${strictOperator} ${rightText}`;context.report({node,messageId:"insecureComparison",data:{operator:node.operator,strictOperator,example},suggest:[{messageId:"useStrictEquality",fix:fixer=>{return fixer.replaceText(node,example)}}]})}}return{before(){const[options={}]=currentOptions();({allowInTests=false,ignorePatterns=[],reportLooseEquality=true}=options);const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);sourceCode=context.sourceCode;isCodemodFile=(()=>{if(/\/codemod[s]?\//i.test(filename))return true;if(/codemod\.[mc]?[jt]sx?$/i.test(filename))return true;return fileUsesAstTooling(sourceCode.ast)})()},BinaryExpression:checkBinaryExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureComparison=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const fileUsesAstTooling=(0,eslint_devkit_2.createModuleEvidence)({packages:["@babel/types","@babel/traverse","@babel/generator","@babel/parser","recast","jscodeshift","estree-walker","unist-util-visit","@typescript-eslint/utils","@typescript-eslint/typescript-estree","typescript","ts-morph","eslint"]});exports.noInsecureComparison=(0,eslint_devkit_2.createRule)({name:"no-insecure-comparison",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-insecure-comparison.md",description:"Detects insecure comparison operators (==, !=) that can lead to type coercion vulnerabilities",cwe:"CWE-697",cvss:5.3},hasSuggestions:true,messages:{insecureComparison:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure Comparison",cwe:"CWE-697",description:"Insecure comparison operator ({{operator}}) detected - can lead to type coercion vulnerabilities",severity:"HIGH",fix:"Use strict equality ({{strictOperator}}) instead: {{example}} \u2014 Not a finding if the comparison is against null, which tests null and undefined together on purpose",documentationLink:"https://cwe.mitre.org/data/definitions/697.html"}),useStrictEquality:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Strict Equality",description:"Use strict equality operator",severity:"LOW",fix:"Replace == with === and != with !== \u2014 Not a finding if the comparison is the idiomatic `x == null` nullish test",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality"}),useTimingSafeEqual:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use A Constant-Time Comparison",description:"Compare secrets in constant time, not with an operator that short-circuits",severity:"LOW",fix:"Rewrite as crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)) \u2014 Not a finding if neither side is a secret the caller can guess one character at a time",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"}),timingUnsafeComparison:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Timing Attack Risk",cwe:"CWE-208",description:"Secret comparison with {{operator}} can leak timing information",severity:"HIGH",fix:"Use crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b)) \u2014 Not a finding if the compared value is public, such as an id or a status",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow insecure comparison in test files"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},reportLooseEquality:{type:"boolean",default:true,description:"Report `==` between non-secret operands. Turn off to keep only the secret-comparison findings and leave generic type coercion to eqeqeq."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,ignorePatterns:[],reportLooseEquality:true}],createOnce(context,currentOptions){let allowInTests;let ignorePatterns;let reportLooseEquality;let isTestFile;let sourceCode;let isCodemodFile;function matchesIgnorePattern(text,patterns){return patterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return text.toLowerCase().includes(pattern.toLowerCase())}})}function isNullLiteral(node){return node.type==="Literal"&&node.raw==="null"}function isStringTyped(node,seen=new Set){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return typeof node.value==="string";if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral)return true;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(seen.has(node.name))return false;seen.add(node.name);for(let scope=sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length===0)return false;return writes.every(ref=>{const written=ref.writeExpr;return written!=null&&isStringTyped(written,seen)})}return false}function checkBinaryExpression(node){if(isTestFile){return}if(isCodemodFile){return}const secretKeywords=new Set(["secret","secrets","token","tokens","password","passwd","pwd","apikey","api_key","secretkey","secret_key","privatekey","private_key","signature","hmac","digest","checksum","nonce","otp","passwordhash","password_hash","hashedpassword","hashed_password","credential","credentials"]);const nameSegments=name=>{const parts=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(Boolean).map(p=>p.toLowerCase());const pairs=[];for(let i=0;i+1<parts.length;i+=1){pairs.push(`${parts[i]}_${parts[i+1]}`)}return[...parts,...pairs,parts.join(""),parts.join("_"),name.toLowerCase()]};const scopeAtNode=sourceCode.getScope(node);const PATTERN_PARTS=new Set(["Property","ObjectPattern","ArrayPattern","AssignmentPattern","RestElement"]);const destructuringKeys=(pattern,target)=>{const keys=[];const walkPattern=n=>{if(n.type==="ObjectPattern"){for(const property of n.properties){if(property.type!=="Property")continue;const bound=property.value.type==="AssignmentPattern"?property.value.left:property.value;const key=(0,eslint_devkit_1.objectKeyName)(property);if(bound===target&&key!==null)keys.push(key);walkPattern(property.value)}}else if(n.type==="ArrayPattern"){for(const element of n.elements)if(element)walkPattern(element)}else if(n.type==="AssignmentPattern"){walkPattern(n.left)}};walkPattern(pattern);return keys};const namesIn=expr=>{const out=[];const visited=new Set;const walk=n=>{if(visited.has(n))return;visited.add(n);if(n.type==="Identifier"){out.push(n.name);resolveIdentifier(n)}else if(n.type==="MemberExpression"){walk(n.object);const key=(0,eslint_devkit_1.propertyName)(n);if(key!==null)out.push(key);else walk(n.property)}else if(n.type==="CallExpression"){walk(n.callee)}else if(n.type==="ConditionalExpression"){walk(n.consequent);walk(n.alternate)}else if(n.type==="TSAsExpression"||n.type==="TSSatisfiesExpression"||n.type==="TSNonNullExpression"){walk(n.expression)}};function resolveIdentifier(identifier){for(let scope=scopeAtNode;scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite());const isObjectDestructured=variable.defs.some(def=>def.type==="Variable"&&def.node.id.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern);if(!isObjectDestructured&&writes.length===1&&writes[0].writeExpr){walk(writes[0].writeExpr)}for(const def of variable.defs){let pattern=def.name;while(pattern.parent!==void 0&&PATTERN_PARTS.has(pattern.parent.type)){pattern=pattern.parent}out.push(...destructuringKeys(pattern,def.name))}return}}walk(expr);return out};const isPotentialSecret=expr=>namesIn(expr).flatMap(nameSegments).some(segment=>secretKeywords.has(segment));if((node.operator==="==="||node.operator==="!==")&&(isPotentialSecret(node.left)||isPotentialSecret(node.right))){const isLengthComparison=expr=>{return expr.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(expr)==="length"};if(isLengthComparison(node.left)||isLengthComparison(node.right)){return}const isNonSecretLiteral=expr=>expr.type===eslint_devkit_1.AST_NODE_TYPES.Literal||expr.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&expr.expressions.length===0||expr.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&expr.argument.type===eslint_devkit_1.AST_NODE_TYPES.Literal||expr.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&expr.name==="undefined";if(isNonSecretLiteral(node.left)||isNonSecretLiteral(node.right)){return}const leftText=sourceCode.getText(node.left);const rightText=sourceCode.getText(node.right);const example=`crypto.timingSafeEqual(Buffer.from(${leftText}), Buffer.from(${rightText}))`;context.report({node,messageId:"timingUnsafeComparison",data:{operator:node.operator,strictOperator:node.operator,example},suggest:[{messageId:"useTimingSafeEqual",fix:fixer=>fixer.replaceText(node,example)}]});return}if(node.operator==="=="||node.operator==="!="){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isNullLiteral(node.left)||isNullLiteral(node.right)){return}if(isStringTyped(node.left)&&isStringTyped(node.right)){return}const comparesSecret=isPotentialSecret(node.left)||isPotentialSecret(node.right);if(!reportLooseEquality&&!comparesSecret){return}const strictOperator=node.operator==="=="?"===":"!==";const leftText=sourceCode.getText(node.left);const rightText=sourceCode.getText(node.right);const example=`${leftText} ${strictOperator} ${rightText}`;context.report({node,messageId:"insecureComparison",data:{operator:node.operator,strictOperator,example},suggest:[{messageId:"useStrictEquality",fix:fixer=>{return fixer.replaceText(node,example)}}]})}}return{before(){const[options={}]=currentOptions();({allowInTests=false,ignorePatterns=[],reportLooseEquality=true}=options);const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);sourceCode=context.sourceCode;isCodemodFile=(()=>{if(/\/codemod[s]?\//i.test(filename))return true;if(/codemod\.[mc]?[jt]sx?$/i.test(filename))return true;return fileUsesAstTooling(sourceCode.ast)})()},BinaryExpression:checkBinaryExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLdapInjection=void 0;exports.containsDangerousLdapFilter=containsDangerousLdapFilter;exports.looksLikeLdapFilterGrammar=looksLikeLdapFilterGrammar;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 containsDangerousLdapFilter(filterText){const dangerousPatterns=[/\*\)$/,/\|\)$/,/&\)$/,/!\)$/,/\*\|\*/,/\*&\*/,/\*!/];return dangerousPatterns.some(pattern=>pattern.test(filterText))}function looksLikeLdapFilterGrammar(staticText){return/\(\s*[A-Za-z][\w.;-]*\s*(?:[:~<>]?=)/.test(staticText)}const DEFAULT_LDAP_PACKAGES=["ldapjs","ldapts","ldapauth-fork","passport-ldapauth","ldap-authentication","ldap-escape","ldap-filter","activedirectory","activedirectory2","node-ldap"];const LDAP_SCOPES=new Set(["@ldapjs"]);const SEARCH_METHODS=new Set(["search","searchAsync","searchPaginated"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","httpRequest"];const DEFAULT_LDAP_FUNCTIONS=["search","searchAsync","searchPaginated","bind","modify","modifyDN","add","del","delete","compare"];const DEFAULT_ESCAPE_FUNCTIONS=["escape.filterValue","escape.dnValue","filterValue","dnValue","filterEscape","dnEscape"];const DEFAULT_VALIDATION_FUNCTIONS=["validateLdapInput","sanitizeLdapFilter","cleanLdapValue","checkLdapFilter"];exports.noLdapInjection=(0,eslint_devkit_1.createRule)({name:"no-ldap-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-ldap-injection.md",description:"Detects LDAP injection vulnerabilities",cwe:"CWE-90"},messages:{ldapInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"LDAP Injection",cwe:"CWE-90",description:"LDAP injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),unsafeLdapFilter:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe LDAP Filter",cwe:"CWE-90",description:"LDAP filter constructed with unsafe string operations",severity:"HIGH",fix:"Use ldap.escape.filterValue() to escape user input",documentationLink:"https://ldap.com/ldap-filters/"}),unescapedLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unescaped LDAP Input",cwe:"CWE-90",description:"LDAP operation uses unescaped user input",severity:"MEDIUM",fix:"Escape all user input before LDAP operations",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),dangerousLdapOperation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous LDAP Operation",cwe:"CWE-90",description:"LDAP operation allows dangerous filter patterns",severity:"HIGH",fix:"Validate LDAP filters and restrict allowed operations",documentationLink:"https://ldap.com/ldap-filters/"}),validateLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate LDAP Input",description:"Validate LDAP input before processing",severity:"LOW",fix:"Validate input against allowed patterns",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"})},schema:[{type:"object",properties:{ldapFunctions:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_FUNCTIONS,description:"LDAP client methods treated as query sinks"},ldapEscapeFunctions:{type:"array",items:{type:"string"},default:DEFAULT_ESCAPE_FUNCTIONS,description:"Function names that escape LDAP filter or DN values"},ldapValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_VALIDATION_FUNCTIONS,description:"Function names that count as LDAP input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as LDAP 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)"},ldapPackages:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_PACKAGES,description:"Package specifiers whose import opens the file gate. Nothing in a file is examined unless one of these is loaded. Replaces the built-in list."},additionalLdapPackages:{type:"array",items:{type:"string"},default:[],description:"Extra LDAP client packages, on top of `ldapPackages` \u2014 a house wrapper around ldapjs belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifiers naming a framework request object, matched as the exact ROOT of a member chain \u2014 never as a substring of the printed expression. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."}},additionalProperties:false}]},defaultOptions:[{ldapFunctions:DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions:DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions:DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers:[],trustedAnnotations:[],strictMode:false,ldapPackages:DEFAULT_LDAP_PACKAGES,additionalLdapPackages:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[]}],createOnce(context){let ldapFunctions;let ldapEscapeFunctions;let ldapValidationFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let ldapPackages;let additionalLdapPackages;let requestRoots;let additionalRequestRoots;let ldapPackageSet;let requestRootSet;let fileImportsLdapClient;let sourceCode;let filename;let safetyChecker;let ldapLocals;let ldapInFile;let reported;const collectLdapLocals=program=>{const record=node=>{if(node?.type==="Identifier")ldapLocals.add(node.name);else if(node?.type==="ObjectPattern"){for(const property of node.properties){if(property.type==="Property")record(property.value)}}};const isLdapSource=raw=>typeof raw==="string"&&(ldapPackageSet.has(raw)||[...LDAP_SCOPES].some(scope=>raw.startsWith(`${scope}/`)));for(const statement of program.body){if(statement.type==="ImportDeclaration"&&isLdapSource(statement.source.value)){for(const specifier of statement.specifiers)record(specifier.local)}if(statement.type==="VariableDeclaration"){for(const declarator of statement.declarations){const init=declarator.init;if(init?.type==="CallExpression"&&init.callee.type==="Identifier"&&init.callee.name==="require"&&init.arguments[0]?.type==="Literal"&&isLdapSource(init.arguments[0].value)){record(declarator.id)}}}}};const unwrap=node=>{let current=node;while(current.type==="TSAsExpression"||current.type==="TSSatisfiesExpression"||current.type==="TSNonNullExpression"||current.type==="ChainExpression"){current=current.expression}return current};const writesOf=identifier=>{for(let scope=sourceCode.getScope(identifier);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;return variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr).map(ref=>ref.writeExpr)}return[]};const soleWriteOf=identifier=>{const writes=writesOf(identifier);return writes.length===1?writes[0]:void 0};const isLdapConstruction=node=>{const expression=unwrap(node);if(expression.type==="NewExpression"){const{callee:callee2}=expression;if(callee2.type==="Identifier")return ldapLocals.has(callee2.name);return callee2.type==="MemberExpression"&&callee2.object.type==="Identifier"&&ldapLocals.has(callee2.object.name)}if(expression.type!=="CallExpression")return false;const{callee}=expression;if(callee.type==="Identifier")return ldapLocals.has(callee.name);return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&ldapLocals.has(callee.object.name)};const enclosingClassBody=node=>{for(let current=node;current;current=current.parent){if(current.type==="ClassBody")return current}return void 0};const isProvablyNotLdapReceiver=receiver=>{const expression=unwrap(receiver);if(expression.type==="ArrayExpression"||expression.type==="ObjectExpression"||expression.type==="Literal"){return true}if(expression.type==="NewExpression"||expression.type==="CallExpression"){return!isLdapConstruction(expression)}if(expression.type==="Identifier"){const writes=writesOf(expression);if(writes.length===0)return false;if(writes.some(isLdapConstruction))return false;return writes.every(write=>{const value=unwrap(write);return value.type==="NewExpression"||value.type==="CallExpression"||value.type==="ArrayExpression"||value.type==="ObjectExpression"||value.type==="Literal"})}const fieldName=(0,eslint_devkit_1.memberPropertyName)(expression);if(expression.type==="MemberExpression"&&expression.object.type==="ThisExpression"&&fieldName!==null){const body=enclosingClassBody(expression);if(!body)return false;const field=body.body.find(member=>member.type==="PropertyDefinition"&&!member.computed&&member.key.type==="Identifier"&&member.key.name===fieldName);if(!field?.value)return false;return!isLdapConstruction(field.value)}return false};const isEscaped=node=>{const expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(write&&write!==expression&&isEscapedAt(write))return true}return isEscapedAt(node)};function isEscapedAt(node){for(let current=node;current;current=current.parent){if(current.type!=="CallExpression")continue;const{callee}=current;const escapeMethod=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&escapeMethod!==null){if(ldapEscapeFunctions.some(escapeFunc=>escapeFunc===escapeMethod||escapeFunc.endsWith(`.${escapeMethod}`))){return true}}if(callee.type==="Identifier"&&(ldapValidationFunctions.includes(callee.name)||ldapEscapeFunctions.includes(callee.name))){return true}}return false}const isStatic=node=>(0,eslint_devkit_1.isStaticExpression)({node,scope:sourceCode.getScope(node)});const dynamicParts=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return null;seen.add(expression);if(expression.type==="TemplateLiteral"){return expression.expressions.filter(part=>!isStatic(part)&&!isEscaped(part))}if(expression.type==="BinaryExpression"&&expression.operator==="+"){const leaves=[];const flatten=n=>{const inner=unwrap(n);if(inner.type==="BinaryExpression"&&inner.operator==="+"){flatten(inner.left);flatten(inner.right)}else leaves.push(inner)};flatten(expression);const hasStringPart=leaves.some(leaf=>(0,eslint_devkit_1.staticString)(leaf)!==null||leaf.type==="TemplateLiteral");if(!hasStringPart)return null;return leaves.filter(leaf=>!isStatic(leaf)&&!isEscaped(leaf))}if(expression.type==="ConditionalExpression"){const consequent=dynamicParts(expression.consequent,seen);const alternate=dynamicParts(expression.alternate,seen);if(consequent===null&&alternate===null)return null;return[...consequent??[],...alternate??[]]}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?dynamicParts(write,seen):null}return null};const isRequestValue=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return false;seen.add(expression);if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?isRequestValue(write,seen):false}if(expression.type==="CallExpression"){if(isEscaped(expression))return false;return expression.arguments.some(argument=>argument.type!=="SpreadElement"&&isRequestValue(argument,seen))}if(expression.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(expression)===null)return false;return!isStatic(expression)&&isUntrustedRequestChain(expression)};function isUntrustedRequestChain(node){let current=node;while(current.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(current)===null)return false;current=current.object}if(current.type!=="Identifier")return false;if(requestRootSet.has(current.name))return true;for(let scope=sourceCode.getScope(current);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===current.name);if(!variable)continue;return variable.defs.some(def=>{if(def.type!=="Variable")return false;const init=def.node.init?unwrap(def.node.init):void 0;if(!init)return false;if(init.type==="Identifier")return requestRootSet.has(init.name);return init.type==="MemberExpression"&&isUntrustedRequestChain(init)})}return false}const filterOption=node=>{let expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(!write)return void 0;expression=unwrap(write)}if(expression.type!=="ObjectExpression")return void 0;for(const property of expression.properties){if(property.type!=="Property")continue;const{key}=property;if(!property.computed&&key.type==="Identifier"&&key.name==="filter"){return property.value}if(key.type==="Literal"&&key.value==="filter")return property.value;if(property.computed&&key.type==="Identifier"){const keyWrite=soleWriteOf(key);if(keyWrite&&unwrap(keyWrite).type==="Literal"){const literal=unwrap(keyWrite);if(literal.value==="filter")return property.value}}}return void 0};const report=(node,messageId,data)=>{if(reported.has(node))return;if(safetyChecker.isSafe(node,context))return;reported.add(node);context.report({node,messageId,data:{filePath:filename,line:String(node.loc.start.line),...data}})};const staticSkeleton=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return"";seen.add(expression);if(expression.type==="Literal"){return typeof expression.value==="string"?expression.value:""}if(expression.type==="TemplateLiteral"){return expression.quasis.map(quasi=>quasi.value.raw).join("\0")}if(expression.type==="BinaryExpression"&&expression.operator==="+"){return staticSkeleton(expression.left,seen)+"\0"+staticSkeleton(expression.right,seen)}if(expression.type==="ConditionalExpression"){return staticSkeleton(expression.consequent,seen)+"\0"+staticSkeleton(expression.alternate,seen)}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?staticSkeleton(write,seen):""}return""};const originOf=node=>{let current=unwrap(node);for(let hops=0;current.type==="Identifier"&&hops<8;hops+=1){const write=soleWriteOf(current);if(!write)break;current=unwrap(write)}return current};const checkFilter=rawFilterNode=>{const filterNode=originOf(rawFilterNode);const parts=dynamicParts(filterNode);if(parts&&parts.length>0){report(filterNode,"unsafeLdapFilter",{});return}if(isRequestValue(filterNode)){report(filterNode,"unescapedLdapInput",{});return}if(containsDangerousLdapFilter(staticSkeleton(filterNode).split("\0").join(""))){report(filterNode,"dangerousLdapOperation",{})}};const checkDn=rawDnNode=>{const dnNode=originOf(rawDnNode);const parts=dynamicParts(dnNode);if(parts&&parts.length>0){report(dnNode,"ldapInjection",{severity:"HIGH",safeAlternative:"Use ldap.escape.dnValue() or build the DN from validated components"});return}if(isRequestValue(dnNode)){report(dnNode,"ldapInjection",{severity:"MEDIUM",safeAlternative:"Use proper LDAP escaping and validation"})}};const checkConstructedFilter=node=>{if(!looksLikeLdapFilterGrammar(staticSkeleton(node)))return;checkFilter(node)};return{before(){const options=context.options[0]||{};({ldapFunctions=DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions=DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions=DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers=[],trustedAnnotations=[],strictMode=false,ldapPackages=DEFAULT_LDAP_PACKAGES,additionalLdapPackages=[],requestRoots=DEFAULT_REQUEST_ROOTS,additionalRequestRoots=[]}=options);ldapPackageSet=new Set([...ldapPackages,...additionalLdapPackages]);requestRootSet=new Set([...requestRoots,...additionalRequestRoots]);fileImportsLdapClient=(0,eslint_devkit_1.createModuleEvidence)({packages:[...ldapPackageSet],scopes:[...LDAP_SCOPES]});sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});ldapLocals=new Set;ldapInFile=false;reported=new Set},Program(program){ldapInFile=fileImportsLdapClient(program);if(ldapInFile)collectLdapLocals(program)},VariableDeclarator(node){if(!ldapInFile||!node.init)return;checkConstructedFilter(node.init)},AssignmentExpression(node){if(!ldapInFile)return;checkConstructedFilter(node.right)},CallExpression(node){if(!ldapInFile)return;const callee=unwrap(node.callee);if(callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return;if(!ldapFunctions.includes(method))return;if(isProvablyNotLdapReceiver(callee.object))return;const args=node.arguments.filter(argument=>argument.type!=="SpreadElement");if(args.length===0)return;checkDn(args[0]);if(args.length<2)return;if(SEARCH_METHODS.has(method)){const optionsFilter=filterOption(args[1]);checkFilter(optionsFilter??args[1]);return}checkConstructedFilter(args[1])}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLdapInjection=void 0;exports.containsDangerousLdapFilter=containsDangerousLdapFilter;exports.looksLikeLdapFilterGrammar=looksLikeLdapFilterGrammar;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 containsDangerousLdapFilter(filterText){const dangerousPatterns=[/\*\)$/,/&\)$/,/\*\|\*/,/\*&\*/,/\*!/];return dangerousPatterns.some(pattern=>pattern.test(filterText))}function looksLikeLdapFilterGrammar(staticText){return/\(\s*[A-Za-z][\w.;-]*\s*(?:[:~<>]?=)/.test(staticText)}const DEFAULT_LDAP_PACKAGES=["ldapjs","ldapts","ldapauth-fork","passport-ldapauth","ldap-authentication","ldap-escape","ldap-filter","activedirectory","activedirectory2","node-ldap"];const LDAP_SCOPES=new Set(["@ldapjs"]);const SEARCH_METHODS=new Set(["search","searchAsync","searchPaginated"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","httpRequest"];const DEFAULT_LDAP_FUNCTIONS=["search","searchAsync","searchPaginated","bind","modify","modifyDN","add","del","delete","compare"];const DEFAULT_ESCAPE_FUNCTIONS=["escape.filterValue","escape.dnValue","filterValue","dnValue","filterEscape","dnEscape"];const DEFAULT_VALIDATION_FUNCTIONS=["validateLdapInput","sanitizeLdapFilter","cleanLdapValue","checkLdapFilter"];exports.noLdapInjection=(0,eslint_devkit_1.createRule)({name:"no-ldap-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-ldap-injection.md",description:"Detects LDAP injection vulnerabilities",cwe:"CWE-90"},messages:{ldapInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"LDAP Injection",cwe:"CWE-90",description:"LDAP injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),unsafeLdapFilter:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe LDAP Filter",cwe:"CWE-90",description:"LDAP filter constructed with unsafe string operations",severity:"HIGH",fix:"Use ldap.escape.filterValue() to escape user input",documentationLink:"https://ldap.com/ldap-filters/"}),unescapedLdapInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unescaped LDAP Input",cwe:"CWE-90",description:"LDAP operation uses unescaped user input",severity:"MEDIUM",fix:"Escape all user input before LDAP operations",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),dangerousLdapOperation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous LDAP Operation",cwe:"CWE-90",description:"LDAP operation allows dangerous filter patterns",severity:"HIGH",fix:"Validate LDAP filters and restrict allowed operations",documentationLink:"https://ldap.com/ldap-filters/"})},schema:[{type:"object",properties:{ldapFunctions:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_FUNCTIONS,description:"LDAP client methods treated as query sinks"},ldapEscapeFunctions:{type:"array",items:{type:"string"},default:DEFAULT_ESCAPE_FUNCTIONS,description:"Function names that escape LDAP filter or DN values"},ldapValidationFunctions:{type:"array",items:{type:"string"},default:DEFAULT_VALIDATION_FUNCTIONS,description:"Function names that count as LDAP input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as LDAP 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)"},ldapPackages:{type:"array",items:{type:"string"},default:DEFAULT_LDAP_PACKAGES,description:"Package specifiers whose import opens the file gate. Nothing in a file is examined unless one of these is loaded. Replaces the built-in list."},additionalLdapPackages:{type:"array",items:{type:"string"},default:[],description:"Extra LDAP client packages, on top of `ldapPackages` \u2014 a house wrapper around ldapjs belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifiers naming a framework request object, matched as the exact ROOT of a member chain \u2014 never as a substring of the printed expression. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."}},additionalProperties:false}]},defaultOptions:[{ldapFunctions:DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions:DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions:DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers:[],trustedAnnotations:[],strictMode:false,ldapPackages:DEFAULT_LDAP_PACKAGES,additionalLdapPackages:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[]}],createOnce(context){let ldapFunctions;let ldapEscapeFunctions;let ldapValidationFunctions;let trustedSanitizers;let trustedAnnotations;let strictMode;let ldapPackages;let additionalLdapPackages;let requestRoots;let additionalRequestRoots;let ldapPackageSet;let requestRootSet;let fileImportsLdapClient;let sourceCode;let safetyChecker;let ldapLocals;let ldapInFile;let reported;const collectLdapLocals=program=>{const record=node=>{if(node.type==="Identifier")ldapLocals.add(node.name);else if(node.type==="ObjectPattern"){for(const property of node.properties){if(property.type==="Property")record(property.value)}}};const isLdapSource=specifier=>{const[scope,name]=specifier.split("/");return ldapPackageSet.has(specifier)||name!==void 0&&LDAP_SCOPES.has(scope)};for(const statement of program.body){if(statement.type==="ImportDeclaration"&&isLdapSource(statement.source.value)){for(const specifier of statement.specifiers)record(specifier.local)}if(statement.type==="VariableDeclaration"){for(const declarator of statement.declarations){const init=declarator.init;const specifier=init?.type==="CallExpression"&&init.callee.type==="Identifier"&&init.callee.name==="require"?(0,eslint_devkit_1.staticString)(init.arguments[0]):null;if(specifier!==null&&isLdapSource(specifier)){record(declarator.id)}}}}};const unwrap=node=>{let current=node;while(current.type==="TSAsExpression"||current.type==="TSSatisfiesExpression"||current.type==="TSNonNullExpression"||current.type==="ChainExpression"){current=current.expression}return current};const writesOf=identifier=>{for(let scope=sourceCode.getScope(identifier);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;return variable.references.flatMap(ref=>ref.writeExpr?[ref.writeExpr]:[])}return[]};const soleWriteOf=identifier=>{const writes=writesOf(identifier);return writes.length===1?unwrap(writes[0]):void 0};const isLdapConstruction=expression=>{const{callee}=expression;if(callee.type==="Identifier")return ldapLocals.has(callee.name);return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&ldapLocals.has(callee.object.name)};const enclosingClassBody=node=>{for(let current=node;current;current=current.parent){if(current.type==="ClassBody")return current}return void 0};const isNonLdapValue=node=>{const value=unwrap(node);switch(value.type){case"ArrayExpression":case"ObjectExpression":case"Literal":return true;case"NewExpression":case"CallExpression":return!isLdapConstruction(value);default:return false}};const isProvablyNotLdapReceiver=receiver=>{const expression=unwrap(receiver);if(expression.type==="Identifier"){const writes=writesOf(expression);return writes.length>0&&writes.every(isNonLdapValue)}const fieldName=(0,eslint_devkit_1.memberPropertyName)(expression);if(expression.type==="MemberExpression"&&expression.object.type==="ThisExpression"&&fieldName!==null){const body=enclosingClassBody(expression);if(!body)return false;const field=body.body.find(member=>member.type==="PropertyDefinition"&&!member.computed&&member.key.type==="Identifier"&&member.key.name===fieldName);return field?.value!=null&&isNonLdapValue(field.value)}return isNonLdapValue(expression)};const isEscaped=node=>{const expression=unwrap(node);if(expression.type==="Identifier"&&isEscapedAt(soleWriteOf(expression))){return true}return isEscapedAt(node)};function isEscapedAt(node){for(let current=node;current;current=current.parent){if(current.type!=="CallExpression")continue;const{callee}=current;const escapeMethod=(0,eslint_devkit_1.memberPropertyName)(callee);if(escapeMethod!==null){if(ldapEscapeFunctions.some(escapeFunc=>escapeFunc===escapeMethod||escapeFunc.endsWith(`.${escapeMethod}`))){return true}}if(callee.type==="Identifier"&&(ldapValidationFunctions.includes(callee.name)||ldapEscapeFunctions.includes(callee.name))){return true}}return false}const isStatic=node=>(0,eslint_devkit_1.isStaticExpression)({node,scope:sourceCode.getScope(node)});const dynamicParts=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return[];seen.add(expression);if(expression.type==="TemplateLiteral"){return expression.expressions.filter(part=>!isStatic(part)&&!isEscaped(part))}if(expression.type==="BinaryExpression"&&expression.operator==="+"){const leaves=[];const flatten=n=>{const inner=unwrap(n);if(inner.type==="BinaryExpression"&&inner.operator==="+"){flatten(inner.left);flatten(inner.right)}else leaves.push(inner)};flatten(expression);const hasStringPart=leaves.some(leaf=>(0,eslint_devkit_1.staticString)(leaf)!==null||leaf.type==="TemplateLiteral");if(!hasStringPart)return[];return leaves.filter(leaf=>!isStatic(leaf)&&!isEscaped(leaf))}if(expression.type==="ConditionalExpression"){return[...dynamicParts(expression.consequent,seen),...dynamicParts(expression.alternate,seen)]}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?dynamicParts(write,seen):[]}return[]};const isRequestValue=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return false;seen.add(expression);if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?isRequestValue(write,seen):false}if(expression.type==="CallExpression"){if(isEscaped(expression))return false;return expression.arguments.some(argument=>isRequestValue(argument.type==="SpreadElement"?argument.argument:argument,seen))}if(expression.type!=="MemberExpression")return false;return!isStatic(expression)&&isUntrustedRequestChain(expression)};function isUntrustedRequestChain(node){let current=node;while(current.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(current)===null)return false;current=current.object}if(current.type!=="Identifier")return false;if(requestRootSet.has(current.name))return true;for(let scope=sourceCode.getScope(current);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===current.name);if(!variable)continue;return variable.defs.some(def=>{if(def.type!=="Variable")return false;const init=def.node.init?unwrap(def.node.init):void 0;if(!init)return false;if(init.type==="Identifier")return requestRootSet.has(init.name);return init.type==="MemberExpression"&&isUntrustedRequestChain(init)})}return false}const filterOption=node=>{let expression=unwrap(node);if(expression.type==="Identifier"){const write=soleWriteOf(expression);if(!write)return void 0;expression=unwrap(write)}if(expression.type!=="ObjectExpression")return void 0;for(const property of expression.properties){if(property.type!=="Property")continue;if((0,eslint_devkit_1.objectKeyName)(property)==="filter")return property.value;const{key}=property;if(property.computed&&key.type==="Identifier"&&(0,eslint_devkit_1.staticString)(soleWriteOf(key))==="filter"){return property.value}}return void 0};const report=(node,messageId,data)=>{if(reported.has(node))return;if(safetyChecker.isSafe(node,context))return;reported.add(node);context.report({node,messageId,data})};const staticSkeleton=(node,seen=new Set)=>{const expression=unwrap(node);if(seen.has(expression))return"";seen.add(expression);if(expression.type==="Literal")return String(expression.value);if(expression.type==="TemplateLiteral"){return expression.quasis.map(quasi=>quasi.value.raw).join("\0")}if(expression.type==="BinaryExpression"&&expression.operator==="+"){return staticSkeleton(expression.left,seen)+"\0"+staticSkeleton(expression.right,seen)}if(expression.type==="ConditionalExpression"){return staticSkeleton(expression.consequent,seen)+"\0"+staticSkeleton(expression.alternate,seen)}if(expression.type==="Identifier"){const write=soleWriteOf(expression);return write?staticSkeleton(write,seen):""}return""};const originOf=node=>{const seen=new Set;let current=unwrap(node);while(current.type==="Identifier"&&!seen.has(current)){seen.add(current);const write=soleWriteOf(current);if(!write)break;current=write}return current};const checkFilter=rawFilterNode=>{const filterNode=originOf(rawFilterNode);if(dynamicParts(filterNode).length>0){report(filterNode,"unsafeLdapFilter",{});return}if(isRequestValue(filterNode)){report(filterNode,"unescapedLdapInput",{});return}if(containsDangerousLdapFilter(staticSkeleton(filterNode).split("\0").join(""))){report(filterNode,"dangerousLdapOperation",{})}};const checkDn=rawDnNode=>{const dnNode=originOf(rawDnNode);if(dynamicParts(dnNode).length>0){report(dnNode,"ldapInjection",{severity:"HIGH",safeAlternative:"Use ldap.escape.dnValue() or build the DN from validated components"});return}if(isRequestValue(dnNode)){report(dnNode,"ldapInjection",{severity:"MEDIUM",safeAlternative:"Use proper LDAP escaping and validation"})}};const checkConstructedFilter=node=>{if(!looksLikeLdapFilterGrammar(staticSkeleton(node)))return;checkFilter(node)};return{before(){const options=context.options[0]||{};({ldapFunctions=DEFAULT_LDAP_FUNCTIONS,ldapEscapeFunctions=DEFAULT_ESCAPE_FUNCTIONS,ldapValidationFunctions=DEFAULT_VALIDATION_FUNCTIONS,trustedSanitizers=[],trustedAnnotations=[],strictMode=false,ldapPackages=DEFAULT_LDAP_PACKAGES,additionalLdapPackages=[],requestRoots=DEFAULT_REQUEST_ROOTS,additionalRequestRoots=[]}=options);ldapPackageSet=new Set([...ldapPackages,...additionalLdapPackages]);requestRootSet=new Set([...requestRoots,...additionalRequestRoots]);fileImportsLdapClient=(0,eslint_devkit_1.createModuleEvidence)({packages:[...ldapPackageSet],scopes:[...LDAP_SCOPES]});sourceCode=context.sourceCode;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});ldapLocals=new Set;reported=new Set},Program(program){ldapInFile=fileImportsLdapClient(program);if(ldapInFile)collectLdapLocals(program)},VariableDeclarator(node){if(!ldapInFile||!node.init)return;checkConstructedFilter(node.init)},AssignmentExpression(node){if(!ldapInFile)return;checkConstructedFilter(node.right)},CallExpression(node){if(!ldapInFile)return;const callee=unwrap(node.callee);if(callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return;if(!ldapFunctions.includes(method))return;if(isProvablyNotLdapReceiver(callee.object))return;const args=node.arguments.filter(argument=>argument.type!=="SpreadElement");if(args.length===0)return;checkDn(args[0]);if(args.length<2)return;if(SEARCH_METHODS.has(method)){const optionsFilter=filterOption(args[1]);checkFilter(optionsFilter??args[1]);return}checkConstructedFilter(args[1])}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLogInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_LOGGER_RECEIVERS=["console","log","logger","winston","pino","bunyan"];const LOG_LEVEL_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];function requestFieldOf(node,roots,requestProperties){if(node.type!=="MemberExpression")return null;const properties=[];let root=node;while(root.type==="MemberExpression"){const name=(0,eslint_devkit_1.propertyName)(root);if(name!==null)properties.unshift(name);root=root.object}if(root.type!=="Identifier")return null;if(!roots.has(root.name))return null;if(!properties.some(p=>requestProperties.has(p)))return null;return`${root.name}.${properties.join(".")}`}function findLocalVariable(scope,name){let current=scope;for(;;){const variable=current.set.get(name);if(variable)return variable;if(current.type==="function"||!current.upper)return null;current=current.upper}}const LOOP_TYPES=new Set(["ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement"]);function isAncestor(outer,inner){for(let n=inner;n;n=n.parent){if(n===outer)return true}return false}function isStraightLineTo(target,read){const statement=target.parent.parent;if(statement?.type!=="ExpressionStatement"&&statement?.type!=="VariableDeclaration"){return false}const block=statement.parent;return(block?.type==="BlockStatement"||block?.type==="Program")&&isAncestor(block,read)}function isCarriedByLoop(write,read,dominator){for(let n=read;n;n=n.parent){if(LOOP_TYPES.has(n.type)&&isAncestor(n,write)&&!(dominator&&isAncestor(n,dominator))){return true}}return false}function writtenRequestField(ref,init,roots,requestProperties){if(ref.init)return requestFieldOf(init,roots,requestProperties);const write=ref.identifier.parent;if(write.type!=="AssignmentExpression"||write.operator!=="="){return null}return requestFieldOf(write.right,roots,requestProperties)}function attributableSource(node,scope,roots,requestProperties){if(node.type==="Identifier"){const variable=findLocalVariable(scope,node.name);if(!variable)return null;const definition=variable.defs[0];if(!definition||definition.type!=="Variable"||!definition.node.init){return null}const writes=variable.references.filter(ref=>ref.isWrite());const reaching=[];let dominator;for(const ref of writes.filter(w=>w.identifier.range[0]<node.range[0]).reverse()){reaching.push(ref);if(isStraightLineTo(ref.identifier,node)){dominator=ref.identifier;break}}for(const ref of writes){if(ref.identifier.range[0]>node.range[0]&&isCarriedByLoop(ref.identifier,node,dominator)){reaching.push(ref)}}for(const ref of reaching){const field=writtenRequestField(ref,definition.node.init,roots,requestProperties);if(field)return field}return null}return requestFieldOf(node,roots,requestProperties)}function isMessageShaped(node){return node.type==="TemplateLiteral"||node.type==="BinaryExpression"&&node.operator==="+"}function directOperands(node,out){if(node.type==="TemplateLiteral"){for(const expression of node.expressions)out.push(expression);return}if(node.type==="BinaryExpression"&&node.operator==="+"){directOperands(node.left,out);directOperands(node.right,out);return}out.push(node)}function receiverName(object,receivers){if(object.type==="Identifier"){return receivers.has(object.name)?object.name:null}if(object.type==="MemberExpression"){const held=(0,eslint_devkit_1.propertyName)(object);return held!==null&&receivers.has(held)?held:null}return null}exports.noLogInjection=(0,eslint_devkit_1.createRule)({name:"no-log-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-log-injection.md",description:"Detects request data concatenated into a log message, which lets an attacker forge log records",cwe:"CWE-117",cvss:5.3},messages:{logInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Log Injection",cwe:"CWE-117",description:"Log message embeds {{source}} directly - a CR/LF in that value forges a log record",severity:"MEDIUM",fix:'Log it as a structured field (logger.info({ value }, "message")) or strip CR/LF/control characters first',documentationLink:"https://cwe.mitre.org/data/definitions/117.html"})},schema:[{type:"object",properties:{loggerReceivers:{type:"array",items:{type:"string"},default:DEFAULT_LOGGER_RECEIVERS,description:"Receiver names whose level methods write a log line, compared as an exact name and never as a substring. Replaces the built-in list."},loggerNames:{type:"array",items:{type:"string"},default:[],description:"Additional receiver names whose level methods write a log line, on top of `loggerReceivers`"},requestRootNames:{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."},requestRoots:{type:"array",items:{type:"string"},default:[],description:"Additional identifier roots that denote an inbound request, on top of `requestRootNames`"},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"}},additionalProperties:false}]},defaultOptions:[{loggerReceivers:DEFAULT_LOGGER_RECEIVERS,loggerNames:[],requestRootNames:DEFAULT_REQUEST_ROOTS,requestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[]}],createOnce(context){let receivers;let roots;let requestProperties;let sourceCode;function isLoggingCall(node){const callee=node.callee;if(callee.type!=="MemberExpression")return false;if(!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),LOG_LEVEL_METHODS))return false;return receiverName(callee.object,receivers)!==null}return{before(){const options=context.options[0]??{};receivers=new Set([...options.loggerReceivers??DEFAULT_LOGGER_RECEIVERS,...options.loggerNames??[]]);roots=new Set([...options.requestRootNames??DEFAULT_REQUEST_ROOTS,...options.requestRoots??[]]);requestProperties=new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]);sourceCode=context.sourceCode},CallExpression(node){if(!isLoggingCall(node))return;for(const argument of node.arguments){if(!isMessageShaped(argument))continue;const operands=[];directOperands(argument,operands);for(const operand of operands){const source=attributableSource(operand,sourceCode.getScope(operand),roots,requestProperties);if(source===null)continue;context.report({node:argument,messageId:"logInjection",data:{source}});return}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLogInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_LOGGER_RECEIVERS=["console","log","logger","winston","pino","bunyan"];const LOG_LEVEL_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];function requestFieldOf(node,roots,requestProperties){if(node.type!=="MemberExpression")return null;const properties=[];let root=node;while(root.type==="MemberExpression"){const name=(0,eslint_devkit_1.propertyName)(root);if(name!==null)properties.unshift(name);root=root.object}if(root.type!=="Identifier")return null;if(!roots.has(root.name))return null;if(!properties.some(p=>requestProperties.has(p)))return null;return`${root.name}.${properties.join(".")}`}function findLocalVariable(scope,name){let current=scope;for(;;){const variable=current.set.get(name);if(variable)return variable;if(current.type==="function"||!current.upper)return null;current=current.upper}}const LOOP_TYPES=new Set(["ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement"]);function isAncestor(outer,inner){for(let n=inner;n;n=n.parent){if(n===outer)return true}return false}function isStraightLineTo(target,read){const statement=target.parent.parent;if(statement?.type!=="ExpressionStatement"&&statement?.type!=="VariableDeclaration"){return false}const block=statement.parent;return(block?.type==="BlockStatement"||block?.type==="Program")&&isAncestor(block,read)}function isCarriedByLoop(write,read,dominator){for(let n=read;n;n=n.parent){if(LOOP_TYPES.has(n.type)&&isAncestor(n,write)&&!(dominator&&isAncestor(n,dominator))){return true}}return false}function writtenRequestField(ref,roots,requestProperties){if(ref.init){return requestFieldOf(ref.writeExpr,roots,requestProperties)}const write=ref.identifier.parent;if(write.type!=="AssignmentExpression"||write.operator!=="="){return null}return requestFieldOf(write.right,roots,requestProperties)}function attributableSource(node,scope,roots,requestProperties){if(node.type==="Identifier"){const variable=findLocalVariable(scope,node.name);if(!variable)return null;const writes=variable.references.filter(ref=>ref.isWrite());const reaching=[];let dominator;for(const ref of writes.filter(w=>w.identifier.range[0]<node.range[0]).reverse()){reaching.push(ref);if(isStraightLineTo(ref.identifier,node)){dominator=ref.identifier;break}}for(const ref of writes){if(ref.identifier.range[0]>node.range[0]&&isCarriedByLoop(ref.identifier,node,dominator)){reaching.push(ref)}}for(const ref of reaching){const field=writtenRequestField(ref,roots,requestProperties);if(field)return field}return null}return requestFieldOf(node,roots,requestProperties)}function isMessageShaped(node){return node.type==="TemplateLiteral"||node.type==="BinaryExpression"&&node.operator==="+"}function directOperands(node,out){if(node.type==="TemplateLiteral"){for(const expression of node.expressions)out.push(expression);return}if(node.type==="BinaryExpression"&&node.operator==="+"){directOperands(node.left,out);directOperands(node.right,out);return}out.push(node)}function receiverName(object,receivers){if(object.type==="Identifier"){return receivers.has(object.name)?object.name:null}if(object.type==="MemberExpression"){const held=(0,eslint_devkit_1.propertyName)(object);return held!==null&&receivers.has(held)?held:null}return null}exports.noLogInjection=(0,eslint_devkit_1.createRule)({name:"no-log-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-log-injection.md",description:"Detects request data concatenated into a log message, which lets an attacker forge log records",cwe:"CWE-117",cvss:5.3},messages:{logInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Log Injection",cwe:"CWE-117",description:"Log message embeds {{source}} directly - a CR/LF in that value forges a log record",severity:"MEDIUM",fix:'Log it as a structured field (logger.info({ value }, "message")) or strip CR/LF/control characters first',documentationLink:"https://cwe.mitre.org/data/definitions/117.html"})},schema:[{type:"object",properties:{loggerReceivers:{type:"array",items:{type:"string"},default:DEFAULT_LOGGER_RECEIVERS,description:"Receiver names whose level methods write a log line, compared as an exact name and never as a substring. Replaces the built-in list."},loggerNames:{type:"array",items:{type:"string"},default:[],description:"Additional receiver names whose level methods write a log line, on top of `loggerReceivers`"},requestRootNames:{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."},requestRoots:{type:"array",items:{type:"string"},default:[],description:"Additional identifier roots that denote an inbound request, on top of `requestRootNames`"},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"}},additionalProperties:false}]},defaultOptions:[{loggerReceivers:DEFAULT_LOGGER_RECEIVERS,loggerNames:[],requestRootNames:DEFAULT_REQUEST_ROOTS,requestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[]}],createOnce(context){let receivers;let roots;let requestProperties;let sourceCode;function isLoggingCall(node){const callee=node.callee;if(callee.type!=="MemberExpression")return false;if(!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),LOG_LEVEL_METHODS))return false;return receiverName(callee.object,receivers)!==null}return{before(){const options=context.options[0]??{};receivers=new Set([...options.loggerReceivers??DEFAULT_LOGGER_RECEIVERS,...options.loggerNames??[]]);roots=new Set([...options.requestRootNames??DEFAULT_REQUEST_ROOTS,...options.requestRoots??[]]);requestProperties=new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]);sourceCode=context.sourceCode},CallExpression(node){if(!isLoggingCall(node))return;for(const argument of node.arguments){if(!isMessageShaped(argument))continue;const operands=[];directOperands(argument,operands);for(const operand of operands){const source=attributableSource(operand,sourceCode.getScope(operand),roots,requestProperties);if(source===null)continue;context.report({node:argument,messageId:"logInjection",data:{source}});return}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingAuthentication=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_AUTH_MIDDLEWARE_PATTERNS=["authenticate","auth","requireAuth","isAuthenticated","verifyToken","checkAuth","ensureAuthenticated","passport.authenticate","jwt","session"];const DEFAULT_PUBLIC_ROUTE_PATTERNS=["login","logout","signin","sign-in","signup","sign-up","register","forgot-password","reset-password","password-reset","verify-email","health","healthz","readyz","livez","alive","liveness","readiness","heartbeat","status","metrics","ping","favicon","webhook","/public/","oauth","callback"];const DEFAULT_ROUTE_HANDLER_PATTERNS=["get","post","put","delete","patch","all","use"];const ROUTER_NAME_WORDS=["app","router","route","server","express","fastify","koa","hapi"];const ROUTER_FACTORY_NAMES=new Set(["express","Router","fastify","polka","restify","connect","Koa"]);const ROUTER_FACTORY_MEMBERS=new Set(["Router","router","Server","server","createServer"]);function routeChainBase(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&current.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if((0,eslint_devkit_2.propertyName)(current.callee)==="route"){return current}current=current.callee.object}return null}function isDefinitelyNotRouter(init){return init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression}function isRouterFactory(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return false}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_NAMES.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_2.propertyName)(callee)!==null){return ROUTER_FACTORY_MEMBERS.has((0,eslint_devkit_2.propertyName)(callee))}return false}function referencedName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.name}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=(0,eslint_devkit_1.propertyName)(node);if(property===null)return null;const objectPart=node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${node.object.name}.`:"";return`${objectPart}${property}`}return null}function isAuthMiddlewareArg(arg,authPatterns){const target=arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression?arg.callee:arg;const name=referencedName(target);return name!==null&&(0,eslint_devkit_1.nameHasAnyWord)(name,authPatterns)}function isInsideAuthMiddleware(node,authPatterns){let current=node;while(current){if(current.parent&&current.parent.type==="CallExpression"){const callExpr=current.parent;const isArgument=callExpr.arguments.some(arg=>arg===current);if(!isArgument){current=current.parent;continue}const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,authPatterns)){return true}}if(callee.type==="MemberExpression"&&(0,eslint_devkit_2.propertyName)(callee)!==null){const propertyName=(0,eslint_devkit_2.propertyName)(callee).toLowerCase();if(propertyName==="use"||propertyName==="all"){for(const arg of callExpr.arguments){if(isAuthMiddlewareArg(arg,authPatterns)){return true}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}exports.noMissingAuthentication=(0,eslint_devkit_2.createRule)({name:"no-missing-authentication",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-missing-authentication.md",description:"Detects missing authentication checks in route handlers",cwe:"CWE-287",cvss:9.8},messages:{missingAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Authentication",cwe:"CWE-287",description:"Route handler missing authentication check: {{route}}",severity:"CRITICAL",fix:"Add authentication middleware: app.{{method}}('{{path}}', authenticate(), handler)",documentationLink:"https://cwe.mitre.org/data/definitions/287.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing authentication in test files"},authMiddlewarePatterns:{type:"array",items:{type:"string"},default:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,description:"Authentication middleware patterns to recognize"},routeHandlerPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROUTE_HANDLER_PATTERNS,description:"Route handler patterns to check"},ignorePatterns:{type:"array",items:{type:"string"},default:DEFAULT_PUBLIC_ROUTE_PATTERNS,description:"Route paths that are public by definition and need no authentication. Replaces the built-in list; supplying it also widens matching from the route path to the whole registration text."},routerNameWords:{type:"array",items:{type:"string"},default:ROUTER_NAME_WORDS,description:"Object names that denote an HTTP application or router, compared as WHOLE WORDS and never as a substring. Read only when the binding cannot be resolved to a framework factory call. Replaces the built-in list."},additionalRouterNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra router-object name words, on top of `routerNameWords`."},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,authMiddlewarePatterns:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns:DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns:DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords:ROUTER_NAME_WORDS,additionalRouterNameWords:[]}],createOnce(context,currentOptions){let allowInTests;let testFilePattern;let authMiddlewarePatterns;let routeHandlerPatterns;let ignorePatterns;let routerNameWords;let additionalRouterNameWords;let routerWords;let isTestFile;let sourceCode;let scansWholeCallText;function looksLikeRouter(object){const scope=sourceCode.getScope(object);const reference=scope.references.find(ref=>ref.identifier===object);const resolved=reference?.resolved;for(const def of resolved?.defs??[]){const parent=def.name.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){if(isRouterFactory(parent.init)){return true}if(isDefinitelyNotRouter(parent.init)){return false}}}return(0,eslint_devkit_1.nameHasAnyWord)(object.name,routerWords)}function findVariableDeclaration(identifier){const varName=identifier.name;let current=identifier;while(current){if(current.type==="Program"||current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const scopeBody=current.type==="Program"?current.body:current.body.type==="BlockStatement"?current.body.body:[];for(const stmt of scopeBody){if(stmt.type==="VariableDeclaration"){for(const declarator of stmt.declarations){if(declarator.id.type==="Identifier"&&declarator.id.name===varName){return declarator}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return null}function isIdentifierFromAuthMiddleware(identifier){const declarator=findVariableDeclaration(identifier);if(!declarator||!declarator.init){return false}if(declarator.init.type==="CallExpression"&&declarator.init.callee.type==="Identifier"){return(0,eslint_devkit_1.nameHasAnyWord)(declarator.init.callee.name,authMiddlewarePatterns)}return false}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const object=node.callee.object;let chainedPath;if(object.type==="Identifier"){if(!looksLikeRouter(object)){return}}else{const base=routeChainBase(object);const baseObject=base?.callee.type==="MemberExpression"?base.callee.object:void 0;if(!base||baseObject?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!looksLikeRouter(baseObject)){return}chainedPath=base.arguments[0]}const resolvedMethod=(0,eslint_devkit_2.propertyName)(node.callee);if(resolvedMethod!==null){const methodName=resolvedMethod.toLowerCase();if(routeHandlerPatterns.includes(methodName)){if(methodName!=="use"&&chainedPath===void 0&&node.arguments.length<2){return}if(methodName==="use"){const first=node.arguments[0];const mountsAPath=first!==void 0&&first.type==="Literal"&&typeof first.value==="string";if(!mountsAPath){return}}const pathArgument=chainedPath??node.arguments[0];const routePath=pathArgument.type==="Literal"?String(pathArgument.value):sourceCode.getText(pathArgument);const text=sourceCode.getText(node);if(matchesIgnorePattern(routePath,ignorePatterns)){return}if(scansWholeCallText&&matchesIgnorePattern(text,ignorePatterns)){return}const firstMiddlewareIndex=chainedPath===void 0?1:0;const middlewareArgs=methodName==="use"?node.arguments.slice(firstMiddlewareIndex):node.arguments.slice(firstMiddlewareIndex,-1);let hasAuth=false;for(const arg of middlewareArgs){if(isAuthMiddlewareArg(arg,authMiddlewarePatterns)){hasAuth=true;break}if(arg.type==="Identifier"&&isIdentifierFromAuthMiddleware(arg)){hasAuth=true;break}}if(!hasAuth&&node.arguments.length>0){const lastArg=node.arguments[node.arguments.length-1];if(lastArg.type==="ArrowFunctionExpression"||lastArg.type==="FunctionExpression"){if(isInsideAuthMiddleware(lastArg,authMiddlewarePatterns)){hasAuth=true}}}if(!hasAuth){context.report({node:node.callee,messageId:"missingAuthentication",data:{route:`${methodName}(${routePath})`,method:methodName,path:routePath}})}}}}}return{before(){const[options={}]=currentOptions();({allowInTests=false,testFilePattern,authMiddlewarePatterns=DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns=DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns=DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords=ROUTER_NAME_WORDS,additionalRouterNameWords=[]}=options);routerWords=[...routerNameWords,...additionalRouterNameWords];const filename=context.filename;isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));sourceCode=context.sourceCode;scansWholeCallText=context.options[0]?.ignorePatterns!==void 0},CallExpression:checkCallExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingAuthentication=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_AUTH_MIDDLEWARE_PATTERNS=["authenticate","auth","requireAuth","isAuthenticated","verifyToken","checkAuth","ensureAuthenticated","passport.authenticate","jwt","session"];const DEFAULT_PUBLIC_ROUTE_PATTERNS=["login","logout","signin","sign-in","signup","sign-up","register","forgot-password","reset-password","password-reset","verify-email","health","healthz","readyz","livez","alive","liveness","readiness","heartbeat","status","metrics","ping","favicon","webhook","/public/","oauth","callback"];const DEFAULT_ROUTE_HANDLER_PATTERNS=["get","post","put","delete","patch","all","use"];const ROUTER_NAME_WORDS=["app","router","route","server","express","fastify","koa","hapi"];const ROUTER_FACTORY_NAMES=new Set(["express","Router","fastify","polka","restify","connect","Koa"]);const ROUTER_FACTORY_MEMBERS=new Set(["Router","router","Server","server","createServer"]);function routeChainBase(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&current.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if((0,eslint_devkit_2.propertyName)(current.callee)==="route"){return current}current=current.callee.object}return null}function isDefinitelyNotRouter(init){return init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression}function isRouterFactory(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return false}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_NAMES.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_2.propertyName)(callee)!==null){return ROUTER_FACTORY_MEMBERS.has((0,eslint_devkit_2.propertyName)(callee))}return false}function referencedName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.name}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=(0,eslint_devkit_1.propertyName)(node);const objectName=node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.object.name:null;if(property===null){return objectName}return objectName===null?property:`${objectName}.${property}`}return null}function isAuthMiddlewareArg(arg,authPatterns){const target=arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression?arg.callee:arg;const name=referencedName(target);return name!==null&&(0,eslint_devkit_1.nameHasAnyWord)(name,authPatterns)}function isInsideAuthMiddleware(node,authPatterns){let current=node;while(current){if(current.parent&&current.parent.type==="CallExpression"){const callExpr=current.parent;const isArgument=callExpr.arguments.some(arg=>arg===current);if(!isArgument){current=current.parent;continue}const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,authPatterns)){return true}}if(callee.type==="MemberExpression"&&(0,eslint_devkit_2.propertyName)(callee)!==null){const propertyName=(0,eslint_devkit_2.propertyName)(callee).toLowerCase();if(propertyName==="use"||propertyName==="all"){for(const arg of callExpr.arguments){if(isAuthMiddlewareArg(arg,authPatterns)){return true}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}exports.noMissingAuthentication=(0,eslint_devkit_2.createRule)({name:"no-missing-authentication",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-missing-authentication.md",description:"Detects missing authentication checks in route handlers",cwe:"CWE-287",cvss:9.8},messages:{missingAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Authentication",cwe:"CWE-287",description:"Route handler missing authentication check: {{route}}",severity:"CRITICAL",fix:"Add authentication middleware: app.{{method}}('{{path}}', authenticate(), handler)",documentationLink:"https://cwe.mitre.org/data/definitions/287.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing authentication in test files"},authMiddlewarePatterns:{type:"array",items:{type:"string"},default:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,description:"Authentication middleware patterns to recognize"},routeHandlerPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROUTE_HANDLER_PATTERNS,description:"Route handler patterns to check"},ignorePatterns:{type:"array",items:{type:"string"},default:DEFAULT_PUBLIC_ROUTE_PATTERNS,description:"Route paths that are public by definition and need no authentication. Replaces the built-in list; supplying it also widens matching from the route path to the whole registration text."},routerNameWords:{type:"array",items:{type:"string"},default:ROUTER_NAME_WORDS,description:"Object names that denote an HTTP application or router, compared as WHOLE WORDS and never as a substring. Read only when the binding cannot be resolved to a framework factory call. Replaces the built-in list."},additionalRouterNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra router-object name words, on top of `routerNameWords`."},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,authMiddlewarePatterns:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns:DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns:DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords:ROUTER_NAME_WORDS,additionalRouterNameWords:[]}],createOnce(context,currentOptions){let allowInTests;let testFilePattern;let authMiddlewarePatterns;let routeHandlerPatterns;let ignorePatterns;let routerNameWords;let additionalRouterNameWords;let routerWords;let isTestFile;let sourceCode;let scansWholeCallText;function looksLikeRouter(object){const scope=sourceCode.getScope(object);const reference=scope.references.find(ref=>ref.identifier===object);const resolved=reference?.resolved;for(const def of resolved?.defs??[]){const parent=def.name.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){if(isRouterFactory(parent.init)){return true}if(isDefinitelyNotRouter(parent.init)){return false}}}return(0,eslint_devkit_1.nameHasAnyWord)(object.name,routerWords)}function findVariableDeclaration(identifier){const varName=identifier.name;let current=identifier;while(current){if(current.type==="Program"||current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const scopeBody=current.type==="Program"?current.body:current.body.type==="BlockStatement"?current.body.body:[];for(const stmt of scopeBody){if(stmt.type==="VariableDeclaration"){for(const declarator of stmt.declarations){if(declarator.id.type==="Identifier"&&declarator.id.name===varName){return declarator}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return null}function isIdentifierFromAuthMiddleware(identifier){const declarator=findVariableDeclaration(identifier);if(!declarator||!declarator.init){return false}return declarator.init.type==="CallExpression"&&isAuthMiddlewareArg(declarator.init,authMiddlewarePatterns)}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const object=node.callee.object;let chainedPath;if(object.type==="Identifier"){if(!looksLikeRouter(object)){return}}else{const base=routeChainBase(object);const baseObject=base?.callee.type==="MemberExpression"?base.callee.object:void 0;if(!base||baseObject?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!looksLikeRouter(baseObject)){return}chainedPath=base.arguments[0]}const resolvedMethod=(0,eslint_devkit_2.propertyName)(node.callee);if(resolvedMethod!==null){const methodName=resolvedMethod.toLowerCase();if(routeHandlerPatterns.includes(methodName)){if(methodName!=="use"&&chainedPath===void 0&&node.arguments.length<2){return}if(methodName==="use"){const first=node.arguments.at(0);const mountsAPath=first!==void 0&&((0,eslint_devkit_1.staticString)(first)!==null||first.type==="Literal"&&"regex"in first);if(!mountsAPath){return}}const pathArgument=chainedPath??node.arguments[0];const routePath=pathArgument.type==="Literal"?String(pathArgument.value):sourceCode.getText(pathArgument);const text=sourceCode.getText(node);if(matchesIgnorePattern(routePath,ignorePatterns)){return}if(scansWholeCallText&&matchesIgnorePattern(text,ignorePatterns)){return}const firstMiddlewareIndex=chainedPath===void 0?1:0;const middlewareArgs=methodName==="use"?node.arguments:node.arguments.slice(firstMiddlewareIndex,-1);let hasAuth=false;for(const arg of middlewareArgs){if(isAuthMiddlewareArg(arg,authMiddlewarePatterns)){hasAuth=true;break}if(arg.type==="Identifier"&&isIdentifierFromAuthMiddleware(arg)){hasAuth=true;break}}if(!hasAuth){const lastArg=node.arguments[node.arguments.length-1];if(isInsideAuthMiddleware(lastArg,authMiddlewarePatterns)){hasAuth=true}}if(!hasAuth){context.report({node:node.callee,messageId:"missingAuthentication",data:{route:`${methodName}(${routePath})`,method:methodName,path:routePath}})}}}}}return{before(){const[options={}]=currentOptions();({allowInTests=false,testFilePattern,authMiddlewarePatterns=DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns=DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns=DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords=ROUTER_NAME_WORDS,additionalRouterNameWords=[]}=options);routerWords=[...routerNameWords,...additionalRouterNameWords];const filename=context.filename;isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));sourceCode=context.sourceCode;scansWholeCallText=context.options[0]?.ignorePatterns!==void 0},CallExpression:checkCallExpression}}});