eslint-plugin-secure-coding 3.6.1 → 3.7.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-secure-coding",
3
- "version": "3.6.1",
3
+ "version": "3.7.0",
4
4
  "description": "ESLint plugin for secure coding — detects LDAP, XPath, XXE, GraphQL and template injection, unsafe deserialization, ReDoS, missing authentication, and PII in logs.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
package/src/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;exports.rules={get"no-graphql-injection"(){return require("./rules/no-graphql-injection").noGraphqlInjection},get"no-xxe-injection"(){return require("./rules/no-xxe-injection").noXxeInjection},get"no-xpath-injection"(){return require("./rules/no-xpath-injection").noXpathInjection},get"no-ldap-injection"(){return require("./rules/no-ldap-injection").noLdapInjection},get"no-directive-injection"(){return require("./rules/no-directive-injection").noDirectiveInjection},get"no-format-string-injection"(){return require("./rules/no-format-string-injection").noFormatStringInjection},get"no-template-injection"(){return require("./rules/no-template-injection").noTemplateInjection},get"detect-non-literal-regexp"(){return require("./rules/detect-non-literal-regexp").detectNonLiteralRegexp},get"no-redos-vulnerable-regex"(){return require("./rules/no-redos-vulnerable-regex").noRedosVulnerableRegex},get"no-unsafe-regex-construction"(){return require("./rules/no-unsafe-regex-construction").noUnsafeRegexConstruction},get"detect-object-injection"(){return require("./rules/detect-object-injection").detectObjectInjection},get"no-unsafe-deserialization"(){return require("./rules/no-unsafe-deserialization").noUnsafeDeserialization},get"no-insecure-comparison"(){return require("./rules/no-insecure-comparison").noInsecureComparison},get"no-improper-sanitization"(){return require("./rules/no-improper-sanitization").noImproperSanitization},get"no-improper-type-validation"(){return require("./rules/no-improper-type-validation").noImproperTypeValidation},get"no-missing-authentication"(){return require("./rules/no-missing-authentication").noMissingAuthentication},get"no-privilege-escalation"(){return require("./rules/no-privilege-escalation").noPrivilegeEscalation},get"no-weak-password-recovery"(){return require("./rules/no-weak-password-recovery").noWeakPasswordRecovery},get"require-backend-authorization"(){return require("./rules/require-backend-authorization").requireBackendAuthorization},get"no-hardcoded-credentials"(){return require("./rules/no-hardcoded-credentials").noHardcodedCredentials},get"no-sensitive-data-exposure"(){return require("./rules/no-sensitive-data-exposure").noSensitiveDataExposure},get"no-pii-in-logs"(){return require("./rules/no-pii-in-logs").noPiiInLogs},get"no-unlimited-resource-allocation"(){return require("./rules/no-unlimited-resource-allocation").noUnlimitedResourceAllocation},get"no-unchecked-loop-condition"(){return require("./rules/no-unchecked-loop-condition").noUncheckedLoopCondition},get"detect-weak-password-validation"(){return require("./rules/detect-weak-password-validation").detectWeakPasswordValidation},get"no-electron-security-issues"(){return require("./rules/no-electron-security-issues").noElectronSecurityIssues},get"no-hardcoded-session-tokens"(){return require("./rules/no-hardcoded-session-tokens").noHardcodedSessionTokens},get"require-secure-defaults"(){return require("./rules/require-secure-defaults").requireSecureDefaults}};exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"3.6.1"},rules:exports.rules};const recommendedRules={"secure-coding/no-graphql-injection":"warn","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-unsafe-deserialization":"warn","secure-coding/detect-non-literal-regexp":"warn","secure-coding/no-redos-vulnerable-regex":"error","secure-coding/no-unsafe-regex-construction":"error","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-template-injection":"error","secure-coding/no-improper-sanitization":"error","secure-coding/no-privilege-escalation":"warn","secure-coding/no-weak-password-recovery":"warn","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-unlimited-resource-allocation":"warn"};exports.configs={flagship:{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-hardcoded-credentials":"error","secure-coding/no-redos-vulnerable-regex":"error"}},recommended:{plugins:{"secure-coding":exports.plugin},rules:recommendedRules},"recommended-strict":{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(recommendedRules).map(rule=>[rule,"error"]))},strict:{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`secure-coding/${ruleName}`,"error"]))},"owasp-top-10":{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-privilege-escalation":"warn","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-graphql-injection":"error","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-weak-password-recovery":"error","secure-coding/no-improper-type-validation":"error","secure-coding/no-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;exports.rules={get"no-graphql-injection"(){return require("./rules/no-graphql-injection").noGraphqlInjection},get"no-xxe-injection"(){return require("./rules/no-xxe-injection").noXxeInjection},get"no-xpath-injection"(){return require("./rules/no-xpath-injection").noXpathInjection},get"no-ldap-injection"(){return require("./rules/no-ldap-injection").noLdapInjection},get"no-directive-injection"(){return require("./rules/no-directive-injection").noDirectiveInjection},get"no-format-string-injection"(){return require("./rules/no-format-string-injection").noFormatStringInjection},get"no-template-injection"(){return require("./rules/no-template-injection").noTemplateInjection},get"detect-non-literal-regexp"(){return require("./rules/detect-non-literal-regexp").detectNonLiteralRegexp},get"no-redos-vulnerable-regex"(){return require("./rules/no-redos-vulnerable-regex").noRedosVulnerableRegex},get"no-unsafe-regex-construction"(){return require("./rules/no-unsafe-regex-construction").noUnsafeRegexConstruction},get"detect-object-injection"(){return require("./rules/detect-object-injection").detectObjectInjection},get"no-unsafe-deserialization"(){return require("./rules/no-unsafe-deserialization").noUnsafeDeserialization},get"no-insecure-comparison"(){return require("./rules/no-insecure-comparison").noInsecureComparison},get"no-improper-sanitization"(){return require("./rules/no-improper-sanitization").noImproperSanitization},get"no-improper-type-validation"(){return require("./rules/no-improper-type-validation").noImproperTypeValidation},get"no-missing-authentication"(){return require("./rules/no-missing-authentication").noMissingAuthentication},get"no-privilege-escalation"(){return require("./rules/no-privilege-escalation").noPrivilegeEscalation},get"no-weak-password-recovery"(){return require("./rules/no-weak-password-recovery").noWeakPasswordRecovery},get"require-backend-authorization"(){return require("./rules/require-backend-authorization").requireBackendAuthorization},get"no-hardcoded-credentials"(){return require("./rules/no-hardcoded-credentials").noHardcodedCredentials},get"no-sensitive-data-exposure"(){return require("./rules/no-sensitive-data-exposure").noSensitiveDataExposure},get"no-pii-in-logs"(){return require("./rules/no-pii-in-logs").noPiiInLogs},get"no-unlimited-resource-allocation"(){return require("./rules/no-unlimited-resource-allocation").noUnlimitedResourceAllocation},get"no-unchecked-loop-condition"(){return require("./rules/no-unchecked-loop-condition").noUncheckedLoopCondition},get"detect-weak-password-validation"(){return require("./rules/detect-weak-password-validation").detectWeakPasswordValidation},get"no-electron-security-issues"(){return require("./rules/no-electron-security-issues").noElectronSecurityIssues},get"no-hardcoded-session-tokens"(){return require("./rules/no-hardcoded-session-tokens").noHardcodedSessionTokens},get"require-secure-defaults"(){return require("./rules/require-secure-defaults").requireSecureDefaults}};exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"3.7.0"},rules:exports.rules};const recommendedRules={"secure-coding/no-graphql-injection":"warn","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-unsafe-deserialization":"warn","secure-coding/detect-non-literal-regexp":"warn","secure-coding/no-redos-vulnerable-regex":"error","secure-coding/no-unsafe-regex-construction":"error","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-template-injection":"error","secure-coding/no-improper-sanitization":"error","secure-coding/no-privilege-escalation":"warn","secure-coding/no-weak-password-recovery":"warn","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-unlimited-resource-allocation":"warn"};exports.configs={flagship:{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-hardcoded-credentials":"error","secure-coding/no-redos-vulnerable-regex":"error"}},recommended:{plugins:{"secure-coding":exports.plugin},rules:recommendedRules},"recommended-strict":{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(recommendedRules).map(rule=>[rule,"error"]))},strict:{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`secure-coding/${ruleName}`,"error"]))},"owasp-top-10":{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-privilege-escalation":"warn","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-graphql-injection":"error","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-weak-password-recovery":"error","secure-coding/no-improper-type-validation":"error","secure-coding/no-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDirectiveInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noDirectiveInjection=(0,eslint_devkit_1.createRule)({name:"no-directive-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-directive-injection.md",description:"Detects directive injection vulnerabilities in templates",cwe:"CWE-96"},messages:{directiveInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Directive Injection",cwe:"CWE-96",description:"User input injected into directive or template",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeDirectiveName:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Directive Name",cwe:"CWE-96",description:"Directive name controlled by user input",severity:"CRITICAL",fix:"Use hardcoded directive names or validate against whitelist",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dynamicDirectiveCreation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dynamic Directive Creation",cwe:"CWE-96",description:"Dynamic creation of directives from user input",severity:"HIGH",fix:"Validate directive names against trusted list",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),templateInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Template Injection",cwe:"CWE-96",description:"User input injected into template content",severity:"HIGH",fix:"Sanitize template input or use safe rendering",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeComponentBinding:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Component Binding",cwe:"CWE-96",description:"Dynamic component binding with user input",severity:"HIGH",fix:"Use component whitelist or validate component names",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),userControlledTemplate:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Template",cwe:"CWE-96",description:"Template content controlled by user input",severity:"CRITICAL",fix:"Sanitize template input before compilation",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dangerousInnerHTML:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous innerHTML",cwe:"CWE-96",description:"innerHTML set with user-controlled content",severity:"HIGH",fix:"Use textContent or sanitize HTML content",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML"}),untrustedDirectiveSource:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Untrusted Directive Source",cwe:"CWE-96",description:"Directive loaded from untrusted source",severity:"MEDIUM",fix:"Load directives from trusted, verified sources",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),useTrustedDirectives:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Trusted Directives",description:"Use only trusted, verified directives",severity:"LOW",fix:"Maintain whitelist of allowed directives",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),sanitizeTemplateInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Sanitize Template Input",description:"Sanitize user input before template processing",severity:"LOW",fix:"Use DOMPurify or equivalent sanitization",documentationLink:"https://github.com/cure53/DOMPurify"}),validateDirectiveNames:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate Directive Names",description:"Validate directive names against whitelist",severity:"LOW",fix:"Check directive names before dynamic creation",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),strategyTemplateSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Template Sanitization Strategy",description:"Implement template input sanitization",severity:"LOW",fix:"Sanitize all user input before template processing",documentationLink:"https://owasp.org/www-community/xss-filter-evasion-cheatsheet"}),strategyContentSecurity:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Content Security Strategy",description:"Use CSP to restrict directive execution",severity:"LOW",fix:"Implement strict CSP with script-src restrictions",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate all template inputs",severity:"LOW",fix:"Use schema validation for template inputs",documentationLink:"https://joi.dev/"})},schema:[{type:"object",properties:{trustedDirectives:{type:"array",items:{type:"string"},default:["ngIf","ngFor","ngClass","v-if","v-for","v-bind","v-on"],description:"Template directives treated as safe"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},frameworks:{type:"array",items:{type:"string"},default:["angular","vue","react","svelte"],description:"Template frameworks to analyse"},allowDynamicInComponents:{type:"boolean",default:false,description:"Allow dynamic directives inside component code"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as template sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{trustedDirectives:["ngIf","ngFor","ngClass","v-if","v-for","v-bind","v-on"],userInputVariables:["req","request","body","query","params","input","data","userInput"],frameworks:["angular","vue","react","svelte"],allowDynamicInComponents:false,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{userInputVariables=["req","request","body","query","params","input","data","userInput"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isUserInput=varName=>{return userInputVariables.some(input=>varName.includes(input))||varName.startsWith("user")};return{JSXAttribute(node){const attrName=node.name;const attrValue=node.value;if(attrName.type==="JSXIdentifier"&&attrName.name==="dangerouslySetInnerHTML"){if(attrValue&&attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;const expressionText=sourceCode.getText(expression);if(userInputVariables.some(input=>expressionText.includes(input))){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}const isNamespaceDirective=attrName.type==="JSXNamespacedName"&&(attrName.namespace.name==="v"||attrName.namespace.name==="ng")||attrName.type==="JSXIdentifier"&&(attrName.name.startsWith("ng:")||attrName.name.startsWith("v:"));if(isNamespaceDirective&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(expression.type==="Identifier"&&isUserInput(expression.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"directiveInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded directive values or validate user input"}})}}}if(attrName.type==="JSXIdentifier"){const attrNameStr=attrName.name;if(attrNameStr==="is"&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(expression.type==="Identifier"&&isUserInput(expression.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"unsafeComponentBinding",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},AssignmentExpression(node){const left=node.left;const right=node.right;if(left.type==="MemberExpression"&&left.property.type==="Identifier"&&left.property.name==="innerHTML"){const rightText=sourceCode.getText(right);if(userInputVariables.some(input=>rightText.includes(input))){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const methodName=callee.property.name;const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(["compile","template","$compile","$interpolate"].includes(methodName)||objectName==="Handlebars"&&methodName==="compile"||objectName==="_"&&methodName==="template"||objectName==="ejs"&&methodName==="render"||objectName==="pug"&&methodName==="render"||objectName==="mustache"&&methodName==="render"){const args=node.arguments;if(args.length>0){const templateArg=args[0];if(templateArg.type==="Identifier"&&isUserInput(templateArg.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:templateArg,messageId:"userControlledTemplate",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}if(objectName==="Vue"&&methodName==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(directiveName.type==="Identifier"&&isUserInput(directiveName.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"unsafeDirectiveName",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}if(callee.type==="Identifier"&&callee.name==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(directiveName.type==="Identifier"&&isUserInput(directiveName.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"dynamicDirectiveCreation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},TemplateLiteral(node){let current=node;let isInDangerousContext=false;while(current){if(current.type==="JSXExpressionContainer"){if(current.parent?.type==="JSXAttribute"&&current.parent.name.type==="JSXIdentifier"&&current.parent.name.name==="dangerouslySetInnerHTML"){isInDangerousContext=true;break}}else if(current.type==="AssignmentExpression"){const left=current.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"&&left.property.name==="innerHTML"){isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext){const hasUserInput=node.expressions.some(expr=>expr.type==="Identifier"&&isUserInput(expr.name)||expr.type==="MemberExpression"&&expr.object.type==="Identifier"&&isUserInput(expr.object.name));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"templateInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Sanitize template input before insertion"}})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDirectiveInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const DANGEROUS_TAGS=new Set(["script","iframe","object","embed","base"]);const DANGEROUS_ATTRS=new Set(["srcdoc","formaction","xlink:href"]);const TAG_OPTIONS=new Set(["ADD_TAGS","ALLOWED_TAGS"]);const ATTR_OPTIONS=new Set(["ADD_ATTR","ALLOWED_ATTR"]);function staticStringArray(node){if(node.type!=="ArrayExpression")return null;const out=[];for(const element of node.elements){if(element?.type==="Literal"&&typeof element.value==="string"){out.push(element.value)}}return out}function findUnsafeSanitizerConfig(node){const callee=node.callee;if(callee.type!=="MemberExpression")return null;if(callee.property.type!=="Identifier"||callee.property.name!=="sanitize")return null;if(callee.object.type!=="Identifier")return null;if(!callee.object.name.toLowerCase().includes("purify"))return null;const config=node.arguments[1];if(!config||config.type!=="ObjectExpression")return null;for(const property of config.properties){if(property.type!=="Property")continue;if(property.computed)continue;const option=property.key.type==="Identifier"?property.key.name:property.key.type==="Literal"&&typeof property.key.value==="string"?property.key.value:null;if(option===null)continue;if(property.shorthand)continue;const values=staticStringArray(property.value);if(!values)continue;if(TAG_OPTIONS.has(option)){const bad=values.find(v=>DANGEROUS_TAGS.has(v.toLowerCase()));if(bad)return{node:property,option,allowed:`<${bad}>`}}if(ATTR_OPTIONS.has(option)){const bad=values.find(v=>v.toLowerCase().startsWith("on")||DANGEROUS_ATTRS.has(v.toLowerCase()));if(bad)return{node:property,option,allowed:`the "${bad}" attribute`}}}return null}exports.noDirectiveInjection=(0,eslint_devkit_1.createRule)({name:"no-directive-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-directive-injection.md",description:"Detects directive injection vulnerabilities in templates",cwe:"CWE-96"},messages:{directiveInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Directive Injection",cwe:"CWE-96",description:"User input injected into directive or template",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeDirectiveName:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Directive Name",cwe:"CWE-96",description:"Directive name controlled by user input",severity:"CRITICAL",fix:"Use hardcoded directive names or validate against whitelist",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dynamicDirectiveCreation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dynamic Directive Creation",cwe:"CWE-96",description:"Dynamic creation of directives from user input",severity:"HIGH",fix:"Validate directive names against trusted list",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),templateInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Template Injection",cwe:"CWE-96",description:"User input injected into template content",severity:"HIGH",fix:"Sanitize template input or use safe rendering",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeComponentBinding:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Component Binding",cwe:"CWE-96",description:"Dynamic component binding with user input",severity:"HIGH",fix:"Use component whitelist or validate component names",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),userControlledTemplate:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Template",cwe:"CWE-96",description:"Template content controlled by user input",severity:"CRITICAL",fix:"Sanitize template input before compilation",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dangerousInnerHTML:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous innerHTML",cwe:"CWE-96",description:"innerHTML set with user-controlled content",severity:"HIGH",fix:"Use textContent or sanitize HTML content",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML"}),untrustedDirectiveSource:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Untrusted Directive Source",cwe:"CWE-96",description:"Directive loaded from untrusted source",severity:"MEDIUM",fix:"Load directives from trusted, verified sources",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),useTrustedDirectives:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Trusted Directives",description:"Use only trusted, verified directives",severity:"LOW",fix:"Maintain whitelist of allowed directives",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeSanitizerConfig:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Sanitizer configured to allow {{allowed}}",cwe:"CWE-96",description:"DOMPurify was configured with {{option}} re-enabling {{allowed}}, which is exactly what the sanitizer removes by default. The call returns markup that can execute script, so the sanitization provides no protection.",severity:"HIGH",fix:"Drop {{allowed}} from {{option}}. If the markup genuinely needs it, render it outside the sanitized region rather than widening the allow-list.",documentationLink:"https://github.com/cure53/DOMPurify#can-i-configure-dompurify"}),sanitizeTemplateInput:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Sanitize Template Input",description:"Sanitize user input before template processing",severity:"LOW",fix:"Use DOMPurify or equivalent sanitization",documentationLink:"https://github.com/cure53/DOMPurify"}),validateDirectiveNames:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Validate Directive Names",description:"Validate directive names against whitelist",severity:"LOW",fix:"Check directive names before dynamic creation",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),strategyTemplateSanitization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Template Sanitization Strategy",description:"Implement template input sanitization",severity:"LOW",fix:"Sanitize all user input before template processing",documentationLink:"https://owasp.org/www-community/xss-filter-evasion-cheatsheet"}),strategyContentSecurity:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Content Security Strategy",description:"Use CSP to restrict directive execution",severity:"LOW",fix:"Implement strict CSP with script-src restrictions",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP"}),strategyInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.STRATEGY,issueName:"Input Validation Strategy",description:"Validate all template inputs",severity:"LOW",fix:"Use schema validation for template inputs",documentationLink:"https://joi.dev/"})},schema:[{type:"object",properties:{trustedDirectives:{type:"array",items:{type:"string"},default:["ngIf","ngFor","ngClass","v-if","v-for","v-bind","v-on"],description:"Template directives treated as safe"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},frameworks:{type:"array",items:{type:"string"},default:["angular","vue","react","svelte"],description:"Template frameworks to analyse"},allowDynamicInComponents:{type:"boolean",default:false,description:"Allow dynamic directives inside component code"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as template sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{trustedDirectives:["ngIf","ngFor","ngClass","v-if","v-for","v-bind","v-on"],userInputVariables:["req","request","body","query","params","input","data","userInput"],frameworks:["angular","vue","react","svelte"],allowDynamicInComponents:false,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{userInputVariables=["req","request","body","query","params","input","data","userInput"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isUserInput=varName=>{return userInputVariables.some(input=>varName.includes(input))||varName.startsWith("user")};return{JSXAttribute(node){const attrName=node.name;const attrValue=node.value;if(attrName.type==="JSXIdentifier"&&attrName.name==="dangerouslySetInnerHTML"){if(attrValue&&attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;const expressionText=sourceCode.getText(expression);if(userInputVariables.some(input=>expressionText.includes(input))){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}const isNamespaceDirective=attrName.type==="JSXNamespacedName"&&(attrName.namespace.name==="v"||attrName.namespace.name==="ng")||attrName.type==="JSXIdentifier"&&(attrName.name.startsWith("ng:")||attrName.name.startsWith("v:"));if(isNamespaceDirective&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(expression.type==="Identifier"&&isUserInput(expression.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"directiveInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded directive values or validate user input"}})}}}if(attrName.type==="JSXIdentifier"){const attrNameStr=attrName.name;if(attrNameStr==="is"&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(expression.type==="Identifier"&&isUserInput(expression.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"unsafeComponentBinding",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},AssignmentExpression(node){const left=node.left;const right=node.right;if(left.type==="MemberExpression"&&left.property.type==="Identifier"&&left.property.name==="innerHTML"){const rightText=sourceCode.getText(right);if(userInputVariables.some(input=>rightText.includes(input))){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;const unsafeConfig=findUnsafeSanitizerConfig(node);if(unsafeConfig){context.report({node:unsafeConfig.node,messageId:"unsafeSanitizerConfig",data:{option:unsafeConfig.option,allowed:unsafeConfig.allowed}})}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const methodName=callee.property.name;const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(["compile","template","$compile","$interpolate"].includes(methodName)||objectName==="Handlebars"&&methodName==="compile"||objectName==="_"&&methodName==="template"||objectName==="ejs"&&methodName==="render"||objectName==="pug"&&methodName==="render"||objectName==="mustache"&&methodName==="render"){const args=node.arguments;if(args.length>0){const templateArg=args[0];if(templateArg.type==="Identifier"&&isUserInput(templateArg.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:templateArg,messageId:"userControlledTemplate",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}if(objectName==="Vue"&&methodName==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(directiveName.type==="Identifier"&&isUserInput(directiveName.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"unsafeDirectiveName",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}if(callee.type==="Identifier"&&callee.name==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(directiveName.type==="Identifier"&&isUserInput(directiveName.name)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"dynamicDirectiveCreation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},TemplateLiteral(node){let current=node;let isInDangerousContext=false;while(current){if(current.type==="JSXExpressionContainer"){if(current.parent?.type==="JSXAttribute"&&current.parent.name.type==="JSXIdentifier"&&current.parent.name.name==="dangerouslySetInnerHTML"){isInDangerousContext=true;break}}else if(current.type==="AssignmentExpression"){const left=current.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"&&left.property.name==="innerHTML"){isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext){const hasUserInput=node.expressions.some(expr=>expr.type==="Identifier"&&isUserInput(expr.name)||expr.type==="MemberExpression"&&expr.object.type==="Identifier"&&isUserInput(expr.object.name));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"templateInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Sanitize template input before insertion"}})}}}}}});
@@ -1 +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;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-z_\-. ]*$/.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;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 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:false,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:false,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=false,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;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=(()=>{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""})();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}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}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;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-z_\-. ]*$/.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;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 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;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=(()=>{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""})();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}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}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.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[^:=\\n]{0,24}[:=]\\s*\\S`,"i").test(normalized)})}function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}const REDACTION_SUGGESTIONS=[{messageId:"redactData",fix:()=>null},{messageId:"useMasking",fix:()=>null},{messageId:"removeFromLogs",fix:()=>null}];exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},hasSuggestions:true,messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),redactData:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Redact Data",description:"Redact sensitive data before logging",severity:"LOW",fix:"Redact sensitive fields before logging",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),useMasking:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Masking",description:"Use data masking function",severity:"LOW",fix:"maskSensitive(data)",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),removeFromLogs:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Remove From Logs",description:"Remove sensitive data from logs and errors",severity:"LOW",fix:"Filter sensitive data before logging",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},checkApiResponses:{type:"boolean",default:true,description:"Check API responses"}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,checkApiResponses:true}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true}=options||{};function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type==="MemberExpression"){const object=node.callee.object;const property=node.callee.property;if(property.type==="Identifier"){const methodName=property.name.toLowerCase();if(["log","info","warn","error","debug","trace"].includes(methodName)){if(object.type==="Identifier"){const objName=object.name.toLowerCase();if(objName==="console"||objName==="logger"){return true}}}}}else if(node.callee.type==="Identifier"){const calleeName=node.callee.name.toLowerCase();if(calleeName.includes("log")||calleeName.includes("logger")){return true}}return false})();if(isLoggingCall&&checkConsoleLog){for(const arg of node.arguments){if(arg.type==="Literal"&&typeof arg.value==="string"){const text=arg.value;const matchedPattern=literalCarriesSecret(text,sensitivePatterns)?containsSensitiveData(text,sensitivePatterns):null;if(matchedPattern){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:matchedPattern},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type==="BinaryExpression"&&arg.operator==="+"){const side=(arg.left?.type==="Literal"&&typeof arg.left.value==="string"&&containsSensitiveData(arg.left.value,sensitivePatterns)?{node:arg.left,pattern:containsSensitiveData(arg.left.value,sensitivePatterns)}:void 0)??(arg.right?.type==="Identifier"&&containsSensitiveData(arg.right.name,sensitivePatterns)?{node:arg.right,pattern:containsSensitiveData(arg.right.name,sensitivePatterns)}:void 0);if(side?.pattern){context.report({node:side.node,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:side.pattern},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type==="Identifier"&&arg.name){const matchedPattern2=containsSensitiveData(arg.name,sensitivePatterns);if(matchedPattern2){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:matchedPattern2},suggest:REDACTION_SUGGESTIONS});return}}}}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee&&node.callee.type==="Identifier"&&node.callee.name==="Error"){for(const arg of node.arguments){if(arg.type==="Literal"&&typeof arg.value==="string"){const text=arg.value;const matchedErrPattern=literalCarriesSecret(text,sensitivePatterns)?containsSensitiveData(text,sensitivePatterns):null;if(matchedErrPattern){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"error messages",dataType:matchedErrPattern},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type==="BinaryExpression"&&arg.operator==="+"){if(arg.left&&arg.left.type==="Literal"&&typeof arg.left.value==="string"){const leftText=arg.left.value;const leftMatchedPattern=containsSensitiveData(leftText,sensitivePatterns);if(leftMatchedPattern){context.report({node:arg.left,messageId:"sensitiveDataExposure",data:{context:"error messages",dataType:leftMatchedPattern},suggest:REDACTION_SUGGESTIONS});return}}if(arg.right&&arg.right.type==="Identifier"&&arg.right.name){const rightMatchedPattern=containsSensitiveData(arg.right.name,sensitivePatterns);if(rightMatchedPattern){context.report({node:arg.right,messageId:"sensitiveDataExposure",data:{context:"error messages",dataType:rightMatchedPattern},suggest:REDACTION_SUGGESTIONS});return}}}}}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[^:=\\n]{0,24}[:=]\\s*\\S`,"i").test(normalized)})}function memberCarriesSecret(node,patterns){const prop=node.property;const propName=node.computed?prop.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value==="string"?prop.value:null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?containsSensitiveData(propName,patterns):null;if(fromProp)return fromProp;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?containsSensitiveData(node.object.name,patterns):null}function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}const REDACTION_SUGGESTIONS=[{messageId:"redactData",fix:()=>null},{messageId:"useMasking",fix:()=>null},{messageId:"removeFromLogs",fix:()=>null}];exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},hasSuggestions:true,messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),redactData:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Redact Data",description:"Redact sensitive data before logging",severity:"LOW",fix:"Redact sensitive fields before logging",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),useMasking:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Masking",description:"Use data masking function",severity:"LOW",fix:"maskSensitive(data)",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"}),removeFromLogs:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Remove From Logs",description:"Remove sensitive data from logs and errors",severity:"LOW",fix:"Filter sensitive data before logging",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},checkApiResponses:{type:"boolean",default:true,description:"Check API responses"}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,checkApiResponses:true}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true}=options||{};function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type==="MemberExpression"){const object=node.callee.object;const property=node.callee.property;if(property.type==="Identifier"){const methodName=property.name.toLowerCase();if(["log","info","warn","error","debug","trace"].includes(methodName)){if(object.type==="Identifier"){const objName=object.name.toLowerCase();if(objName==="console"||objName==="logger"){return true}}}}}else if(node.callee.type==="Identifier"){const calleeName=node.callee.name.toLowerCase();if(calleeName.includes("log")||calleeName.includes("logger")){return true}}return false})();if(isLoggingCall&&checkConsoleLog){for(const arg of node.arguments){if(arg.type==="Literal"&&typeof arg.value==="string"){const text=arg.value;const matchedPattern=literalCarriesSecret(text,sensitivePatterns)?containsSensitiveData(text,sensitivePatterns):null;if(matchedPattern){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:matchedPattern},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type==="BinaryExpression"&&arg.operator==="+"){const side=(arg.left?.type==="Literal"&&typeof arg.left.value==="string"&&containsSensitiveData(arg.left.value,sensitivePatterns)?{node:arg.left,pattern:containsSensitiveData(arg.left.value,sensitivePatterns)}:void 0)??(arg.right?.type==="Identifier"&&containsSensitiveData(arg.right.name,sensitivePatterns)?{node:arg.right,pattern:containsSensitiveData(arg.right.name,sensitivePatterns)}:void 0);if(side?.pattern){context.report({node:side.node,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:side.pattern},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const matchedMember=memberCarriesSecret(arg,sensitivePatterns);if(matchedMember){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:matchedMember},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>e.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?containsSensitiveData(e.name,sensitivePatterns):e.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?memberCarriesSecret(e,sensitivePatterns):null).find(m=>Boolean(m));const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const fromText=arg.expressions.length>0&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;const matchedTemplate=fromExpression??fromText;if(matchedTemplate){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:matchedTemplate},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.name){const matchedPattern2=containsSensitiveData(arg.name,sensitivePatterns);if(matchedPattern2){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"logs",dataType:matchedPattern2},suggest:REDACTION_SUGGESTIONS});return}}}}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee&&node.callee.type==="Identifier"&&node.callee.name==="Error"){for(const arg of node.arguments){if(arg.type==="Literal"&&typeof arg.value==="string"){const text=arg.value;const matchedErrPattern=literalCarriesSecret(text,sensitivePatterns)?containsSensitiveData(text,sensitivePatterns):null;if(matchedErrPattern){context.report({node:arg,messageId:"sensitiveDataExposure",data:{context:"error messages",dataType:matchedErrPattern},suggest:REDACTION_SUGGESTIONS});return}}else if(arg.type==="BinaryExpression"&&arg.operator==="+"){if(arg.left&&arg.left.type==="Literal"&&typeof arg.left.value==="string"){const leftText=arg.left.value;const leftMatchedPattern=containsSensitiveData(leftText,sensitivePatterns);if(leftMatchedPattern){context.report({node:arg.left,messageId:"sensitiveDataExposure",data:{context:"error messages",dataType:leftMatchedPattern},suggest:REDACTION_SUGGESTIONS});return}}if(arg.right&&arg.right.type==="Identifier"&&arg.right.name){const rightMatchedPattern=containsSensitiveData(arg.right.name,sensitivePatterns);if(rightMatchedPattern){context.report({node:arg.right,messageId:"sensitiveDataExposure",data:{context:"error messages",dataType:rightMatchedPattern},suggest:REDACTION_SUGGESTIONS});return}}}}}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});