eslint-plugin-secure-coding 5.3.3 → 5.3.5

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": "5.3.3",
3
+ "version": "5.3.5",
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;const eslint_devkit_1=require("@interlace/eslint-devkit");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"no-sql-injection"(){return require("./rules/no-sql-injection").noSqlInjection},get"no-log-injection"(){return require("./rules/no-log-injection").noLogInjection},get"no-fail-open-auth"(){return require("./rules/no-fail-open-auth").noFailOpenAuth},get"no-homoglyph-identifiers"(){return require("./rules/no-homoglyph-identifiers").noHomoglyphIdentifiers},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},get"no-bidi-characters"(){return require("./rules/no-bidi-characters").noBidiCharacters}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-secure-coding",exports.rules);exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"5.3.3"},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-sql-injection":"error","secure-coding/no-log-injection":"error","secure-coding/no-fail-open-auth":"error","secure-coding/no-homoglyph-identifiers":"error","secure-coding/no-unsafe-deserialization":"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-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");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"no-sql-injection"(){return require("./rules/no-sql-injection").noSqlInjection},get"no-log-injection"(){return require("./rules/no-log-injection").noLogInjection},get"no-fail-open-auth"(){return require("./rules/no-fail-open-auth").noFailOpenAuth},get"no-homoglyph-identifiers"(){return require("./rules/no-homoglyph-identifiers").noHomoglyphIdentifiers},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},get"no-bidi-characters"(){return require("./rules/no-bidi-characters").noBidiCharacters}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-secure-coding",exports.rules);exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"5.3.5"},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-sql-injection":"error","secure-coding/no-log-injection":"error","secure-coding/no-fail-open-auth":"error","secure-coding/no-homoglyph-identifiers":"error","secure-coding/no-unsafe-deserialization":"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-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
@@ -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;if(meaningful.every(isPronounceable))return true;if(/[0-9]/.test(value))return false;const waived=meaningful.filter(token=>!isPronounceable(token));if(waived.some(token=>token.length>4))return false;return waived.length*2<=meaningful.length}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 isUrlOrPath(value){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value)){return!/^[^/]*\/\/[^/@]*:[^/@]*@/.test(value)}const rooted=value.replace(/^(?:<[A-Za-z_$][\w$]*>|\[[A-Za-z_$][\w$]*\])(?=\/)/,"");if(rooted!==value)return isUrlOrPath(rooted);if(!value.startsWith("/")||value.startsWith("//"))return false;const path=value.split(/[?#]/)[0];const segments=path.slice(1).split("/");if(!segments.every(segment=>/^[A-Za-z0-9._~%:@-]*$/.test(segment))){return false}const looksGenerated=segment=>/[a-z]/.test(segment)&&/[A-Z]/.test(segment)&&/[0-9]/.test(segment);if(segments.length===1){return!looksGenerated(segments[0])}return!segments.some(segment=>segment.length>=16&&looksGenerated(segment))}function echoesItsOwnSlotName(value,slotName){if(slotName==="")return false;const fold=text=>text.replace(/[-_.\s]/g,"").toLowerCase();return fold(value)===fold(slotName)}function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isUrlOrPath(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;const dunder=/^__(.+)__$/.exec(trimmed);if(dunder!==null){const inner=dunder[1];const candidate=inner.trim();return/^[^A-Za-z]*[A-Z]{3,}/.test(candidate)&&!looksRandom(candidate)}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}if(/^0x[A-Fa-f0-9]{40}$/.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"){const named=(0,eslint_devkit_1.propertyName)(left);if(named!==null)return named.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{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:{credentialWords:{type:"array",items:{type:"string"},default:[...CREDENTIAL_VARIABLE_NAMES],description:"Variable and property names this project uses for a credential. REPLACES the default list."},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 credentialWords=new Set((options.credentialWords??[...CREDENTIAL_VARIABLE_NAMES]).map(w=>w.toLowerCase()));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"){const slot=(0,eslint_devkit_1.propertyName)(left);if(slot!==null&&LABEL_CONTEXT_NAMES.has(slot))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;const keyText=key.type==="Identifier"?key.name:(0,eslint_devkit_1.staticString)(key)!==null?(0,eslint_devkit_1.staticString)(key):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(credentialWords.has(lower)||credentialWords.has(singular))return true;return[...credentialWords].some(word=>lower.endsWith(word)||lower.endsWith(`${word}s`))};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"){const slot=(0,eslint_devkit_1.propertyName)(left);if(slot!==null&&matches(slot))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"&&(0,eslint_devkit_1.propertyName)(left.object)==="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 echoesSlot=confidence!=="structural"&&parent!==void 0&&echoesItsOwnSlotName(value,slotNameOf(parent));if(echoesSlot){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value,placeholderWordSet);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!echoesSlot&&!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.isStyleToken=isStyleToken;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;if(meaningful.every(isPronounceable))return true;if(/[0-9]/.test(value))return false;const waived=meaningful.filter(token=>!isPronounceable(token));if(waived.some(token=>token.length>4))return false;return waived.length*2<=meaningful.length}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 isStyleToken(value){if(/\b(?:var|env)\(\s*--[\w-]+/.test(value))return true;if(/^--[a-z][\w-]*$/i.test(value))return true;if(/^[a-z][\w-]*-\[[^\]]+\]$/i.test(value))return true;return false}function isUrlOrPath(value){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(value)){return!/^[^/]*\/\/[^/@]*:[^/@]*@/.test(value)}const rooted=value.replace(/^(?:<[A-Za-z_$][\w$]*>|\[[A-Za-z_$][\w$]*\])(?=\/)/,"");if(rooted!==value)return isUrlOrPath(rooted);if(!value.startsWith("/")||value.startsWith("//"))return false;const path=value.split(/[?#]/)[0];const segments=path.slice(1).split("/");if(!segments.every(segment=>/^[A-Za-z0-9._~%:@-]*$/.test(segment))){return false}const looksGenerated=segment=>/[a-z]/.test(segment)&&/[A-Z]/.test(segment)&&/[0-9]/.test(segment);if(segments.length===1){return!looksGenerated(segments[0])}return!segments.some(segment=>segment.length>=16&&looksGenerated(segment))}function echoesItsOwnSlotName(value,slotName){if(slotName==="")return false;const fold=text=>text.replace(/[-_.\s]/g,"").toLowerCase();return fold(value)===fold(slotName)}function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isUrlOrPath(value))return false;if(isStyleToken(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;const dunder=/^__(.+)__$/.exec(trimmed);if(dunder!==null){const inner=dunder[1];const candidate=inner.trim();return/^[^A-Za-z]*[A-Z]{3,}/.test(candidate)&&!looksRandom(candidate)}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}if(/^0x[A-Fa-f0-9]{40}$/.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"){const named=(0,eslint_devkit_1.propertyName)(left);if(named!==null)return named.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{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:{credentialWords:{type:"array",items:{type:"string"},default:[...CREDENTIAL_VARIABLE_NAMES],description:"Variable and property names this project uses for a credential. REPLACES the default list."},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 credentialWords=new Set((options.credentialWords??[...CREDENTIAL_VARIABLE_NAMES]).map(w=>w.toLowerCase()));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"){const slot=(0,eslint_devkit_1.propertyName)(left);if(slot!==null&&LABEL_CONTEXT_NAMES.has(slot))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;const keyText=key.type==="Identifier"?key.name:(0,eslint_devkit_1.staticString)(key)!==null?(0,eslint_devkit_1.staticString)(key):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(credentialWords.has(lower)||credentialWords.has(singular))return true;return[...credentialWords].some(word=>lower.endsWith(word)||lower.endsWith(`${word}s`))};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"){const slot=(0,eslint_devkit_1.propertyName)(left);if(slot!==null&&matches(slot))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"&&(0,eslint_devkit_1.propertyName)(left.object)==="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 echoesSlot=confidence!=="structural"&&parent!==void 0&&echoesItsOwnSlotName(value,slotNameOf(parent));if(echoesSlot){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value,placeholderWordSet);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!echoesSlot&&!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.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"},reportLooseEquality:{type:"boolean",default:true,description:"Report `==` between non-secret operands. Turn off to keep only the secret-comparison findings and leave generic type coercion to eqeqeq."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,ignorePatterns:[],reportLooseEquality:true}],create(context,[options={}]){const{allowInTests=false,ignorePatterns=[],reportLooseEquality=true}=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);const key=(0,eslint_devkit_1.propertyName)(n);if(key!==null)out.push(key);else walk(n.property)}else if(n.type==="CallExpression"){walk(n.callee)}else if(n.type==="ConditionalExpression"){walk(n.consequent);walk(n.alternate)}else if(n.type==="TSAsExpression"||n.type==="TSSatisfiesExpression"||n.type==="TSNonNullExpression"){walk(n.expression)}};function resolveIdentifier(identifier){for(let scope=scopeAtNode;scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite());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&&(0,eslint_devkit_1.propertyName)(expr)==="length"};if(isLengthComparison(node.left)||isLengthComparison(node.right)){return}const isNonSecretLiteral=expr=>expr.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&(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 comparesSecret=isPotentialSecret(node.left)||isPotentialSecret(node.right);if(!reportLooseEquality&&!comparesSecret){return}const strictOperator=node.operator==="=="?"===":"!==";const leftText=sourceCode.getText(node.left);const rightText=sourceCode.getText(node.right);const example=`${leftText} ${strictOperator} ${rightText}`;context.report({node,messageId:"insecureComparison",data:{operator:node.operator,strictOperator,example},suggest:[{messageId:"useStrictEquality",fix:fixer=>{return fixer.replaceText(node,example)}}]})}}return{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"},reportLooseEquality:{type:"boolean",default:true,description:"Report `==` between non-secret operands. Turn off to keep only the secret-comparison findings and leave generic type coercion to eqeqeq."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,ignorePatterns:[],reportLooseEquality:true}],create(context,[options={}]){const{allowInTests=false,ignorePatterns=[],reportLooseEquality=true}=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);const key=(0,eslint_devkit_1.propertyName)(n);if(key!==null)out.push(key);else walk(n.property)}else if(n.type==="CallExpression"){walk(n.callee)}else if(n.type==="ConditionalExpression"){walk(n.consequent);walk(n.alternate)}else if(n.type==="TSAsExpression"||n.type==="TSSatisfiesExpression"||n.type==="TSNonNullExpression"){walk(n.expression)}};function resolveIdentifier(identifier){for(let scope=scopeAtNode;scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===identifier.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite());const isObjectDestructured=variable.defs.some(def=>def.type==="Variable"&&def.node.id.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern);if(!isObjectDestructured&&writes.length===1&&writes[0].writeExpr){walk(writes[0].writeExpr)}for(const def of variable.defs){if(def.type!=="Variable")continue;out.push(...destructuringKeys(def.node.id,def.name))}return}}walk(expr);return out};const isPotentialSecret=expr=>namesIn(expr).flatMap(nameSegments).some(segment=>secretKeywords.has(segment));if((node.operator==="==="||node.operator==="!==")&&(isPotentialSecret(node.left)||isPotentialSecret(node.right))){const isLengthComparison=expr=>{return expr.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(expr)==="length"};if(isLengthComparison(node.left)||isLengthComparison(node.right)){return}const isNonSecretLiteral=expr=>expr.type===eslint_devkit_1.AST_NODE_TYPES.Literal||expr.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&expr.expressions.length===0||expr.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&expr.argument.type===eslint_devkit_1.AST_NODE_TYPES.Literal||expr.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&expr.name==="undefined";if(isNonSecretLiteral(node.left)||isNonSecretLiteral(node.right)){return}const leftText=sourceCode.getText(node.left);const rightText=sourceCode.getText(node.right);const example=`crypto.timingSafeEqual(Buffer.from(${leftText}), Buffer.from(${rightText}))`;context.report({node,messageId:"timingUnsafeComparison",data:{operator:node.operator,strictOperator:node.operator,example},suggest:[{messageId:"useTimingSafeEqual",fix:fixer=>fixer.replaceText(node,example)}]});return}if(node.operator==="=="||node.operator==="!="){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isNullLiteral(node.left)||isNullLiteral(node.right)){return}if(isStringTyped(node.left)&&isStringTyped(node.right)){return}const comparesSecret=isPotentialSecret(node.left)||isPotentialSecret(node.right);if(!reportLooseEquality&&!comparesSecret){return}const strictOperator=node.operator==="=="?"===":"!==";const leftText=sourceCode.getText(node.left);const rightText=sourceCode.getText(node.right);const example=`${leftText} ${strictOperator} ${rightText}`;context.report({node,messageId:"insecureComparison",data:{operator:node.operator,strictOperator,example},suggest:[{messageId:"useStrictEquality",fix:fixer=>{return fixer.replaceText(node,example)}}]})}}return{BinaryExpression:checkBinaryExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUncheckedLoopCondition=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noUncheckedLoopCondition=(0,eslint_devkit_1.createRule)({name:"no-unchecked-loop-condition",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unchecked-loop-condition.md",description:"Detects unchecked loop conditions that could cause DoS",cwe:"CWE-400"},messages:{uncheckedLoopCondition:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unchecked Loop Condition",cwe:"CWE-400",description:"Loop condition may cause DoS through excessive iterations",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),infiniteLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Infinite Loop",cwe:"CWE-400",description:"Loop may run indefinitely",severity:"CRITICAL",fix:"Add termination condition or iteration limit",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),userControlledLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Loop Bound",cwe:"CWE-606",description:"Loop bound controlled by user input",severity:"HIGH",fix:"Limit maximum iterations or validate input",documentationLink:"https://cwe.mitre.org/data/definitions/606.html"}),missingLoopTermination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Loop Termination",cwe:"CWE-400",description:"Loop lacks clear termination condition",severity:"MEDIUM",fix:"Add explicit termination condition",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),largeLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Large Loop Bound",cwe:"CWE-400",description:"Loop may iterate excessively",severity:"MEDIUM",fix:"Limit maximum iterations",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),unsafeRecursion:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Recursion",cwe:"CWE-674",description:"Recursive function may cause stack overflow",severity:"HIGH",fix:"Add recursion depth limit or use iterative approach",documentationLink:"https://cwe.mitre.org/data/definitions/674.html"})},schema:[{type:"object",properties:{maxStaticIterations:{type:"number",minimum:100,default:1e4,description:"Literal iteration count above which a loop is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},allowWhileTrueWithBreak:{type:"boolean",default:true,description:"Allow `while (true)` when the body contains a `break`"},maxRecursionDepth:{type:"number",minimum:1,default:10,description:"Recursion depth above which a call is reported"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as loop protectors"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{maxStaticIterations:1e4,userInputVariables:["req","request","body","query","params","input","data"],allowWhileTrueWithBreak:true,maxRecursionDepth:10,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const functionCalls=new Map;const reportedRecursion=new Set;const currentFunctionStack=[];const taintedVariables=new Set;const REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"]);const isUserInput=varName=>{if(taintedVariables.has(varName)){return true}const lowerVarName=varName.toLowerCase();const isUsingDefaults=userInputVariables.length===7&&userInputVariables.includes("req")&&userInputVariables.includes("input");if(!isUsingDefaults){return userInputVariables.some(input=>lowerVarName===input.toLowerCase())}return REQUEST_OBJECTS.has(lowerVarName)};const checkIfCollectionIsValidated=(forOfNode,collection)=>{const guarded=collection;const validates=test=>{let sawArrayCheck=false;let sawLengthComparison=false;const walk=node=>{if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Array"&&(0,eslint_devkit_1.propertyName)(node.callee)==="isArray"&&node.arguments.some(a=>a.type!=="SpreadElement"&&samePath(a,guarded))){sawArrayCheck=true}if(node.type==="BinaryExpression"&&["<","<=",">",">=","===","==","!==","!="].includes(node.operator)){for(const side of[node.left,node.right]){if(side.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(side)==="length"&&samePath(side.object,guarded)){sawLengthComparison=true}}}const walkIfNode=value=>{if(value&&typeof value==="object"&&"type"in value)walk(value)};for(const key of["left","right","argument","expression","test","object","callee"]){walkIfNode(node[key])}const args=node.arguments;if(Array.isArray(args)){for(const a of args)walkIfNode(a)}};walk(test);return sawArrayCheck&&sawLengthComparison};for(let current=forOfNode.parent;current;current=current.parent){if(current.type==="IfStatement"&&validates(current.test))return true;if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}for(let current=forOfNode;current;current=current.parent){const parent=current.parent;if(parent?.type==="BlockStatement"||parent?.type==="Program"){const body=parent.body;const index=body.indexOf(current);for(const statement of body.slice(0,index)){if(statement.type==="IfStatement"&&validates(statement.test))return true}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}return false};const resolveVariable=node=>{const scope=sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(variable)return variable}return null};const samePath=(left,right)=>{const a=(0,eslint_devkit_3.unwrapTypeSyntax)(left);const b=(0,eslint_devkit_3.unwrapTypeSyntax)(right);if(a.type==="Identifier"&&b.type==="Identifier"){const va=resolveVariable(a);const vb=resolveVariable(b);return va||vb?va===vb:a.name===b.name}if(a.type==="MemberExpression"&&b.type==="MemberExpression"){return(0,eslint_devkit_1.propertyName)(a)===(0,eslint_devkit_1.propertyName)(b)&&samePath(a.object,b.object)}return false};const isClamped=node=>{const expression=(0,eslint_devkit_3.unwrapTypeSyntax)(node);if(expression.type==="CallExpression"&&expression.callee.type==="MemberExpression"&&!expression.callee.computed&&expression.callee.object.type==="Identifier"&&expression.callee.object.name==="Math"&&expression.callee.property.type==="Identifier"&&["min","max"].includes(expression.callee.property.name)){return true}if(expression.type==="BinaryExpression"||expression.type==="LogicalExpression"){return isClamped(expression.left)||isClamped(expression.right)}if(expression.type==="ConditionalExpression"){return isClamped(expression.consequent)&&isClamped(expression.alternate)}return false};const involvesUserInput=expression=>{const checkExpression=raw=>{const node=(0,eslint_devkit_3.unwrapTypeSyntax)(raw);if(node.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(node)==="length"){return false}const objectText=sourceCode.getText(node.object);if(isUserInput(objectText)){return true}return checkExpression(node.object)}if(node.type==="Identifier"){return isUserInput(node.name)}if(node.type==="CallExpression"){return checkExpression(node.callee)||node.arguments.filter(arg=>arg.type!=="SpreadElement").some(arg=>checkExpression(arg))}if(node.type==="LogicalExpression"){return node.operator==="&&"?checkExpression(node.right):checkExpression(node.left)||checkExpression(node.right)}if(node.type==="BinaryExpression"){return checkExpression(node.left)||checkExpression(node.right)}if(node.type==="UpdateExpression"){return checkExpression(node.argument)}if(node.type==="UnaryExpression"){return checkExpression(node.argument)}return false};return checkExpression(expression)};const hasBreakStatement=loopBody=>{let hasBreak=false;const visited=new Set;const checkNode=(node,depth=0)=>{if(depth>10||visited.has(node)){return}visited.add(node);if(node.type==="BreakStatement"){hasBreak=true;return}for(const key in node){const child=node[key];if(child&&typeof child==="object"){if("type"in child){checkNode(child,depth+1)}else if(Array.isArray(child)){child.forEach(item=>{if(item&&typeof item==="object"&&"type"in item){checkNode(item,depth+1)}})}}}};checkNode(loopBody);return hasBreak};const isUnconditionalSelfCall=call=>{const BRANCHING=new Set(["IfStatement","ConditionalExpression","LogicalExpression","SwitchStatement","SwitchCase","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement","TryStatement","CatchClause"]);let child=call;for(let current=call.parent;current;child=current,current=current.parent){if(BRANCHING.has(current.type))return false;if(current.type==="BlockStatement"){const index=current.body.indexOf(child);const preceding=current.body.slice(0,index);if(preceding.some(statement=>statement.type==="IfStatement"&&exits(statement))){return false}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return true}}return false};const exits=node=>{if(node.type==="ReturnStatement"||node.type==="ThrowStatement")return true;for(const key in node){const child=node[key];if(key==="parent"||!child||typeof child!=="object")continue;if("type"in child){if(exits(child))return true}else if(Array.isArray(child)){for(const item of child){if(item&&typeof item==="object"&&"type"in item&&exits(item))return true}}}return false};const estimateIterations=loop=>{const test=loop.test;if(test&&test.type==="BinaryExpression"){if(test.operator==="<"||test.operator==="<="||test.operator===">"||test.operator===">="){const right=test.right;if(right.type==="Literal"&&typeof right.value==="number"){return Math.abs(right.value)}}}return null};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){const varName=declarator.id.name;const hasUserInput=involvesUserInput(declarator.init);const isSanitized=isClamped(declarator.init);if(hasUserInput&&!isSanitized){taintedVariables.add(varName)}}}},FunctionDeclaration(node){if(node.id){currentFunctionStack.push(node.id.name)}},"FunctionDeclaration:exit"(node){if(node.id&&currentFunctionStack[currentFunctionStack.length-1]===node.id.name){currentFunctionStack.pop()}},CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"){const functionName=callee.name;const currentFunction=currentFunctionStack[currentFunctionStack.length-1];if(currentFunction&&functionName===currentFunction){const callCount=(functionCalls.get(functionName)||0)+1;functionCalls.set(functionName,callCount);if(!reportedRecursion.has(functionName)){if(callCount>maxRecursionDepth||isUnconditionalSelfCall(node)){if(safetyChecker.isSafe(node,context)){return}reportedRecursion.add(functionName);context.report({node,messageId:"unsafeRecursion",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},WhileStatement(node){const test=node.test;if(test.type==="Literal"&&test.value===true){const hasBreak=hasBreakStatement(node.body);if(allowWhileTrueWithBreak&&hasBreak){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}},ForStatement(node){if(!node.test&&!node.update){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(!node.test){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingLoopTermination",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}const estimatedIterations=estimateIterations(node);if(estimatedIterations&&estimatedIterations>maxStaticIterations){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"largeLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},DoWhileStatement(node){const test=node.test;if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},ForInStatement(node){const right=node.right;if(involvesUserInput(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size or add iteration timeout"}})}},ForOfStatement(node){const right=node.right;if(involvesUserInput(right)){const isValidated=checkIfCollectionIsValidated(node,right);if(isValidated){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size before iteration"}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUncheckedLoopCondition=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noUncheckedLoopCondition=(0,eslint_devkit_1.createRule)({name:"no-unchecked-loop-condition",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unchecked-loop-condition.md",description:"Detects unchecked loop conditions that could cause DoS",cwe:"CWE-400"},messages:{uncheckedLoopCondition:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unchecked Loop Condition",cwe:"CWE-400",description:"Loop condition may cause DoS through excessive iterations",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),infiniteLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Infinite Loop",cwe:"CWE-400",description:"Loop may run indefinitely",severity:"CRITICAL",fix:"Add termination condition or iteration limit",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),userControlledLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Loop Bound",cwe:"CWE-606",description:"Loop bound controlled by user input",severity:"HIGH",fix:"Limit maximum iterations or validate input",documentationLink:"https://cwe.mitre.org/data/definitions/606.html"}),missingLoopTermination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Loop Termination",cwe:"CWE-400",description:"Loop lacks clear termination condition",severity:"MEDIUM",fix:"Add explicit termination condition",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),largeLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Large Loop Bound",cwe:"CWE-400",description:"Loop may iterate excessively",severity:"MEDIUM",fix:"Limit maximum iterations",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),unsafeRecursion:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Recursion",cwe:"CWE-674",description:"Recursive function may cause stack overflow",severity:"HIGH",fix:"Add recursion depth limit or use iterative approach",documentationLink:"https://cwe.mitre.org/data/definitions/674.html"})},schema:[{type:"object",properties:{maxStaticIterations:{type:"number",minimum:100,default:1e4,description:"Literal iteration count above which a loop is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},allowWhileTrueWithBreak:{type:"boolean",default:true,description:"Allow `while (true)` when the body contains a `break`"},maxRecursionDepth:{type:"number",minimum:1,default:10,description:"Recursion depth above which a call is reported"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as loop protectors"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{maxStaticIterations:1e4,userInputVariables:["req","request","body","query","params","input","data"],allowWhileTrueWithBreak:true,maxRecursionDepth:10,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const functionCalls=new Map;const reportedRecursion=new Set;const currentFunctionStack=[];const taintedVariables=new Set;const REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"]);const isUserInput=varName=>{if(taintedVariables.has(varName)){return true}const lowerVarName=varName.toLowerCase();const isUsingDefaults=userInputVariables.length===7&&userInputVariables.includes("req")&&userInputVariables.includes("input");if(!isUsingDefaults){return userInputVariables.some(input=>lowerVarName===input.toLowerCase())}return REQUEST_OBJECTS.has(lowerVarName)};const checkIfCollectionIsValidated=(forOfNode,collection)=>{const guarded=collection;const validates=test=>{let sawArrayCheck=false;let sawLengthComparison=false;const walk=node=>{if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Array"&&(0,eslint_devkit_1.propertyName)(node.callee)==="isArray"&&node.arguments.some(a=>a.type!=="SpreadElement"&&samePath(a,guarded))){sawArrayCheck=true}if(node.type==="BinaryExpression"&&["<","<=",">",">=","===","==","!==","!="].includes(node.operator)){for(const side of[node.left,node.right]){if(side.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(side)==="length"&&samePath(side.object,guarded)){sawLengthComparison=true}}}const walkIfNode=value=>{if(value&&typeof value==="object"&&"type"in value)walk(value)};for(const key of["left","right","argument","expression","test","object","callee"]){walkIfNode(node[key])}const args=node.arguments;if(Array.isArray(args)){for(const a of args)walkIfNode(a)}};walk(test);return sawArrayCheck&&sawLengthComparison};for(let current=forOfNode.parent;current;current=current.parent){if(current.type==="IfStatement"&&validates(current.test))return true;if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}for(let current=forOfNode;current;current=current.parent){const parent=current.parent;if(parent?.type==="BlockStatement"||parent?.type==="Program"){const body=parent.body;const index=body.indexOf(current);for(const statement of body.slice(0,index)){if(statement.type==="IfStatement"&&validates(statement.test))return true}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}return false};const resolveVariable=node=>{const scope=sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(variable)return variable}return null};const samePath=(left,right)=>{const a=(0,eslint_devkit_3.unwrapTypeSyntax)(left);const b=(0,eslint_devkit_3.unwrapTypeSyntax)(right);if(a.type==="Identifier"&&b.type==="Identifier"){const va=resolveVariable(a);const vb=resolveVariable(b);return va||vb?va===vb:a.name===b.name}if(a.type==="MemberExpression"&&b.type==="MemberExpression"){return(0,eslint_devkit_1.propertyName)(a)===(0,eslint_devkit_1.propertyName)(b)&&samePath(a.object,b.object)}return false};const isClamped=node=>{const expression=(0,eslint_devkit_3.unwrapTypeSyntax)(node);if(expression.type==="CallExpression"&&expression.callee.type==="MemberExpression"&&!expression.callee.computed&&expression.callee.object.type==="Identifier"&&expression.callee.object.name==="Math"&&expression.callee.property.type==="Identifier"&&["min","max"].includes(expression.callee.property.name)){return true}if(expression.type==="BinaryExpression"||expression.type==="LogicalExpression"){return isClamped(expression.left)||isClamped(expression.right)}if(expression.type==="ConditionalExpression"){return isClamped(expression.consequent)&&isClamped(expression.alternate)}return false};const involvesUserInput=expression=>{const checkExpression=raw=>{const node=(0,eslint_devkit_3.unwrapTypeSyntax)(raw);if(node.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(node)==="length"){return false}const objectText=sourceCode.getText(node.object);if(isUserInput(objectText)){return true}return checkExpression(node.object)}if(node.type==="Identifier"){return isUserInput(node.name)}if(node.type==="CallExpression"){return checkExpression(node.callee)||node.arguments.filter(arg=>arg.type!=="SpreadElement").some(arg=>checkExpression(arg))}if(node.type==="LogicalExpression"){return node.operator==="&&"?checkExpression(node.right):checkExpression(node.left)||checkExpression(node.right)}if(node.type==="BinaryExpression"){return checkExpression(node.left)||checkExpression(node.right)}if(node.type==="UpdateExpression"){return checkExpression(node.argument)}if(node.type==="UnaryExpression"){return checkExpression(node.argument)}return false};return checkExpression(expression)};const hasBreakStatement=loopBody=>{let hasBreak=false;const visited=new Set;const checkNode=(node,depth=0)=>{if(depth>10||visited.has(node)){return}visited.add(node);if(node.type==="BreakStatement"){hasBreak=true;return}for(const key in node){const child=node[key];if(child&&typeof child==="object"){if("type"in child){checkNode(child,depth+1)}else if(Array.isArray(child)){child.forEach(item=>{if(item&&typeof item==="object"&&"type"in item){checkNode(item,depth+1)}})}}}};checkNode(loopBody);return hasBreak};const hasLoopExit=loopBody=>{let found=false;const innerLabels=new Set;const walk=(node,insideNestedBreakable)=>{if(found)return;switch(node.type){case"FunctionDeclaration":case"FunctionExpression":case"ArrowFunctionExpression":return;case"BreakStatement":if(node.label===null){if(!insideNestedBreakable)found=true}else if(!innerLabels.has(node.label.name)){found=true}return;case"ReturnStatement":case"ThrowStatement":found=true;return;default:break}if(node.type==="LabeledStatement")innerLabels.add(node.label.name);const breakable=insideNestedBreakable||node.type==="ForStatement"||node.type==="ForInStatement"||node.type==="ForOfStatement"||node.type==="WhileStatement"||node.type==="DoWhileStatement"||node.type==="SwitchStatement";for(const key of Object.keys(node)){if(key==="parent")continue;const child=node[key];if(child===null||typeof child!=="object")continue;if(Array.isArray(child)){for(const item of child){if(item!==null&&typeof item==="object"&&"type"in item){walk(item,breakable)}}}else if("type"in child){walk(child,breakable)}}};walk(loopBody,false);return found};const isUnconditionalSelfCall=call=>{const BRANCHING=new Set(["IfStatement","ConditionalExpression","LogicalExpression","SwitchStatement","SwitchCase","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement","TryStatement","CatchClause"]);let child=call;for(let current=call.parent;current;child=current,current=current.parent){if(BRANCHING.has(current.type))return false;if(current.type==="BlockStatement"){const index=current.body.indexOf(child);const preceding=current.body.slice(0,index);if(preceding.some(statement=>statement.type==="IfStatement"&&exits(statement))){return false}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return true}}return false};const exits=node=>{if(node.type==="ReturnStatement"||node.type==="ThrowStatement")return true;for(const key in node){const child=node[key];if(key==="parent"||!child||typeof child!=="object")continue;if("type"in child){if(exits(child))return true}else if(Array.isArray(child)){for(const item of child){if(item&&typeof item==="object"&&"type"in item&&exits(item))return true}}}return false};const estimateIterations=loop=>{const test=loop.test;if(test&&test.type==="BinaryExpression"){if(test.operator==="<"||test.operator==="<="||test.operator===">"||test.operator===">="){const right=test.right;if(right.type==="Literal"&&typeof right.value==="number"){return Math.abs(right.value)}}}return null};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){const varName=declarator.id.name;const hasUserInput=involvesUserInput(declarator.init);const isSanitized=isClamped(declarator.init);if(hasUserInput&&!isSanitized){taintedVariables.add(varName)}}}},FunctionDeclaration(node){if(node.id){currentFunctionStack.push(node.id.name)}},"FunctionDeclaration:exit"(node){if(node.id&&currentFunctionStack[currentFunctionStack.length-1]===node.id.name){currentFunctionStack.pop()}},CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"){const functionName=callee.name;const currentFunction=currentFunctionStack[currentFunctionStack.length-1];if(currentFunction&&functionName===currentFunction){const callCount=(functionCalls.get(functionName)||0)+1;functionCalls.set(functionName,callCount);if(!reportedRecursion.has(functionName)){if(callCount>maxRecursionDepth||isUnconditionalSelfCall(node)){if(safetyChecker.isSafe(node,context)){return}reportedRecursion.add(functionName);context.report({node,messageId:"unsafeRecursion",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},WhileStatement(node){const test=node.test;if(test.type==="Literal"&&test.value===true){const hasBreak=hasBreakStatement(node.body);if(allowWhileTrueWithBreak&&hasBreak){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}},ForStatement(node){if(!node.test&&!node.update){if(safetyChecker.isSafe(node,context)){return}if(allowWhileTrueWithBreak&&hasLoopExit(node.body)){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(!node.test){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingLoopTermination",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}const estimatedIterations=estimateIterations(node);if(estimatedIterations&&estimatedIterations>maxStaticIterations){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"largeLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},DoWhileStatement(node){const test=node.test;if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},ForInStatement(node){const right=node.right;if(involvesUserInput(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size or add iteration timeout"}})}},ForOfStatement(node){const right=node.right;if(involvesUserInput(right)){const isValidated=checkIfCollectionIsValidated(node,right);if(isValidated){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size before iteration"}})}}}}});