eslint-plugin-secure-coding 4.3.0 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/package.json +9 -3
  2. package/src/index.js +1 -1
  3. package/src/rules/detect-non-literal-regexp/index.js +1 -1
  4. package/src/rules/detect-object-injection/index.js +1 -1
  5. package/src/rules/detect-weak-password-validation/index.js +1 -1
  6. package/src/rules/no-bidi-characters/index.js +1 -1
  7. package/src/rules/no-directive-injection/index.js +1 -1
  8. package/src/rules/no-electron-security-issues/index.js +1 -1
  9. package/src/rules/no-format-string-injection/index.js +1 -1
  10. package/src/rules/no-graphql-injection/index.js +1 -1
  11. package/src/rules/no-hardcoded-credentials/index.js +1 -1
  12. package/src/rules/no-improper-sanitization/index.js +1 -1
  13. package/src/rules/no-improper-type-validation/index.js +1 -1
  14. package/src/rules/no-insecure-comparison/index.js +1 -1
  15. package/src/rules/no-ldap-injection/index.js +1 -1
  16. package/src/rules/no-log-injection/index.js +1 -1
  17. package/src/rules/no-missing-authentication/index.js +1 -1
  18. package/src/rules/no-pii-in-logs/index.js +1 -1
  19. package/src/rules/no-privilege-escalation/index.js +1 -1
  20. package/src/rules/no-redos-vulnerable-regex/index.js +0 -0
  21. package/src/rules/no-sensitive-data-exposure/index.js +1 -1
  22. package/src/rules/no-sql-injection/index.js +1 -1
  23. package/src/rules/no-template-injection/index.js +1 -1
  24. package/src/rules/no-unchecked-loop-condition/index.js +1 -1
  25. package/src/rules/no-unlimited-resource-allocation/index.js +1 -1
  26. package/src/rules/no-unsafe-deserialization/index.js +1 -1
  27. package/src/rules/no-unsafe-regex-construction/index.js +1 -1
  28. package/src/rules/no-weak-password-recovery/index.js +1 -1
  29. package/src/rules/no-xpath-injection/index.js +1 -1
  30. package/src/rules/no-xxe-injection/index.js +1 -1
  31. package/src/rules/require-backend-authorization/index.js +1 -1
  32. package/src/rules/require-secure-defaults/index.js +1 -1
  33. package/src/utils/redos-oracle.js +1 -0
  34. package/src/utils/regexp-intrinsic.js +1 -0
  35. package/src/utils/resolve-reference.js +1 -0
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noGraphqlInjection=(0,eslint_devkit_1.createRule)({name:"no-graphql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-graphql-injection.md",description:"Detects GraphQL injection vulnerabilities and DoS attacks",cwe:"CWE-89"},hasSuggestions:true,messages:{graphqlInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"GraphQL Injection",cwe:"CWE-89",description:"GraphQL injection vulnerability detected",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://owasp.org/Top10/2025/A05_2025-Injection/"}),introspectionQuery:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Introspection Query",cwe:"CWE-200",description:"Introspection query may leak schema information",severity:"HIGH",fix:"Disable introspection in production",documentationLink:"https://graphql.org/learn/introspection/"}),complexQueryDos:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Complex Query DoS Risk",cwe:"CWE-400",description:"Complex query may cause DoS",severity:"MEDIUM",fix:"Limit query depth and complexity",documentationLink:"https://graphql.org/learn/queries/"}),unsafeVariableInterpolation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Variable Interpolation",cwe:"CWE-89",description:"Unsafe interpolation in GraphQL query",severity:"HIGH",fix:"Use GraphQL variables instead of string interpolation",documentationLink:"https://graphql.org/learn/queries/#variables"}),missingInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Input Validation",cwe:"CWE-20",description:"GraphQL input not validated",severity:"MEDIUM",fix:"Validate all user inputs before GraphQL execution",documentationLink:"https://graphql.org/learn/validation/"}),useQueryBuilder:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Query Builder",description:"Use GraphQL query builders for safe construction",severity:"LOW",fix:"Use graphql-tag or similar libraries",documentationLink:"https://www.npmjs.com/package/graphql-tag"}),disableIntrospection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Disable Introspection",description:"Disable GraphQL introspection in production",severity:"LOW",fix:"Set introspection: false in GraphQL config",documentationLink:"https://www.apollographql.com/docs/apollo-server/security/introspection/"}),limitQueryDepth:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Limit Query Depth",description:"Limit maximum query depth",severity:"LOW",fix:"Use depth limiting plugins or custom validation",documentationLink:"https://www.npmjs.com/package/graphql-depth-limit"}),strategyQueryBuilder:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Query Builder Strategy",description:"Use typed query builders for compile-time safety",severity:"LOW",fix:"Use GraphQL code generation tools",documentationLink:"https://graphql-code-generator.com/"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate all inputs at GraphQL resolver level",severity:"LOW",fix:"Implement custom scalars and input validation",documentationLink:"https://graphql.org/learn/schema/#scalar-types"}),strategyIntrospection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Introspection Strategy",description:"Control introspection access based on environment",severity:"LOW",fix:"Enable introspection only for development/admin users",documentationLink:"https://www.apollographql.com/docs/apollo-server/security/introspection/"})},schema:[{type:"object",properties:{allowIntrospection:{type:"boolean",default:false,description:"Allow introspection queries"},maxQueryDepth:{type:"number",minimum:1,default:10,description:"Maximum query nesting depth before reporting a DoS risk"},trustedGraphqlLibraries:{type:"array",items:{type:"string"},default:["graphql","apollo-server","graphql-tools","graphql-tag"],description:"GraphQL libraries recognised as query builders"},validationFunctions:{type:"array",items:{type:"string"},default:["validate","sanitize","isValid","assertValid"],description:"Function names that count as query validation"},safeTemplateLiteralCallers:{type:"array",items:{type:"string"},default:[],description:"Additional callers where template literals are never GraphQL. Format: object.method or ClassName."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as GraphQL sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{allowIntrospection:false,maxQueryDepth:10,trustedGraphqlLibraries:["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions:["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowIntrospection=false,maxQueryDepth=10,trustedGraphqlLibraries=["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions=["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isGraphqlRelated=node=>{const callee=node.callee;if(callee.type==="Identifier"){return trustedGraphqlLibraries.some(lib=>callee.name.toLowerCase().includes(lib.toLowerCase()))}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){const objectName=callee.object.name;return trustedGraphqlLibraries.some(lib=>objectName.toLowerCase().includes(lib.toLowerCase()))}return false};const BUILTIN_SAFE_MEMBER_CALLERS=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.trace","logger.log","logger.info","logger.warn","logger.error","logger.debug"]);const BUILTIN_SAFE_CONSTRUCTORS=new Set(["URL","Error","TypeError","RangeError"]);const safeMemberCallers=new Set(BUILTIN_SAFE_MEMBER_CALLERS);const safeConstructors=new Set(BUILTIN_SAFE_CONSTRUCTORS);for(const caller of safeTemplateLiteralCallers){if(caller.includes(".")){safeMemberCallers.add(caller)}else{safeConstructors.add(caller)}}const isInSafeCallerContext=node=>{let current=node.parent;while(current){if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){const key=`${callee.object.name}.${callee.property.name}`;if(safeMemberCallers.has(key))return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){if(current.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&safeConstructors.has(current.callee.name)){return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration){break}current=current.parent}return false};const isWordChar=ch=>{const code=ch.charCodeAt(0);return code>=65&&code<=90||code>=97&&code<=122||code>=48&&code<=57||code===95};const isWhitespace=ch=>ch===" "||ch==="\n"||ch===" "||ch==="\r";const GRAPHQL_OP_KEYWORDS=["query","mutation","subscription"];const GRAPHQL_SCHEMA_KEYWORDS=["type","interface","enum","scalar","input"];const isAtLineStart=(text,idx)=>{for(let i=idx-1;i>=0;i--){const ch=text[i];if(ch==="\n")return true;if(!isWhitespace(ch))return false}return true};const isStandaloneSelectionSet=text=>{const trimmed=text.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))return false;if(/\{\{|\}\}/.test(trimmed))return false;if(/"[^"]*"\s*:/.test(trimmed))return false;let braceDepth=0;for(const ch of trimmed){if(ch==="{"){braceDepth++;if(braceDepth>=2)return true}else if(ch==="}"){braceDepth=Math.max(0,braceDepth-1)}}return false};const findKeywordAtBoundary=(text,keyword,startFrom=0)=>{let pos=startFrom;while(true){const idx=text.indexOf(keyword,pos);if(idx===-1)return-1;const beforeOk=idx===0||!isWordChar(text[idx-1]);const afterIdx=idx+keyword.length;const afterOk=afterIdx>=text.length||!isWordChar(text[afterIdx]);if(beforeOk&&afterOk)return idx;pos=idx+1}};const GRAPHQL_TAG_NAMES=new Set(["gql","graphql"]);const GRAPHQL_SCHEMA_BINDING=/typedef|schema|sdl/i;const hasGraphqlAttribution=node=>{let current=node;while(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){current=current.parent}const parent=current.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){const tag=parent.tag;const tagName=tag.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.name:tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&tag.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.property.name:"";return GRAPHQL_TAG_NAMES.has(tagName.toLowerCase())}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.id.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.key.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isGraphqlRelated(parent)}return false};const isGraphqlTemplate=node=>{const staticText=node.quasis.map(q=>(q.value.cooked??q.value.raw).toLowerCase()).join("");for(const keyword of GRAPHQL_OP_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&staticText[scan]==="("){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 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==="Literal"&&typeof node.value==="string")return node.value;if(node.type==="TemplateLiteral"){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}return""};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};return{TemplateLiteral(node){if(isInSafeCallerContext(node)){return}if(!isGraphqlTemplate(node)){return}if(!allowIntrospection&&templateHasIntrospection(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(node.expressions.length>0){const allExpressionsSafe=node.expressions.every(expr=>isInputValidated(expr)||safetyChecker.isSafe(expr,context));if(!allExpressionsSafe){context.report({node,messageId:"unsafeVariableInterpolation",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"useQueryBuilder",fix:()=>null}]})}}const depth=templateQueryDepth(node);if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"limitQueryDepth",fix:()=>null}]})}},Literal(node){if(typeof node.value!=="string"){return}const queryText=node.value;if(!containsGraphqlText(queryText,hasGraphqlAttribution(node))){return}if(!allowIntrospection&&hasIntrospectionField(queryText)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}let depth=0;let bc=0;for(const ch of queryText){if(ch==="{"){bc++;depth=Math.max(depth,bc)}else if(ch==="}"){bc--}}if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}const fullText=concatenatedStaticText(node);if(!containsGraphqlText(fullText,hasGraphqlAttribution(node))){return}if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"graphqlInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use GraphQL variables or query builders instead of string concatenation"}})},CallExpression(node){if(!isGraphqlRelated(node)){return}const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&["execute","executeQuery","query","mutate","subscribe"].includes(callee.property.name)){for(const arg of node.arguments){if(arg.type==="Identifier"&&!isInputValidated(arg)){if(safetyChecker.isSafe(arg,context)){continue}context.report({node:arg,messageId:"missingInputValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noGraphqlInjection=(0,eslint_devkit_1.createRule)({name:"no-graphql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-graphql-injection.md",description:"Detects GraphQL injection vulnerabilities and DoS attacks",cwe:"CWE-89"},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}],create(context){const options=context.options[0]||{};const{allowIntrospection=false,maxQueryDepth=10,trustedGraphqlLibraries=["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions=["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isGraphqlRelated=node=>{const callee=node.callee;if(callee.type==="Identifier"){return trustedGraphqlLibraries.some(lib=>callee.name.toLowerCase().includes(lib.toLowerCase()))}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){const objectName=callee.object.name;return trustedGraphqlLibraries.some(lib=>objectName.toLowerCase().includes(lib.toLowerCase()))}return false};const BUILTIN_SAFE_MEMBER_CALLERS=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.trace","logger.log","logger.info","logger.warn","logger.error","logger.debug"]);const BUILTIN_SAFE_CONSTRUCTORS=new Set(["URL","Error","TypeError","RangeError"]);const safeMemberCallers=new Set(BUILTIN_SAFE_MEMBER_CALLERS);const safeConstructors=new Set(BUILTIN_SAFE_CONSTRUCTORS);for(const caller of safeTemplateLiteralCallers){if(caller.includes(".")){safeMemberCallers.add(caller)}else{safeConstructors.add(caller)}}const isInSafeCallerContext=node=>{let current=node.parent;while(current){if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.property.type==="Identifier"){const key=`${callee.object.name}.${callee.property.name}`;if(safeMemberCallers.has(key))return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){if(current.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&safeConstructors.has(current.callee.name)){return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration){break}current=current.parent}return false};const isWordChar=ch=>{const code=ch.charCodeAt(0);return code>=65&&code<=90||code>=97&&code<=122||code>=48&&code<=57||code===95};const isWhitespace=ch=>ch===" "||ch==="\n"||ch===" "||ch==="\r";const GRAPHQL_OP_KEYWORDS=["query","mutation","subscription"];const GRAPHQL_SCHEMA_KEYWORDS=["type","interface","enum","scalar","input"];const isAtLineStart=(text,idx)=>{for(let i=idx-1;i>=0;i--){const ch=text[i];if(ch==="\n")return true;if(!isWhitespace(ch))return false}return true};const isStandaloneSelectionSet=text=>{const trimmed=text.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))return false;if(/\{\{|\}\}/.test(trimmed))return false;if(/"[^"]*"\s*:/.test(trimmed))return false;let braceDepth=0;for(const ch of trimmed){if(ch==="{"){braceDepth++;if(braceDepth>=2)return true}else if(ch==="}"){braceDepth=Math.max(0,braceDepth-1)}}return false};const findKeywordAtBoundary=(text,keyword,startFrom=0)=>{let pos=startFrom;while(true){const idx=text.indexOf(keyword,pos);if(idx===-1)return-1;const beforeOk=idx===0||!isWordChar(text[idx-1]);const afterIdx=idx+keyword.length;const afterOk=afterIdx>=text.length||!isWordChar(text[afterIdx]);if(beforeOk&&afterOk)return idx;pos=idx+1}};const GRAPHQL_TAG_NAMES=new Set(["gql","graphql"]);const GRAPHQL_SCHEMA_BINDING=/typedef|schema|sdl/i;const hasGraphqlAttribution=node=>{let current=node;while(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){current=current.parent}const parent=current.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){const tag=parent.tag;const tagName=tag.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.name:tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&tag.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.property.name:"";return GRAPHQL_TAG_NAMES.has(tagName.toLowerCase())}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.id.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.key.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isGraphqlRelated(parent)}return false};const isGraphqlTemplate=node=>{const staticText=node.quasis.map(q=>(q.value.cooked??q.value.raw).toLowerCase()).join("");for(const keyword of GRAPHQL_OP_KEYWORDS){let pos=0;while(pos<staticText.length){const idx=findKeywordAtBoundary(staticText,keyword,pos);if(idx===-1)break;pos=idx+1;if(!isAtLineStart(staticText,idx))continue;let scan=idx+keyword.length;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;while(scan<staticText.length&&isWordChar(staticText[scan]))scan++;while(scan<staticText.length&&isWhitespace(staticText[scan]))scan++;if(scan<staticText.length&&staticText[scan]==="("){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 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==="Literal"&&typeof node.value==="string")return node.value;if(node.type==="TemplateLiteral"){return node.quasis.map(q=>q.value.cooked??q.value.raw).join("")}return""};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};return{TemplateLiteral(node){if(isInSafeCallerContext(node)){return}if(!isGraphqlTemplate(node)){return}if(!allowIntrospection&&templateHasIntrospection(node)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(node.expressions.length>0){const allExpressionsSafe=node.expressions.every(expr=>isInputValidated(expr)||safetyChecker.isSafe(expr,context));if(!allExpressionsSafe){context.report({node,messageId:"unsafeVariableInterpolation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}const depth=templateQueryDepth(node);if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},Literal(node){if(typeof node.value!=="string"){return}const queryText=node.value;if(!containsGraphqlText(queryText,hasGraphqlAttribution(node))){return}if(!allowIntrospection&&hasIntrospectionField(queryText)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}let depth=0;let bc=0;for(const ch of queryText){if(ch==="{"){bc++;depth=Math.max(depth,bc)}else if(ch==="}"){bc--}}if(depth>maxQueryDepth){context.report({node,messageId:"complexQueryDos",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},BinaryExpression(node){if(node.operator!=="+"){return}const fullText=concatenatedStaticText(node);if(!containsGraphqlText(fullText,hasGraphqlAttribution(node))){return}if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"graphqlInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use GraphQL variables or query builders instead of string concatenation"}})},CallExpression(node){if(!isGraphqlRelated(node)){return}const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&["execute","executeQuery","query","mutate","subscribe"].includes(callee.property.name)){for(const arg of node.arguments){if(arg.type==="Identifier"&&!isInputValidated(arg)){if(safetyChecker.isSafe(arg,context)){continue}context.report({node:arg,messageId:"missingInputValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;exports.isNaturalWordString=isNaturalWordString;exports.looksRandom=looksRandom;exports.isSecretShaped=isSecretShaped;exports.isPlaceholderValue=isPlaceholderValue;exports.isPublishableKeyValue=isPublishableKeyValue;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const CREDENTIAL_PATTERNS={apiKey:/^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,jwtToken:/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,oauthToken:/^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,awsAccessKey:/^AKIA[0-9A-Z]{16}$/,databaseString:/^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,commonPassword:/^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,secretKey:/^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/};const CREDENTIAL_VARIABLE_NAMES=new Set(["apikey","api_key","apiKey","secret","secretkey","secret_key","secretKey","clientsecret","client_secret","clientSecret","token","authtoken","auth_token","authToken","accesstoken","access_token","accessToken","refreshtoken","refresh_token","refreshToken","idtoken","id_token","idToken","password","passwd","pass","pwd","privatekey","private_key","privateKey","credentials","creds","authorization","auth","connectionstring","connection_string","connectionString","connectionuri","connectionURI","dburl","db_url","dbUrl","databaseurl","database_url","databaseUrl"]);const WORD_SEPARATORS=new Set(["_","-","."," "]);function shannonEntropy(value){const freq=new Map;for(const ch of value)freq.set(ch,(freq.get(ch)??0)+1);let entropy=0;for(const count of freq.values()){const p=count/value.length;entropy-=p*Math.log2(p)}return entropy}function charClasses(value){const classes={lower:false,upper:false,digit:false,symbol:false};for(const ch of value){if(WORD_SEPARATORS.has(ch))continue;if(ch>="a"&&ch<="z")classes.lower=true;else if(ch>="A"&&ch<="Z")classes.upper=true;else if(ch>="0"&&ch<="9")classes.digit=true;else classes.symbol=true}return classes}function classCount(classes){return Number(classes.lower)+Number(classes.upper)+Number(classes.digit)+Number(classes.symbol)}function isPronounceable(token){const lower=token.toLowerCase();if(!/[aeiouy]/.test(lower))return false;if(/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))return false;return true}function isNaturalWordString(value){if(!/^[A-Za-z][A-Za-z0-9_\-. ]*$/.test(value))return false;const digits=value.replace(/[^0-9]/g,"").length;if(digits>0&&(digits/value.length>.2||/[0-9]{4,}/.test(value)))return false;const tokens=value.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[^A-Za-z]+/).filter(Boolean);const meaningful=tokens.filter(t=>t.length>=3);if(meaningful.length===0)return false;return meaningful.every(isPronounceable)}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;if(isNaturalWordString(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const PLACEHOLDER_WORDS=new Set(["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"]);function isPlaceholderValue(value){const trimmed=value.trim();if(trimmed.length===0)return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>PLACEHOLDER_WORDS.has(token))}function isPublishableKeyValue(value){if(/^pk_(?:live|test)_[A-Za-z0-9_-]{8,}$/.test(value))return true;if(/^phc_[A-Za-z0-9]{20,}$/.test(value))return true;if(/^https?:\/\/[A-Za-z0-9]+@[A-Za-z0-9.-]+(?::\d+)?\/\d+$/.test(value)){return true}return false}const SECRET_SIDE_VALUE=/^(?:sk|rk)_(?:live|test)_|^sk-[A-Za-z0-9]|^gh[pousr]_|^ph[xs]_|^sntry[su]_|^xox[baprs]-|^AKIA[0-9A-Z]{16}$|^ey[A-Za-z0-9_-]+\.ey|-----BEGIN|^(?:mysql|postgres|mongodb|redis):\/\//;const SECRET_SIDE_SLOT=/secret|private|signing|password|passwd|serviceaccount|serverkey|adminkey|masterkey/;const PUBLISHABLE_VENDORS=[{vendor:"Bugsnag",packages:["bugsnag","bugsnag-js","bugsnag-build-reporter","bugsnag-sourcemaps"],scopes:["@bugsnag"],named:/bugsnag/,slots:/^(?:bugsnag)?(?:notifier)?(?:api)?key$/},{vendor:"Sentry",scopes:["@sentry"],named:/sentry/,slots:/^(?:sentry)?dsn$/},{vendor:"PostHog",packages:["posthog-js","posthog-node"],named:/posthog/,slots:/^(?:posthog)?(?:project)?(?:api)?key$/},{vendor:"Segment",packages:["analytics-node"],scopes:["@segment"],named:/segment/,slots:/^(?:segment)?write(?:key|token)$/},{vendor:"Amplitude",packages:["amplitude-js"],scopes:["@amplitude"],named:/amplitude/,slots:/^(?:amplitude)?(?:api)?key$/},{vendor:"Mixpanel",packages:["mixpanel","mixpanel-browser"],named:/mixpanel/,slots:/^(?:mixpanel)?(?:project)?token$/},{vendor:"Firebase",packages:["firebase"],scopes:["@firebase"],named:/firebase/,slots:/^(?:firebase)?(?:web)?apikey$/}];const VENDOR_PROBES=PUBLISHABLE_VENDORS.map(entry=>({entry,loadsSdk:(0,eslint_devkit_2.createModuleEvidence)({packages:entry.packages,scopes:entry.scopes})}));function slotNameOf(parent){if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){return parent.id.name.toLowerCase()}if(parent.type==="Property"){const key=parent.key;if(key.type==="Identifier")return key.name.toLowerCase();return String(key.value).toLowerCase()}if(parent.type==="AssignmentExpression"){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){return left.property.name.toLowerCase()}}return""}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch(error){continue}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(value.length>=32&&CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),strategyEnv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Environment Variable Strategy",description:"Move credentials to environment variables",severity:"MEDIUM",fix:"Store credentials in environment variables (process.env)",documentationLink:"https://12factor.net/config"}),strategyConfig:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Configuration File Strategy",description:"Store credentials in encrypted configuration files",severity:"MEDIUM",fix:"Use encrypted configuration files with proper access controls",documentationLink:"https://owasp.org/www-project-cheat-sheets/cheatsheets/Configuration_Management_Cheat_Sheet.html"}),strategyVault:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Secret Vault Strategy",cwe:"CWE-798",description:"Use dedicated secret management system",severity:"HIGH",fix:"Implement HashiCorp Vault, AWS Secrets Manager, or similar secret vault",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),strategyAuto:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.DEVELOPMENT,issueName:"Context-Aware Strategy",description:"Apply context-aware credential management",severity:"MEDIUM",fix:"Choose strategy based on deployment environment and security requirements",documentationLink:"https://owasp.org/www-project-cheat-sheets/cheatsheets/Secrets_Management_Cheat_Sheet.html"})},schema:[{type:"object",properties:{ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:true,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},strategy:{type:"string",enum:["env","config","vault","auto"],default:"auto",description:"Strategy for fixing hardcoded credentials (auto = smart detection)"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:true,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],strategy:"auto",allowPlaceholders:true}],create(context){const options=context.options[0]||{};const{ignorePatterns=[],allowInTests=true,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true}=options;const filename=context.filename;const isTestFile=allowInTests&&(filename.includes(".test.")||filename.includes(".spec.")||filename.includes(".fixture.")||filename.includes(".mock.")||filename.includes("__tests__")||filename.includes("__mocks__")||filename.includes("/test/")||filename.includes("/tests/")||filename.includes("/fixtures/")||filename.includes("/mocks/"));const compiledIgnorePatterns=ignorePatterns.map(pattern=>new RegExp(pattern));const detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};const LABEL_CONTEXT_NAMES=new Set(["type","name","id","placeholder","label","title","role","autocomplete","autoFocus","autocapitalize","inputmode","aria-label","aria-labelledby","aria-describedby","fieldName","fieldType","fieldLabel","inputType","inputName","displayName","columnName","paramName","i18nKey","translationKey","messageKey"]);function isLabelContext(node,parent){if(!parent)return false;if(parent.type==="ObjectExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const n=parent.id.name.toLowerCase();if(LABEL_CONTEXT_NAMES.has(n)||n==="labels"||n.endsWith("label")||n.endsWith("labels")||n.endsWith("name")||n.endsWith("placeholder"))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(LABEL_CONTEXT_NAMES.has(left.property.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;const keyText=key.type==="Identifier"?key.name:key.type==="Literal"&&typeof key.value==="string"?key.value:null;if(keyText!==null&&node.type==="Literal"&&typeof node.value==="string"){const keyTokens=keyText.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);if(keyTokens.includes(node.value.toUpperCase()))return true}if(key.type==="Identifier"&&LABEL_CONTEXT_NAMES.has(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(LABEL_CONTEXT_NAMES.has(key.value))return true}const obj=parent.parent;if(obj?.type==="ObjectExpression"){const grand=obj.parent;if(grand)return isLabelContext(node,grand)}}if(parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"){const callee=parent.callee;const methodName=callee.property.name;if(methodName==="setAttribute"||methodName==="getAttribute"){const args=parent.arguments;if(args[1]===node)return true}}if(parent.type==="JSXAttribute")return true;return false}function inferCredentialTypeFromContext(parent){const name=slotNameOf(parent);if(/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))return"apikey";return"other"}function isCredentialContext(node,parent){if(!parent)return false;const matches=name=>{const lower=name.toLowerCase();if(lower==="key"||lower==="keys"){return node.type==="Literal"&&typeof node.value==="string"&&looksRandom(node.value)}const singular=lower.endsWith("s")?lower.slice(0,-1):lower;if(CREDENTIAL_VARIABLE_NAMES.has(lower)||CREDENTIAL_VARIABLE_NAMES.has(singular))return true;return lower.endsWith("apikey")||lower.endsWith("apikeys")||lower.endsWith("secret")||lower.endsWith("secrets")||lower.endsWith("token")||lower.endsWith("tokens")||lower.endsWith("password")||lower.endsWith("passwords")||lower.endsWith("passwd")||lower.endsWith("credential")||lower.endsWith("credentials")};if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isCredentialContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){if(matches(parent.id.name))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(matches(left.property.name))return true}if(left.type==="Identifier"){if(matches(left.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&matches(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(matches(key.value))return true}}return false}let loadedVendors=null;function vendorsInFile(){if(loadedVendors===null){const found=new Set;for(const{entry,loadsSdk}of VENDOR_PROBES){if(loadsSdk(context.sourceCode.ast))found.add(entry.vendor)}loadedVendors=found}return loadedVendors}function isPublishableKey(value,parent){if(SECRET_SIDE_VALUE.test(value))return false;if(isPublishableKeyValue(value))return true;const slot=slotNameOf(parent);if(slot===""||SECRET_SIDE_SLOT.test(slot))return false;for(const{entry}of VENDOR_PROBES){if(!entry.named.test(slot)&&!vendorsInFile().has(entry.vendor)){continue}if(entry.slots.test(slot))return true}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator==="||"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&left.object.property.type==="Identifier"&&left.object.property.name==="env"){return}}if(isLabelContext(node,parent)){return}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(node,parent)){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(node,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}if(isPublishableKey(value,parent)){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",data:{credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{isCredential,type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",data:{credentialType:type},fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){if(quasi.value.raw){const{isCredential,type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;exports.isNaturalWordString=isNaturalWordString;exports.looksRandom=looksRandom;exports.isSecretShaped=isSecretShaped;exports.isPlaceholderValue=isPlaceholderValue;exports.isPublishableKeyValue=isPublishableKeyValue;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const CREDENTIAL_PATTERNS={apiKey:/^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,jwtToken:/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,oauthToken:/^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,awsAccessKey:/^AKIA[0-9A-Z]{16}$/,databaseString:/^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,commonPassword:/^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,secretKey:/^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/};const CREDENTIAL_VARIABLE_NAMES=new Set(["apikey","api_key","apiKey","secret","secretkey","secret_key","secretKey","clientsecret","client_secret","clientSecret","token","authtoken","auth_token","authToken","accesstoken","access_token","accessToken","refreshtoken","refresh_token","refreshToken","idtoken","id_token","idToken","password","passwd","pass","pwd","privatekey","private_key","privateKey","credentials","creds","authorization","auth","connectionstring","connection_string","connectionString","connectionuri","connectionURI","dburl","db_url","dbUrl","databaseurl","database_url","databaseUrl"]);const WORD_SEPARATORS=new Set(["_","-","."," "]);function shannonEntropy(value){const freq=new Map;for(const ch of value)freq.set(ch,(freq.get(ch)??0)+1);let entropy=0;for(const count of freq.values()){const p=count/value.length;entropy-=p*Math.log2(p)}return entropy}function charClasses(value){const classes={lower:false,upper:false,digit:false,symbol:false};for(const ch of value){if(WORD_SEPARATORS.has(ch))continue;if(ch>="a"&&ch<="z")classes.lower=true;else if(ch>="A"&&ch<="Z")classes.upper=true;else if(ch>="0"&&ch<="9")classes.digit=true;else classes.symbol=true}return classes}function classCount(classes){return Number(classes.lower)+Number(classes.upper)+Number(classes.digit)+Number(classes.symbol)}function isPronounceable(token){const lower=token.toLowerCase();if(!/[aeiouy]/.test(lower))return false;if(/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))return false;return true}function isNaturalWordString(value){if(!/^[A-Za-z][A-Za-z0-9_\-. ]*$/.test(value))return false;const digits=value.replace(/[^0-9]/g,"").length;if(digits>0&&(digits/value.length>.2||/[0-9]{4,}/.test(value)))return false;const tokens=value.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[^A-Za-z]+/).filter(Boolean);const meaningful=tokens.filter(t=>t.length>=3);if(meaningful.length===0)return false;return meaningful.every(isPronounceable)}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;if(isNaturalWordString(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const DEFAULT_PLACEHOLDER_WORDS=["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"];function isPlaceholderValue(value,words){const trimmed=value.trim();if(trimmed.length===0)return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>words.has(token))}function isPublishableKeyValue(value){if(/^pk_(?:live|test)_[A-Za-z0-9_-]{8,}$/.test(value))return true;if(/^phc_[A-Za-z0-9]{20,}$/.test(value))return true;if(/^https?:\/\/[A-Za-z0-9]+@[A-Za-z0-9.-]+(?::\d+)?\/\d+$/.test(value)){return true}return false}const SECRET_SIDE_VALUE=/^(?:sk|rk)_(?:live|test)_|^sk-[A-Za-z0-9]|^gh[pousr]_|^ph[xs]_|^sntry[su]_|^xox[baprs]-|^AKIA[0-9A-Z]{16}$|^ey[A-Za-z0-9_-]+\.ey|-----BEGIN|^(?:mysql|postgres|mongodb|redis):\/\//;const SECRET_SIDE_SLOT=/secret|private|signing|password|passwd|serviceaccount|serverkey|adminkey|masterkey/;const PUBLISHABLE_VENDORS=[{vendor:"Bugsnag",packages:["bugsnag","bugsnag-js","bugsnag-build-reporter","bugsnag-sourcemaps"],scopes:["@bugsnag"],named:/bugsnag/,slots:/^(?:bugsnag)?(?:notifier)?(?:api)?key$/},{vendor:"Sentry",scopes:["@sentry"],named:/sentry/,slots:/^(?:sentry)?dsn$/},{vendor:"PostHog",packages:["posthog-js","posthog-node"],named:/posthog/,slots:/^(?:posthog)?(?:project)?(?:api)?key$/},{vendor:"Segment",packages:["analytics-node"],scopes:["@segment"],named:/segment/,slots:/^(?:segment)?write(?:key|token)$/},{vendor:"Amplitude",packages:["amplitude-js"],scopes:["@amplitude"],named:/amplitude/,slots:/^(?:amplitude)?(?:api)?key$/},{vendor:"Mixpanel",packages:["mixpanel","mixpanel-browser"],named:/mixpanel/,slots:/^(?:mixpanel)?(?:project)?token$/},{vendor:"Firebase",packages:["firebase"],scopes:["@firebase"],named:/firebase/,slots:/^(?:firebase)?(?:web)?apikey$/}];const VENDOR_PROBES=PUBLISHABLE_VENDORS.map(entry=>({entry,loadsSdk:(0,eslint_devkit_2.createModuleEvidence)({packages:entry.packages,scopes:entry.scopes})}));function slotNameOf(parent){if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){return parent.id.name.toLowerCase()}if(parent.type==="Property"){const key=parent.key;if(key.type==="Identifier")return key.name.toLowerCase();return String(key.value).toLowerCase()}if(parent.type==="AssignmentExpression"){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){return left.property.name.toLowerCase()}}return""}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch(error){continue}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(value.length>=32&&CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"})},schema:[{type:"object",properties:{ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:true,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"},placeholderWords:{type:"array",items:{type:"string"},default:DEFAULT_PLACEHOLDER_WORDS,description:"Words that mark a value as a self-evident stand-in rather than a secret, matched as a WHOLE token inside the value and never as a substring. Replaces the built-in list. Read only when `allowPlaceholders` is true."},additionalPlaceholderWords:{type:"array",items:{type:"string"},default:[],description:"Extra placeholder words, on top of `placeholderWords`."}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:true,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],allowPlaceholders:true,placeholderWords:DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords:[]}],create(context){const options=context.options[0]||{};const{ignorePatterns=[],allowInTests=true,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true,placeholderWords=DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords=[]}=options;const placeholderWordSet=new Set([...placeholderWords,...additionalPlaceholderWords]);const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_2.isTestFilePath)(filename);const compiledIgnorePatterns=(0,eslint_devkit_1.compileUserPatterns)(ignorePatterns);const detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};const LABEL_CONTEXT_NAMES=new Set(["type","name","id","placeholder","label","title","role","autocomplete","autoFocus","autocapitalize","inputmode","aria-label","aria-labelledby","aria-describedby","fieldName","fieldType","fieldLabel","inputType","inputName","displayName","columnName","paramName","i18nKey","translationKey","messageKey"]);function isLabelContext(node,parent){if(!parent)return false;if(parent.type==="ObjectExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const n=parent.id.name.toLowerCase();if(LABEL_CONTEXT_NAMES.has(n)||n==="labels"||n.endsWith("label")||n.endsWith("labels")||n.endsWith("name")||n.endsWith("placeholder"))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(LABEL_CONTEXT_NAMES.has(left.property.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;const keyText=key.type==="Identifier"?key.name:key.type==="Literal"&&typeof key.value==="string"?key.value:null;if(keyText!==null&&node.type==="Literal"&&typeof node.value==="string"){const keyTokens=keyText.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);if(keyTokens.includes(node.value.toUpperCase()))return true}if(key.type==="Identifier"&&LABEL_CONTEXT_NAMES.has(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(LABEL_CONTEXT_NAMES.has(key.value))return true}const obj=parent.parent;if(obj?.type==="ObjectExpression"){const grand=obj.parent;if(grand)return isLabelContext(node,grand)}}if(parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"){const callee=parent.callee;const methodName=callee.property.name;if(methodName==="setAttribute"||methodName==="getAttribute"){const args=parent.arguments;if(args[1]===node)return true}}if(parent.type==="JSXAttribute")return true;return false}function inferCredentialTypeFromContext(parent){const name=slotNameOf(parent);if(/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))return"apikey";return"other"}function isCredentialContext(node,parent){if(!parent)return false;const matches=name=>{const lower=name.toLowerCase();if(lower==="key"||lower==="keys"){return node.type==="Literal"&&typeof node.value==="string"&&looksRandom(node.value)}const singular=lower.endsWith("s")?lower.slice(0,-1):lower;if(CREDENTIAL_VARIABLE_NAMES.has(lower)||CREDENTIAL_VARIABLE_NAMES.has(singular))return true;return lower.endsWith("apikey")||lower.endsWith("apikeys")||lower.endsWith("secret")||lower.endsWith("secrets")||lower.endsWith("token")||lower.endsWith("tokens")||lower.endsWith("password")||lower.endsWith("passwords")||lower.endsWith("passwd")||lower.endsWith("credential")||lower.endsWith("credentials")};if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isCredentialContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){if(matches(parent.id.name))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(matches(left.property.name))return true}if(left.type==="Identifier"){if(matches(left.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&matches(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(matches(key.value))return true}}return false}let loadedVendors=null;function vendorsInFile(){if(loadedVendors===null){const found=new Set;for(const{entry,loadsSdk}of VENDOR_PROBES){if(loadsSdk(context.sourceCode.ast))found.add(entry.vendor)}loadedVendors=found}return loadedVendors}function isPublishableKey(value,parent){if(SECRET_SIDE_VALUE.test(value))return false;if(isPublishableKeyValue(value))return true;const slot=slotNameOf(parent);if(slot===""||SECRET_SIDE_SLOT.test(slot))return false;for(const{entry}of VENDOR_PROBES){if(!entry.named.test(slot)&&!vendorsInFile().has(entry.vendor)){continue}if(entry.slots.test(slot))return true}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator==="||"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&left.object.property.type==="Identifier"&&left.object.property.name==="env"){return}}if(isLabelContext(node,parent)){return}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(node,parent)){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value,placeholderWordSet);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(node,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}if(isPublishableKey(value,parent)){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",data:{credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{isCredential,type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",data:{credentialType:type},fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){if(quasi.value.raw){const{isCredential,type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}}});
@@ -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:{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:{improperSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Improper Sanitization",cwe:"CWE-116",description:"User input sanitization is insufficient or incorrect",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/116.html"}),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:"Unsafe Replace Sanitization",cwe:"CWE-116",description:"Simple replace() calls are insufficient for sanitization",severity:"MEDIUM",fix:"Use comprehensive sanitization libraries",documentationLink:"https://cwe.mitre.org/data/definitions/116.html"}),missingContextEncoding:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Context Encoding",cwe:"CWE-116",description:"Output encoding missing for specific context",severity:"MEDIUM",fix:"Encode output according to usage context (HTML, URL, SQL, etc.)",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"}),sqlInjectionSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"SQL Injection Sanitization",cwe:"CWE-89",description:"SQL input sanitization is insufficient",severity:"HIGH",fix:"Use parameterized queries instead of sanitization",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"}),commandInjectionSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Command Injection Sanitization",cwe:"CWE-78",description:"Command input sanitization is insufficient",severity:"CRITICAL",fix:"Avoid shell commands with user input, use safe APIs",documentationLink:"https://owasp.org/www-community/attacks/Command_Injection"}),useProperSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Proper Sanitization",description:"Use proper sanitization methods for each context",severity:"LOW",fix:"HTML: DOMPurify, URL: encodeURIComponent, SQL: parameterized queries",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html"}),validateSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate Sanitization",description:"Validate that sanitization is effective",severity:"LOW",fix:"Test sanitization with malicious inputs",documentationLink:"https://cwe.mitre.org/data/definitions/116.html"}),implementContextAware:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Implement Context Aware Sanitization",description:"Use different sanitization for different contexts",severity:"LOW",fix:`HTML context: escape <>&"' , URL context: encodeURIComponent`,documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html"}),strategyDefenseInDepth:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Defense in Depth Strategy",description:"Implement multiple layers of input validation",severity:"LOW",fix:"Validate input, sanitize output, use CSP, implement rate limiting",documentationLink:"https://owasp.org/www-community/controls/Defense_in_depth"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate input at multiple layers",severity:"LOW",fix:"Client-side, server-side, and database-level validation",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html"}),strategyOutputEncoding:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Output Encoding Strategy",description:"Encode output according to context",severity:"LOW",fix:"Use appropriate encoding for HTML, JavaScript, CSS, URL contexts",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.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"},trustedLibraries:{type:"array",items:{type:"string"},default:["DOMPurify","he","validator","express-validator"],description:"Libraries whose sanitizers are trusted"},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"],trustedLibraries:["DOMPurify","he","validator","express-validator"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{safeSanitizers=["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],dangerousChars=["<",">",'"',"'","&"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isSafeSanitizer=callText=>{return safeSanitizers.some(sanitizer=>callText.includes(sanitizer))};const isReplaceCall=node=>node?.type==="CallExpression"&&node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"&&node.callee.property.name==="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 ENTITY=/&(?:amp|lt|gt|quot|apos|#x[0-9a-f]+|#\d+);/i;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{CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="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==="MemberExpression"&&left.property.type==="Identifier"){const propertyName=left.property.name.toLowerCase();if(["innerhtml","outerhtml","innertext","textcontent"].includes(propertyName)){const encodingContext=needsContextEncoding(node);if(encodingContext==="html"&&propertyName==="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(left.property.type==="Identifier"&&["innerHTML","outerHTML"].includes(left.property.name)){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"&&left.property.type==="Identifier"&&["innerHTML","outerHTML"].includes(left.property.name)){isInDangerousContext=true;break}}else if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&["write","send","json"].includes(callee.property.name)){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==="MemberExpression"&&parent.object===current2&&parent.property.type==="Identifier"&&parent.property.name==="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")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==="MemberExpression"&&!expr.computed&&expr.property.type==="Identifier"&&expr.property.name==="length"){return true}if(expr.type==="CallExpression"){const callee=expr.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="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:{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:"Unsafe Replace Sanitization",cwe:"CWE-116",description:"Simple replace() calls are insufficient for sanitization",severity:"MEDIUM",fix:"Use comprehensive sanitization libraries",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}],create(context){const options=context.options[0]||{};const{safeSanitizers=["DOMPurify.sanitize","he.encode","encodeURIComponent","encodeURI","escape"],dangerousChars=["<",">",'"',"'","&"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isSafeSanitizer=callText=>{return safeSanitizers.some(sanitizer=>callText.includes(sanitizer))};const isReplaceCall=node=>node?.type==="CallExpression"&&node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"&&node.callee.property.name==="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 ENTITY=/&(?:amp|lt|gt|quot|apos|#x[0-9a-f]+|#\d+);/i;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{CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="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==="MemberExpression"&&left.property.type==="Identifier"){const propertyName=left.property.name.toLowerCase();if(["innerhtml","outerhtml","innertext","textcontent"].includes(propertyName)){const encodingContext=needsContextEncoding(node);if(encodingContext==="html"&&propertyName==="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(left.property.type==="Identifier"&&["innerHTML","outerHTML"].includes(left.property.name)){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"&&left.property.type==="Identifier"&&["innerHTML","outerHTML"].includes(left.property.name)){isInDangerousContext=true;break}}else if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&["write","send","json"].includes(callee.property.name)){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==="MemberExpression"&&parent.object===current2&&parent.property.type==="Identifier"&&parent.property.name==="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")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==="MemberExpression"&&!expr.computed&&expr.property.type==="Identifier"&&expr.property.name==="length"){return true}if(expr.type==="CallExpression"){const callee=expr.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="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 +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");exports.noImproperTypeValidation=(0,eslint_devkit_1.createRule)({name:"no-improper-type-validation",meta:{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"},hasSuggestions:true,messages:{improperTypeValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Improper Type Validation",cwe:"CWE-1287",description:"Type validation may be bypassed or incomplete",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/1287.html"}),unsafeTypeofCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe typeof Check",cwe:"CWE-1287",description:"typeof check misses null values",severity:"MEDIUM",fix:'Use value != null && typeof value === "object"',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",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",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"}),missingNullCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Missing Null Check",cwe:"CWE-1287",description:"Type check doesn't handle null values",severity:"MEDIUM",fix:"Check for both null and undefined",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof"}),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",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor"}),incompleteTypeValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Incomplete Type Validation",cwe:"CWE-1287",description:"Type validation is incomplete",severity:"LOW",fix:"Use comprehensive type checking",documentationLink:"https://cwe.mitre.org/data/definitions/1287.html"}),useTypeofCorrectly:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use typeof Correctly",description:"Use typeof with null checks for objects",severity:"LOW",fix:'if (value != null && typeof value === "object")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof"}),useProperTypeGuards:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Proper Type Guards",description:"Use proper type guard functions",severity:"LOW",fix:"Array.isArray(), Number.isNaN(), etc.",documentationLink:"https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types"}),validateUserInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate User Input",description:"Validate user input before processing",severity:"LOW",fix:"Use schema validation libraries",documentationLink:"https://joi.dev/"}),strategyTypeGuards:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Type Guards Strategy",description:"Use type guards for runtime type checking",severity:"LOW",fix:"Implement custom type guard functions",documentationLink:"https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types"}),strategySchemaValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Schema Validation Strategy",description:"Use schema validation for complex inputs",severity:"LOW",fix:"Use Joi, Yup, or Zod for input validation",documentationLink:"https://joi.dev/"}),strategyDefensiveProgramming:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Defensive Programming Strategy",description:"Use defensive programming techniques",severity:"LOW",fix:"Check types and handle edge cases explicitly",documentationLink:"https://en.wikipedia.org/wiki/Defensive_programming"})},schema:[{type:"object",properties:{userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},safeTypeCheckFunctions:{type:"array",items:{type:"string"},default:["isArray","isString","isNumber","isObject","validateType","checkType"],description:"Function names that count as a type check"},allowInstanceofSameRealm:{type:"boolean",default:true,description:"Allow instanceof for same-realm objects"},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}]},defaultOptions:[{userInputVariables:["req","request","body","query","params","input","data","userInput"],safeTypeCheckFunctions:["isArray","isString","isNumber","isObject","validateType","checkType"],allowInstanceofSameRealm:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{userInputVariables=["req","request","body","query","params","input","data","userInput"],allowInstanceofSameRealm=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isUserInput=varName=>{return userInputVariables.some(input=>varName.includes(input))};const isUnsafeTypeof=node=>{if(node.operator!=="==="&&node.operator!=="!=="){return false}const left=node.left;const right=node.right;if(left.type==="UnaryExpression"&&left.operator==="typeof"&&right.type==="Literal"&&right.value==="object"){let varName="";if(left.argument.type==="Identifier"){varName=left.argument.name}if(varName){let current=node.parent;let child=node;while(current){if(current.type==="LogicalExpression"&&current.operator==="&&"){if(current.right===child){const leftText=sourceCode.getText(current.left);if(leftText.includes(`${varName} !== null`)||leftText.includes(`${varName} != null`)){return false}}}if(current.type.includes("Statement")||current.type.includes("Declaration")){break}child=current;current=current.parent}}return true}return false};const isUnsafeInstanceof=node=>{if(node.operator!=="instanceof"){return false}if(!allowInstanceofSameRealm){return true}return false};const isLooseEqualityTypeCheck=node=>{if(node.operator!=="=="&&node.operator!=="!="){return false}const leftText=sourceCode.getText(node.left).toLowerCase();const rightText=sourceCode.getText(node.right).toLowerCase();return leftText.includes("null")||rightText.includes("null")||leftText.includes("undefined")||rightText.includes("undefined")};const isUnreliableConstructorCheck=node=>{return node.property.type==="Identifier"&&node.property.name==="name"&&node.object.type==="MemberExpression"&&node.object.property.type==="Identifier"&&node.object.property.name==="constructor"};return{BinaryExpression(node){if(isUnsafeTypeof(node)){const left=node.left;let matchesUserInput=false;if(left.argument.type==="Identifier"&&isUserInput(left.argument.name)){matchesUserInput=true}else if(left.argument.type==="MemberExpression"&&left.argument.object.type==="Identifier"&&isUserInput(left.argument.object.name)){matchesUserInput=true}if(matchesUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:left,messageId:"unsafeTypeofCheck",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"useTypeofCorrectly",fix:()=>null}]})}}if(isUnsafeInstanceof(node)){const left=node.left;if(left.type==="Identifier"&&isUserInput(left.name)){context.report({node,messageId:"unsafeInstanceofUsage",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}if(isLooseEqualityTypeCheck(node)){const left=node.left;const right=node.right;const leftText=sourceCode.getText(left);const rightText=sourceCode.getText(right);if(left.type==="Identifier"&&isUserInput(left.name)||right.type==="Identifier"&&isUserInput(right.name)||leftText.includes("null")||rightText.includes("null")){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"looseEqualityTypeCheck",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},MemberExpression(node){if(isUnreliableConstructorCheck(node)){let current=node;let involvesUserInput=false;while(current?.parent){current=current.parent;if(current.type==="VariableDeclarator"&&current.init===node){involvesUserInput=true;break}if(current.type==="BinaryExpression"&&(current.left===node||current.right===node)){involvesUserInput=true;break}}if(involvesUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"unreliableConstructorCheck",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const methodName=callee.property.name;const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(["isArray","isString","isNumber","isObject"].includes(methodName)&&objectName&&["Array","Number","String","Object"].includes(objectName)){return}}if(callee.type==="Identifier"&&callee.name==="typeof"){context.report({node,messageId:"improperTypeValidation",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"LOW",safeAlternative:"Use typeof as unary operator: typeof value"}})}},IfStatement(node){const test=node.test;if(test.type==="Identifier"&&isUserInput(test.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"improperTypeValidation",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"LOW",safeAlternative:"Explicitly check for null/undefined or type"}})}if(test.type==="BinaryExpression"){const testText=sourceCode.getText(test).toLowerCase();if((testText.includes("!= null")||testText.includes("== null"))&&!testText.includes("!== undefined")&&!testText.includes("=== undefined")){if(test.left.type==="Identifier"&&isUserInput(test.left.name)||test.right.type==="Identifier"&&isUserInput(test.right.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"missingNullCheck",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}}}});
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");exports.noImproperTypeValidation=(0,eslint_devkit_1.createRule)({name:"no-improper-type-validation",meta:{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"},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,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowInstanceofSameRealm=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isNullish=node=>node.type==="Literal"&&node.raw==="null"||node.type==="Identifier"&&node.name==="undefined";const sameExpression=(a,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;const wanted=negated2?["===","=="]:["!==","!="];if(!wanted.includes(expression.operator))return false;if(isNullish(expression.right))return sameExpression(expression.left,operand);if(isNullish(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"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="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(node.operator!=="==="&&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{BinaryExpression(node){const operand=typeofObjectOperand(node);if(operand&&!hasNullGuard(node,operand)){report(node.left,"unsafeTypeofCheck");return}if(node.operator==="instanceof"&&!allowInstanceofSameRealm){report(node,"unsafeInstanceofUsage");return}if(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(node.computed||node.property.type!=="Identifier")return;if(node.property.name!=="name")return;const inner=node.object;if(inner.type!=="MemberExpression"||inner.computed||inner.property.type!=="Identifier"||inner.property.name!=="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:{type:"problem",deprecated:true,replacedBy:["node-security/no-timing-unsafe-compare"],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}}",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 !==",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality"}),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))",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"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,ignorePatterns:[]}],create(context,[options={}]){const{allowInTests=false,ignorePatterns=[]}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);const sourceCode=context.sourceCode;const isCodemodFile=(()=>{if(/\/codemod[s]?\//i.test(filename))return true;if(/codemod\.[mc]?[jt]sx?$/i.test(filename))return true;return fileUsesAstTooling(sourceCode.ast)})();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;if(variable.references.filter(ref=>ref.isWrite()).length!==1)return false;const[def]=variable.defs;if(!def||def.type!=="Variable"||!def.node.init)return false;return isStringTyped(def.node.init,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"]);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());return[...parts,parts.join(""),parts.join("_"),name.toLowerCase()]};const namesIn=expr=>{const out=[];const walk=n=>{if(n.type==="Identifier")out.push(n.name);else if(n.type==="MemberExpression"){walk(n.object);if(!n.computed&&n.property.type==="Identifier")out.push(n.property.name);else walk(n.property)}else if(n.type==="CallExpression"){walk(n.callee)}};walk(expr);return out};const isSecurityContext=(()=>{let current=node;while(current){if((current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression")&&"id"in current&&current.id?.name){if(/security|auth|crypto|hash|token|secret|insecure|verify|validate/i.test(current.id.name)){return true}}if(current.type==="MethodDefinition"&&current.key.type==="Identifier"){if(/security|auth|crypto|hash|token|secret|insecure|verify|validate/i.test(current.key.name)){return true}}current=current.parent}return false})();const isPotentialSecret=expr=>{const segments=namesIn(expr).flatMap(nameSegments);if(segments.some(segment=>secretKeywords.has(segment)))return true;if(isSecurityContext){const contextKeywords=new Set(["provided","expected","actual","input","value","data"]);return segments.some(segment=>contextKeywords.has(segment))}return false};if((node.operator==="==="||node.operator==="!==")&&(isPotentialSecret(node.left)||isPotentialSecret(node.right))){const isLengthComparison=expr=>{return expr.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&expr.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&expr.property.name==="length"};if(isLengthComparison(node.left)||isLengthComparison(node.right)){return}const isNonSecretLiteral=expr=>expr.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(typeof expr.value==="boolean"||expr.value===null)||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:"useStrictEquality",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 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{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:{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"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,ignorePatterns:[]}],create(context,[options={}]){const{allowInTests=false,ignorePatterns=[]}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);const sourceCode=context.sourceCode;const isCodemodFile=(()=>{if(/\/codemod[s]?\//i.test(filename))return true;if(/codemod\.[mc]?[jt]sx?$/i.test(filename))return true;return fileUsesAstTooling(sourceCode.ast)})();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);if(!n.computed&&n.property.type==="Identifier")out.push(n.property.name);else if(n.computed&&n.property.type==="Literal"&&typeof n.property.value==="string"){out.push(n.property.value)}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());if(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&&expr.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&expr.property.name==="length"};if(isLengthComparison(node.left)||isLengthComparison(node.right)){return}const isNonSecretLiteral=expr=>expr.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(typeof expr.value==="boolean"||expr.value===null)||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 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{BinaryExpression:checkBinaryExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLdapInjection=void 0;exports.containsDangerousLdapFilter=containsDangerousLdapFilter;exports.containsLdapInterpolation=containsLdapInterpolation;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 containsLdapInterpolation(text){return/\$\{[^}]+\}/.test(text)||/'[^']*\+[^+]*'/.test(text)||/"[^"]*\+[^+]*"/.test(text)}const fileImportsLdapClient=(0,eslint_devkit_1.createModuleEvidence)({packages:["ldapjs","ldapts","ldapauth-fork","passport-ldapauth","ldap-authentication","ldap-escape","ldap-filter","activedirectory","activedirectory2","node-ldap"],scopes:["@ldapjs"]});exports.noLdapInjection=(0,eslint_devkit_1.createRule)({name:"no-ldap-injection",meta:{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"},hasSuggestions:true,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/"}),useLdapEscaping:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use LDAP Escaping",description:"Use proper LDAP escaping functions",severity:"LOW",fix:"Use ldap.escape.filterValue() or equivalent",documentationLink:"https://www.npmjs.com/package/ldap-escape"}),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"}),useParameterizedLdap:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Parameterized LDAP",description:"Use parameterized LDAP queries when possible",severity:"LOW",fix:"Use prepared LDAP statements or safe construction",documentationLink:"https://ldap.com/ldap-filters/"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate LDAP input at application boundary",severity:"LOW",fix:"Implement input validation and length limits",documentationLink:"https://cwe.mitre.org/data/definitions/90.html"}),strategySafeLibraries:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Safe Libraries Strategy",description:"Use LDAP libraries with built-in escaping",severity:"LOW",fix:"Use ldapjs or libraries with automatic escaping",documentationLink:"https://www.npmjs.com/package/ldapjs"}),strategyFilterConstruction:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Filter Construction Strategy",description:"Use safe LDAP filter construction methods",severity:"LOW",fix:"Build filters programmatically with escaped values",documentationLink:"https://ldap.com/ldap-filters/"})},schema:[{type:"object",properties:{ldapFunctions:{type:"array",items:{type:"string"},default:["search","bind","modify","add","delete","compare","searchAsync"],description:"LDAP client methods treated as query sinks"},ldapEscapeFunctions:{type:"array",items:{type:"string"},default:["escape.filterValue","escape.dnValue","filterEscape","dnEscape"],description:"Function names that escape LDAP filter or DN values"},ldapValidationFunctions:{type:"array",items:{type:"string"},default:["validateLdapInput","sanitizeLdapFilter","cleanLdapValue","checkLdapFilter"],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)"}},additionalProperties:false}]},defaultOptions:[{ldapFunctions:["search","bind","modify","add","delete","compare","searchAsync"],ldapEscapeFunctions:["escape.filterValue","escape.dnValue","filterEscape","dnEscape"],ldapValidationFunctions:["validateLdapInput","sanitizeLdapFilter","cleanLdapValue","checkLdapFilter"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{ldapFunctions=["search","bind","modify","add","delete","compare","searchAsync"],ldapEscapeFunctions=["escape.filterValue","escape.dnValue","filterEscape","dnEscape"],ldapValidationFunctions=["validateLdapInput","sanitizeLdapFilter","cleanLdapValue","checkLdapFilter"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isLdapOperation=node=>{const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&ldapFunctions.includes(callee.property.name)){return true}return false};const isUntrustedLdapInput=inputNode=>{if(inputNode.type==="MemberExpression"){const fullName=sourceCode.getText(inputNode).toLowerCase();return fullName.includes("req.")||fullName.includes("request.")||fullName.includes("query.")||fullName.includes("params.")||fullName.includes("body.")}if(inputNode.type==="Identifier"){const varName=inputNode.name.toLowerCase();return["userid","username","userinput","input","term","name","search","query","param","password","id","dn"].includes(varName)||varName.startsWith("user")||varName.startsWith("input")||varName.endsWith("input")||varName.includes("user")||varName.includes("input")}return false};const isLdapInputEscaped=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"){const callee=current.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const propertyName=callee.property.name;if(ldapEscapeFunctions.some(escapeFunc=>escapeFunc.includes(propertyName)||propertyName.includes("escape"))){return true}}if(callee.type==="Identifier"&&ldapValidationFunctions.includes(callee.name)){return true}}current=current.parent}return false};let ldapInFile=false;return{Program(program){ldapInFile=fileImportsLdapClient(program)},CallExpression(node){if(!ldapInFile||!isLdapOperation(node)){return}const args=node.arguments;if(args.length<2){return}const filterArg=args[1];if(isUntrustedLdapInput(filterArg)){if(safetyChecker.isSafe(filterArg,context)){return}context.report({node:filterArg,messageId:"unescapedLdapInput",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"useLdapEscaping",fix:()=>null}]})}else if(filterArg.type==="TemplateLiteral"&&filterArg.expressions.length>0){if(safetyChecker.isSafe(filterArg,context)){return}context.report({node:filterArg,messageId:"unescapedLdapInput",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"useLdapEscaping",fix:()=>null}]})}},VariableDeclarator(node){if(!ldapInFile||!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name.toLowerCase();const isLdapRelated=varName.includes("filter")||varName.includes("ldap")||varName.includes("query")||varName.includes("search")||varName.includes("dn")||varName.includes("bind");if(!isLdapRelated&&node.init){const initText=sourceCode.getText(node.init);if(!initText.includes("(")||!initText.includes(")")){return}}if(node.init.type==="Literal"&&typeof node.init.value==="string"){if(containsDangerousLdapFilter(node.init.value)){if(safetyChecker.isSafe(node.init,context)){return}context.report({node:node.init,messageId:"dangerousLdapOperation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(node.init.type==="TemplateLiteral"){const fullText=sourceCode.getText(node.init);if(containsLdapInterpolation(fullText)){const hasUntrustedInterpolation=node.init.expressions.some(expr=>isUntrustedLdapInput(expr)&&!isLdapInputEscaped(expr));if(hasUntrustedInterpolation){if(safetyChecker.isSafe(node.init,context)){return}context.report({node:node.init,messageId:"unsafeLdapFilter",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"useLdapEscaping",fix:()=>null}]})}}if(containsDangerousLdapFilter(fullText)){if(safetyChecker.isSafe(node.init,context)){return}context.report({node:node.init,messageId:"dangerousLdapOperation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}else if(node.init.type==="BinaryExpression"&&node.init.operator==="+"){const fullText=sourceCode.getText(node.init);if(fullText.includes("(")&&fullText.includes(")")){const hasUntrustedInput=expr=>{if(isUntrustedLdapInput(expr)&&!isLdapInputEscaped(expr)){return true}if(expr.type==="BinaryExpression"&&expr.operator==="+"){return hasUntrustedInput(expr.left)||hasUntrustedInput(expr.right)}return false};if(hasUntrustedInput(node.init.left)||hasUntrustedInput(node.init.right)){if(safetyChecker.isSafe(node.init,context)){return}context.report({node:node.init,messageId:"ldapInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use ldap.escape.filterValue() or parameterized LDAP queries"},suggest:[{messageId:"useLdapEscaping",fix:()=>null}]})}}}else if(isUntrustedLdapInput(node.init)&&!isLdapInputEscaped(node.init)){if(safetyChecker.isSafe(node.init,context)){return}context.report({node:node.init,messageId:"ldapInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Use proper LDAP escaping and validation"},suggest:[{messageId:"useLdapEscaping",fix:()=>null}]})}}}}});
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:{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:[]}],create(context){const options=context.options[0]||{};const{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;const ldapPackageSet=new Set([...ldapPackages,...additionalLdapPackages]);const requestRootSet=new Set([...requestRoots,...additionalRequestRoots]);const fileImportsLdapClient=(0,eslint_devkit_1.createModuleEvidence)({packages:[...ldapPackageSet],scopes:[...LDAP_SCOPES]});const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const ldapLocals=new Set;let ldapInFile=false;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"})}if(expression.type==="MemberExpression"&&expression.object.type==="ThisExpression"&&!expression.computed&&expression.property.type==="Identifier"){const fieldName=expression.property.name;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;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const propertyName=callee.property.name;if(ldapEscapeFunctions.some(escapeFunc=>escapeFunc===propertyName||escapeFunc.endsWith(`.${propertyName}`))){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=>leaf.type==="Literal"&&typeof leaf.value==="string"||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"||expression.computed)return false;return!isStatic(expression)&&isUntrustedRequestChain(expression)};function isUntrustedRequestChain(node){let current=node;while(current.type==="MemberExpression")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 reported=new Set;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{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"||callee.computed)return;if(callee.property.type!=="Identifier")return;const method=callee.property.name;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=new Set(["console","log","logger","winston","pino","bunyan"]);const LOG_LEVEL_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);const REQUEST_ROOTS=new Set(["req","request","ctx","event","message"]);const REQUEST_PROPERTIES=new Set(["query","params","body","headers","url","path","cookies","data"]);function requestFieldOf(node,roots){if(node.type!=="MemberExpression")return null;const properties=[];let root=node;while(root.type==="MemberExpression"){const property=root.property;if(!root.computed&&property.type==="Identifier"){properties.unshift(property.name)}else if(property.type==="Literal"&&typeof property.value==="string"){properties.unshift(property.value)}root=root.object}if(root.type!=="Identifier")return null;if(!roots.has(root.name))return null;if(!properties.some(p=>REQUEST_PROPERTIES.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}}function attributableSource(node,scope,roots){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}return requestFieldOf(definition.node.init,roots)}return requestFieldOf(node,roots)}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"&&object.property.type==="Identifier"){return receivers.has(object.property.name)?object.property.name:null}return null}exports.noLogInjection=(0,eslint_devkit_1.createRule)({name:"no-log-injection",meta:{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:{loggerNames:{type:"array",items:{type:"string"},default:[],description:"Additional receiver names whose level methods write a log line"},requestRoots:{type:"array",items:{type:"string"},default:[],description:"Additional identifier roots that denote an inbound request"}},additionalProperties:false}]},defaultOptions:[{loggerNames:[],requestRoots:[]}],create(context){const options=context.options[0]??{};const receivers=new Set([...DEFAULT_LOGGER_RECEIVERS,...options.loggerNames??[]]);const roots=new Set([...REQUEST_ROOTS,...options.requestRoots??[]]);const sourceCode=context.sourceCode;function isLoggingCall(node){const callee=node.callee;if(callee.type!=="MemberExpression")return false;if(callee.property.type!=="Identifier")return false;if(!LOG_LEVEL_METHODS.has(callee.property.name))return false;return receiverName(callee.object,receivers)!==null}return{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);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 property=root.property;if(!root.computed&&property.type==="Identifier"){properties.unshift(property.name)}else if(property.type==="Literal"&&typeof property.value==="string"){properties.unshift(property.value)}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}}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}return requestFieldOf(definition.node.init,roots,requestProperties)}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"&&object.property.type==="Identifier"){return receivers.has(object.property.name)?object.property.name:null}return null}exports.noLogInjection=(0,eslint_devkit_1.createRule)({name:"no-log-injection",meta:{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:[]}],create(context){const options=context.options[0]??{};const receivers=new Set([...options.loggerReceivers??DEFAULT_LOGGER_RECEIVERS,...options.loggerNames??[]]);const roots=new Set([...options.requestRootNames??DEFAULT_REQUEST_ROOTS,...options.requestRoots??[]]);const requestProperties=new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]);const sourceCode=context.sourceCode;function isLoggingCall(node){const callee=node.callee;if(callee.type!=="MemberExpression")return false;if(callee.property.type!=="Identifier")return false;if(!LOG_LEVEL_METHODS.has(callee.property.name))return false;return receiverName(callee.object,receivers)!==null}return{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","status","metrics","ping","favicon","webhook","/public/","oauth","callback"];const DEFAULT_ROUTE_HANDLER_PATTERNS=["get","post","put","delete","patch","all","use"];function isInsideAuthMiddleware(node,sourceCode,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"){const calleeName=callee.name.toLowerCase();if(authPatterns.some(pattern=>calleeName.includes(pattern.toLowerCase()))){return true}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const propertyName=callee.property.name.toLowerCase();if(propertyName==="use"||propertyName==="all"){for(const arg of callExpr.arguments){const argText=sourceCode.getText(arg);if(authPatterns.some(pattern=>argText.toLowerCase().includes(pattern.toLowerCase()))){return true}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}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())}})}exports.noMissingAuthentication=(0,eslint_devkit_2.createRule)({name:"no-missing-authentication",meta:{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},hasSuggestions:true,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"}),addAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Authentication",description:"Add authentication middleware before route handler",severity:"LOW",fix:'app.get("/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:[],description:"Additional patterns to ignore"},testFilePattern:{type:"string",default:"\\.(test|spec)\\.(ts|tsx|js|jsx)$",description:"Test file pattern regex string"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,testFilePattern:"\\.(test|spec)\\.(ts|tsx|js|jsx)$",authMiddlewarePatterns:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns:DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns:DEFAULT_PUBLIC_ROUTE_PATTERNS}],create(context,[options={}]){const{allowInTests=false,testFilePattern="\\.(test|spec)\\.(ts|tsx|js|jsx)$",authMiddlewarePatterns=DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns=DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns=DEFAULT_PUBLIC_ROUTE_PATTERNS}=options;const filename=context.filename;const testFileRegex=new RegExp(testFilePattern);const isTestFile=allowInTests&&testFileRegex.test(filename);const sourceCode=context.sourceCode;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"){const calleeName=declarator.init.callee.name.toLowerCase();return authMiddlewarePatterns.some(pattern=>calleeName.includes(pattern.toLowerCase()))}return false}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const property=node.callee.property;const object=node.callee.object;if(object.type!=="Identifier"){return}const objectName=object.name.toLowerCase();const routerLikeNames=["app","router","server","route","express","fastify","koa","hapi"];const looksLikeRouter=routerLikeNames.some(name=>objectName.includes(name));if(!looksLikeRouter){return}if(property.type==="Identifier"){const methodName=property.name.toLowerCase();if(routeHandlerPatterns.includes(methodName)){if(methodName==="use"){const first=node.arguments[0];const mountsAPath=first!==void 0&&first.type==="Literal"&&typeof first.value==="string";if(!mountsAPath){return}}let routePath="unknown";if(node.arguments.length>0&&node.arguments[0].type==="Literal"){routePath=String(node.arguments[0].value)}else if(node.arguments.length>0){const pathText=sourceCode.getText(node.arguments[0]);routePath=pathText}const text=sourceCode.getText(node);if(matchesIgnorePattern(routePath,ignorePatterns)){return}if(matchesIgnorePattern(text,ignorePatterns)){return}let hasAuth=false;for(const arg of node.arguments){const argText=sourceCode.getText(arg);if(authMiddlewarePatterns.some(pattern=>argText.toLowerCase().includes(pattern.toLowerCase()))){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,sourceCode,authMiddlewarePatterns)){hasAuth=true}}}if(!hasAuth){context.report({node:node.callee,messageId:"missingAuthentication",data:{route:`${methodName}(${routePath})`,method:methodName,path:routePath},suggest:[{messageId:"addAuthentication",fix:_fixer=>null}]})}}}}}return{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","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){const property=current.callee.property;if(property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.name==="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&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_MEMBERS.has(callee.property.name)}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&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const objectPart=node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${node.object.name}.`:"";return`${objectPart}${node.property.name}`}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"&&callee.property.type==="Identifier"){const propertyName=callee.property.name.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:{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:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,authMiddlewarePatterns=DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns=DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns=DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords=ROUTER_NAME_WORDS,additionalRouterNameWords=[]}=options;const routerWords=[...routerNameWords,...additionalRouterNameWords];const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const scansWholeCallText=context.options[0]?.ignorePatterns!==void 0;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 property=node.callee.property;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]}if(property.type==="Identifier"){const methodName=property.name.toLowerCase();if(routeHandlerPatterns.includes(methodName)){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];let routePath="unknown";if(pathArgument!==void 0&&pathArgument.type==="Literal"){routePath=String(pathArgument.value)}else if(pathArgument!==void 0){routePath=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{CallExpression:checkCallExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPiiInLogs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.noPiiInLogs=(0,eslint_devkit_1.createRule)({name:"no-pii-in-logs",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-pii-in-logs.md",description:"Prevent PII (email, SSN, credit cards) in console logs",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-359",description:"Prevent PII (email, SSN, credit cards) in console logs detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[]},defaultOptions:[],create(context){function report(node){context.report({node,messageId:"violationDetected"})}return{CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.object.name==="console"&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&["log","error","warn","info"].includes(node.callee.property.name)){for(const arg of node.arguments){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&arg.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const propName=arg.property.name.toLowerCase();const piiProps=["email","ssn","password","creditcard","phone"];if(piiProps.some(p=>propName.includes(p))){report(node)}}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"){const text=arg.value.toLowerCase();if(text.includes("email:")||text.includes("ssn:")||text.includes("password:")){report(node)}}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPiiInLogs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_CONSOLE_METHODS=["log","error","warn","info"];const DEFAULT_PII_TERMS=["email","ssn","password","credit card","phone"];const DEFAULT_PII_LABELS=["email:","ssn:","password:","credit card:","creditcard:"];function collectLoggedValues(root){const found=[];const pending=[root];while(pending.length>0){const node=pending.pop();found.push(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression){pending.push(node.expression)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){pending.push(...node.expressions)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){pending.push(node.left,node.right)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of node.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property){pending.push(property.value)}}}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){pending.push(node.consequent,node.alternate)}}return found}function isPiiFieldAccess(node,piiTerms){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(node.property.name,piiTerms)}exports.noPiiInLogs=(0,eslint_devkit_1.createRule)({name:"no-pii-in-logs",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-pii-in-logs.md",description:"Prevent PII (email, SSN, credit cards) in console logs",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-359",description:"Prevent PII (email, SSN, credit cards) in console logs detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[{type:"object",properties:{consoleMethods:{type:"array",items:{type:"string"},default:DEFAULT_CONSOLE_METHODS,description:"`console` methods treated as a log sink, matched as an exact method name. Replaces the built-in list."},additionalConsoleMethods:{type:"array",items:{type:"string"},default:[],description:"Extra `console` methods, on top of `consoleMethods`."},piiTerms:{type:"array",items:{type:"string"},default:DEFAULT_PII_TERMS,description:'Field vocabulary, matched as WHOLE WORDS of an identifier \u2014 never as a substring. Multi-word terms such as "credit card" match consecutive segments. Replaces the built-in list.'},additionalPiiTerms:{type:"array",items:{type:"string"},default:[],description:"Extra PII field terms, on top of `piiTerms`."},piiLabels:{type:"array",items:{type:"string"},default:DEFAULT_PII_LABELS,description:"String literals that are EXACTLY a field label announcing the next argument. Compared case-insensitively after trimming. Replaces the built-in list."},additionalPiiLabels:{type:"array",items:{type:"string"},default:[],description:"Extra field labels, on top of `piiLabels`."}},additionalProperties:false}]},defaultOptions:[{consoleMethods:DEFAULT_CONSOLE_METHODS,additionalConsoleMethods:[],piiTerms:DEFAULT_PII_TERMS,additionalPiiTerms:[],piiLabels:DEFAULT_PII_LABELS,additionalPiiLabels:[]}],create(context,[options={}]){const{consoleMethods=DEFAULT_CONSOLE_METHODS,additionalConsoleMethods=[],piiTerms=DEFAULT_PII_TERMS,additionalPiiTerms=[],piiLabels=DEFAULT_PII_LABELS,additionalPiiLabels=[]}=options;const logMethods=new Set([...consoleMethods,...additionalConsoleMethods]);const terms=[...piiTerms,...additionalPiiTerms];const labels=new Set([...piiLabels,...additionalPiiLabels].map(label=>label.trim().toLowerCase()));const sourceCode=context.sourceCode;function report(node){context.report({node,messageId:"violationDetected"})}function isPiiBinding(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);const resolved=reference?.resolved;if(!resolved){return false}return resolved.defs.some(def=>{const declared=def.name;const parent=declared.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return(0,eslint_devkit_1.nameHasAnyWord)(parent.key.name,terms)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){return isPiiFieldAccess(parent.init,terms)}return false})}return{CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||node.callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.object.name!=="console"||node.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!logMethods.has(node.callee.property.name)){return}for(const[index,arg]of node.arguments.entries()){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&index<node.arguments.length-1&&labels.has(arg.value.trim().toLowerCase())){report(node);return}for(const value of collectLoggedValues(arg)){if(isPiiFieldAccess(value,terms)||isPiiBinding(value)){report(node);return}}}}}}});