eslint-plugin-secure-coding 5.0.0 → 5.1.1

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.0.0",
3
+ "version": "5.1.1",
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",
@@ -78,7 +78,7 @@
78
78
  "node": ">=18.0.0"
79
79
  },
80
80
  "dependencies": {
81
- "@interlace/eslint-devkit": "^1.16.1",
81
+ "@interlace/eslint-devkit": "^1.17.0",
82
82
  "scslre": "^0.3.0",
83
83
  "@eslint-community/regexpp": "^4.10.0"
84
84
  },
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.0.0"},rules:exports.rules};const recommendedRules={"secure-coding/no-graphql-injection":"warn","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-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-improper-type-validation":"error","secure-coding/no-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;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.1.1"},rules:exports.rules};const recommendedRules={"secure-coding/no-graphql-injection":"warn","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-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;return meaningful.every(isPronounceable)}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;if(isNaturalWordString(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const DEFAULT_PLACEHOLDER_WORDS=["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"];function isPlaceholderValue(value,words){const trimmed=value.trim();if(trimmed.length===0)return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>words.has(token))}function isPublishableKeyValue(value){if(/^pk_(?:live|test)_[A-Za-z0-9_-]{8,}$/.test(value))return true;if(/^phc_[A-Za-z0-9]{20,}$/.test(value))return true;if(/^https?:\/\/[A-Za-z0-9]+@[A-Za-z0-9.-]+(?::\d+)?\/\d+$/.test(value)){return true}return false}const SECRET_SIDE_VALUE=/^(?:sk|rk)_(?:live|test)_|^sk-[A-Za-z0-9]|^gh[pousr]_|^ph[xs]_|^sntry[su]_|^xox[baprs]-|^AKIA[0-9A-Z]{16}$|^ey[A-Za-z0-9_-]+\.ey|-----BEGIN|^(?:mysql|postgres|mongodb|redis):\/\//;const SECRET_SIDE_SLOT=/secret|private|signing|password|passwd|serviceaccount|serverkey|adminkey|masterkey/;const PUBLISHABLE_VENDORS=[{vendor:"Bugsnag",packages:["bugsnag","bugsnag-js","bugsnag-build-reporter","bugsnag-sourcemaps"],scopes:["@bugsnag"],named:/bugsnag/,slots:/^(?:bugsnag)?(?:notifier)?(?:api)?key$/},{vendor:"Sentry",scopes:["@sentry"],named:/sentry/,slots:/^(?:sentry)?dsn$/},{vendor:"PostHog",packages:["posthog-js","posthog-node"],named:/posthog/,slots:/^(?:posthog)?(?:project)?(?:api)?key$/},{vendor:"Segment",packages:["analytics-node"],scopes:["@segment"],named:/segment/,slots:/^(?:segment)?write(?:key|token)$/},{vendor:"Amplitude",packages:["amplitude-js"],scopes:["@amplitude"],named:/amplitude/,slots:/^(?:amplitude)?(?:api)?key$/},{vendor:"Mixpanel",packages:["mixpanel","mixpanel-browser"],named:/mixpanel/,slots:/^(?:mixpanel)?(?:project)?token$/},{vendor:"Firebase",packages:["firebase"],scopes:["@firebase"],named:/firebase/,slots:/^(?:firebase)?(?:web)?apikey$/}];const VENDOR_PROBES=PUBLISHABLE_VENDORS.map(entry=>({entry,loadsSdk:(0,eslint_devkit_2.createModuleEvidence)({packages:entry.packages,scopes:entry.scopes})}));function slotNameOf(parent){if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){return parent.id.name.toLowerCase()}if(parent.type==="Property"){const key=parent.key;if(key.type==="Identifier")return key.name.toLowerCase();return String(key.value).toLowerCase()}if(parent.type==="AssignmentExpression"){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){return left.property.name.toLowerCase()}}return""}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch(error){continue}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(value.length>=32&&CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"})},schema:[{type:"object",properties:{ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:true,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"},placeholderWords:{type:"array",items:{type:"string"},default:DEFAULT_PLACEHOLDER_WORDS,description:"Words that mark a value as a self-evident stand-in rather than a secret, matched as a WHOLE token inside the value and never as a substring. Replaces the built-in list. Read only when `allowPlaceholders` is true."},additionalPlaceholderWords:{type:"array",items:{type:"string"},default:[],description:"Extra placeholder words, on top of `placeholderWords`."}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:true,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],allowPlaceholders:true,placeholderWords:DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords:[]}],create(context){const options=context.options[0]||{};const{ignorePatterns=[],allowInTests=true,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true,placeholderWords=DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords=[]}=options;const placeholderWordSet=new Set([...placeholderWords,...additionalPlaceholderWords]);const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_2.isTestFilePath)(filename);const compiledIgnorePatterns=(0,eslint_devkit_1.compileUserPatterns)(ignorePatterns);const detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};const LABEL_CONTEXT_NAMES=new Set(["type","name","id","placeholder","label","title","role","autocomplete","autoFocus","autocapitalize","inputmode","aria-label","aria-labelledby","aria-describedby","fieldName","fieldType","fieldLabel","inputType","inputName","displayName","columnName","paramName","i18nKey","translationKey","messageKey"]);function isLabelContext(node,parent){if(!parent)return false;if(parent.type==="ObjectExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const n=parent.id.name.toLowerCase();if(LABEL_CONTEXT_NAMES.has(n)||n==="labels"||n.endsWith("label")||n.endsWith("labels")||n.endsWith("name")||n.endsWith("placeholder"))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(LABEL_CONTEXT_NAMES.has(left.property.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;const keyText=key.type==="Identifier"?key.name:key.type==="Literal"&&typeof key.value==="string"?key.value:null;if(keyText!==null&&node.type==="Literal"&&typeof node.value==="string"){const keyTokens=keyText.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);if(keyTokens.includes(node.value.toUpperCase()))return true}if(key.type==="Identifier"&&LABEL_CONTEXT_NAMES.has(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(LABEL_CONTEXT_NAMES.has(key.value))return true}const obj=parent.parent;if(obj?.type==="ObjectExpression"){const grand=obj.parent;if(grand)return isLabelContext(node,grand)}}if(parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"){const callee=parent.callee;const methodName=callee.property.name;if(methodName==="setAttribute"||methodName==="getAttribute"){const args=parent.arguments;if(args[1]===node)return true}}if(parent.type==="JSXAttribute")return true;return false}function inferCredentialTypeFromContext(parent){const name=slotNameOf(parent);if(/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))return"apikey";return"other"}function isCredentialContext(node,parent){if(!parent)return false;const matches=name=>{const lower=name.toLowerCase();if(lower==="key"||lower==="keys"){return node.type==="Literal"&&typeof node.value==="string"&&looksRandom(node.value)}const singular=lower.endsWith("s")?lower.slice(0,-1):lower;if(CREDENTIAL_VARIABLE_NAMES.has(lower)||CREDENTIAL_VARIABLE_NAMES.has(singular))return true;return lower.endsWith("apikey")||lower.endsWith("apikeys")||lower.endsWith("secret")||lower.endsWith("secrets")||lower.endsWith("token")||lower.endsWith("tokens")||lower.endsWith("password")||lower.endsWith("passwords")||lower.endsWith("passwd")||lower.endsWith("credential")||lower.endsWith("credentials")};if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isCredentialContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){if(matches(parent.id.name))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(matches(left.property.name))return true}if(left.type==="Identifier"){if(matches(left.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&matches(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(matches(key.value))return true}}return false}let loadedVendors=null;function vendorsInFile(){if(loadedVendors===null){const found=new Set;for(const{entry,loadsSdk}of VENDOR_PROBES){if(loadsSdk(context.sourceCode.ast))found.add(entry.vendor)}loadedVendors=found}return loadedVendors}function isPublishableKey(value,parent){if(SECRET_SIDE_VALUE.test(value))return false;if(isPublishableKeyValue(value))return true;const slot=slotNameOf(parent);if(slot===""||SECRET_SIDE_SLOT.test(slot))return false;for(const{entry}of VENDOR_PROBES){if(!entry.named.test(slot)&&!vendorsInFile().has(entry.vendor)){continue}if(entry.slots.test(slot))return true}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator==="||"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&left.object.property.type==="Identifier"&&left.object.property.name==="env"){return}}if(isLabelContext(node,parent)){return}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(node,parent)){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value,placeholderWordSet);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(node,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}if(isPublishableKey(value,parent)){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",data:{credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{isCredential,type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",data:{credentialType:type},fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){if(quasi.value.raw){const{isCredential,type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHardcodedCredentials=void 0;exports.isNaturalWordString=isNaturalWordString;exports.looksRandom=looksRandom;exports.isSecretShaped=isSecretShaped;exports.isPlaceholderValue=isPlaceholderValue;exports.isPublishableKeyValue=isPublishableKeyValue;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const CREDENTIAL_PATTERNS={apiKey:/^(?:[A-Za-z0-9_-]{32,}|sk_[A-Za-z0-9_-]{32,}|pk_[A-Za-z0-9_-]{32,}|AKIA[0-9A-Z]{16})$/,jwtToken:/^eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,oauthToken:/^(?:ghp_|gho_|ghu_|ghs_|ghr_)[A-Za-z0-9]{36,}$/,awsAccessKey:/^AKIA[0-9A-Z]{16}$/,databaseString:/^(?:mysql|postgres|mongodb|redis):\/\/[^:]+:[^@]+@/,commonPassword:/^(?:password|admin|123456|qwerty|letmein|welcome|monkey|1234567890|12345678|password123|root|test|guest)$/i,secretKey:/^(?:[A-Za-z0-9+/]{32,}={0,2}|[A-Fa-f0-9]{32,})$/};const CREDENTIAL_VARIABLE_NAMES=new Set(["apikey","api_key","apiKey","secret","secretkey","secret_key","secretKey","clientsecret","client_secret","clientSecret","token","authtoken","auth_token","authToken","accesstoken","access_token","accessToken","refreshtoken","refresh_token","refreshToken","idtoken","id_token","idToken","password","passwd","pass","pwd","privatekey","private_key","privateKey","credentials","creds","authorization","auth","connectionstring","connection_string","connectionString","connectionuri","connectionURI","dburl","db_url","dbUrl","databaseurl","database_url","databaseUrl"]);const WORD_SEPARATORS=new Set(["_","-","."," "]);function shannonEntropy(value){const freq=new Map;for(const ch of value)freq.set(ch,(freq.get(ch)??0)+1);let entropy=0;for(const count of freq.values()){const p=count/value.length;entropy-=p*Math.log2(p)}return entropy}function charClasses(value){const classes={lower:false,upper:false,digit:false,symbol:false};for(const ch of value){if(WORD_SEPARATORS.has(ch))continue;if(ch>="a"&&ch<="z")classes.lower=true;else if(ch>="A"&&ch<="Z")classes.upper=true;else if(ch>="0"&&ch<="9")classes.digit=true;else classes.symbol=true}return classes}function classCount(classes){return Number(classes.lower)+Number(classes.upper)+Number(classes.digit)+Number(classes.symbol)}function isPronounceable(token){const lower=token.toLowerCase();if(!/[aeiouy]/.test(lower))return false;if(/[bcdfghjklmnpqrstvwxz]{4,}/.test(lower))return false;return true}function isNaturalWordString(value){if(!/^[A-Za-z][A-Za-z0-9_\-. ]*$/.test(value))return false;const digits=value.replace(/[^0-9]/g,"").length;if(digits>0&&(digits/value.length>.2||/[0-9]{4,}/.test(value)))return false;const tokens=value.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[^A-Za-z]+/).filter(Boolean);const meaningful=tokens.filter(t=>t.length>=3);if(meaningful.length===0)return false;return meaningful.every(isPronounceable)}function hasSequentialRun(value,min=5){let run=1;for(let i=1;i<value.length;i++){run=value.charCodeAt(i)===value.charCodeAt(i-1)+1?run+1:1;if(run>=min)return true}return false}function looksRandom(value){if(value.length<20)return false;if(!/^[A-Za-z0-9]+$/.test(value))return false;const classes=charClasses(value);if(!classes.lower||!classes.upper||!classes.digit)return false;if(hasSequentialRun(value))return false;if(isNaturalWordString(value))return false;return shannonEntropy(value)>=3.5}const CONTEXT_FREE_RANDOM_LENGTH=32;function isSecretShaped(value,minLength){if(value.length<minLength)return false;if(/\s/.test(value))return false;if(isNaturalWordString(value))return false;if(classCount(charClasses(value))>=2)return true;return value.length>=20&&shannonEntropy(value)>=3}const DEFAULT_PLACEHOLDER_WORDS=["changeme","change","replaceme","replace","yours","your","placeholder","example","sample","dummy","todo","tbd","redacted","notreal","xxx"];function isPlaceholderValue(value,words){const trimmed=value.trim();if(trimmed.length===0)return false;if(/^(?:<.*>|\{\{.*\}\}|\$\{.*\}|\[.*\])$/.test(trimmed))return true;if(trimmed.length>=4&&new Set(trimmed).size===1)return true;const tokens=trimmed.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);return tokens.some(token=>words.has(token))}function isPublishableKeyValue(value){if(/^pk_(?:live|test)_[A-Za-z0-9_-]{8,}$/.test(value))return true;if(/^phc_[A-Za-z0-9]{20,}$/.test(value))return true;if(/^https?:\/\/[A-Za-z0-9]+@[A-Za-z0-9.-]+(?::\d+)?\/\d+$/.test(value)){return true}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"&&left.property.type==="Identifier"){return left.property.name.toLowerCase()}}return""}function looksLikeCredential(value,options,ignorePatterns){const NONE={isCredential:false,type:"",confidence:"ambiguous"};if(ignorePatterns.some(pattern=>pattern.test(value)))return NONE;for(const customPattern of options.customPatterns){try{const regex=new RegExp(customPattern.pattern);if(regex.test(value)){return{isCredential:true,type:customPattern.type,confidence:"structural"}}}catch(error){continue}}if(options.detectPasswords&&CREDENTIAL_PATTERNS.commonPassword.test(value)){return{isCredential:true,type:"Common password",confidence:"ambiguous"}}if(options.detectDatabaseStrings&&CREDENTIAL_PATTERNS.databaseString.test(value)){return{isCredential:true,type:"Database connection string",confidence:"structural"}}if(value.length<options.minLength)return NONE;if(options.detectTokens&&CREDENTIAL_PATTERNS.jwtToken.test(value)){return{isCredential:true,type:"JWT token",confidence:"structural"}}if(options.detectTokens&&CREDENTIAL_PATTERNS.oauthToken.test(value)){return{isCredential:true,type:"OAuth token",confidence:"structural"}}if(options.detectApiKeys&&CREDENTIAL_PATTERNS.awsAccessKey.test(value)){return{isCredential:true,type:"AWS access key",confidence:"structural"}}if(options.detectApiKeys&&/^(?:sk|pk|rk)_(?:live|test)_[A-Za-z0-9_-]{16,}$/.test(value)){return{isCredential:true,type:"API key",confidence:"structural"}}if(options.detectApiKeys&&looksRandom(value)){return{isCredential:true,type:"Secret key",confidence:value.length>=CONTEXT_FREE_RANDOM_LENGTH?"structural":"ambiguous"}}if(value.length>=32&&CREDENTIAL_PATTERNS.secretKey.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"Secret key",confidence:"ambiguous"}}if(options.detectApiKeys&&/^[A-Za-z0-9_-]{32,}$/.test(value)&&!isNaturalWordString(value)){return{isCredential:true,type:"API key",confidence:"ambiguous"}}return NONE}exports.noHardcodedCredentials=(0,eslint_devkit_2.createRule)({name:"no-hardcoded-credentials",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-hardcoded-credentials.md",description:"Detects hardcoded passwords, API keys, tokens, and other sensitive credentials",cwe:"CWE-798",cvss:9.8,confidence:"medium"},fixable:"code",hasSuggestions:true,messages:{useEnvironmentVariable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Hard-coded Credential",cwe:"CWE-798",description:"Hard-coded {{credentialType}} detected",severity:"CRITICAL",fix:"Use environment variable: process.env.{{envVarName}} or secret management service",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"}),useSecretManager:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Use Secret Manager",cwe:"CWE-798",description:"Use secure secret management service",severity:"HIGH",fix:"Use AWS Secrets Manager, HashiCorp Vault, Azure Key Vault, or similar",documentationLink:"https://cwe.mitre.org/data/definitions/798.html"})},schema:[{type:"object",properties:{ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Regex patterns to ignore"},allowInTests:{type:"boolean",default:true,description:"Allow credentials in test files"},minLength:{type:"number",default:8,description:"Minimum length for credential detection"},detectApiKeys:{type:"boolean",default:true,description:"Detect API keys"},detectPasswords:{type:"boolean",default:true,description:"Detect passwords"},detectTokens:{type:"boolean",default:true,description:"Detect tokens"},detectDatabaseStrings:{type:"boolean",default:true,description:"Detect database connection strings"},customPatterns:{type:"array",items:{type:"object",properties:{type:{type:"string",description:'The type of credential (e.g., "API key", "token")'},pattern:{type:"string",description:"Regex pattern to match"}},required:["type","pattern"],additionalProperties:false},default:[],description:"Custom credential patterns to detect"},allowPlaceholders:{type:"boolean",default:true,description:"Skip self-evident placeholder values (`<your-secret-here>`, `changeme`, `xxxxxxxx`)"},placeholderWords:{type:"array",items:{type:"string"},default:DEFAULT_PLACEHOLDER_WORDS,description:"Words that mark a value as a self-evident stand-in rather than a secret, matched as a WHOLE token inside the value and never as a substring. Replaces the built-in list. Read only when `allowPlaceholders` is true."},additionalPlaceholderWords:{type:"array",items:{type:"string"},default:[],description:"Extra placeholder words, on top of `placeholderWords`."}},additionalProperties:false}]},defaultOptions:[{ignorePatterns:[],allowInTests:true,minLength:8,detectApiKeys:true,detectPasswords:true,detectTokens:true,detectDatabaseStrings:true,customPatterns:[],allowPlaceholders:true,placeholderWords:DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords:[]}],create(context){const options=context.options[0]||{};const{ignorePatterns=[],allowInTests=true,minLength=8,detectApiKeys=true,detectPasswords=true,detectTokens=true,detectDatabaseStrings=true,customPatterns=[],allowPlaceholders=true,placeholderWords=DEFAULT_PLACEHOLDER_WORDS,additionalPlaceholderWords=[]}=options;const placeholderWordSet=new Set([...placeholderWords,...additionalPlaceholderWords]);const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_2.isTestFilePath)(filename);const compiledIgnorePatterns=(0,eslint_devkit_1.compileUserPatterns)(ignorePatterns);const detectionOptions={minLength,detectApiKeys,detectPasswords,detectTokens,detectDatabaseStrings,customPatterns};const LABEL_CONTEXT_NAMES=new Set(["type","name","id","placeholder","label","title","role","autocomplete","autoFocus","autocapitalize","inputmode","aria-label","aria-labelledby","aria-describedby","fieldName","fieldType","fieldLabel","inputType","inputName","displayName","columnName","paramName","i18nKey","translationKey","messageKey"]);function isLabelContext(node,parent){if(!parent)return false;if(parent.type==="ObjectExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isLabelContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const n=parent.id.name.toLowerCase();if(LABEL_CONTEXT_NAMES.has(n)||n==="labels"||n.endsWith("label")||n.endsWith("labels")||n.endsWith("name")||n.endsWith("placeholder"))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(LABEL_CONTEXT_NAMES.has(left.property.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;const keyText=key.type==="Identifier"?key.name:key.type==="Literal"&&typeof key.value==="string"?key.value:null;if(keyText!==null&&node.type==="Literal"&&typeof node.value==="string"){const keyTokens=keyText.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean);if(keyTokens.includes(node.value.toUpperCase()))return true}if(key.type==="Identifier"&&LABEL_CONTEXT_NAMES.has(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(LABEL_CONTEXT_NAMES.has(key.value))return true}const obj=parent.parent;if(obj?.type==="ObjectExpression"){const grand=obj.parent;if(grand)return isLabelContext(node,grand)}}if(parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"){const callee=parent.callee;const methodName=callee.property.name;if(methodName==="setAttribute"||methodName==="getAttribute"){const args=parent.arguments;if(args[1]===node)return true}}if(parent.type==="JSXAttribute")return true;return false}function inferCredentialTypeFromContext(parent){const name=slotNameOf(parent);if(/(?:^|[_-])(password|passwd|pass|pwd)$/.test(name))return"password";if(/(?:^|[_-])(token|authtoken|auth_token|accesstoken|access_token|refreshtoken|refresh_token|idtoken|id_token)$/.test(name))return"token";if(/(?:^|[_-])(dburl|db_url|databaseurl|database_url|connectionstring|connection_string|connectionuri)$/.test(name))return"database";if(/(?:^|[_-])(apikey|api_key|secretkey|secret_key|privatekey|private_key|secret|key|clientsecret|client_secret)$/.test(name))return"apikey";return"other"}function isCredentialContext(node,parent){if(!parent)return false;const matches=name=>{const lower=name.toLowerCase();if(lower==="key"||lower==="keys"){return node.type==="Literal"&&typeof node.value==="string"&&looksRandom(node.value)}const singular=lower.endsWith("s")?lower.slice(0,-1):lower;if(CREDENTIAL_VARIABLE_NAMES.has(lower)||CREDENTIAL_VARIABLE_NAMES.has(singular))return true;return lower.endsWith("apikey")||lower.endsWith("apikeys")||lower.endsWith("secret")||lower.endsWith("secrets")||lower.endsWith("token")||lower.endsWith("tokens")||lower.endsWith("password")||lower.endsWith("passwords")||lower.endsWith("passwd")||lower.endsWith("credential")||lower.endsWith("credentials")};if(parent.type==="ArrayExpression"){const grand=parent.parent;if(grand)return isCredentialContext(node,grand);return false}if(parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){if(matches(parent.id.name))return true}if(parent.type==="AssignmentExpression"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.property.type==="Identifier"){if(matches(left.property.name))return true}if(left.type==="Identifier"){if(matches(left.name))return true}}if(parent.type==="Property"&&parent.value===node){const key=parent.key;if(key.type==="Identifier"&&matches(key.name))return true;if(key.type==="Literal"&&typeof key.value==="string"){if(matches(key.value))return true}}return false}let loadedVendors=null;function vendorsInFile(){if(loadedVendors===null){const found=new Set;for(const{entry,loadsSdk}of VENDOR_PROBES){if(loadsSdk(context.sourceCode.ast))found.add(entry.vendor)}loadedVendors=found}return loadedVendors}function isPublishableKey(value,parent){if(SECRET_SIDE_VALUE.test(value))return false;if(isPublishableKeyValue(value))return true;const slot=slotNameOf(parent);if(slot===""||SECRET_SIDE_SLOT.test(slot))return false;for(const{entry}of VENDOR_PROBES){if(!entry.named.test(slot)&&!vendorsInFile().has(entry.vendor)){continue}if(entry.slots.test(slot))return true}return false}function checkStringLiteral(node,parent){if(typeof node.value!=="string"){return}const value=node.value;if(isTestFile){return}if(parent?.type==="LogicalExpression"&&parent.operator==="||"&&parent.right===node){const left=parent.left;if(left.type==="MemberExpression"&&left.object.type==="MemberExpression"&&left.object.object.type==="Identifier"&&left.object.object.name==="process"&&left.object.property.type==="Identifier"&&left.object.property.name==="env"){return}}if(isLabelContext(node,parent)){return}const{isCredential,type,confidence}=looksLikeCredential(value,detectionOptions,compiledIgnorePatterns);let finalIsCredential=isCredential;let finalType=type;if(isCredential&&confidence==="ambiguous"&&!isCredentialContext(node,parent)){finalIsCredential=false}const isPlaceholder=allowPlaceholders&&isPlaceholderValue(value,placeholderWordSet);if(isPlaceholder&&confidence!=="structural"){finalIsCredential=false}if(!finalIsCredential&&!isPlaceholder&&!compiledIgnorePatterns.some(pattern=>pattern.test(value))&&isSecretShaped(value,detectionOptions.minLength)&&isCredentialContext(node,parent)){const ctxType=inferCredentialTypeFromContext(parent);const optionAllows=ctxType==="password"&&detectionOptions.detectPasswords||ctxType==="token"&&detectionOptions.detectTokens||ctxType==="database"&&detectionOptions.detectDatabaseStrings||ctxType==="apikey"&&detectionOptions.detectApiKeys||ctxType==="other";if(optionAllows){finalIsCredential=true;finalType=type||"Credential value"}}if(!finalIsCredential){return}if(isPublishableKey(value,parent)){return}let envVarName="API_KEY";if(parent&&parent.type==="Property"&&parent.key.type==="Identifier"){const keyName=parent.key.name;envVarName=keyName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}else if(parent&&parent.type==="VariableDeclarator"&&parent.id.type==="Identifier"){const varName=parent.id.name;envVarName=varName.replace(/([a-z])([A-Z])/g,"$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g,"_")}context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:finalType,envVarName},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName,credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`process.env.${envVarName} || '${value}'`)}},{messageId:"useSecretManager",data:{credentialType:finalType},fix:fixer=>{return fixer.replaceText(node,`await getSecret('${envVarName.toLowerCase()}')`)}}]})}return{Literal(node){checkStringLiteral(node,node.parent)},TemplateLiteral(node){if(node.expressions.length===0){const fullText=node.quasis.map(q=>q.value.raw).join("");const{isCredential,type,confidence}=looksLikeCredential(fullText,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"},suggest:[{messageId:"useEnvironmentVariable",data:{envVarName:"API_KEY",credentialType:type},fix:fixer=>{return fixer.replaceText(node,`process.env.API_KEY || \`${fullText}\``)}},{messageId:"useSecretManager",data:{credentialType:type},fix:fixer=>{return fixer.replaceText(node,`await getSecret('api_key')`)}}]})}}else{for(const quasi of node.quasis){if(quasi.value.raw){const{isCredential,type,confidence}=looksLikeCredential(quasi.value.raw,detectionOptions,compiledIgnorePatterns);if(isCredential&&!isTestFile&&confidence==="structural"){context.report({node:quasi,messageId:"useEnvironmentVariable",data:{credentialType:type,envVarName:"API_KEY"}})}}}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noImproperTypeValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noImproperTypeValidation=(0,eslint_devkit_1.createRule)({name:"no-improper-type-validation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-improper-type-validation.md",description:"Detects improper type validation in user input handling",cwe:"CWE-1287"},messages:{unsafeTypeofCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe typeof Check",cwe:"CWE-1287",description:"typeof x === 'object' also matches null and arrays",severity:"MEDIUM",fix:'Use value != null && typeof value === "object" && !Array.isArray(value) \u2014 Not a finding if the value is already known non-null on this path',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof"}),unsafeInstanceofUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe instanceof Usage",cwe:"CWE-1287",description:"instanceof may fail across contexts",severity:"LOW",fix:"Use Array.isArray() or typeof checks \u2014 Not a finding if the value never crosses a realm boundary (no vm, iframe, or worker)",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof"}),looseEqualityTypeCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Loose Equality Type Check",cwe:"CWE-1287",description:"Loose equality may cause type confusion",severity:"LOW",fix:"Use strict equality (===) for type checking \u2014 Not a finding if both operands are already the same primitive type",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"}),unreliableConstructorCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unreliable Constructor Check",cwe:"CWE-1287",description:"constructor.name can be spoofed",severity:"MEDIUM",fix:"Use Object.prototype.toString.call() or duck typing \u2014 Not a finding if the value never came from parsed input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor"})},schema:[{type:"object",properties:{allowInstanceofSameRealm:{type:"boolean",default:true,description:"Allow instanceof for same-realm objects"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as type validators"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowInstanceofSameRealm:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowInstanceofSameRealm=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isNullish=node=>node.type==="Literal"&&node.raw==="null"||node.type==="Identifier"&&node.name==="undefined";const sameExpression=(a,b)=>{if(a.type!==b.type)return false;if(a.type==="Identifier"&&b.type==="Identifier")return a.name===b.name;if(a.type==="ThisExpression")return true;if(a.type==="MemberExpression"&&b.type==="MemberExpression"){if(a.computed!==b.computed)return false;return sameExpression(a.object,b.object)&&sameExpression(a.property,b.property)}if(a.type==="Literal"&&b.type==="Literal")return a.raw===b.raw;return false};const hasNullGuard=(node,operand)=>{const excludesNullish=(expression,negated2)=>{if(sameExpression(expression,operand))return!negated2;if(expression.type==="UnaryExpression"&&expression.operator==="!"){return sameExpression(expression.argument,operand)&&negated2}if(expression.type!=="BinaryExpression")return false;const wanted=negated2?["===","=="]:["!==","!="];if(!wanted.includes(expression.operator))return false;if(isNullish(expression.right))return sameExpression(expression.left,operand);if(isNullish(expression.left))return sameExpression(expression.right,operand);return false};const negated=node.operator==="!=="||node.operator==="!=";const combinator=negated?"||":"&&";const guards=expression=>{if(expression.type==="LogicalExpression"&&expression.operator===combinator){return guards(expression.left)||guards(expression.right)}return excludesNullish(expression,negated)};let chain=node;while(chain.parent?.type==="LogicalExpression"&&chain.parent.operator===combinator){chain=chain.parent}return chain!==node&&guards(chain)};const primitiveTypeOf=(node,seen=new Set)=>{if(node.type==="Literal"){if(typeof node.value==="string")return"string";if(typeof node.value==="number")return"number";return void 0}if(node.type==="TemplateLiteral")return"string";if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="length"){return"number"}if(node.type==="CallExpression"&&node.callee.type==="Identifier"){if(node.callee.name==="String")return"string";if(node.callee.name==="Number"||node.callee.name==="parseInt")return"number"}if(node.type!=="Identifier")return void 0;if(seen.has(node.name))return void 0;seen.add(node.name);for(let scope=sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr);if(writes.length===0)return void 0;const types=writes.map(ref=>primitiveTypeOf(ref.writeExpr,seen));return types.every(type=>type!==void 0&&type===types[0])?types[0]:void 0}return void 0};const typeofObjectOperand=node=>{if(node.operator!=="==="&&node.operator!=="!==")return void 0;const{left,right}=node;if(left.type==="UnaryExpression"&&left.operator==="typeof"&&right.type==="Literal"&&right.value==="object"){return left.argument}return void 0};const report=(node,messageId)=>{if(safetyChecker.isSafe(node,context))return;context.report({node,messageId,data:{filePath:filename,line:String(node.loc.start.line)}})};return{BinaryExpression(node){const operand=typeofObjectOperand(node);if(operand&&!hasNullGuard(node,operand)){report(node.left,"unsafeTypeofCheck");return}if(node.operator==="instanceof"&&!allowInstanceofSameRealm){report(node,"unsafeInstanceofUsage");return}if(node.operator==="=="||node.operator==="!="){if(isNullish(node.left)||isNullish(node.right))return;const leftType=primitiveTypeOf(node.left);if(leftType!==void 0&&leftType===primitiveTypeOf(node.right))return;report(node,"looseEqualityTypeCheck")}},MemberExpression(node){if(node.computed||node.property.type!=="Identifier")return;if(node.property.name!=="name")return;const inner=node.object;if(inner.type!=="MemberExpression"||inner.computed||inner.property.type!=="Identifier"||inner.property.name!=="constructor"){return}if(node.parent?.type!=="BinaryExpression")return;report(node,"unreliableConstructorCheck")}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noImproperTypeValidation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noImproperTypeValidation=(0,eslint_devkit_1.createRule)({name:"no-improper-type-validation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-improper-type-validation.md",description:"Detects improper type validation in user input handling",cwe:"CWE-1287"},messages:{unsafeTypeofCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe typeof Check",cwe:"CWE-1287",description:"typeof x === 'object' also matches null and arrays",severity:"MEDIUM",fix:'Use value != null && typeof value === "object" && !Array.isArray(value) \u2014 Not a finding if the value is already known non-null on this path',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof"}),unsafeInstanceofUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unsafe instanceof Usage",cwe:"CWE-1287",description:"instanceof may fail across contexts",severity:"LOW",fix:"Use Array.isArray() or typeof checks \u2014 Not a finding if the value never crosses a realm boundary (no vm, iframe, or worker)",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof"}),looseEqualityTypeCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Loose Equality Type Check",cwe:"CWE-1287",description:"Loose equality may cause type confusion",severity:"LOW",fix:"Use strict equality (===) for type checking \u2014 Not a finding if both operands are already the same primitive type",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality"}),unreliableConstructorCheck:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Unreliable Constructor Check",cwe:"CWE-1287",description:"constructor.name can be spoofed",severity:"MEDIUM",fix:"Use Object.prototype.toString.call() or duck typing \u2014 Not a finding if the value never came from parsed input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor"})},schema:[{type:"object",properties:{allowInstanceofSameRealm:{type:"boolean",default:true,description:"Allow instanceof for same-realm objects"},checkLooseEquality:{type:"boolean",default:true,description:"Report loose == / != between operands of unprovable type. Set false to keep only the structural typeof/instanceof/constructor arms."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as type validators"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowInstanceofSameRealm:true,checkLooseEquality:true,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{allowInstanceofSameRealm=true,checkLooseEquality=true,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const isNullish=node=>node.type==="Literal"&&node.raw==="null"||node.type==="Identifier"&&node.name==="undefined";const sameExpression=(a,b)=>{if(a.type!==b.type)return false;if(a.type==="Identifier"&&b.type==="Identifier")return a.name===b.name;if(a.type==="ThisExpression")return true;if(a.type==="MemberExpression"&&b.type==="MemberExpression"){if(a.computed!==b.computed)return false;return sameExpression(a.object,b.object)&&sameExpression(a.property,b.property)}if(a.type==="Literal"&&b.type==="Literal")return a.raw===b.raw;return false};const hasNullGuard=(node,operand)=>{const excludesNullish=(expression,negated2)=>{if(sameExpression(expression,operand))return!negated2;if(expression.type==="UnaryExpression"&&expression.operator==="!"){return sameExpression(expression.argument,operand)&&negated2}if(expression.type!=="BinaryExpression")return false;const wanted=negated2?["===","=="]:["!==","!="];if(!wanted.includes(expression.operator))return false;if(isNullish(expression.right))return sameExpression(expression.left,operand);if(isNullish(expression.left))return sameExpression(expression.right,operand);return false};const negated=node.operator==="!=="||node.operator==="!=";const combinator=negated?"||":"&&";const guards=expression=>{if(expression.type==="LogicalExpression"&&expression.operator===combinator){return guards(expression.left)||guards(expression.right)}return excludesNullish(expression,negated)};let chain=node;while(chain.parent?.type==="LogicalExpression"&&chain.parent.operator===combinator){chain=chain.parent}return chain!==node&&guards(chain)};const primitiveTypeOf=(node,seen=new Set)=>{if(node.type==="Literal"){if(typeof node.value==="string")return"string";if(typeof node.value==="number")return"number";return void 0}if(node.type==="TemplateLiteral")return"string";if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"&&node.property.name==="length"){return"number"}if(node.type==="CallExpression"&&node.callee.type==="Identifier"){if(node.callee.name==="String")return"string";if(node.callee.name==="Number"||node.callee.name==="parseInt")return"number"}if(node.type!=="Identifier")return void 0;if(seen.has(node.name))return void 0;seen.add(node.name);for(let scope=sourceCode.getScope(node);scope;scope=scope.upper){const variable=scope.variables.find(v=>v.name===node.name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite()&&ref.writeExpr);if(writes.length===0)return void 0;const types=writes.map(ref=>primitiveTypeOf(ref.writeExpr,seen));return types.every(type=>type!==void 0&&type===types[0])?types[0]:void 0}return void 0};const typeofObjectOperand=node=>{if(!["===","!==","==","!="].includes(node.operator))return void 0;const{left,right}=node;if(left.type==="UnaryExpression"&&left.operator==="typeof"&&right.type==="Literal"&&right.value==="object"){return left.argument}return void 0};const report=(node,messageId)=>{if(safetyChecker.isSafe(node,context))return;context.report({node,messageId,data:{filePath:filename,line:String(node.loc.start.line)}})};return{BinaryExpression(node){const operand=typeofObjectOperand(node);if(operand){if(!hasNullGuard(node,operand))report(node.left,"unsafeTypeofCheck");return}if(node.operator==="instanceof"&&!allowInstanceofSameRealm){report(node,"unsafeInstanceofUsage");return}if(checkLooseEquality&&(node.operator==="=="||node.operator==="!=")){if(isNullish(node.left)||isNullish(node.right))return;const leftType=primitiveTypeOf(node.left);if(leftType!==void 0&&leftType===primitiveTypeOf(node.right))return;report(node,"looseEqualityTypeCheck")}},MemberExpression(node){if(node.computed||node.property.type!=="Identifier")return;if(node.property.name!=="name")return;const inner=node.object;if(inner.type!=="MemberExpression"||inner.computed||inner.property.type!=="Identifier"||inner.property.name!=="constructor"){return}if(node.parent?.type!=="BinaryExpression")return;report(node,"unreliableConstructorCheck")}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingAuthentication=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_AUTH_MIDDLEWARE_PATTERNS=["authenticate","auth","requireAuth","isAuthenticated","verifyToken","checkAuth","ensureAuthenticated","passport.authenticate","jwt","session"];const DEFAULT_PUBLIC_ROUTE_PATTERNS=["login","logout","signin","sign-in","signup","sign-up","register","forgot-password","reset-password","password-reset","verify-email","health","healthz","readyz","livez","status","metrics","ping","favicon","webhook","/public/","oauth","callback"];const DEFAULT_ROUTE_HANDLER_PATTERNS=["get","post","put","delete","patch","all","use"];const ROUTER_NAME_WORDS=["app","router","route","server","express","fastify","koa","hapi"];const ROUTER_FACTORY_NAMES=new Set(["express","Router","fastify","polka","restify","connect","Koa"]);const ROUTER_FACTORY_MEMBERS=new Set(["Router","router","Server","server","createServer"]);function routeChainBase(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&current.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=current.callee.property;if(property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.name==="route"){return current}current=current.callee.object}return null}function isDefinitelyNotRouter(init){return init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression}function isRouterFactory(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return false}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_NAMES.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_MEMBERS.has(callee.property.name)}return false}function referencedName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.name}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const objectPart=node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${node.object.name}.`:"";return`${objectPart}${node.property.name}`}return null}function isAuthMiddlewareArg(arg,authPatterns){const target=arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression?arg.callee:arg;const name=referencedName(target);return name!==null&&(0,eslint_devkit_1.nameHasAnyWord)(name,authPatterns)}function isInsideAuthMiddleware(node,authPatterns){let current=node;while(current){if(current.parent&&current.parent.type==="CallExpression"){const callExpr=current.parent;const isArgument=callExpr.arguments.some(arg=>arg===current);if(!isArgument){current=current.parent;continue}const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,authPatterns)){return true}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const propertyName=callee.property.name.toLowerCase();if(propertyName==="use"||propertyName==="all"){for(const arg of callExpr.arguments){if(isAuthMiddlewareArg(arg,authPatterns)){return true}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}exports.noMissingAuthentication=(0,eslint_devkit_2.createRule)({name:"no-missing-authentication",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-missing-authentication.md",description:"Detects missing authentication checks in route handlers",cwe:"CWE-287",cvss:9.8},messages:{missingAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Authentication",cwe:"CWE-287",description:"Route handler missing authentication check: {{route}}",severity:"CRITICAL",fix:"Add authentication middleware: app.{{method}}('{{path}}', authenticate(), handler)",documentationLink:"https://cwe.mitre.org/data/definitions/287.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing authentication in test files"},authMiddlewarePatterns:{type:"array",items:{type:"string"},default:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,description:"Authentication middleware patterns to recognize"},routeHandlerPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROUTE_HANDLER_PATTERNS,description:"Route handler patterns to check"},ignorePatterns:{type:"array",items:{type:"string"},default:DEFAULT_PUBLIC_ROUTE_PATTERNS,description:"Route paths that are public by definition and need no authentication. Replaces the built-in list; supplying it also widens matching from the route path to the whole registration text."},routerNameWords:{type:"array",items:{type:"string"},default:ROUTER_NAME_WORDS,description:"Object names that denote an HTTP application or router, compared as WHOLE WORDS and never as a substring. Read only when the binding cannot be resolved to a framework factory call. Replaces the built-in list."},additionalRouterNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra router-object name words, on top of `routerNameWords`."},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,authMiddlewarePatterns:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns:DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns:DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords:ROUTER_NAME_WORDS,additionalRouterNameWords:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,authMiddlewarePatterns=DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns=DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns=DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords=ROUTER_NAME_WORDS,additionalRouterNameWords=[]}=options;const routerWords=[...routerNameWords,...additionalRouterNameWords];const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const scansWholeCallText=context.options[0]?.ignorePatterns!==void 0;function looksLikeRouter(object){const scope=sourceCode.getScope(object);const reference=scope.references.find(ref=>ref.identifier===object);const resolved=reference?.resolved;for(const def of resolved?.defs??[]){const parent=def.name.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){if(isRouterFactory(parent.init)){return true}if(isDefinitelyNotRouter(parent.init)){return false}}}return(0,eslint_devkit_1.nameHasAnyWord)(object.name,routerWords)}function findVariableDeclaration(identifier){const varName=identifier.name;let current=identifier;while(current){if(current.type==="Program"||current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const scopeBody=current.type==="Program"?current.body:current.body.type==="BlockStatement"?current.body.body:[];for(const stmt of scopeBody){if(stmt.type==="VariableDeclaration"){for(const declarator of stmt.declarations){if(declarator.id.type==="Identifier"&&declarator.id.name===varName){return declarator}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return null}function isIdentifierFromAuthMiddleware(identifier){const declarator=findVariableDeclaration(identifier);if(!declarator||!declarator.init){return false}if(declarator.init.type==="CallExpression"&&declarator.init.callee.type==="Identifier"){return(0,eslint_devkit_1.nameHasAnyWord)(declarator.init.callee.name,authMiddlewarePatterns)}return false}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const property=node.callee.property;const object=node.callee.object;let chainedPath;if(object.type==="Identifier"){if(!looksLikeRouter(object)){return}}else{const base=routeChainBase(object);const baseObject=base?.callee.type==="MemberExpression"?base.callee.object:void 0;if(!base||baseObject?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!looksLikeRouter(baseObject)){return}chainedPath=base.arguments[0]}if(property.type==="Identifier"){const methodName=property.name.toLowerCase();if(routeHandlerPatterns.includes(methodName)){if(methodName==="use"){const first=node.arguments[0];const mountsAPath=first!==void 0&&first.type==="Literal"&&typeof first.value==="string";if(!mountsAPath){return}}const pathArgument=chainedPath??node.arguments[0];let routePath="unknown";if(pathArgument!==void 0&&pathArgument.type==="Literal"){routePath=String(pathArgument.value)}else if(pathArgument!==void 0){routePath=sourceCode.getText(pathArgument)}const text=sourceCode.getText(node);if(matchesIgnorePattern(routePath,ignorePatterns)){return}if(scansWholeCallText&&matchesIgnorePattern(text,ignorePatterns)){return}const firstMiddlewareIndex=chainedPath===void 0?1:0;const middlewareArgs=methodName==="use"?node.arguments.slice(firstMiddlewareIndex):node.arguments.slice(firstMiddlewareIndex,-1);let hasAuth=false;for(const arg of middlewareArgs){if(isAuthMiddlewareArg(arg,authMiddlewarePatterns)){hasAuth=true;break}if(arg.type==="Identifier"&&isIdentifierFromAuthMiddleware(arg)){hasAuth=true;break}}if(!hasAuth&&node.arguments.length>0){const lastArg=node.arguments[node.arguments.length-1];if(lastArg.type==="ArrowFunctionExpression"||lastArg.type==="FunctionExpression"){if(isInsideAuthMiddleware(lastArg,authMiddlewarePatterns)){hasAuth=true}}}if(!hasAuth){context.report({node:node.callee,messageId:"missingAuthentication",data:{route:`${methodName}(${routePath})`,method:methodName,path:routePath}})}}}}}return{CallExpression:checkCallExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingAuthentication=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_AUTH_MIDDLEWARE_PATTERNS=["authenticate","auth","requireAuth","isAuthenticated","verifyToken","checkAuth","ensureAuthenticated","passport.authenticate","jwt","session"];const DEFAULT_PUBLIC_ROUTE_PATTERNS=["login","logout","signin","sign-in","signup","sign-up","register","forgot-password","reset-password","password-reset","verify-email","health","healthz","readyz","livez","alive","liveness","readiness","heartbeat","status","metrics","ping","favicon","webhook","/public/","oauth","callback"];const DEFAULT_ROUTE_HANDLER_PATTERNS=["get","post","put","delete","patch","all","use"];const ROUTER_NAME_WORDS=["app","router","route","server","express","fastify","koa","hapi"];const ROUTER_FACTORY_NAMES=new Set(["express","Router","fastify","polka","restify","connect","Koa"]);const ROUTER_FACTORY_MEMBERS=new Set(["Router","router","Server","server","createServer"]);function routeChainBase(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&current.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=current.callee.property;if(property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.name==="route"){return current}current=current.callee.object}return null}function isDefinitelyNotRouter(init){return init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression}function isRouterFactory(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return false}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_NAMES.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_MEMBERS.has(callee.property.name)}return false}function referencedName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.name}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const objectPart=node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${node.object.name}.`:"";return`${objectPart}${node.property.name}`}return null}function isAuthMiddlewareArg(arg,authPatterns){const target=arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression?arg.callee:arg;const name=referencedName(target);return name!==null&&(0,eslint_devkit_1.nameHasAnyWord)(name,authPatterns)}function isInsideAuthMiddleware(node,authPatterns){let current=node;while(current){if(current.parent&&current.parent.type==="CallExpression"){const callExpr=current.parent;const isArgument=callExpr.arguments.some(arg=>arg===current);if(!isArgument){current=current.parent;continue}const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,authPatterns)){return true}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const propertyName=callee.property.name.toLowerCase();if(propertyName==="use"||propertyName==="all"){for(const arg of callExpr.arguments){if(isAuthMiddlewareArg(arg,authPatterns)){return true}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}exports.noMissingAuthentication=(0,eslint_devkit_2.createRule)({name:"no-missing-authentication",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-missing-authentication.md",description:"Detects missing authentication checks in route handlers",cwe:"CWE-287",cvss:9.8},messages:{missingAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Authentication",cwe:"CWE-287",description:"Route handler missing authentication check: {{route}}",severity:"CRITICAL",fix:"Add authentication middleware: app.{{method}}('{{path}}', authenticate(), handler)",documentationLink:"https://cwe.mitre.org/data/definitions/287.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing authentication in test files"},authMiddlewarePatterns:{type:"array",items:{type:"string"},default:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,description:"Authentication middleware patterns to recognize"},routeHandlerPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROUTE_HANDLER_PATTERNS,description:"Route handler patterns to check"},ignorePatterns:{type:"array",items:{type:"string"},default:DEFAULT_PUBLIC_ROUTE_PATTERNS,description:"Route paths that are public by definition and need no authentication. Replaces the built-in list; supplying it also widens matching from the route path to the whole registration text."},routerNameWords:{type:"array",items:{type:"string"},default:ROUTER_NAME_WORDS,description:"Object names that denote an HTTP application or router, compared as WHOLE WORDS and never as a substring. Read only when the binding cannot be resolved to a framework factory call. Replaces the built-in list."},additionalRouterNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra router-object name words, on top of `routerNameWords`."},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,authMiddlewarePatterns:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns:DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns:DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords:ROUTER_NAME_WORDS,additionalRouterNameWords:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,authMiddlewarePatterns=DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns=DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns=DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords=ROUTER_NAME_WORDS,additionalRouterNameWords=[]}=options;const routerWords=[...routerNameWords,...additionalRouterNameWords];const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const scansWholeCallText=context.options[0]?.ignorePatterns!==void 0;function looksLikeRouter(object){const scope=sourceCode.getScope(object);const reference=scope.references.find(ref=>ref.identifier===object);const resolved=reference?.resolved;for(const def of resolved?.defs??[]){const parent=def.name.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){if(isRouterFactory(parent.init)){return true}if(isDefinitelyNotRouter(parent.init)){return false}}}return(0,eslint_devkit_1.nameHasAnyWord)(object.name,routerWords)}function findVariableDeclaration(identifier){const varName=identifier.name;let current=identifier;while(current){if(current.type==="Program"||current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const scopeBody=current.type==="Program"?current.body:current.body.type==="BlockStatement"?current.body.body:[];for(const stmt of scopeBody){if(stmt.type==="VariableDeclaration"){for(const declarator of stmt.declarations){if(declarator.id.type==="Identifier"&&declarator.id.name===varName){return declarator}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return null}function isIdentifierFromAuthMiddleware(identifier){const declarator=findVariableDeclaration(identifier);if(!declarator||!declarator.init){return false}if(declarator.init.type==="CallExpression"&&declarator.init.callee.type==="Identifier"){return(0,eslint_devkit_1.nameHasAnyWord)(declarator.init.callee.name,authMiddlewarePatterns)}return false}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const property=node.callee.property;const object=node.callee.object;let chainedPath;if(object.type==="Identifier"){if(!looksLikeRouter(object)){return}}else{const base=routeChainBase(object);const baseObject=base?.callee.type==="MemberExpression"?base.callee.object:void 0;if(!base||baseObject?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!looksLikeRouter(baseObject)){return}chainedPath=base.arguments[0]}if(property.type==="Identifier"){const methodName=property.name.toLowerCase();if(routeHandlerPatterns.includes(methodName)){if(methodName==="use"){const first=node.arguments[0];const mountsAPath=first!==void 0&&first.type==="Literal"&&typeof first.value==="string";if(!mountsAPath){return}}const pathArgument=chainedPath??node.arguments[0];let routePath="unknown";if(pathArgument!==void 0&&pathArgument.type==="Literal"){routePath=String(pathArgument.value)}else if(pathArgument!==void 0){routePath=sourceCode.getText(pathArgument)}const text=sourceCode.getText(node);if(matchesIgnorePattern(routePath,ignorePatterns)){return}if(scansWholeCallText&&matchesIgnorePattern(text,ignorePatterns)){return}const firstMiddlewareIndex=chainedPath===void 0?1:0;const middlewareArgs=methodName==="use"?node.arguments.slice(firstMiddlewareIndex):node.arguments.slice(firstMiddlewareIndex,-1);let hasAuth=false;for(const arg of middlewareArgs){if(isAuthMiddlewareArg(arg,authMiddlewarePatterns)){hasAuth=true;break}if(arg.type==="Identifier"&&isIdentifierFromAuthMiddleware(arg)){hasAuth=true;break}}if(!hasAuth&&node.arguments.length>0){const lastArg=node.arguments[node.arguments.length-1];if(lastArg.type==="ArrowFunctionExpression"||lastArg.type==="FunctionExpression"){if(isInsideAuthMiddleware(lastArg,authMiddlewarePatterns)){hasAuth=true}}}if(!hasAuth){context.report({node:node.callee,messageId:"missingAuthentication",data:{route:`${methodName}(${routePath})`,method:methodName,path:routePath}})}}}}}return{CallExpression:checkCallExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noRedosVulnerableRegex=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const regexpp_1=require("@eslint-community/regexpp");const scslre_1=require("scslre");const regexp_intrinsic_1=require("../../utils/regexp-intrinsic");const redos_oracle_1=require("../../utils/redos-oracle");const COMPLEMENTARY_CLASS_PROBES=[["\\\\S","\\\\s"],["\\\\W","\\\\w"],["\\\\D","\\\\d"]].map(([x,y])=>({group:new RegExp(`\\(\\s*(?:${x}|${y})[+*][^)]*(?:${x}|${y})[+*?][^)]*\\)[+*]`),a:new RegExp(`${x}[+*]`),b:new RegExp(`${y}[+*?]`)}));const REGEXPP_PARSER=new regexpp_1.RegExpParser;const INTERPOLATION_PLACEHOLDER="\uE000";function relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern){const edits=[];const walk=(node,underUnbounded)=>{const n=node;if(n.type==="Quantifier"){const{min=0,max=0}=n;if(underUnbounded&&Number.isFinite(max)&&max>1&&min!==max){edits.push([n.element.end,n.end,`{${min},}${n.greedy===false?"?":""}`])}walk(n.element,underUnbounded||max===Infinity);return}for(const child of[...n.alternatives??[],...n.elements??[]]){walk(child,underUnbounded)}};walk(ast,false);if(edits.length===0)return pattern;let out=pattern;for(const[start,end,text]of edits.sort((a,b)=>b[0]-a[0])){out=out.slice(0,start)+text+out.slice(end)}return out}const isRegExpLiteral=node=>{return node.type==="Literal"&&Object.prototype.hasOwnProperty.call(node,"regex")};exports.noRedosVulnerableRegex=(0,eslint_devkit_2.createRule)({name:"no-redos-vulnerable-regex",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-redos-vulnerable-regex.md",description:"Detects ReDoS-vulnerable regex patterns in literal regex patterns",cwe:"CWE-400"},messages:{redosVulnerable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"ReDoS vulnerable regex",cwe:"CWE-400",description:"{{vulnerabilityName}}: {{description}}",severity:"{{severity}}",fix:"{{fix}} \u2014 Not a finding if the quantifiers cannot overlap",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"})},schema:[{type:"object",properties:{allowCommonPatterns:{type:"boolean",default:false,description:"Deprecated and ignored. Gated the removed heuristic layer; kept so existing configs still load."},maxPatternLength:{type:"number",default:500,minimum:1,description:"Maximum pattern length to analyze"}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowCommonPatterns:false,maxPatternLength:500}],create(context,[options={}]){const{maxPatternLength=500}=options||{};const MAX_SAFE_REPETITION=5;function isProvablyLinear(pattern){const groupUnderUnboundedQuantifier=/\)[*+]/.test(pattern);const bounded=groupUnderUnboundedQuantifier?null:/\)\{(\d+)(?:,(\d+))?\}/.exec(pattern);if(bounded!==null){const max=bounded[2]!==void 0?Number(bounded[2]):Number(bounded[1]);if(max<=MAX_SAFE_REPETITION)return true}for(const{group,a,b}of COMPLEMENTARY_CLASS_PROBES){if(!group.test(pattern))continue;if(a.test(pattern)&&b.test(pattern))return true}return false}function isProvablyCatastrophic(pattern){const m=/\(([^()|]+)\|([^()|]+)\)[+*]/.exec(pattern);return m!==null&&m[1]===m[2]}function checkWithScslre(node,pattern,flags,runtimeBuilt=false){try{const parse=source=>REGEXPP_PARSER.parsePattern(source,0,source.length,{unicode:flags.includes("u"),unicodeSets:flags.includes("v")});const run=ast2=>(0,scslre_1.analyse)({pattern:ast2,flags:{ignoreCase:flags.includes("i"),unicode:flags.includes("u"),dotAll:flags.includes("s"),multiline:flags.includes("m")}},{reportTypes:{Move:false}});const ast=parse(pattern);let result=run(ast);if(result.reports.length===0){const relaxed=relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern);if(relaxed!==pattern){result=run(parse(relaxed))}}if(isProvablyLinear(pattern)){return}if(result.reports.length===0&&isProvablyCatastrophic(pattern)){if(!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:"Ambiguous alternation (exponential backtracking)",description:"Alternatives inside a quantified group match the same input, so every character can be taken by either branch and the engine explores 2^n paths before failing.",severity:"CRITICAL",fix:"Remove the duplicate alternative, or make the branches mutually exclusive"}});return}const worst=result.reports.find(r=>r.exponential)??result.reports[0];if(worst&&!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;for(const report of worst?[worst]:[]){const isExp=report.exponential;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:`${runtimeBuilt?"Runtime-built ":""}${report.type==="Self"?`Self-loop quantifier (${isExp?"exponential":"polynomial"} backtracking)`:`Cross-quantifier trade (${isExp?"exponential":"polynomial"} backtracking)`}`,description:report.type==="Self"?`A quantifier reaches itself via the parent loop. An attacker can craft input that triggers ${isExp?"exponential":"polynomial"} backtracking.`:`Two quantifiers can exchange characters, enabling ${isExp?"exponential":"polynomial"} backtracking on crafted input.`,severity:isExp?"CRITICAL":"HIGH",fix:"Atomic group, possessive quantifier, or rewrite to remove the ambiguity"}})}}catch{}}function checkLiteralRegExp(node){if(!isRegExpLiteral(node)){return}const pattern=node.regex.pattern;const flags=node.regex.flags||"";if(pattern.length>maxPatternLength){return}checkWithScslre(node,pattern,flags)}function resolvePatternSource(node,seen){if(seen.has(node))return null;seen.add(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?{pattern:node.value,exact:true}:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return joinQuasis(node.quasis.map(q=>q.value.cooked??q.value.raw),node.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression&&node.tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.tag.computed&&node.tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.tag.object.name==="String"&&node.tag.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.tag.property.name==="raw"&&!isShadowed("String",node)){return joinQuasis(node.quasi.quasis.map(q=>q.value.raw),node.quasi.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=resolveOrPlaceholder(node.left,seen);const right=resolveOrPlaceholder(node.right,seen);return{pattern:left.pattern+right.pattern,exact:left.exact&&right.exact}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=resolveBindingInit(node);return init?resolvePatternSource(init,seen):null}return null}function joinQuasis(staticParts,expressions,seen){let pattern="";let exact=true;for(const[index,part]of staticParts.entries()){pattern+=part;const expression=expressions[index];if(!expression)continue;const resolved=resolveOrPlaceholder(expression,seen);pattern+=resolved.pattern;exact&&=resolved.exact}return{pattern,exact}}function resolveOrPlaceholder(node,seen){return resolvePatternSource(node,seen)??{pattern:INTERPOLATION_PLACEHOLDER,exact:false}}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;const writes=variable.references.filter(r=>r.isWrite());return writes.length===1?def.node.init:null}return null}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function checkNewRegExp(node){const callee=node.callee;if(!(0,regexp_intrinsic_1.isRegExpConstructor)(callee,context.sourceCode)){return}const firstArg=node.arguments[0];if(!firstArg||firstArg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const resolved=resolvePatternSource(firstArg,new Set);if(!resolved||resolved.pattern.length>maxPatternLength){return}const flagsArg=node.arguments[1];const flags=flagsArg?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof flagsArg.value==="string"?flagsArg.value:"";checkWithScslre(node,resolved.pattern,flags,!resolved.exact)}return{Literal:checkLiteralRegExp,CallExpression:node=>checkNewRegExp((0,regexp_intrinsic_1.asDirectConstruction)(node,context.sourceCode)),NewExpression:checkNewRegExp}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noRedosVulnerableRegex=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const regexpp_1=require("@eslint-community/regexpp");const scslre_1=require("scslre");const regexp_intrinsic_1=require("../../utils/regexp-intrinsic");const redos_oracle_1=require("../../utils/redos-oracle");const COMPLEMENTARY_CLASS_PROBES=[["\\\\S","\\\\s"],["\\\\W","\\\\w"],["\\\\D","\\\\d"]].map(([x,y])=>({group:new RegExp(`\\(\\s*(?:${x}|${y})[+*][^)]*(?:${x}|${y})[+*?][^)]*\\)[+*]`),a:new RegExp(`${x}[+*]`),b:new RegExp(`${y}[+*?]`)}));const REGEXPP_PARSER=new regexpp_1.RegExpParser;const INTERPOLATION_PLACEHOLDER="\uE000";function relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern){const edits=[];const walk=(node,underUnbounded)=>{const n=node;if(n.type==="Quantifier"){const{min=0,max=0}=n;if(underUnbounded&&Number.isFinite(max)&&max>1&&min!==max){edits.push([n.element.end,n.end,`{${min},}${n.greedy===false?"?":""}`])}walk(n.element,underUnbounded||max===Infinity);return}for(const child of[...n.alternatives??[],...n.elements??[]]){walk(child,underUnbounded)}};walk(ast,false);if(edits.length===0)return pattern;let out=pattern;for(const[start,end,text]of edits.sort((a,b)=>b[0]-a[0])){out=out.slice(0,start)+text+out.slice(end)}return out}const isRegExpLiteral=node=>{return node.type==="Literal"&&Object.prototype.hasOwnProperty.call(node,"regex")};exports.noRedosVulnerableRegex=(0,eslint_devkit_2.createRule)({name:"no-redos-vulnerable-regex",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-redos-vulnerable-regex.md",description:"Detects ReDoS-vulnerable regex patterns in literal regex patterns",cwe:"CWE-400"},messages:{redosVulnerable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"ReDoS vulnerable regex",cwe:"CWE-400",description:"{{vulnerabilityName}}: {{description}}",severity:"{{severity}}",fix:"{{fix}} \u2014 Not a finding if the quantifiers cannot overlap",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"})},schema:[{type:"object",properties:{allowCommonPatterns:{type:"boolean",default:false,description:"Deprecated and ignored. Gated the removed heuristic layer; kept so existing configs still load."},maxPatternLength:{type:"number",default:500,minimum:1,description:"Maximum pattern length to analyze"},reportSecondDegreePolynomial:{type:"boolean",default:true,description:"Report quadratic backtracking. On by default \u2014 the CWE-1333 corpus pins a degree-2 fixture as must-detect. Turn it off only for patterns that provably run over short, sized input; doing so costs recall. Requires the recheck oracle."}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowCommonPatterns:false,maxPatternLength:500,reportSecondDegreePolynomial:true}],create(context,[options={}]){const{maxPatternLength=500,reportSecondDegreePolynomial=true}=options||{};const MAX_SAFE_REPETITION=5;function isProvablyLinear(pattern){const groupUnderUnboundedQuantifier=/\)[*+]/.test(pattern);const bounded=groupUnderUnboundedQuantifier?null:/\)\{(\d+)(?:,(\d+))?\}/.exec(pattern);if(bounded!==null){const max=bounded[2]!==void 0?Number(bounded[2]):Number(bounded[1]);if(max<=MAX_SAFE_REPETITION)return true}for(const{group,a,b}of COMPLEMENTARY_CLASS_PROBES){if(!group.test(pattern))continue;if(a.test(pattern)&&b.test(pattern))return true}return false}function isProvablyCatastrophic(pattern){const m=/\(([^()|]+)\|([^()|]+)\)[+*]/.exec(pattern);return m!==null&&m[1]===m[2]}function checkWithScslre(node,pattern,flags,runtimeBuilt=false){try{const parse=source=>REGEXPP_PARSER.parsePattern(source,0,source.length,{unicode:flags.includes("u"),unicodeSets:flags.includes("v")});const run=ast2=>(0,scslre_1.analyse)({pattern:ast2,flags:{ignoreCase:flags.includes("i"),unicode:flags.includes("u"),dotAll:flags.includes("s"),multiline:flags.includes("m")}},{reportTypes:{Move:false}});const ast=parse(pattern);let result=run(ast);if(result.reports.length===0){const relaxed=relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern);if(relaxed!==pattern){result=run(parse(relaxed))}}if(isProvablyLinear(pattern)){return}if(result.reports.length===0&&isProvablyCatastrophic(pattern)){if(!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:"Ambiguous alternation (exponential backtracking)",description:"Alternatives inside a quantified group match the same input, so every character can be taken by either branch and the engine explores 2^n paths before failing.",severity:"CRITICAL",fix:"Remove the duplicate alternative, or make the branches mutually exclusive"}});return}const worst=result.reports.find(r=>r.exponential)??result.reports[0];if(worst&&!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;if(worst&&!reportSecondDegreePolynomial){const degree=(0,redos_oracle_1.worstBacktrackingDegree)(pattern,flags);if(degree!==null&&degree<=2)return}for(const report of worst?[worst]:[]){const isExp=report.exponential;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:`${runtimeBuilt?"Runtime-built ":""}${report.type==="Self"?`Self-loop quantifier (${isExp?"exponential":"polynomial"} backtracking)`:`Cross-quantifier trade (${isExp?"exponential":"polynomial"} backtracking)`}`,description:report.type==="Self"?`A quantifier reaches itself via the parent loop. An attacker can craft input that triggers ${isExp?"exponential":"polynomial"} backtracking.`:`Two quantifiers can exchange characters, enabling ${isExp?"exponential":"polynomial"} backtracking on crafted input.`,severity:isExp?"CRITICAL":"HIGH",fix:"Atomic group, possessive quantifier, or rewrite to remove the ambiguity"}})}}catch{}}function checkLiteralRegExp(node){if(!isRegExpLiteral(node)){return}const pattern=node.regex.pattern;const flags=node.regex.flags||"";if(pattern.length>maxPatternLength){return}checkWithScslre(node,pattern,flags)}function resolvePatternSource(node,seen){if(seen.has(node))return null;seen.add(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?{pattern:node.value,exact:true}:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return joinQuasis(node.quasis.map(q=>q.value.cooked??q.value.raw),node.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression&&node.tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.tag.computed&&node.tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.tag.object.name==="String"&&node.tag.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.tag.property.name==="raw"&&!isShadowed("String",node)){return joinQuasis(node.quasi.quasis.map(q=>q.value.raw),node.quasi.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=resolveOrPlaceholder(node.left,seen);const right=resolveOrPlaceholder(node.right,seen);return{pattern:left.pattern+right.pattern,exact:left.exact&&right.exact}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=resolveBindingInit(node);return init?resolvePatternSource(init,seen):null}return null}function joinQuasis(staticParts,expressions,seen){let pattern="";let exact=true;for(const[index,part]of staticParts.entries()){pattern+=part;const expression=expressions[index];if(!expression)continue;const resolved=resolveOrPlaceholder(expression,seen);pattern+=resolved.pattern;exact&&=resolved.exact}return{pattern,exact}}function resolveOrPlaceholder(node,seen){return resolvePatternSource(node,seen)??{pattern:INTERPOLATION_PLACEHOLDER,exact:false}}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;const writes=variable.references.filter(r=>r.isWrite());return writes.length===1?def.node.init:null}return null}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function checkNewRegExp(node){const callee=node.callee;if(!(0,regexp_intrinsic_1.isRegExpConstructor)(callee,context.sourceCode)){return}const firstArg=node.arguments[0];if(!firstArg||firstArg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const resolved=resolvePatternSource(firstArg,new Set);if(!resolved||resolved.pattern.length>maxPatternLength){return}const flagsArg=node.arguments[1];const flags=flagsArg?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof flagsArg.value==="string"?flagsArg.value:"";checkWithScslre(node,resolved.pattern,flags,!resolved.exact)}return{Literal:checkLiteralRegExp,CallExpression:node=>checkNewRegExp((0,regexp_intrinsic_1.asDirectConstruction)(node,context.sourceCode)),NewExpression:checkNewRegExp}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[ _-]{0,2}(?:[a-z0-9]{1,12}[ _-]{0,2})?[:=]\\s*\\S`,"i").test(normalized)&&/[:=]\s*\S+\s*$/.test(text)})}function literalLabelsValue(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b\\s*[:=]\\s*$`,"i").test(normalized)){return pattern}}return null}const DESCRIPTOR_SEGMENTS=["msg","message","error","err","label","prompt","hint","description","desc","regex","pattern","placeholder","warning","notice"];function identifierNamesSecret(name,patterns,descriptors){const matched=containsSensitiveData(name,patterns);if(!matched)return null;const last=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(-1).join("");return descriptors.has(last)?null:matched}function memberCarriesSecret(node,patterns,descriptors){const prop=node.property;const propName=node.computed?prop.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value==="string"?prop.value:null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?identifierNamesSecret(propName,patterns,descriptors):null;if(fromProp)return fromProp;if(propName&&VALUE_FREE_PROPERTIES.has(propName))return null;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(node.object.name,patterns,descriptors):null}const VALUE_FREE_PROPERTIES=new Set(["length","size","byteLength","byteOffset"]);function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},descriptorSegments:{type:"array",items:{type:"string"},default:DESCRIPTOR_SEGMENTS,description:"Trailing name segments that describe a secret rather than hold one, so `apiKeyMsg` and `passwordError` are not reported. Compared as the whole FINAL segment of the name, never as a substring. Replaces the built-in list."},additionalDescriptorSegments:{type:"array",items:{type:"string"},default:[],description:"Extra descriptor segments, on top of `descriptorSegments`."}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,descriptorSegments:DESCRIPTOR_SEGMENTS,additionalDescriptorSegments:[]}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true,descriptorSegments=DESCRIPTOR_SEGMENTS,additionalDescriptorSegments=[]}=options||{};const descriptors=new Set([...descriptorSegments,...additionalDescriptorSegments]);const LOGGER_RECEIVERS=new Set(["console","logger","log"]);const LOG_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);function isLoggerReceiver(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return LOGGER_RECEIVERS.has(node.name.toLowerCase())}return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOGGER_RECEIVERS.has(node.property.name.toLowerCase())}function describeExposure(argument){const arg=(0,eslint_devkit_1.unwrapTypeSyntax)(argument);if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"){const pattern=literalCarriesSecret(arg.value,sensitivePatterns)?containsSensitiveData(arg.value,sensitivePatterns):null;return pattern?{node:arg,pattern}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){if(arg.left.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.left.value==="string"){const labelled=literalLabelsValue(arg.left.value,sensitivePatterns);if(labelled)return{node:arg.left,pattern:labelled}}else{const fromLeft=describeExposure(arg.left);if(fromLeft)return fromLeft}return namedValueExposure(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>namedValueExposure(e)).find(m=>Boolean(m));if(fromExpression)return{node:arg,pattern:fromExpression.pattern};const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const fromText=arg.expressions.length>0&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;return fromText?{node:arg,pattern:fromText}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of arg.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const keyName=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"?property.key.value:null;const pattern=keyName?identifierNamesSecret(keyName,sensitivePatterns,descriptors):null;if(!pattern)continue;if((0,eslint_devkit_1.isStaticExpression)({node:property.value,scope:context.sourceCode.getScope(arg)})){continue}return{node:property,pattern}}return null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return describeExposure(arg.consequent)??describeExposure(arg.alternate)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="String"&&arg.arguments.length===1&&arg.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!isShadowed("String",arg)){return describeExposure(arg.arguments[0])}return namedValueExposure(arg)}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function namedValueExposure(node,seen=new Set){const value=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(seen.has(value))return null;seen.add(value);if(value.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return namedValueExposure(value.expression,seen)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const pattern=identifierNamesSecret(value.name,sensitivePatterns,descriptors);if(pattern)return{node:value,pattern};const init=resolveBindingInit(value);const viaBinding=init?namedValueExposure(init,seen):null;return viaBinding?{node:value,pattern:viaBinding.pattern}:null}if(value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const pattern=memberCarriesSecret(value,sensitivePatterns,descriptors);return pattern?{node:value,pattern}:null}return null}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;return variable.references.filter(r=>r.isWrite()).length===1?def.node.init:null}return null}function reportFirstExposure(argumentList,exposureContext){for(const argument of argumentList){const exposure=describeExposure(argument);if(exposure){context.report({node:exposure.node,messageId:"sensitiveDataExposure",data:{context:exposureContext,dataType:exposure.pattern}});return}}}function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;return!node.callee.computed&&property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOG_METHODS.has(property.name.toLowerCase())&&isLoggerReceiver(node.callee.object)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const words=node.callee.name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.includes("log")||words.includes("logger")}return false})();if(isLoggingCall&&checkConsoleLog){reportFirstExposure(node.arguments,"logs")}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Error"){reportFirstExposure(node.arguments,"error messages")}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[ _-]{0,2}(?:[a-z0-9]{1,12}[ _-]{0,2})?[:=]\\s*\\S`,"i").test(normalized)&&/[:=]\s*\S+\s*$/.test(text)})}function literalLabelsValue(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b\\s*[:=]\\s*$`,"i").test(normalized)){return pattern}}return null}const DESCRIPTOR_SEGMENTS=["msg","message","error","err","label","prompt","hint","description","desc","regex","pattern","placeholder","warning","notice"];function identifierNamesSecret(name,patterns,descriptors){const matched=containsSensitiveData(name,patterns);if(!matched)return null;const last=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(-1).join("");return descriptors.has(last)?null:matched}function memberCarriesSecret(node,patterns,descriptors){const prop=node.property;const propName=node.computed?prop.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value==="string"?prop.value:null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?identifierNamesSecret(propName,patterns,descriptors):null;if(fromProp)return fromProp;if(propName&&(VALUE_FREE_PROPERTIES.has(propName)||DIAGNOSTIC_ACCESSORS.has(propName)))return null;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(node.object.name,patterns,descriptors):null}const VALUE_FREE_PROPERTIES=new Set(["length","size","byteLength","byteOffset"]);const DIAGNOSTIC_ACCESSORS=new Set(["message","stack","name","status","statusText"]);function isDiagnosticAccessor(node){const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);const value=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;return value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!value.computed&&value.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DIAGNOSTIC_ACCESSORS.has(value.property.name)}function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},descriptorSegments:{type:"array",items:{type:"string"},default:DESCRIPTOR_SEGMENTS,description:"Trailing name segments that describe a secret rather than hold one, so `apiKeyMsg` and `passwordError` are not reported. Compared as the whole FINAL segment of the name, never as a substring. Replaces the built-in list."},additionalDescriptorSegments:{type:"array",items:{type:"string"},default:[],description:"Extra descriptor segments, on top of `descriptorSegments`."}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,descriptorSegments:DESCRIPTOR_SEGMENTS,additionalDescriptorSegments:[]}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true,descriptorSegments=DESCRIPTOR_SEGMENTS,additionalDescriptorSegments=[]}=options||{};const descriptors=new Set([...descriptorSegments,...additionalDescriptorSegments]);const LOGGER_RECEIVERS=new Set(["console","logger","log"]);const LOG_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);function isLoggerReceiver(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return LOGGER_RECEIVERS.has(node.name.toLowerCase())}return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOGGER_RECEIVERS.has(node.property.name.toLowerCase())}function describeExposure(argument){const arg=(0,eslint_devkit_1.unwrapTypeSyntax)(argument);if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"){const pattern=literalCarriesSecret(arg.value,sensitivePatterns)?containsSensitiveData(arg.value,sensitivePatterns):null;return pattern?{node:arg,pattern}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){if(arg.left.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.left.value==="string"){const labelled=literalLabelsValue(arg.left.value,sensitivePatterns);if(labelled)return{node:arg.left,pattern:labelled}}else{const fromLeft=describeExposure(arg.left);if(fromLeft)return fromLeft}return namedValueExposure(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>namedValueExposure(e)).find(m=>Boolean(m));if(fromExpression)return{node:arg,pattern:fromExpression.pattern};const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const allHolesAreDiagnostic=arg.expressions.every(isNonSecretHole);const fromText=arg.expressions.length>0&&!allHolesAreDiagnostic&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;return fromText?{node:arg,pattern:fromText}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of arg.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const keyName=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"?property.key.value:null;const pattern=keyName?identifierNamesSecret(keyName,sensitivePatterns,descriptors):null;if(!pattern)continue;if((0,eslint_devkit_1.isStaticExpression)({node:property.value,scope:context.sourceCode.getScope(arg)})){continue}return{node:property,pattern}}return null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return describeExposure(arg.consequent)??describeExposure(arg.alternate)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="String"&&arg.arguments.length===1&&arg.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!isShadowed("String",arg)){return describeExposure(arg.arguments[0])}return namedValueExposure(arg)}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function namedValueExposure(node,seen=new Set){const value=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(seen.has(value))return null;seen.add(value);if(value.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return namedValueExposure(value.expression,seen)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const pattern=identifierNamesSecret(value.name,sensitivePatterns,descriptors);if(pattern)return{node:value,pattern};const init=resolveBindingInit(value);const viaBinding=init?namedValueExposure(init,seen):null;return viaBinding?{node:value,pattern:viaBinding.pattern}:null}if(value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const pattern=memberCarriesSecret(value,sensitivePatterns,descriptors);return pattern?{node:value,pattern}:null}return null}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;return variable.references.filter(r=>r.isWrite()).length===1?def.node.init:null}return null}function isNonSecretHole(expression){if(!isDiagnosticAccessor(expression))return false;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(expression);const member=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;if(member.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return true;const init=resolveBindingInit(member.object);if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return true;const key=member.property.name;const assigned=init.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.key.name===key||property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.key.value===key));if(!assigned)return true;return namedValueExposure(assigned.value)===null}function reportFirstExposure(argumentList,exposureContext){for(const argument of argumentList){const exposure=describeExposure(argument);if(exposure){context.report({node:exposure.node,messageId:"sensitiveDataExposure",data:{context:exposureContext,dataType:exposure.pattern}});return}}}function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;return!node.callee.computed&&property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOG_METHODS.has(property.name.toLowerCase())&&isLoggerReceiver(node.callee.object)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const words=node.callee.name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.includes("log")||words.includes("logger")}return false})();if(isLoggingCall&&checkConsoleLog){reportFirstExposure(node.arguments,"logs")}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Error"){reportFirstExposure(node.arguments,"error messages")}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDeserialization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const TIMER_FUNCTIONS=new Set(["setTimeout","setInterval"]);const MODULE_SINKS={"js-yaml":new Set(["load","loadAll"]),"node-serialize":new Set(["unserialize"]),funcster:new Set(["deserialize","deepDeserialize"]),v8:new Set(["deserialize"])};const ALWAYS_UNSAFE_MODULES=new Set(["node-serialize","funcster"]);const DEFAULT_SAFE_YAML_SCHEMAS=["JSON_SCHEMA","CORE_SCHEMA","FAILSAFE_SCHEMA"];const DEFAULT_NON_EXECUTING_PACKAGES=["yaml","bson","cbor","msgpackr","@msgpack/msgpack","protobufjs"];function isStringValued(arg){if(!arg)return false;if(arg.type==="Literal")return typeof arg.value==="string";if(arg.type==="TemplateLiteral")return true;if(arg.type==="BinaryExpression"&&arg.operator==="+"){return isStringValued(arg.left)||isStringValued(arg.right)}return false}exports.noUnsafeDeserialization=(0,eslint_devkit_1.createRule)({name:"no-unsafe-deserialization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-deserialization.md",description:"Detects unsafe deserialization of untrusted data",cwe:"CWE-502"},fixable:"code",hasSuggestions:true,messages:{unsafeDeserialization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Deserialization",cwe:"CWE-502",description:"Unsafe deserialization of untrusted data (incl. model/tool output)",severity:"{{severity}}",fix:"{{safeAlternative}} | validate model/tool output via schema and size limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),dangerousEvalUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous eval() Usage",cwe:"CWE-502",description:"eval() used for deserialization (code execution vulnerability)",severity:"CRITICAL",fix:"Use JSON.parse() or safe deserialization libraries",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),unsafeYamlParsing:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe YAML Parsing",cwe:"CWE-502",description:"YAML parsing may execute code during deserialization",severity:"HIGH",fix:"Use yaml.safeLoad() or disable code execution",documentationLink:"https://www.npmjs.com/package/js-yaml#loadstr---options-"}),dangerousFunctionConstructor:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Function Constructor",cwe:"CWE-502",description:"Function constructor used with untrusted data",severity:"CRITICAL",fix:"Avoid Function constructor with user input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function"}),useSafeDeserializer:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Safe Deserializer",description:"Use safe deserialization libraries",severity:"LOW",fix:"Use JSON.parse, safe-json-parse, or validated libraries",documentationLink:"https://www.npmjs.com/package/safe-json-parse"})},schema:[{type:"object",properties:{dangerousFunctions:{type:"array",items:{type:"string"},default:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],description:"Functions that execute or deserialize untrusted input"},validationFunctions:{type:"array",items:{type:"string"},default:["validateInput","sanitizeData","checkSchema","validateSchema"],description:"Function names that count as input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as safe deserializers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},safeYamlSchemas:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_YAML_SCHEMAS,description:"js-yaml schema exports that make `load` inert, matched against a resolved js-yaml binding. Add DEFAULT_SCHEMA on a repository pinned to js-yaml v4. Replaces the built-in list."},additionalSafeYamlSchemas:{type:"array",items:{type:"string"},default:[],description:"Extra safe js-yaml schema exports, on top of `safeYamlSchemas`."},nonExecutingPackages:{type:"array",items:{type:"string"},default:DEFAULT_NON_EXECUTING_PACKAGES,description:"Packages whose parse entry point cannot execute code or instantiate a payload-named type, matched against a resolved import binding. Replaces the built-in list."},additionalNonExecutingPackages:{type:"array",items:{type:"string"},default:[],description:"Extra non-executing packages, on top of `nonExecutingPackages`."}},additionalProperties:false}]},defaultOptions:[{dangerousFunctions:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions:["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false,safeYamlSchemas:DEFAULT_SAFE_YAML_SCHEMAS,additionalSafeYamlSchemas:[],nonExecutingPackages:DEFAULT_NON_EXECUTING_PACKAGES,additionalNonExecutingPackages:[]}],create(context){const options=context.options[0]||{};const{dangerousFunctions=["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions=["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false,safeYamlSchemas=DEFAULT_SAFE_YAML_SCHEMAS,additionalSafeYamlSchemas=[],nonExecutingPackages=DEFAULT_NON_EXECUTING_PACKAGES,additionalNonExecutingPackages=[]}=options;const safeSchemas=new Set([...safeYamlSchemas,...additionalSafeYamlSchemas]);const inertPackages=new Set([...nonExecutingPackages,...additionalNonExecutingPackages]);const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const validatedVariables=new Set;const untrustedVariables=new Set;const literalPathFileVars=new Set;const pinsSafeYamlSchema=node=>{const optionsArg=node.arguments[1];if(optionsArg?.type!=="ObjectExpression")return false;return optionsArg.properties.some(property=>{if(property.type!=="Property"||property.computed)return false;if(property.key.type!=="Identifier"||property.key.name!=="schema"){return false}const schema=(0,eslint_devkit_1.resolveModuleBinding)(property.value,sourceCode.getScope(property.value));return schema?.module==="js-yaml"&&safeSchemas.has(schema.path.at(-1)??"")})};const isDangerousDeserialization=node=>{const callee=node.callee;const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));if(binding){const sinks=MODULE_SINKS[binding.module];if(sinks&&binding.path.some(segment=>sinks.has(segment))){return!pinsSafeYamlSchema(node)}if(inertPackages.has(binding.module))return false}if(callee.type==="Identifier"&&dangerousFunctions.includes(callee.name)){if(TIMER_FUNCTIONS.has(callee.name)){return isStringValued(node.arguments[0])}return true}if(callee.type==="MemberExpression"){const memberName=callee.property.type==="Identifier"?callee.property.name:"";const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(callee.object.type==="Super"||callee.object.type==="ThisExpression"){return false}if(TIMER_FUNCTIONS.has(memberName)){return isStringValued(node.arguments[0])}if(objectName==="JSON"&&memberName==="parse"||objectName==="yaml"&&memberName==="safeLoad"){return false}if(dangerousFunctions.includes(memberName)){return true}if(["yaml","js-yaml","node-serialize","serialize-javascript"].includes(objectName.toLowerCase())&&["load","parse","unserialize","deserialize"].includes(memberName)){return true}}if(callee.type==="Identifier"&&callee.name==="require"){const args=node.arguments;if(args.length>0&&args[0].type==="Literal"&&typeof args[0].value==="string"){const moduleName=args[0].value.toLowerCase();if(["node-serialize","serialize-javascript","yaml","js-yaml"].includes(moduleName)){return true}}}return false};const isUntrustedInput=inputNode=>{const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(inputNode);if(bare!==inputNode)return isUntrustedInput(bare);if(inputNode.type==="BinaryExpression"&&inputNode.operator==="+"){return isUntrustedInput(inputNode.left)||isUntrustedInput(inputNode.right)}if(inputNode.type==="TemplateLiteral"){return inputNode.expressions.some(e=>isUntrustedInput(e))}if(inputNode.type==="AwaitExpression"){return isUntrustedInput(inputNode.argument)}if(inputNode.type==="CallExpression"){const callee=inputNode.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(["text","json","arrayBuffer","formData","blob"].includes(callee.property.name)){return true}if(["readFile","readFileSync"].includes(callee.property.name)){return true}if(isUntrustedInput(callee.object)){return true}}return inputNode.arguments.some(arg=>arg.type!=="SpreadElement"&&isUntrustedInput(arg))}if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"){return true}}if(inputNode.type==="Identifier"){if(untrustedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;if(func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})){return true}}current=current.parent}}return false};const isInsideDeserializerImplementation=node=>{const DESERIALIZER_NAMES=new Set(["deserialize","unserialize","fromJSON","fromBuffer"]);let current=node.parent;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const fn=current;if("id"in fn&&fn.id?.name&&DESERIALIZER_NAMES.has(fn.id.name))return true;const owner=fn.parent;if(owner?.type==="MethodDefinition"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="Property"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="VariableDeclarator"&&owner.id.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.id.name))return true}current=current.parent}return false};const isAlwaysUnsafeSink=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,sourceCode.getScope(node.callee));return binding!==void 0&&ALWAYS_UNSAFE_MODULES.has(binding.module)};const checkCallExpression=node=>{if((node.type==="NewExpression"||node.type==="CallExpression")&&node.callee.type==="Identifier"&&node.callee.name==="Function"){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg));if(hasUntrustedInput){if(safetyChecker.isSafe(node,context))return;context.report({node,messageId:"dangerousFunctionConstructor",data:{filePath:context.filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Avoid dynamic function creation"}});return}}if(isDangerousDeserialization(node)&&!isInsideDeserializerImplementation(node)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg))||isAlwaysUnsafeSink(node);if(hasUntrustedInput){const safe=safetyChecker.isSafe(node,context);if(!safe){let messageId="unsafeDeserialization";const calleeText=sourceCode.getText(node.callee);if(calleeText.includes("yaml")||calleeText.includes("YAML")){messageId="unsafeYamlParsing"}if(node.callee.type==="Identifier"&&["eval","setTimeout","setInterval"].includes(node.callee.name)){messageId="dangerousEvalUsage"}context.report({node,messageId,data:{library:calleeText,filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use JSON.parse() or validated safe deserialization libraries"},suggest:messageId==="dangerousEvalUsage"?[{messageId:"useSafeDeserializer",fix:fixer=>{return fixer.replaceText(node,`JSON.parse(${sourceCode.getText(node.arguments[0])})`)}}]:void 0})}}}};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){if(isUntrustedInput(declarator.init)){untrustedVariables.add(declarator.id.name)}if(declarator.init.type==="CallExpression"){const callee=declarator.init.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&callee.property.type==="Identifier"&&["readFile","readFileSync"].includes(callee.property.name)){untrustedVariables.add(declarator.id.name);const pathArg=declarator.init.arguments[0];if(pathArg?.type==="Literal"&&typeof pathArg.value==="string"){literalPathFileVars.add(declarator.id.name)}}}}}},AssignmentExpression(node){if(node.left.type==="Identifier"&&isUntrustedInput(node.right)){untrustedVariables.add(node.left.name)}},CallExpression(node){checkCallExpression(node)},NewExpression(node){checkCallExpression(node)},VariableDeclarator(node){if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(validationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(node.id.name)}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDeserialization=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const TIMER_FUNCTIONS=new Set(["setTimeout","setInterval"]);const MODULE_SINKS={"js-yaml":new Set(["load","loadAll"]),"node-serialize":new Set(["unserialize"]),funcster:new Set(["deserialize","deepDeserialize"]),v8:new Set(["deserialize"])};const ALWAYS_UNSAFE_MODULES=new Set(["node-serialize","funcster"]);const DEFAULT_SAFE_YAML_SCHEMAS=["JSON_SCHEMA","CORE_SCHEMA","FAILSAFE_SCHEMA"];const DEFAULT_NON_EXECUTING_PACKAGES=["yaml","bson","cbor","msgpackr","@msgpack/msgpack","protobufjs"];function isStringValued(arg){if(!arg)return false;if(arg.type==="Literal")return typeof arg.value==="string";if(arg.type==="TemplateLiteral")return true;if(arg.type==="BinaryExpression"&&arg.operator==="+"){return isStringValued(arg.left)||isStringValued(arg.right)}return false}exports.noUnsafeDeserialization=(0,eslint_devkit_1.createRule)({name:"no-unsafe-deserialization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unsafe-deserialization.md",description:"Detects unsafe deserialization of untrusted data",cwe:"CWE-502"},fixable:"code",hasSuggestions:true,messages:{unsafeDeserialization:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Deserialization",cwe:"CWE-502",description:"Unsafe deserialization of untrusted data (incl. model/tool output)",severity:"{{severity}}",fix:"{{safeAlternative}} | validate model/tool output via schema and size limits",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),dangerousEvalUsage:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous eval() Usage",cwe:"CWE-502",description:"eval() used for deserialization (code execution vulnerability)",severity:"CRITICAL",fix:"Use JSON.parse() or safe deserialization libraries",documentationLink:"https://cwe.mitre.org/data/definitions/502.html"}),unsafeYamlParsing:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe YAML Parsing",cwe:"CWE-502",description:"YAML parsing may execute code during deserialization",severity:"HIGH",fix:"Use yaml.safeLoad() or disable code execution",documentationLink:"https://www.npmjs.com/package/js-yaml#loadstr---options-"}),dangerousFunctionConstructor:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Function Constructor",cwe:"CWE-502",description:"Function constructor used with untrusted data",severity:"CRITICAL",fix:"Avoid Function constructor with user input",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function"}),useSafeDeserializer:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Use Safe Deserializer",description:"Use safe deserialization libraries",severity:"LOW",fix:"Use JSON.parse, safe-json-parse, or validated libraries",documentationLink:"https://www.npmjs.com/package/safe-json-parse"})},schema:[{type:"object",properties:{dangerousFunctions:{type:"array",items:{type:"string"},default:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],description:"Functions that execute or deserialize untrusted input"},validationFunctions:{type:"array",items:{type:"string"},default:["validateInput","sanitizeData","checkSchema","validateSchema"],description:"Function names that count as input validation"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as safe deserializers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"},safeYamlSchemas:{type:"array",items:{type:"string"},default:DEFAULT_SAFE_YAML_SCHEMAS,description:"js-yaml schema exports that make `load` inert, matched against a resolved js-yaml binding. Add DEFAULT_SCHEMA on a repository pinned to js-yaml v4. Replaces the built-in list."},additionalSafeYamlSchemas:{type:"array",items:{type:"string"},default:[],description:"Extra safe js-yaml schema exports, on top of `safeYamlSchemas`."},nonExecutingPackages:{type:"array",items:{type:"string"},default:DEFAULT_NON_EXECUTING_PACKAGES,description:"Packages whose parse entry point cannot execute code or instantiate a payload-named type, matched against a resolved import binding. Replaces the built-in list."},additionalNonExecutingPackages:{type:"array",items:{type:"string"},default:[],description:"Extra non-executing packages, on top of `nonExecutingPackages`."}},additionalProperties:false}]},defaultOptions:[{dangerousFunctions:["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions:["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false,safeYamlSchemas:DEFAULT_SAFE_YAML_SCHEMAS,additionalSafeYamlSchemas:[],nonExecutingPackages:DEFAULT_NON_EXECUTING_PACKAGES,additionalNonExecutingPackages:[]}],create(context){const options=context.options[0]||{};const{dangerousFunctions=["eval","Function","setTimeout","setInterval","unserialize","deserialize","parseUnsafe"],validationFunctions=["validateInput","sanitizeData","checkSchema","validateSchema"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false,safeYamlSchemas=DEFAULT_SAFE_YAML_SCHEMAS,additionalSafeYamlSchemas=[],nonExecutingPackages=DEFAULT_NON_EXECUTING_PACKAGES,additionalNonExecutingPackages=[]}=options;const safeSchemas=new Set([...safeYamlSchemas,...additionalSafeYamlSchemas]);const inertPackages=new Set([...nonExecutingPackages,...additionalNonExecutingPackages]);const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const validatedVariables=new Set;const untrustedVariables=new Set;const literalPathFileVars=new Set;const pinsSafeYamlSchema=node=>{const optionsArg=node.arguments[1];if(optionsArg?.type!=="ObjectExpression")return false;return optionsArg.properties.some(property=>{if(property.type!=="Property"||property.computed)return false;if(property.key.type!=="Identifier"||property.key.name!=="schema"){return false}const schema=(0,eslint_devkit_1.resolveModuleBinding)(property.value,sourceCode.getScope(property.value));return schema?.module==="js-yaml"&&safeSchemas.has(schema.path.at(-1)??"")})};const isDangerousDeserialization=node=>{const callee=node.callee;const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));if(binding){const sinks=MODULE_SINKS[binding.module];if(sinks&&binding.path.some(segment=>sinks.has(segment))){return!pinsSafeYamlSchema(node)}if(inertPackages.has(binding.module))return false}if(callee.type==="Identifier"&&dangerousFunctions.includes(callee.name)){if(TIMER_FUNCTIONS.has(callee.name)){return isStringValued(node.arguments[0])}if(!isGlobalBinding(callee))return false;return true}if(callee.type==="MemberExpression"){const memberName=callee.property.type==="Identifier"?callee.property.name:"";const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(callee.object.type==="Super"||callee.object.type==="ThisExpression"){return false}if(TIMER_FUNCTIONS.has(memberName)){return isStringValued(node.arguments[0])}if(objectName==="JSON"&&memberName==="parse"||objectName==="yaml"&&memberName==="safeLoad"){return false}if(dangerousFunctions.includes(memberName)){return true}if(["yaml","js-yaml","node-serialize","serialize-javascript"].includes(objectName.toLowerCase())&&["load","parse","unserialize","deserialize"].includes(memberName)){return true}}if(callee.type==="Identifier"&&callee.name==="require"){const args=node.arguments;if(args.length>0&&args[0].type==="Literal"&&typeof args[0].value==="string"){const moduleName=args[0].value.toLowerCase();if(["node-serialize","serialize-javascript","yaml","js-yaml"].includes(moduleName)){return true}}}return false};const isUntrustedInput=inputNode=>{const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(inputNode);if(bare!==inputNode)return isUntrustedInput(bare);if(inputNode.type==="BinaryExpression"&&inputNode.operator==="+"){return isUntrustedInput(inputNode.left)||isUntrustedInput(inputNode.right)}if(inputNode.type==="TemplateLiteral"){return inputNode.expressions.some(e=>isUntrustedInput(e))}if(inputNode.type==="AwaitExpression"){return isUntrustedInput(inputNode.argument)}if(inputNode.type==="CallExpression"){const callee=inputNode.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(["text","json","arrayBuffer","formData","blob"].includes(callee.property.name)){return true}if(["readFile","readFileSync"].includes(callee.property.name)){return true}if(isUntrustedInput(callee.object)){return true}}return inputNode.arguments.some(arg=>arg.type!=="SpreadElement"&&isUntrustedInput(arg))}if(inputNode.type==="MemberExpression"){if(inputNode.object.type==="Identifier"&&inputNode.object.name==="req"){return true}if(inputNode.object.type==="MemberExpression"&&inputNode.object.object.type==="Identifier"&&inputNode.object.object.name==="req"){return true}}if(inputNode.type==="Identifier"){if(untrustedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const func=current;if(func.params.some(param=>{if(param.type==="Identifier"){return param.name===inputNode.name}return false})){return true}}current=current.parent}}return false};const isInsideDeserializerImplementation=node=>{const DESERIALIZER_NAMES=new Set(["deserialize","unserialize","fromJSON","fromBuffer"]);let current=node.parent;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const fn=current;if("id"in fn&&fn.id?.name&&DESERIALIZER_NAMES.has(fn.id.name))return true;const owner=fn.parent;if(owner?.type==="MethodDefinition"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="Property"&&owner.key.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.key.name))return true;if(owner?.type==="VariableDeclarator"&&owner.id.type==="Identifier"&&DESERIALIZER_NAMES.has(owner.id.name))return true}current=current.parent}return false};const isAlwaysUnsafeSink=node=>{const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,sourceCode.getScope(node.callee));return binding!==void 0&&ALWAYS_UNSAFE_MODULES.has(binding.module)};const isGlobalBinding=identifier=>{let scope=sourceCode.getScope(identifier);while(scope){const found=scope.variables.find(v=>v.name===identifier.name);if(found)return found.defs.length===0;scope=scope.upper}return true};const checkCallExpression=node=>{if((node.type==="NewExpression"||node.type==="CallExpression")&&node.callee.type==="Identifier"&&node.callee.name==="Function"&&isGlobalBinding(node.callee)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg));if(hasUntrustedInput){if(safetyChecker.isSafe(node,context))return;context.report({node,messageId:"dangerousFunctionConstructor",data:{filePath:context.filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Avoid dynamic function creation"}});return}}if(isDangerousDeserialization(node)&&!isInsideDeserializerImplementation(node)){const args=node.arguments;const hasUntrustedInput=args.some(arg=>isUntrustedInput(arg))||isAlwaysUnsafeSink(node);if(hasUntrustedInput){const safe=safetyChecker.isSafe(node,context);if(!safe){let messageId="unsafeDeserialization";const calleeText=sourceCode.getText(node.callee);if(calleeText.includes("yaml")||calleeText.includes("YAML")){messageId="unsafeYamlParsing"}if(node.callee.type==="Identifier"&&["eval","setTimeout","setInterval"].includes(node.callee.name)){messageId="dangerousEvalUsage"}context.report({node,messageId,data:{library:calleeText,filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use JSON.parse() or validated safe deserialization libraries"},suggest:messageId==="dangerousEvalUsage"?[{messageId:"useSafeDeserializer",fix:fixer=>{return fixer.replaceText(node,`JSON.parse(${sourceCode.getText(node.arguments[0])})`)}}]:void 0})}}}};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){if(isUntrustedInput(declarator.init)){untrustedVariables.add(declarator.id.name)}if(declarator.init.type==="CallExpression"){const callee=declarator.init.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="fs"&&callee.property.type==="Identifier"&&["readFile","readFileSync"].includes(callee.property.name)){untrustedVariables.add(declarator.id.name);const pathArg=declarator.init.arguments[0];if(pathArg?.type==="Literal"&&typeof pathArg.value==="string"){literalPathFileVars.add(declarator.id.name)}}}}}},AssignmentExpression(node){if(node.left.type==="Identifier"&&isUntrustedInput(node.right)){untrustedVariables.add(node.left.name)}},CallExpression(node){checkCallExpression(node)},NewExpression(node){checkCallExpression(node)},VariableDeclarator(node){if(!node.init){return}if(node.id.type==="Identifier"&&node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&(validationFunctions.includes(node.init.callee.name)||trustedSanitizers.includes(node.init.callee.name))){validatedVariables.add(node.id.name)}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.confirmsRedos=confirmsRedos;exports.oracleAvailable=oracleAvailable;exports.resetOracleForTests=resetOracleForTests;exports.__setOracleForTests=__setOracleForTests;let loaded;let moduleId="recheck";function oracle(){if(loaded!==void 0)return loaded;try{loaded=require(moduleId)}catch{loaded=null}return loaded}const decided=new Map;function confirmsRedos(source,flags,timeoutMs=1e3){const recheck=oracle();if(recheck===null)return true;const key=`${flags} ${source}`;const memo=decided.get(key);if(memo!==void 0)return memo;let survives=true;try{const result=recheck.checkSync(source,flags,{timeout:timeoutMs});survives=result.status!=="safe"}catch{survives=true}decided.set(key,survives);return survives}function oracleAvailable(){return oracle()!==null}function resetOracleForTests(forceAbsent=false){loaded=forceAbsent?null:void 0;moduleId="recheck";decided.clear()}function __setOracleForTests(next){decided.clear();if(typeof next==="string"){moduleId=next;loaded=void 0;return}loaded=next}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.confirmsRedos=confirmsRedos;exports.worstBacktrackingDegree=worstBacktrackingDegree;exports.oracleAvailable=oracleAvailable;exports.resetOracleForTests=resetOracleForTests;exports.__setOracleForTests=__setOracleForTests;let loaded;let moduleId="recheck";function oracle(){if(loaded!==void 0)return loaded;try{loaded=require(moduleId)}catch{loaded=null}return loaded}const decided=new Map;function confirmsRedos(source,flags,timeoutMs=1e3){const recheck=oracle();if(recheck===null)return true;const key=`${flags} ${source}`;const memo=decided.get(key);if(memo!==void 0)return memo;let survives=true;try{const result=recheck.checkSync(source,flags,{timeout:timeoutMs});survives=result.status!=="safe"}catch{survives=true}decided.set(key,survives);return survives}function worstBacktrackingDegree(source,flags,timeoutMs=1e3){const recheck=oracle();if(recheck===null)return null;const key=`${flags} ${source}`;const memo=degrees.get(key);if(memo!==void 0)return memo;let degree=null;try{const result=recheck.checkSync(source,flags,{timeout:timeoutMs});if(result.status==="vulnerable"){degree=result.complexity?.type==="exponential"?Number.POSITIVE_INFINITY:result.complexity?.degree??null}}catch{degree=null}degrees.set(key,degree);return degree}const degrees=new Map;function oracleAvailable(){return oracle()!==null}function resetOracleForTests(forceAbsent=false){loaded=forceAbsent?null:void 0;moduleId="recheck";decided.clear();degrees.clear()}function __setOracleForTests(next){decided.clear();degrees.clear();if(typeof next==="string"){moduleId=next;loaded=void 0;return}loaded=next}