eslint-plugin-secure-coding 5.5.1 → 5.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -155,7 +155,7 @@ See the [ESLint Version Support Policy](../../docs/ESLINT_VERSION_SUPPORT.md)
155
155
  | Rule | CWE | OWASP | CVSS | Description | 🧠 | 💼 | ⚠️ | 🔧 | 💡 | 🚫 |
156
156
  | :--- | :---: | :---: | :---: | :--- | :---: | :---: | :---: | :---: | :---: | :---: |
157
157
  | [detect-non-literal-regexp](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/detect-non-literal-regexp?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-400 | | | Detects RegExp(variable), which might allow an attacker to DOS your server with a long-running regular expr… | 🟢 | | | | | |
158
- | [detect-object-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/detect-object-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-915 | | | Detects variable[key] as a left- or right-hand assignment operand (prototype pollution) | 🟡 | | | | | |
158
+ | [detect-object-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/detect-object-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-915 | | | Detects variable[key] written as an assignment target, or read and then invoked (prototype pollution, method injection) | 🟡 | | | | | |
159
159
  | [detect-weak-password-validation](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/detect-weak-password-validation?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-521 | A07:2021 | | Detects weak password length requirements (less than 8 characters) in validation code. | 🟢 | | | | | |
160
160
  | [no-bidi-characters](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-bidi-characters?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-1007 | | | Disallows Unicode bidirectional control characters, which let source render differently than it compiles (T… | 🟢 | | | | | |
161
161
  | [no-directive-injection](https://eslint.interlace.tools/docs/security/plugin-secure-coding/rules/no-directive-injection?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-secure-coding) | CWE-94 | | | Detects directive injection vulnerabilities in template systems | 🟢 | | | | | |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-secure-coding",
3
- "version": "5.5.1",
3
+ "version": "5.6.0",
4
4
  "description": "ESLint plugin for secure coding — detects LDAP, XPath, XXE, GraphQL and template injection, unsafe deserialization, ReDoS, missing authentication, and PII in logs.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
package/src/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;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},get"no-invisible-characters"(){return require("./rules/no-invisible-characters").noInvisibleCharacters},get"no-disabled-template-escaping"(){return require("./rules/no-disabled-template-escaping").noDisabledTemplateEscaping}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-secure-coding",exports.rules);exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"5.5.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
+ "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},get"no-invisible-characters"(){return require("./rules/no-invisible-characters").noInvisibleCharacters},get"no-disabled-template-escaping"(){return require("./rules/no-disabled-template-escaping").noDisabledTemplateEscaping}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-secure-coding",exports.rules);exports.plugin={meta:{name:"eslint-plugin-secure-coding",version:"5.6.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-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectObjectInjection=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 resolve_reference_1=require("../../utils/resolve-reference");const fileUsesAstTooling=(0,eslint_devkit_3.createModuleEvidence)({packages:["@babel/types","@babel/traverse","recast","jscodeshift","eslint","estree-walker","ast-types","esrap","unist-util-visit"],scopes:["@typescript-eslint"]});const TYPED_ARRAY_CTORS=new Set(["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"]);const OBJECT_INJECTION_PATTERNS=[{pattern:"__proto__",dangerous:true,vulnerability:"prototype-pollution",safeAlternative:"Object.create(null) or Map",riskLevel:"critical"},{pattern:"prototype",dangerous:true,vulnerability:"prototype-pollution",safeAlternative:"Avoid prototype manipulation",riskLevel:"high"},{pattern:"constructor",dangerous:true,vulnerability:"method-injection",safeAlternative:"Validate property names against whitelist",riskLevel:"medium"}];const KEY_GUARD_CALLEES=new Set(["includes","has","hasOwn","hasOwnProperty","indexOf","call"]);const OWNERSHIP_GUARD_CALLEES=new Set(["hasOwn","hasOwnProperty","call"]);const POLLUTION_KEYS=new Set(["__proto__","constructor","prototype"]);const childNodes=n=>{const out=[];for(const key of Object.keys(n)){if(key==="parent")continue;const child=n[key];for(const item of Array.isArray(child)?child:[child]){if(item&&typeof item==="object"&&"type"in item){out.push(item)}}}return out};const mentionsKey=(n,keyName)=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return n.name===keyName;return childNodes(n).some(child=>mentionsKey(child,keyName))};const bodyGuardsKey=(bodyNode,keyName,{isModuleOwnedAllowlist,deferOwnershipGuards=false})=>{let membershipGuard=false;let guardCoversModuleOwned=false;const guardedObjectPaths=new Set;const writtenObjectPaths=new Set;const objectPath=n=>{const path=(0,eslint_devkit_1.memberPath)(n);return path===null?null:JSON.stringify(path)};const pollutionKeysNamed=new Set;let passesKeyedReadOnward=false;const creditGuardedObject=tested=>{membershipGuard=true;const path=objectPath(tested);if(path===null)return;guardedObjectPaths.add(path);if(isModuleOwnedAllowlist(tested))guardCoversModuleOwned=true};const walk=n=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&n.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&n.left.computed&&mentionsKey(n.left.property,keyName)){const path=objectPath(n.left.object);if(path!==null)writtenObjectPaths.add(path)}if(n.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&n.arguments.some(argument=>argument.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&argument.computed&&mentionsKey(argument.property,keyName))){passesKeyedReadOnward=true}if(n.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&n.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&KEY_GUARD_CALLEES.has((0,eslint_devkit_1.propertyName)(n.callee)??"")&&!(deferOwnershipGuards&&OWNERSHIP_GUARD_CALLEES.has((0,eslint_devkit_1.propertyName)(n.callee)??""))&&n.arguments.some(argument=>mentionsKey(argument,keyName))){const tested=(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(n.callee),["hasOwn","call"])?n.arguments.slice(0,1):[n.callee.object];for(const object of tested)creditGuardedObject(object)}if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&n.operator==="in"&&mentionsKey(n.left,keyName)){creditGuardedObject(n.right)}if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&["===","!==","==","!="].includes(n.operator)){const compared=(0,eslint_devkit_1.staticString)(n.left)??(0,eslint_devkit_1.staticString)(n.right);const other=(0,eslint_devkit_1.staticString)(n.left)===null?n.left:n.right;if(compared!==null&&POLLUTION_KEYS.has(compared)&&mentionsKey(other,keyName)){pollutionKeysNamed.add(compared)}}for(const child of childNodes(n))walk(child)};walk(bodyNode);const guardCoversWrittenObject=[...guardedObjectPaths].some(path=>writtenObjectPaths.has(path));if(guardCoversWrittenObject||guardCoversModuleOwned)return true;if(!membershipGuard&&pollutionKeysNamed.size===0)return false;return!passesKeyedReadOnward||pollutionKeysNamed.size===POLLUTION_KEYS.size};exports.detectObjectInjection=(0,eslint_devkit_3.createRule)({name:"detect-object-injection",meta:{interop:{runtimes:["eslint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/detect-object-injection.md",description:"Detects variable[key] as a left- or right-hand assignment operand",cwe:"CWE-915",confidence:"low"},messages:{objectInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Object injection",cwe:"CWE-915",description:"Object injection/Prototype pollution (incl. model/tool outputs)",severity:"{{riskLevel}}",fix:"{{safeAlternative}} \u2014 Not a finding when the key is a numeric index, a module constant, or guarded by Object.hasOwn / an allowlist",documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),massAssignment:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Mass assignment",cwe:"CWE-915",description:"Every key of an untrusted object is copied onto this target, so the caller chooses which field is written \u2014 including one they should not control, such as isAdmin",severity:"HIGH",fix:"Copy an explicit allowlist of assignable fields instead of the caller's keys \u2014 Not a finding when the iterated object is module-built, or the body checks each key against an allowlist",documentationLink:"https://cwe.mitre.org/data/definitions/915.html"}),globalPrototypeWrite:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Global prototype pollution",cwe:"CWE-1321",description:"Assignment writes THROUGH {{step}}, so the property lands on Object.prototype and every object in the process inherits it",severity:"CRITICAL",fix:"Guard with Object.hasOwn, or build the target with Object.create(null) / a Map \u2014 Not a finding when the path is fixed at build time, or __proto__ / constructor / prototype are rejected first",documentationLink:"https://portswigger.net/web-security/prototype-pollution"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:false,description:"Allow bracket notation with literal strings"},dangerousProperties:{type:"array",items:{type:"string"},default:["__proto__","prototype","constructor"],description:"Property NAMES treated as dangerous where the name is visible in the source \u2014 `obj['__proto__'] = v`. It cannot apply to a dynamic key (`obj[k] = v`), because there is no name to compare, and it does not gate the CWE-1321 traversal check, which is a fact about the language rather than a vocabulary. Set it to [] to stop reporting literal dangerous-property writes."}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowLiterals:false,dangerousProperties:["__proto__","prototype","constructor"]}],createOnce(context){let _allowLiterals;let dangerousProperties;let handledMemberExpressions;let openCopyLoops;let armedLoops;let sourceCode;let isInCodemodContext;const NUMERIC_RENDERING_CHARS=/[0-9NI]/;let REQUEST_ROOTS;let numericVarCache;let numericVarInProgress;let ARRAY_PRODUCING_METHODS;let ELEMENT_FIRST_ITERATORS;const isLiteralString=node=>{return(0,eslint_devkit_1.staticString)(node)!==null};const hasPrecedingValidation=(propertyNode,node,writtenObject)=>{if(propertyNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const keyName=propertyNode.name;const isIncludesCall=testNode=>{return testNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes"&&testNode.arguments.length>0&&testNode.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.arguments[0].name===keyName};const guardCoversWrittenObject=guardObject=>{if(sourceCode.getText(guardObject)===sourceCode.getText(writtenObject)){return true}return isModuleOwnedAllowlist(guardObject)};const isHasOwnPropertyCall=testNode=>{if(testNode.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=testNode.callee;const args=testNode.arguments;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(callee)==="call"&&args.length>=2&&args[1].type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&args[1].name===keyName){return guardCoversWrittenObject(args[0])}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(callee)==="hasOwnProperty"||(0,eslint_devkit_1.propertyName)(callee)==="hasOwn")){const isHasOwn=(0,eslint_devkit_1.propertyName)(callee)==="hasOwn";const keyArg=isHasOwn?args[1]:args[0];const guardObject=isHasOwn?args[0]:callee.object;if(keyArg?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&keyArg.name===keyName){return guardCoversWrittenObject(guardObject)}}return false};const isInOperator=testNode=>{return testNode.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&testNode.operator==="in"&&testNode.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.left.name===keyName};const hasValidation=testNode=>{if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&testNode.operator==="!"){return hasValidation(testNode.argument)}return isIncludesCall(testNode)||isHasOwnPropertyCall(testNode)||isInOperator(testNode)};const hasEarlyExit=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement};let current=node.parent;let foundFunctionBody=false;while(current&&!foundFunctionBody){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(hasValidation(current.test)){return true}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&current.parent&&(current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression)){foundFunctionBody=true;const blockBody=current.body;const nodeIndex=blockBody.findIndex(stmt=>{let check=node;while(check){if(check===stmt)return true;check=check.parent}return false});for(let i=0;i<nodeIndex;i++){const stmt=blockBody[i];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&hasValidation(stmt.test)&&hasEarlyExit(stmt.consequent)){return true}}}current=current.parent}return false};const hasDisqualifyingLiteralAffix=node=>{const literalText=n=>{if(n?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(n),n);if(!variable||variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="Variable")return null;if(variable.references.filter(ref=>ref.isWrite()).length>1)return null;const declarator=def.node;if(declarator.id!==def.name)return null;const init=declarator.init;const value=init?withoutTypeAnnotation(init):null;return value?.type===eslint_devkit_1.AST_NODE_TYPES.Literal?literalText(value):null}if(n?.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return null;const v=n.value;if(typeof v!=="string"&&typeof v!=="number")return null;const s=String(v);return s.length>0?s:null};let prefix=null;let suffix=null;if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){prefix=literalText(node.left);suffix=literalText(node.right)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0){const{quasis,expressions}=node;prefix=quasis[0].value.cooked||literalText(expressions[0]);suffix=quasis[quasis.length-1].value.cooked||literalText(expressions[expressions.length-1])}if(prefix!==null&&!dangerousProperties.some(d=>d.startsWith(prefix))){return true}if(suffix!==null&&!dangerousProperties.some(d=>d.endsWith(suffix))){return true}return false};const hasNumericOperandInConcatenation=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||node.operator!=="+"||dangerousProperties.some(name=>NUMERIC_RENDERING_CHARS.test(name))){return false}const anyNumericOperand=operand=>{if(operand.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&operand.operator==="+"){const chain=operand;return anyNumericOperand(chain.left)||anyNumericOperand(chain.right)}return isNumericKey(operand)};const bin=node;return anyNumericOperand(bin.left)||anyNumericOperand(bin.right)};const hasVisibleNonConstantInitialiser=node=>{const scope=sourceCode.getScope(node);const variable=(0,resolve_reference_1.resolvedReference)(scope,node);if(!variable||variable.defs.length!==1){return false}const def=variable.defs[0];if(def.type!=="Variable"){return false}const init=def.node.init;if(!init){return false}return!(0,eslint_devkit_2.isStaticExpression)({node:init,scope:sourceCode.getScope(init)})};const chainRoot=node=>{let cur=node;while(cur.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression)cur=cur.object;return cur.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?cur:null};const withoutTypeAnnotation=node=>{let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion||current.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression){current=current.expression}return current};const isTsTypeWrapper=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion;const withoutTsWrapper=node=>{let current=node;while(isTsTypeWrapper(current))current=current.expression;return current};const assignmentTarget=node=>withoutTsWrapper(node.left);const isLocallyConstructed=id=>{const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(id),id);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const rawInit=def.node.init;if(!rawInit)return false;const init=withoutTypeAnnotation(rawInit);return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_2.isStaticExpression)({node:init,scope:sourceCode.getScope(init)})};const isUntrustedExpression=node=>{const root=chainRoot(node);if(root===null)return false;if(!REQUEST_ROOTS.has(root.name))return false;return!isLocallyConstructed(root)};const isSymbolKey=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="Symbol"){return true}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(node),node);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const init=def.node.init;if(init?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=init.callee;return callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.name==="Symbol"||callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Symbol"};const isImportedBinding=node=>{const root=chainRoot(node);if(root===null)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(root),root);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type==="ImportBinding"){return true}if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="require"};const isDangerousPropertyAccess=propertyNode=>{if(isSymbolKey(propertyNode))return false;if(isImportedBinding(propertyNode))return false;{const root=chainRoot(propertyNode);if(root!==null&&isLocallyConstructed(root))return false}if(isNumericKey(propertyNode)||hasDisqualifyingLiteralAffix(propertyNode)||hasNumericOperandInConcatenation(propertyNode)){return false}if(propertyNode.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!hasVisibleNonConstantInitialiser(propertyNode)){const name=propertyNode.name;if(/^[A-Z][A-Z0-9_]{2,}$/.test(name)){return false}if(/^[a-z]/.test(name)&&/(?:Code|Status|Version|Kind|Mode|Type|Stage|Level|Phase|Step|Flag|Num|Count)$/.test(name)){return false}}if(isLiteralString(propertyNode)){const propName=String(propertyNode.value);if(dangerousProperties.includes(propName)){return true}return false}return true};const findInitializer=nameNode=>{if(nameNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(nameNode),nameNode);if(!variable||variable.defs.length!==1)return void 0;const def=variable.defs[0];if(def.type!=="Variable")return void 0;return def.node.init??void 0};const isPrototypelessObject=(objectNode,seen=new Set)=>{if(seen.has(objectNode))return false;seen.add(objectNode);if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&objectNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&objectNode.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&objectNode.callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(objectNode.callee)==="assign"&&objectNode.arguments.length>0&&objectNode.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return isPrototypelessObject(objectNode.arguments[0],seen)}if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&objectNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&objectNode.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&objectNode.callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(objectNode.callee)==="create"&&objectNode.arguments.length>0&&objectNode.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&objectNode.arguments[0].value===null){return true}if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const key=(0,eslint_devkit_1.propertyName)(objectNode);if(key===null)return false;const holderInit=findInitializer(objectNode.object);if(holderInit?.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return false;const match=holderInit.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(prop)===key);if(match===void 0||!isPrototypelessObject(match.value,seen)){return false}const holderName=objectNode.object.name;let replaced=false;const seek=node=>{if(replaced||node===null||node===void 0)return;if(node.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression){const left=node.left;if(left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&left.name===holderName){replaced=true;return}if(left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&left.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&left.object.name===holderName&&(0,eslint_devkit_1.propertyName)(left)===key){replaced=true;return}}for(const[childKey,value]of Object.entries(node)){if(childKey==="parent")continue;if(Array.isArray(value)){for(const item of value){if(item!==null&&typeof item==="object"&&"type"in item){seek(item)}}}else if(value!==null&&typeof value==="object"&&"type"in value){seek(value)}}};let root=objectNode;while(root.parent)root=root.parent;seek(root);return!replaced}if(objectNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(objectNode),objectNode);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const declarator=def.node;if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const init=declarator.init;if(!init)return false;if(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&init.elements.length>0&&init.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return true}return init.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isPrototypelessObject(init,seen)};const extractPropertyAccess=node=>{let object;let property;let propertyNode;let isAssignment=false;const left=node.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression?assignmentTarget(node):null;if(left!==null&&left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){object=sourceCode.getText(left.object);property=sourceCode.getText(left.property);propertyNode=left.property;isAssignment=true}else{const memberNode=node;object=sourceCode.getText(memberNode.object);property=sourceCode.getText(memberNode.property);propertyNode=memberNode.property;isAssignment=false}const pattern=OBJECT_INJECTION_PATTERNS.find(p=>new RegExp(p.pattern,"i").test(property)||dangerousProperties.includes(property.replace(/['"]/g,"")))||null;return{object,property,propertyNode,isAssignment,pattern}};const stepName=m=>{if(!m.computed&&m.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return m.property.name;if(m.computed&&m.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof m.property.value==="string"){return m.property.value}return null};const globalPrototypeWrite=node=>{const left=assignmentTarget(node);if(left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const steps=[];let cur=withoutTsWrapper(left.object);while(cur.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const name=stepName(cur);if(name===null)return null;steps.unshift(name);cur=withoutTsWrapper(cur.object)}if(steps.includes("__proto__"))return"__proto__";for(let i=0;i<steps.length-1;i++){if(steps[i]==="constructor"&&steps[i+1]==="prototype")return"constructor.prototype"}return null};const highRiskTarget=node=>{const left=assignmentTarget(node);if(left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return null}if(!left.computed){return null}if(isPrototypelessObject(left.object)){return null}if(isTypedArrayObject(left.object)){return null}if(isArrayAppend(left)){return null}const{propertyNode}=extractPropertyAccess(node);if(isNumericKey(propertyNode)){return null}if(isKeyFromLiteralAllowlist(propertyNode)){return null}if(isForInOrObjectKeysKey(propertyNode)){return null}if(hasPrecedingValidation(propertyNode,node,left.object)){return null}return isDangerousPropertyAccess(propertyNode)?left:null};const isReflectResultAccess=objectNode=>{if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=objectNode.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Reflect"){return true}}if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return isReflectResultAccess(objectNode.expression)}return false};const isHighRiskMemberAccess=node=>{if(!node.computed){return false}if(isReflectResultAccess(node.object)){return false}if(isTypedArrayObject(node.object)){return false}const{propertyNode}=extractPropertyAccess(node);if(isNumericKey(propertyNode)){return false}if(isForInOrObjectKeysKey(propertyNode)){return false}if(hasPrecedingValidation(propertyNode,node,node.object)){return false}return isDangerousPropertyAccess(propertyNode)};const isArrayAppend=member=>{if(member.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const key=member.property;return key.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&key.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&key.object.name===member.object.name&&(0,eslint_devkit_1.propertyName)(key)==="length"};const literalListFromIteratorCallback=(fn,name)=>{if(fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}const first=fn.params[0];if(first?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||first.name!==name){return null}const call=fn.parent;if(call?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||call.arguments[0]!==fn||call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||call.callee.computed){return null}const method=(0,eslint_devkit_1.propertyName)(call.callee);if(method===null||!ELEMENT_FIRST_ITERATORS.has(method))return null;if(call.callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;return call.callee.object};const isKeyFromLiteralAllowlist=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(node),node);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];let listSource;if(def.type==="Variable"){const declaration=def.node.parent;const loop=declaration?.parent;if(loop?.type!==eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||loop.left!==declaration)return false;listSource=loop.right}else if(def.type==="Parameter"){const receiver=literalListFromIteratorCallback(def.node,node.name);if(receiver===null)return false;listSource=receiver}else{return false}let source=withoutTypeAnnotation(listSource);if(source.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&source.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&source.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&source.callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(source.callee)==="freeze"&&source.arguments[0]!==void 0){source=source.arguments[0]}if(source.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const listVar=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(source),source);if(!listVar||listVar.defs.length!==1)return false;const listDef=listVar.defs[0];if(listDef.type!=="Variable")return false;if(listDef.parent?.kind!=="const")return false;if(listDef.node.init===null)return false;source=listDef.node.init}if(source.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&source.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&source.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&source.callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(source.callee)==="freeze"&&source.arguments[0]!==void 0){source=source.arguments[0]}source=withoutTypeAnnotation(source);if(source.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return false;if(source.elements.length===0)return false;return source.elements.every(element=>{const text=element===null?null:(0,eslint_devkit_1.staticString)(element);return text!==null&&!dangerousProperties.includes(text)})};const isNumericKey=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="number"){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression){const op=node.operator;if(op==="+"||op==="-"||op==="~")return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.UpdateExpression){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const op=node.operator;if(op==="|"||op==="&"||op==="^"||op==="<<"||op===">>"||op===">>>"||op==="*"||op==="/"||op==="%"||op==="-"||op==="**"){return true}if(op==="+"){const bin=node;return isNumericKey(bin.left)&&isNumericKey(bin.right)}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){const cond=node;return isNumericKey(cond.consequent)&&isNumericKey(cond.alternate)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=callee.name;if(name==="Number"||name==="parseInt"||name==="parseFloat")return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Math"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return true}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return isNumericIdentifier(node)}return false};const IndexParamPosition=method=>{if(ELEMENT_FIRST_ITERATORS.has(method))return 1;if(method==="reduce"||method==="reduceRight")return 2;return null};const isProvablyArray=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return false;if(callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Array"){return method==="from"||method==="of"}return ARRAY_PRODUCING_METHODS.has(method)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(context.sourceCode.getScope(node),node);const def=variable?.defs.length===1?variable.defs[0]:void 0;if(!def)return false;if(def.type==="Variable"){const declarator=def.node;if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const declared=declarator.id.typeAnnotation;if(declared&&isArrayTypeNode(declared.typeAnnotation))return true;if(def.parent.kind!=="const")return false;const init=declarator.init;if(!init||init===node)return false;return isProvablyArray(init)}if(def.type!=="Parameter")return false;const annotation=def.name.typeAnnotation;return annotation!=null&&isArrayTypeNode(annotation.typeAnnotation)};const isArrayTypeNode=type=>{if(type.type===eslint_devkit_1.AST_NODE_TYPES.TSArrayType)return true;if(type.type===eslint_devkit_1.AST_NODE_TYPES.TSTupleType)return true;if(type.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeOperator){return type.operator==="readonly"&&type.typeAnnotation!=null&&isArrayTypeNode(type.typeAnnotation)}if(type.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference){const name=type.typeName;return name.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(name.name==="Array"||name.name==="ReadonlyArray")}return false};const isArrayIterationIndexParam=node=>{const variable=(0,resolve_reference_1.resolvedReference)(context.sourceCode.getScope(node),node);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def?.type!=="Parameter")return false;if(variable.references.some(ref=>ref.isWrite()))return false;const fn=def.node;if(fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return false}const call=fn.parent;if(call?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||call.arguments[0]!==fn||call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return false}const method=(0,eslint_devkit_1.propertyName)(call.callee);if(method===null)return false;const position=IndexParamPosition(method);if(position===null)return false;const param=fn.params[position];if(param?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||param!==def.name){return false}return isProvablyArray(call.callee.object)};const isNumericIdentifier=node=>{if(isArrayIterationIndexParam(node))return true;const scope=context.sourceCode.getScope(node);const variable=(0,resolve_reference_1.resolvedReference)(scope,node);if(!variable||variable.defs.length===0)return false;const cached=numericVarCache.get(variable);if(cached!==void 0)return cached;if(numericVarInProgress.has(variable))return true;numericVarInProgress.add(variable);let result=false;const def=variable.defs[0];const declarator=def.node;if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&declarator.parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration){result=isNumericKey(declarator.init);if(result){for(const ref of variable.references){const written=ref.writeExpr;if(!written||written===declarator.init)continue;if(!isNumericKey(written)){result=false;break}}}}numericVarInProgress.delete(variable);numericVarCache.set(variable,result);return result};const isObjectKeysCallbackKey=(fn,name)=>{if(fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return false}const first=fn.params[0];const bindsName=first?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&first.name===name||first?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&first.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&first.elements[0].name===name;if(!bindsName)return false;const call=fn.parent;if(call?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||call.arguments[0]!==fn||call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||call.callee.computed||call.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!ELEMENT_FIRST_ITERATORS.has(call.callee.property.name)){return false}const source=call.callee.object;return source.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&source.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&source.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&source.callee.object.name==="Object"&&((0,eslint_devkit_1.propertyName)(source.callee)==="keys"||(0,eslint_devkit_1.propertyName)(source.callee)==="entries")};const isForInOrObjectKeysKey=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const scope=context.sourceCode.getScope(node);const variable=(0,resolve_reference_1.resolvedReference)(scope,node);if(!variable||variable.defs.length===0)return false;const def=variable.defs[0];if(def.type==="Parameter"){return isObjectKeysCallbackKey(def.node,node.name)}const varDecl=def.node?.parent;const loopStmt=varDecl?.parent;if(!varDecl||varDecl.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration)return false;if(loopStmt?.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement&&loopStmt.left===varDecl){return true}if(loopStmt?.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement&&loopStmt.left===varDecl){const right=loopStmt.right;return right.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&right.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&right.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&right.callee.object.name==="Object"&&((0,eslint_devkit_1.propertyName)(right.callee)==="keys"||(0,eslint_devkit_1.propertyName)(right.callee)==="entries")}return false};const isTypedArrayObject=objectNode=>{if(objectNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const varName=objectNode.name;let scope=context.sourceCode.getScope(objectNode);while(scope){const variable=scope.set.get(varName);if(variable){for(const def of variable.defs){const init=def.node.init;if(init?.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TYPED_ARRAY_CTORS.has(init.callee.name)){return true}}break}if(!scope.upper)break;scope=scope.upper}return false};const determineRiskLevel=(pattern,isAssignment)=>{if(pattern?.riskLevel==="critical"||pattern&&isAssignment){return"CRITICAL"}if(pattern?.riskLevel==="high"||isAssignment){return"HIGH"}return"MEDIUM"};const checkAssignmentExpression=node=>{const step=globalPrototypeWrite(node);if(step!==null){for(let m=assignmentTarget(node);m.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression;m=withoutTsWrapper(m.object)){handledMemberExpressions.add(m)}context.report({node,messageId:"globalPrototypeWrite",data:{step}});return}const target=highRiskTarget(node);if(target===null){return}if(keyComesFromConstAllowlist(target.property,node)){return}let me=target;handledMemberExpressions.add(me);for(let inner=withoutTsWrapper(me.object);inner.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&inner.computed;inner=withoutTsWrapper(me.object)){me=inner;handledMemberExpressions.add(me)}const{object,property,isAssignment,pattern}=extractPropertyAccess(node);const riskLevel=determineRiskLevel(pattern,isAssignment);context.report({node,messageId:"objectInjection",data:{pattern:`${object}[${property}]`,riskLevel,vulnerability:pattern?.vulnerability||"object injection",safeAlternative:pattern?.safeAlternative||"Use Map or property whitelisting"}})};const constObjectLiteralOf=(name,from)=>{for(let scope=sourceCode.getScope(from);scope;scope=scope.upper){const variable=scope.set.get(name);if(!variable)continue;if(variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="Variable"||def.parent?.kind!=="const")return null;if(variable.references.some(ref=>ref.isWrite()&&ref.identifier!==def.name)){return null}const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression?init:null}return null};const isReadFromConstObjectLiteral=node=>node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&constObjectLiteralOf(node.object.name,node)!==null;const keyComesFromConstAllowlist=(property,from)=>{if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let scope=sourceCode.getScope(from);scope;scope=scope.upper){const variable=scope.set.get(property.name);if(!variable)continue;if(variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable"||def.parent?.kind!=="const")return false;if(variable.references.some(ref=>ref.isWrite()&&ref.identifier!==def.name)){return false}const init=def.node.init;if(init?.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||!init.computed||init.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const source=constObjectLiteralOf(init.object.name,init);if(!source)return false;return source.properties.every(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&p.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof p.value.value==="string")}return false};const isInvokedRead=node=>{const parent=node.parent;if(parent===void 0)return false;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee===node){return true}if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator||parent.init!==node||parent.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const variable=context.sourceCode.getDeclaredVariables(parent).find(candidate=>candidate.name===parent.id.name);return variable?.references.some(reference=>{const referenceParent=reference.identifier.parent;return referenceParent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&referenceParent.callee===reference.identifier})??false};const isWriteTarget=node=>{let current=node;let parent=current.parent;while(parent!==void 0){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.left===current){return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.UpdateExpression&&parent.argument===current){return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&parent.operator==="delete"){return true}if(isTsTypeWrapper(parent)&&parent.expression===current){current=parent;parent=parent.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrayPattern||parent.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern||parent.type===eslint_devkit_1.AST_NODE_TYPES.RestElement&&parent.argument===current||parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentPattern&&parent.left===current||parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===current&&parent.parent.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern){current=parent;parent=current.parent;continue}if((parent.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement)&&parent.left===current){return true}return false}return false};const checkMemberExpression=node=>{if(!isWriteTarget(node)&&!isInvokedRead(node)){return}if(!isHighRiskMemberAccess(node)){return}if(isReadFromConstObjectLiteral(node)){return}if(handledMemberExpressions.has(node)){return}const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.computed&&parent.object===node){return}let target=node;let holder=parent;while(holder&&isTsTypeWrapper(holder)&&holder.expression===target){target=holder;holder=holder.parent}if(holder&&holder.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&holder.left===target){return}const{object,property,isAssignment,pattern}=extractPropertyAccess(node);const riskLevel=determineRiskLevel(pattern,isAssignment);context.report({node,messageId:"objectInjection",data:{pattern:`${object}[${property}]`,riskLevel,vulnerability:pattern?.vulnerability||"object injection",safeAlternative:pattern?.safeAlternative||"Use Map or property whitelisting"}})};const checkObjectAssignSpread=node=>{if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callee=node.callee;const objectIsObject=callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Object";const propIsAssign=(0,eslint_devkit_1.propertyName)(callee)==="assign";if(!objectIsObject||!propIsAssign)return;if(node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;if(node.arguments[0]&&isPrototypelessObject(node.arguments[0]))return;const sources=node.arguments.slice(1);const anyTaintedSource=sources.some(s=>s.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&s.type!==eslint_devkit_1.AST_NODE_TYPES.Literal);if(!anyTaintedSource)return;context.report({node,messageId:"objectInjection",data:{pattern:"Object.assign(target, untrustedSource)",riskLevel:"HIGH",vulnerability:"object injection via Object.assign spread",safeAlternative:"Validate or whitelist keys before merging: `for (const k of Object.keys(src)) if (!ALLOWED.has(k)) continue;`"}})};const reportMassAssignment=(source,keyName,bodyNode)=>{if(!isCopyLoopSourceOpaque(source))return;if(bodyGuardsKey(bodyNode,keyName,{isModuleOwnedAllowlist}))return;let reported=false;const walk=n=>{if(reported)return;if(n.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&n.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&n.left.computed&&n.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&n.left.property.name===keyName){reported=true;context.report({node:n,messageId:"massAssignment",data:{key:keyName}});return}for(const key of Object.keys(n)){const child=n[key];if(key==="parent"||child===null||typeof child!=="object")continue;for(const c of Array.isArray(child)?child:[child]){if(c&&typeof c.type==="string")walk(c)}}};walk(bodyNode)};const checkMassAssignmentCallback=node=>{const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null||!ELEMENT_FIRST_ITERATORS.has(method))return;const receiver=callee.object;if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||receiver.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||receiver.callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||receiver.callee.object.name!=="Object"||!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(receiver.callee),["keys","entries"])){return}const source=receiver.arguments[0];if(source===void 0)return;const fn=node.arguments[0];if(fn===void 0||fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return}const first=fn.params[0];const keyName=first?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?first.name:first?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&first.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?first.elements[0].name:null;if(keyName===null)return;reportMassAssignment(source,keyName,fn.body)};const checkMassAssignmentLoop=node=>{if(isInCodemodContext)return;const iterated=node.right;if(iterated.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return;const callee=iterated.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||callee.object.name!=="Object"||!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["keys","entries"])){return}const source=iterated.arguments[0];if(source===void 0)return;if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration)return;const bound=node.left.declarations[0]?.id;const keyName=bound?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?bound.name:bound?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&bound.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?bound.elements[0].name:null;if(keyName===null)return;reportMassAssignment(source,keyName,node.body)};const isLiteralAllowlist=init=>{const value=(0,eslint_devkit_1.unwrapTypeSyntax)(init);if(value?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const{callee}=value;const isFreeze=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(callee)==="freeze";return isFreeze&&isLiteralAllowlist(value.arguments[0])}const isOwnedName=name=>name!==null&&!POLLUTION_KEYS.has(name);if(value?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return value.elements.every(element=>element===null||isOwnedName((0,eslint_devkit_1.staticString)(element)))}return value?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&value.properties.every(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&isOwnedName((0,eslint_devkit_1.objectKeyName)(property)))};const isModuleOwnedAllowlist=objectNode=>{if(objectNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(objectNode),objectNode);if(!variable)return true;if(variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable"||def.parent?.kind!=="const"){return false}return isLiteralAllowlist(def.node.init)};const isCopyLoopSourceOpaque=source=>{if(isUntrustedExpression(source))return true;if(source.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return isCopyLoopSourceOpaque(source.expression)}if(source.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return isCopyLoopSourceOpaque(source.object)}if(source.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(source),source);if(!variable)return false;if(variable.defs.some(def2=>def2.type==="Parameter"))return true;const loopDef=variable.defs[0];const loop=loopDef?.type==="Variable"?loopDef.parent?.parent:null;if(loop?.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement&&loop.left===loopDef?.parent&&!(loop.right.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&loop.right.name===variable.name))return isCopyLoopSourceOpaque(loop.right);if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const def=variable.defs[0];if(!def||def.type!=="Variable")return false;const init=def.node.init;return init?isUntrustedExpression(init):false};const checkPrototypePollutingCopyLoop=node=>{if(isInCodemodContext)return;const keyName=node.left.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration?node.left.declarations[0]?.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.left.declarations[0].id.name:void 0:node.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.left.name:void 0;if(!keyName)return;if(!isCopyLoopSourceOpaque(node.right))return;if(bodyGuardsKey(node.body,keyName,{isModuleOwnedAllowlist,deferOwnershipGuards:true})){return}armedLoops.add(node);openCopyLoops.push({keyName,reported:false})};const reportCopyLoopWrite=node=>{const left=assignmentTarget(node);if(left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||!left.computed||left.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const propertyName=left.property.name;const loop=openCopyLoops.find(open=>open.keyName===propertyName&&!open.reported);if(!loop)return false;if(hasPrecedingValidation(left.property,node,left.object)){return false}loop.reported=true;context.report({node,messageId:"objectInjection",data:{riskLevel:"HIGH",safeAlternative:'Guard the key before assigning: `if (k === "__proto__" || k === "constructor" || k === "prototype") continue;` \u2014 or copy with Object.create(null) / structuredClone.'}});return true};return{before(){const options=context.options[0]||{};({allowLiterals:_allowLiterals=false,dangerousProperties=["__proto__","prototype","constructor"]}=options);handledMemberExpressions=new WeakSet;openCopyLoops=[];armedLoops=new WeakSet;sourceCode=context.sourceCode;isInCodemodContext=(()=>{const filename=context.filename;if(/\/codemod[s]?\//i.test(filename))return true;if(/codemod\.[mc]?[jt]sx?$/i.test(filename))return true;return fileUsesAstTooling(sourceCode.ast)})();REQUEST_ROOTS=new Set(["req","request","ctx","context","event"]);numericVarCache=new WeakMap;numericVarInProgress=new WeakSet;ARRAY_PRODUCING_METHODS=new Set(["split","slice","concat","map","filter","flat","flatMap","toSorted","toReversed"]);ELEMENT_FIRST_ITERATORS=new Set(["forEach","map","filter","find","findLast","some","every","flatMap"])},ForOfStatement:checkMassAssignmentLoop,ForInStatement:checkPrototypePollutingCopyLoop,"ForInStatement:exit":node=>{if(armedLoops.has(node))openCopyLoops.pop()},AssignmentExpression:node=>{if(isInCodemodContext)return;if(reportCopyLoopWrite(node))return;return checkAssignmentExpression(node)},MemberExpression:node=>{if(isInCodemodContext)return;return checkMemberExpression(node)},CallExpression:node=>{if(isInCodemodContext)return;checkMassAssignmentCallback(node);return checkObjectAssignSpread(node)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.detectObjectInjection=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 resolve_reference_1=require("../../utils/resolve-reference");const fileUsesAstTooling=(0,eslint_devkit_3.createModuleEvidence)({packages:["@babel/types","@babel/traverse","recast","jscodeshift","eslint","estree-walker","ast-types","esrap","unist-util-visit"],scopes:["@typescript-eslint"]});const TYPED_ARRAY_CTORS=new Set(["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"]);const OBJECT_INJECTION_PATTERNS=[{pattern:"__proto__",safeAlternative:"Object.create(null) or Map",riskLevel:"critical"},{pattern:"prototype",safeAlternative:"Avoid prototype manipulation",riskLevel:"high"},{pattern:"constructor",safeAlternative:"Validate property names against whitelist",riskLevel:"medium"}];const KEY_GUARD_CALLEES=new Set(["includes","has","hasOwn","hasOwnProperty","indexOf","call"]);const OWNERSHIP_GUARD_CALLEES=new Set(["hasOwn","hasOwnProperty","call"]);const POLLUTION_KEYS=new Set(["__proto__","constructor","prototype"]);const childNodes=n=>{const out=[];for(const key of Object.keys(n)){if(key==="parent")continue;const child=n[key];for(const item of Array.isArray(child)?child:[child]){if(item&&typeof item==="object"&&"type"in item){out.push(item)}}}return out};const mentionsKey=(n,keyName)=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return n.name===keyName;return childNodes(n).some(child=>mentionsKey(child,keyName))};const bodyGuardsKey=(bodyNode,keyName,{isModuleOwnedAllowlist,deferOwnershipGuards=false})=>{let membershipGuard=false;let guardCoversModuleOwned=false;const guardedObjectPaths=new Set;const writtenObjectPaths=new Set;const objectPath=n=>{const path=(0,eslint_devkit_1.memberPath)(n);return path===null?null:JSON.stringify(path)};const pollutionKeysNamed=new Set;let passesKeyedReadOnward=false;const creditGuardedObject=tested=>{membershipGuard=true;const path=objectPath(tested);if(path===null)return;guardedObjectPaths.add(path);if(isModuleOwnedAllowlist(tested))guardCoversModuleOwned=true};const walk=n=>{if(n.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&n.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&n.left.computed&&mentionsKey(n.left.property,keyName)){const path=objectPath(n.left.object);if(path!==null)writtenObjectPaths.add(path)}if(n.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&n.arguments.some(argument=>argument.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&argument.computed&&mentionsKey(argument.property,keyName))){passesKeyedReadOnward=true}if(n.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&n.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&KEY_GUARD_CALLEES.has((0,eslint_devkit_1.propertyName)(n.callee)??"")&&!(deferOwnershipGuards&&OWNERSHIP_GUARD_CALLEES.has((0,eslint_devkit_1.propertyName)(n.callee)??""))&&n.arguments.some(argument=>mentionsKey(argument,keyName))){const tested=(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(n.callee),["hasOwn","call"])?n.arguments.slice(0,1):[n.callee.object];for(const object of tested)creditGuardedObject(object)}if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&n.operator==="in"&&mentionsKey(n.left,keyName)){creditGuardedObject(n.right)}if(n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&["===","!==","==","!="].includes(n.operator)){const compared=(0,eslint_devkit_1.staticString)(n.left)??(0,eslint_devkit_1.staticString)(n.right);const other=(0,eslint_devkit_1.staticString)(n.left)===null?n.left:n.right;if(compared!==null&&POLLUTION_KEYS.has(compared)&&mentionsKey(other,keyName)){pollutionKeysNamed.add(compared)}}for(const child of childNodes(n))walk(child)};walk(bodyNode);const guardCoversWrittenObject=[...guardedObjectPaths].some(path=>writtenObjectPaths.has(path));if(guardCoversWrittenObject||guardCoversModuleOwned)return true;if(!membershipGuard&&pollutionKeysNamed.size===0)return false;return!passesKeyedReadOnward||pollutionKeysNamed.size===POLLUTION_KEYS.size};exports.detectObjectInjection=(0,eslint_devkit_3.createRule)({name:"detect-object-injection",meta:{interop:{runtimes:["eslint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/detect-object-injection.md",description:"Detects variable[key] written as an assignment target, or read and then invoked",cwe:"CWE-915",confidence:"low"},messages:{objectInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.WARNING,issueName:"Object injection",cwe:"CWE-915",description:"Object injection/Prototype pollution (incl. model/tool outputs)",severity:"{{riskLevel}}",fix:"{{safeAlternative}} \u2014 Not a finding when the key is a numeric index, a module constant, or guarded by Object.hasOwn / an allowlist",documentationLink:"https://portswigger.net/web-security/prototype-pollution"}),massAssignment:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Mass assignment",cwe:"CWE-915",description:"Every key of an untrusted object is copied onto this target, so the caller chooses which field is written \u2014 including one they should not control, such as isAdmin",severity:"HIGH",fix:"Copy an explicit allowlist of assignable fields instead of the caller's keys \u2014 Not a finding when the iterated object is module-built, or the body checks each key against an allowlist",documentationLink:"https://cwe.mitre.org/data/definitions/915.html"}),globalPrototypeWrite:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Global prototype pollution",cwe:"CWE-1321",description:"Assignment writes THROUGH {{step}}, so the property lands on Object.prototype and every object in the process inherits it",severity:"CRITICAL",fix:"Guard with Object.hasOwn, or build the target with Object.create(null) / a Map \u2014 Not a finding when the path is fixed at build time, or __proto__ / constructor / prototype are rejected first",documentationLink:"https://portswigger.net/web-security/prototype-pollution"})},schema:[{type:"object",properties:{allowLiterals:{type:"boolean",default:false,description:"Allow bracket notation with literal strings"},dangerousProperties:{type:"array",items:{type:"string"},default:["__proto__","prototype","constructor"],description:"Property NAMES treated as dangerous where the name is visible in the source \u2014 `obj['__proto__'] = v`. It cannot apply to a dynamic key (`obj[k] = v`), because there is no name to compare, and it does not gate the CWE-1321 traversal check, which is a fact about the language rather than a vocabulary. Set it to [] to stop reporting literal dangerous-property writes."}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowLiterals:false,dangerousProperties:["__proto__","prototype","constructor"]}],createOnce(context){let dangerousProperties;let handledMemberExpressions;let openCopyLoops;let armedLoops;let sourceCode;let isInCodemodContext;const NUMERIC_RENDERING_CHARS=/[0-9NI]/;let REQUEST_ROOTS;let numericVarCache;let numericVarInProgress;let ARRAY_PRODUCING_METHODS;let ELEMENT_FIRST_ITERATORS;const isLiteralString=node=>{return(0,eslint_devkit_1.staticString)(node)!==null};const hasPrecedingValidation=(propertyNode,node,writtenObject)=>{if(propertyNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const keyName=propertyNode.name;const isIncludesCall=testNode=>{return testNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&testNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(testNode.callee)==="includes"&&testNode.arguments.length>0&&testNode.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.arguments[0].name===keyName};const guardCoversWrittenObject=guardObject=>{if(sourceCode.getText(guardObject)===sourceCode.getText(writtenObject)){return true}return isModuleOwnedAllowlist(guardObject)};const isHasOwnPropertyCall=testNode=>{if(testNode.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=testNode.callee;const args=testNode.arguments;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(callee)==="call"&&args.length>=2&&args[1].type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&args[1].name===keyName){return guardCoversWrittenObject(args[0])}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(callee)==="hasOwnProperty"||(0,eslint_devkit_1.propertyName)(callee)==="hasOwn")){const isHasOwn=(0,eslint_devkit_1.propertyName)(callee)==="hasOwn";const keyArg=isHasOwn?args[1]:args[0];const guardObject=isHasOwn?args[0]:callee.object;if(keyArg?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&keyArg.name===keyName){return guardCoversWrittenObject(guardObject)}}return false};const isInOperator=testNode=>{return testNode.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&testNode.operator==="in"&&testNode.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&testNode.left.name===keyName};const validationPolarity=testNode=>{if(testNode.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&testNode.operator==="!"){return-validationPolarity(testNode.argument)}return isIncludesCall(testNode)||isHasOwnPropertyCall(testNode)||isInOperator(testNode)?1:0};const hasEarlyExit=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||stmt.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement};let child=node;let current=node.parent;let foundFunctionBody=false;while(current&&!foundFunctionBody){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){const polarity=validationPolarity(current.test);if(child===current.consequent?polarity>0:child===current.alternate&&polarity<0){return true}}if(current.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&current.parent&&(current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression)){foundFunctionBody=true;const blockBody=current.body;const nodeIndex=blockBody.indexOf(child);for(let i=0;i<nodeIndex;i++){const stmt=blockBody[i];if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&validationPolarity(stmt.test)<0&&hasEarlyExit(stmt.consequent)){return true}}}child=current;current=current.parent}return false};const hasDisqualifyingLiteralAffix=node=>{const literalText=n=>{if(n?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(n),n);if(!variable||variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="Variable")return null;if(variable.references.filter(ref=>ref.isWrite()).length>1)return null;const declarator=def.node;if(declarator.id!==def.name)return null;const init=declarator.init;const value=init?withoutTypeAnnotation(init):null;return value?.type===eslint_devkit_1.AST_NODE_TYPES.Literal?literalText(value):null}if(n?.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return null;const v=n.value;if(typeof v!=="string"&&typeof v!=="number")return null;const s=String(v);return s.length>0?s:null};let prefix=null;let suffix=null;if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){prefix=literalText(node.left);suffix=literalText(node.right)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0){const{quasis,expressions}=node;prefix=quasis[0].value.cooked||literalText(expressions[0]);suffix=quasis[quasis.length-1].value.cooked||literalText(expressions[expressions.length-1])}if(prefix!==null&&!dangerousProperties.some(d=>d.startsWith(prefix))){return true}if(suffix!==null&&!dangerousProperties.some(d=>d.endsWith(suffix))){return true}return false};const hasNumericOperandInConcatenation=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||node.operator!=="+"||dangerousProperties.some(name=>NUMERIC_RENDERING_CHARS.test(name))){return false}const anyNumericOperand=operand=>{if(operand.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&operand.operator==="+"){const chain=operand;return anyNumericOperand(chain.left)||anyNumericOperand(chain.right)}return isNumericKey(operand)};const bin=node;return anyNumericOperand(bin.left)||anyNumericOperand(bin.right)};const hasVisibleNonConstantInitialiser=node=>{const scope=sourceCode.getScope(node);const variable=(0,resolve_reference_1.resolvedReference)(scope,node);if(!variable||variable.defs.length!==1){return false}const def=variable.defs[0];if(def.type!=="Variable"){return false}const init=def.node.init;if(!init){return false}return!(0,eslint_devkit_2.isStaticExpression)({node:init,scope:sourceCode.getScope(init)})};const chainRoot=node=>{let cur=node;while(cur.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression)cur=cur.object;return cur.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?cur:null};const withoutTypeAnnotation=node=>{let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion||current.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression){current=current.expression}return current};const isTsTypeWrapper=node=>node.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.TSNonNullExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.TSSatisfiesExpression||node.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeAssertion;const withoutTsWrapper=node=>{let current=node;while(isTsTypeWrapper(current))current=current.expression;return current};const assignmentTarget=node=>withoutTsWrapper(node.left);const isLocallyConstructed=id=>{const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(id),id);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const rawInit=def.node.init;if(!rawInit)return false;const init=withoutTypeAnnotation(rawInit);return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_2.isStaticExpression)({node:init,scope:sourceCode.getScope(init)})};const isUntrustedExpression=node=>{const root=chainRoot(node);if(root===null)return false;if(!REQUEST_ROOTS.has(root.name))return false;return!isLocallyConstructed(root)};const isSymbolKey=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.object.name==="Symbol"){return true}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(node),node);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const init=def.node.init;if(init?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=init.callee;return callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.name==="Symbol"||callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Symbol"};const isImportedBinding=node=>{const root=chainRoot(node);if(root===null)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(root),root);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type==="ImportBinding"){return true}if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="require"};const isDangerousPropertyAccess=propertyNode=>{if(isSymbolKey(propertyNode))return false;if(isImportedBinding(propertyNode))return false;{const root=chainRoot(propertyNode);if(root!==null&&isLocallyConstructed(root))return false}if(isNumericKey(propertyNode)||hasDisqualifyingLiteralAffix(propertyNode)||hasNumericOperandInConcatenation(propertyNode)){return false}if(propertyNode.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!hasVisibleNonConstantInitialiser(propertyNode)){const name=propertyNode.name;if(/^[A-Z][A-Z0-9_]{2,}$/.test(name)){return false}if(/^[a-z]/.test(name)&&/(?:Code|Status|Version|Kind|Mode|Type|Stage|Level|Phase|Step|Flag|Num|Count)$/.test(name)){return false}}if(isLiteralString(propertyNode)){const propName=String(propertyNode.value);if(dangerousProperties.includes(propName)){return true}return false}return true};const findInitializer=nameNode=>{if(nameNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(nameNode),nameNode);if(!variable||variable.defs.length!==1)return void 0;const def=variable.defs[0];if(def.type!=="Variable")return void 0;return def.node.init??void 0};const isPrototypelessObject=(objectNode,seen=new Set)=>{if(seen.has(objectNode))return false;seen.add(objectNode);if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&objectNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&objectNode.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&objectNode.callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(objectNode.callee)==="assign"&&objectNode.arguments.length>0&&objectNode.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return isPrototypelessObject(objectNode.arguments[0],seen)}if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&objectNode.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&objectNode.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&objectNode.callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(objectNode.callee)==="create"&&objectNode.arguments.length>0&&objectNode.arguments[0].type===eslint_devkit_1.AST_NODE_TYPES.Literal&&objectNode.arguments[0].value===null){return true}if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const key=(0,eslint_devkit_1.propertyName)(objectNode);if(key===null)return false;const holderInit=findInitializer(objectNode.object);if(holderInit?.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return false;const match=holderInit.properties.find(prop=>prop.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(prop)===key);if(match===void 0||!isPrototypelessObject(match.value,seen)){return false}const holderName=objectNode.object.name;let replaced=false;const seek=node=>{if(replaced||node===null||node===void 0)return;if(node.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression){const left=node.left;if(left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&left.name===holderName){replaced=true;return}if(left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&left.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&left.object.name===holderName&&(0,eslint_devkit_1.propertyName)(left)===key){replaced=true;return}}for(const[childKey,value]of Object.entries(node)){if(childKey==="parent")continue;if(Array.isArray(value)){for(const item of value){if(item!==null&&typeof item==="object"&&"type"in item){seek(item)}}}else if(value!==null&&typeof value==="object"&&"type"in value){seek(value)}}};let root=objectNode;while(root.parent)root=root.parent;seek(root);return!replaced}if(objectNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(objectNode),objectNode);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable")return false;if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const declarator=def.node;if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const init=declarator.init;if(!init)return false;if(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&init.elements.length>0&&init.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return true}return init.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isPrototypelessObject(init,seen)};const injectionPattern=propertyNode=>{const name=(0,eslint_devkit_1.staticString)(propertyNode);return OBJECT_INJECTION_PATTERNS.find(p=>p.pattern===name)??null};const stepName=m=>(0,eslint_devkit_1.propertyName)(m)??"";const globalPrototypeWrite=node=>{const left=assignmentTarget(node);if(left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const steps=[];let cur=withoutTsWrapper(left.object);while(cur.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){steps.unshift(stepName(cur));cur=withoutTsWrapper(cur.object)}if(steps.includes("__proto__"))return"__proto__";for(let i=0;i<steps.length-1;i++){if(steps[i]==="constructor"&&steps[i+1]==="prototype")return"constructor.prototype"}return null};const highRiskTarget=node=>{const left=assignmentTarget(node);if(left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return null}if(!left.computed){return null}if(isPrototypelessObject(left.object)){return null}if(isTypedArrayObject(left.object)){return null}if(isArrayAppend(left)){return null}const propertyNode=left.property;if(isKeyFromLiteralAllowlist(propertyNode)){return null}if(isForInOrObjectKeysKey(propertyNode)){return null}if(hasPrecedingValidation(propertyNode,node,left.object)){return null}return isDangerousPropertyAccess(propertyNode)?left:null};const isReflectResultAccess=objectNode=>{if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=objectNode.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Reflect"){return true}}if(objectNode.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return isReflectResultAccess(objectNode.expression)}return false};const isHighRiskMemberAccess=node=>{if(!node.computed){return false}if(isReflectResultAccess(node.object)){return false}if(isTypedArrayObject(node.object)){return false}const propertyNode=node.property;if(isForInOrObjectKeysKey(propertyNode)){return false}if(hasPrecedingValidation(propertyNode,node,node.object)){return false}return isDangerousPropertyAccess(propertyNode)};const isArrayAppend=member=>{if(member.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const key=member.property;return key.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&key.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&key.object.name===member.object.name&&(0,eslint_devkit_1.propertyName)(key)==="length"};const literalListFromIteratorCallback=(fn,name)=>{if(fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return null}const first=fn.params[0];if(first?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||first.name!==name){return null}const call=fn.parent;if(call?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||call.arguments[0]!==fn||call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||call.callee.computed){return null}const method=(0,eslint_devkit_1.propertyName)(call.callee);if(method===null||!ELEMENT_FIRST_ITERATORS.has(method))return null;return call.callee.object};const isKeyFromLiteralAllowlist=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(node),node);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];let listSource;if(def.type==="Variable"){const declaration=def.node.parent;const loop=declaration?.parent;if(loop?.type!==eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||loop.left!==declaration)return false;listSource=loop.right}else if(def.type==="Parameter"){const receiver=literalListFromIteratorCallback(def.node,node.name);if(receiver===null)return false;listSource=receiver}else{return false}let source=withoutTypeAnnotation(listSource);if(source.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&source.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&source.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&source.callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(source.callee)==="freeze"&&source.arguments[0]!==void 0){source=source.arguments[0]}if(source.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const listVar=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(source),source);if(!listVar||listVar.defs.length!==1)return false;const listDef=listVar.defs[0];if(listDef.type!=="Variable")return false;if(listDef.parent?.kind!=="const")return false;if(listDef.node.init===null)return false;source=listDef.node.init}if(source.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&source.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&source.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&source.callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(source.callee)==="freeze"&&source.arguments[0]!==void 0){source=source.arguments[0]}source=withoutTypeAnnotation(source);if(source.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return false;if(source.elements.length===0)return false;return source.elements.every(element=>{const text=element===null?null:(0,eslint_devkit_1.staticString)(element);return text!==null&&!dangerousProperties.includes(text)})};const isNumericKey=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="number"){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression){const op=node.operator;if(op==="+"||op==="-"||op==="~")return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.UpdateExpression){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const op=node.operator;if(op==="|"||op==="&"||op==="^"||op==="<<"||op===">>"||op===">>>"||op==="*"||op==="/"||op==="%"||op==="-"||op==="**"){return true}if(op==="+"){const bin=node;return isNumericKey(bin.left)&&isNumericKey(bin.right)}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){const cond=node;return isNumericKey(cond.consequent)&&isNumericKey(cond.alternate)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=callee.name;if(name==="Number"||name==="parseInt"||name==="parseFloat")return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Math"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return true}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return isNumericIdentifier(node)}return false};const IndexParamPosition=method=>{if(ELEMENT_FIRST_ITERATORS.has(method))return 1;if(method==="reduce"||method==="reduceRight")return 2;return null};const isProvablyArray=node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return false;if(callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Array"){return method==="from"||method==="of"}return ARRAY_PRODUCING_METHODS.has(method)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(context.sourceCode.getScope(node),node);const def=variable?.defs.length===1?variable.defs[0]:void 0;if(!def)return false;if(def.type==="Variable"){const declarator=def.node;if(declarator.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const declared=declarator.id.typeAnnotation;if(declared&&isArrayTypeNode(declared.typeAnnotation))return true;if(def.parent.kind!=="const")return false;const init=declarator.init;if(!init||init===node)return false;return isProvablyArray(init)}if(def.type!=="Parameter")return false;const annotation=def.name.typeAnnotation;return annotation!=null&&isArrayTypeNode(annotation.typeAnnotation)};const isArrayTypeNode=type=>{if(type.type===eslint_devkit_1.AST_NODE_TYPES.TSArrayType)return true;if(type.type===eslint_devkit_1.AST_NODE_TYPES.TSTupleType)return true;if(type.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeOperator){return type.operator==="readonly"&&type.typeAnnotation!=null&&isArrayTypeNode(type.typeAnnotation)}if(type.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference){const name=type.typeName;return name.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(name.name==="Array"||name.name==="ReadonlyArray")}return false};const isArrayIterationIndexParam=node=>{const variable=(0,resolve_reference_1.resolvedReference)(context.sourceCode.getScope(node),node);if(!variable||variable.defs.length!==1)return false;const def=variable.defs[0];if(def?.type!=="Parameter")return false;if(variable.references.some(ref=>ref.isWrite()))return false;const fn=def.node;if(fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return false}const call=fn.parent;if(call?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||call.arguments[0]!==fn||call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return false}const method=(0,eslint_devkit_1.propertyName)(call.callee);if(method===null)return false;const position=IndexParamPosition(method);if(position===null)return false;const param=fn.params[position];if(param?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||param!==def.name){return false}return isProvablyArray(call.callee.object)};const isNumericIdentifier=node=>{if(isArrayIterationIndexParam(node))return true;const scope=context.sourceCode.getScope(node);const variable=(0,resolve_reference_1.resolvedReference)(scope,node);if(!variable||variable.defs.length===0)return false;const cached=numericVarCache.get(variable);if(cached!==void 0)return cached;if(numericVarInProgress.has(variable))return true;numericVarInProgress.add(variable);let result=false;const def=variable.defs[0];const declarator=def.node;if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&declarator.parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration){result=isNumericKey(declarator.init);if(result){for(const ref of variable.references){const written=ref.writeExpr;if(!written||written===declarator.init)continue;if(!isNumericKey(written)){result=false;break}}}}numericVarInProgress.delete(variable);numericVarCache.set(variable,result);return result};const isObjectKeysCallbackKey=(fn,name)=>{if(fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return false}const first=fn.params[0];const bindsName=first?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&first.name===name||first?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&first.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&first.elements[0].name===name;if(!bindsName)return false;const call=fn.parent;if(call?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||call.arguments[0]!==fn||call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||call.callee.computed||call.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!ELEMENT_FIRST_ITERATORS.has(call.callee.property.name)){return false}const source=call.callee.object;return source.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&source.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&source.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&source.callee.object.name==="Object"&&((0,eslint_devkit_1.propertyName)(source.callee)==="keys"||(0,eslint_devkit_1.propertyName)(source.callee)==="entries")};const isForInOrObjectKeysKey=node=>{if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const scope=context.sourceCode.getScope(node);const variable=(0,resolve_reference_1.resolvedReference)(scope,node);if(!variable||variable.defs.length===0)return false;const def=variable.defs[0];if(def.type==="Parameter"){return isObjectKeysCallbackKey(def.node,node.name)}const varDecl=def.node?.parent;const loopStmt=varDecl?.parent;if(!varDecl||varDecl.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration)return false;if(loopStmt?.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement&&loopStmt.left===varDecl){return true}if(loopStmt?.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement&&loopStmt.left===varDecl){const right=loopStmt.right;return right.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&right.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&right.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&right.callee.object.name==="Object"&&((0,eslint_devkit_1.propertyName)(right.callee)==="keys"||(0,eslint_devkit_1.propertyName)(right.callee)==="entries")}return false};const isTypedArrayObject=objectNode=>{if(objectNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const varName=objectNode.name;let scope=context.sourceCode.getScope(objectNode);while(scope){const variable=scope.set.get(varName);if(variable){for(const def of variable.defs){const init=def.node.init;if(init?.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TYPED_ARRAY_CTORS.has(init.callee.name)){return true}}break}if(!scope.upper)break;scope=scope.upper}return false};const reportInjection=(node,propertyNode,isAssignment)=>{const pattern=injectionPattern(propertyNode);context.report({node,messageId:"objectInjection",data:{riskLevel:isAssignment?pattern?"CRITICAL":"HIGH":(pattern?.riskLevel??"medium").toUpperCase(),safeAlternative:pattern?.safeAlternative??"Use Map or property whitelisting"}})};const checkAssignmentExpression=node=>{const step=globalPrototypeWrite(node);if(step!==null){for(let m=assignmentTarget(node);m.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression;m=withoutTsWrapper(m.object)){handledMemberExpressions.add(m)}context.report({node,messageId:"globalPrototypeWrite",data:{step}});return}const target=highRiskTarget(node);if(target===null){return}if(keyComesFromConstAllowlist(target.property,node)){return}for(let inner=withoutTsWrapper(target.object);inner.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&inner.computed;inner=withoutTsWrapper(inner.object)){handledMemberExpressions.add(inner)}reportInjection(node,target.property,true)};const constObjectLiteralOf=(name,from)=>{for(let scope=sourceCode.getScope(from);scope;scope=scope.upper){const variable=scope.set.get(name);if(!variable)continue;if(variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="Variable"||def.parent?.kind!=="const")return null;if(variable.references.some(ref=>ref.isWrite()&&ref.identifier!==def.name)){return null}const init=def.node.init;return init?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression?init:null}return null};const isReadFromConstObjectLiteral=node=>node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&constObjectLiteralOf(node.object.name,node)!==null;const keyComesFromConstAllowlist=(property,from)=>{if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;for(let scope=sourceCode.getScope(from);scope;scope=scope.upper){const variable=scope.set.get(property.name);if(!variable)continue;if(variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable"||def.parent?.kind!=="const")return false;if(variable.references.some(ref=>ref.isWrite()&&ref.identifier!==def.name)){return false}const init=def.node.init;if(init?.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||!init.computed||init.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const source=constObjectLiteralOf(init.object.name,init);if(!source)return false;return source.properties.every(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Property&&p.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof p.value.value==="string")}return false};const isInvocationOf=(parent,callee)=>(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression||parent.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression)&&parent.callee===callee;const isInvokedRead=node=>{const parent=node.parent;if(parent===void 0)return false;if(isInvocationOf(parent,node)){return true}if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator||parent.init!==node||parent.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}return context.sourceCode.getDeclaredVariables(parent).some(variable=>variable.references.some(reference=>isInvocationOf(reference.identifier.parent,reference.identifier)))};const isWriteTarget=node=>{let current=node;let parent=current.parent;while(parent!==void 0){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.left===current){return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.UpdateExpression&&parent.argument===current){return true}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&parent.operator==="delete"){return true}if((isTsTypeWrapper(parent)||parent.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression)&&parent.expression===current){current=parent;parent=parent.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.ArrayPattern||parent.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern||parent.type===eslint_devkit_1.AST_NODE_TYPES.RestElement&&parent.argument===current||parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentPattern&&parent.left===current||parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===current&&parent.parent.type===eslint_devkit_1.AST_NODE_TYPES.ObjectPattern){current=parent;parent=current.parent;continue}if((parent.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement)&&parent.left===current){return true}return false}return false};const checkMemberExpression=node=>{const isWrite=isWriteTarget(node);if(!isWrite&&!isInvokedRead(node)){return}if(!isHighRiskMemberAccess(node)){return}if(isWrite){if(isReadFromConstObjectLiteral(node)){return}}else if(isPrototypelessObject(node.object)){return}if(handledMemberExpressions.has(node)){return}const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.computed&&parent.object===node){return}let target=node;let holder=parent;while(holder&&isTsTypeWrapper(holder)&&holder.expression===target){target=holder;holder=holder.parent}if(holder&&holder.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&holder.left===target){return}reportInjection(node,node.property,false)};const checkObjectAssignSpread=node=>{if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callee=node.callee;const objectIsObject=callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Object";const propIsAssign=(0,eslint_devkit_1.propertyName)(callee)==="assign";if(!objectIsObject||!propIsAssign)return;if(node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;if(node.arguments[0]&&isPrototypelessObject(node.arguments[0]))return;const sources=node.arguments.slice(1);const anyTaintedSource=sources.some(s=>s.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&s.type!==eslint_devkit_1.AST_NODE_TYPES.Literal);if(!anyTaintedSource)return;context.report({node,messageId:"objectInjection",data:{pattern:"Object.assign(target, untrustedSource)",riskLevel:"HIGH",vulnerability:"object injection via Object.assign spread",safeAlternative:"Validate or whitelist keys before merging: `for (const k of Object.keys(src)) if (!ALLOWED.has(k)) continue;`"}})};const reportMassAssignment=(source,keyName,bodyNode)=>{if(!isCopyLoopSourceOpaque(source))return;if(bodyGuardsKey(bodyNode,keyName,{isModuleOwnedAllowlist}))return;let reported=false;const walk=n=>{if(reported)return;if(n.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&n.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&n.left.computed&&n.left.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&n.left.property.name===keyName){reported=true;context.report({node:n,messageId:"massAssignment"});return}for(const key of Object.keys(n)){const child=n[key];if(key==="parent"||child===null||typeof child!=="object")continue;for(const c of Array.isArray(child)?child:[child]){if(c&&typeof c.type==="string")walk(c)}}};walk(bodyNode)};const checkMassAssignmentCallback=node=>{const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null||!ELEMENT_FIRST_ITERATORS.has(method))return;const receiver=callee.object;if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||receiver.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||receiver.callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||receiver.callee.object.name!=="Object"||!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(receiver.callee),["keys","entries"])){return}const source=receiver.arguments[0];if(source===void 0)return;const fn=node.arguments[0];if(fn===void 0||fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return}const first=fn.params[0];const keyName=first?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?first.name:first?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&first.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?first.elements[0].name:null;if(keyName===null)return;reportMassAssignment(source,keyName,fn.body)};const checkMassAssignmentLoop=node=>{if(isInCodemodContext)return;const iterated=node.right;if(iterated.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return;const callee=iterated.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||callee.object.name!=="Object"||!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["keys","entries"])){return}const source=iterated.arguments[0];if(source===void 0)return;if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration)return;const bound=node.left.declarations[0]?.id;const keyName=bound?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?bound.name:bound?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&bound.elements[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?bound.elements[0].name:null;if(keyName===null)return;reportMassAssignment(source,keyName,node.body)};const isLiteralAllowlist=init=>{const value=(0,eslint_devkit_1.unwrapTypeSyntax)(init);if(value?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const{callee}=value;const isFreeze=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(callee)==="freeze";return isFreeze&&isLiteralAllowlist(value.arguments[0])}const isOwnedName=name=>name!==null&&!POLLUTION_KEYS.has(name);if(value?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return value.elements.every(element=>element===null||isOwnedName((0,eslint_devkit_1.staticString)(element)))}return value?.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&value.properties.every(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&isOwnedName((0,eslint_devkit_1.objectKeyName)(property)))};const isModuleOwnedAllowlist=objectNode=>{if(objectNode.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(objectNode),objectNode);if(!variable)return true;if(variable.defs.length!==1)return false;const def=variable.defs[0];if(def.type!=="Variable"||def.parent?.kind!=="const"){return false}return isLiteralAllowlist(def.node.init)};const isCopyLoopSourceOpaque=source=>{if(isUntrustedExpression(source))return true;if(source.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return isCopyLoopSourceOpaque(source.expression)}if(source.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return isCopyLoopSourceOpaque(source.object)}if(source.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(source),source);if(!variable)return false;if(variable.defs.some(def2=>def2.type==="Parameter"))return true;const loopDef=variable.defs[0];const loop=loopDef?.type==="Variable"?loopDef.parent?.parent:null;if(loop?.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement&&loop.left===loopDef?.parent&&!(loop.right.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&loop.right.name===variable.name))return isCopyLoopSourceOpaque(loop.right);if(variable.references.filter(ref=>ref.isWrite()).length>1)return false;const def=variable.defs[0];if(!def||def.type!=="Variable")return false;const init=def.node.init;return init?isUntrustedExpression(init):false};const checkPrototypePollutingCopyLoop=node=>{const keyName=node.left.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration?node.left.declarations[0]?.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.left.declarations[0].id.name:void 0:node.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?node.left.name:void 0;if(!keyName)return;if(!isCopyLoopSourceOpaque(node.right))return;if(bodyGuardsKey(node.body,keyName,{isModuleOwnedAllowlist,deferOwnershipGuards:true})){return}armedLoops.add(node);openCopyLoops.push({keyName,reported:false})};const reportCopyLoopWrite=node=>{const left=assignmentTarget(node);if(left.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||!left.computed||left.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const propertyName=left.property.name;const loop=openCopyLoops.find(open=>open.keyName===propertyName&&!open.reported);if(!loop)return false;if(hasPrecedingValidation(left.property,node,left.object)){return false}loop.reported=true;context.report({node,messageId:"objectInjection",data:{riskLevel:"HIGH",safeAlternative:'Guard the key before assigning: `if (k === "__proto__" || k === "constructor" || k === "prototype") continue;` \u2014 or copy with Object.create(null) / structuredClone.'}});return true};return{before(){const options=context.options[0]||{};({dangerousProperties=["__proto__","prototype","constructor"]}=options);handledMemberExpressions=new WeakSet;openCopyLoops=[];armedLoops=new WeakSet;sourceCode=context.sourceCode;isInCodemodContext=(()=>{const filename=context.filename;if(/\/codemod[s]?\//i.test(filename))return true;if(/codemod\.[mc]?[jt]sx?$/i.test(filename))return true;return fileUsesAstTooling(sourceCode.ast)})();REQUEST_ROOTS=new Set(["req","request","ctx","context","event"]);numericVarCache=new WeakMap;numericVarInProgress=new WeakSet;ARRAY_PRODUCING_METHODS=new Set(["split","slice","concat","map","filter","flat","flatMap","toSorted","toReversed"]);ELEMENT_FIRST_ITERATORS=new Set(["forEach","map","filter","find","findLast","some","every","flatMap"])},ForOfStatement:checkMassAssignmentLoop,ForInStatement:checkPrototypePollutingCopyLoop,"ForInStatement:exit":node=>{if(armedLoops.has(node))openCopyLoops.pop()},AssignmentExpression:node=>{if(isInCodemodContext)return;if(reportCopyLoopWrite(node))return;return checkAssignmentExpression(node)},MemberExpression:node=>{if(isInCodemodContext)return;return checkMemberExpression(node)},CallExpression:node=>{if(isInCodemodContext)return;checkMassAssignmentCallback(node);return checkObjectAssignSpread(node)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDirectiveInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const DANGEROUS_TAGS=new Set(["script","iframe","object","embed","base"]);const DANGEROUS_ATTRS=new Set(["srcdoc","formaction","xlink:href"]);const TAG_OPTIONS=new Set(["ADD_TAGS","ALLOWED_TAGS"]);const ATTR_OPTIONS=new Set(["ADD_ATTR","ALLOWED_ATTR"]);function staticStringArray(node){if(node.type!=="ArrayExpression")return null;const out=[];for(const element of node.elements){if(element?.type==="Literal"&&typeof element.value==="string"){out.push(element.value)}}return out}function findUnsafeSanitizerConfig(node){const callee=node.callee;if(callee.type!=="MemberExpression")return null;if((0,eslint_devkit_1.propertyName)(callee)!=="sanitize")return null;if(callee.object.type!=="Identifier")return null;if(!callee.object.name.toLowerCase().includes("purify"))return null;const config=node.arguments[1];if(!config||config.type!=="ObjectExpression")return null;for(const property of config.properties){if(property.type!=="Property")continue;if(property.computed)continue;const option=property.key.type==="Identifier"?property.key.name:(0,eslint_devkit_1.staticString)(property.key)!==null?(0,eslint_devkit_1.staticString)(property.key):null;if(option===null)continue;if(property.shorthand)continue;const values=staticStringArray(property.value);if(!values)continue;if(TAG_OPTIONS.has(option)){const bad=values.find(v=>DANGEROUS_TAGS.has(v.toLowerCase()));if(bad)return{node:property,option,allowed:`<${bad}>`}}if(ATTR_OPTIONS.has(option)){const bad=values.find(v=>v.toLowerCase().startsWith("on")||DANGEROUS_ATTRS.has(v.toLowerCase()));if(bad)return{node:property,option,allowed:`the "${bad}" attribute`}}}return null}exports.noDirectiveInjection=(0,eslint_devkit_1.createRule)({name:"no-directive-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-directive-injection.md",description:"Detects directive injection vulnerabilities in templates",cwe:"CWE-96"},messages:{directiveInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Directive Injection",cwe:"CWE-96",description:"User input injected into directive or template",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeDirectiveName:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Directive Name",cwe:"CWE-96",description:"Directive name controlled by user input",severity:"CRITICAL",fix:"Use hardcoded directive names or validate against whitelist",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dynamicDirectiveCreation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dynamic Directive Creation",cwe:"CWE-96",description:"Dynamic creation of directives from user input",severity:"HIGH",fix:"Validate directive names against trusted list",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),templateInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Template Injection",cwe:"CWE-96",description:"User input injected into template content",severity:"HIGH",fix:"Sanitize template input or use safe rendering",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeComponentBinding:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Component Binding",cwe:"CWE-96",description:"Dynamic component binding with user input",severity:"HIGH",fix:"Use component whitelist or validate component names",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),userControlledTemplate:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Template",cwe:"CWE-96",description:"Template content controlled by user input",severity:"CRITICAL",fix:"Sanitize template input before compilation",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dangerousInnerHTML:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous innerHTML",cwe:"CWE-96",description:"innerHTML set with user-controlled content",severity:"HIGH",fix:"Use textContent or sanitize HTML content",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML"}),unsafeSanitizerConfig:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Sanitizer configured to allow {{allowed}}",cwe:"CWE-96",description:"DOMPurify was configured with {{option}} re-enabling {{allowed}}, which is exactly what the sanitizer removes by default. The call returns markup that can execute script, so the sanitization provides no protection.",severity:"HIGH",fix:"Drop {{allowed}} from {{option}}. If the markup genuinely needs it, render it outside the sanitized region rather than widening the allow-list.",documentationLink:"https://github.com/cure53/DOMPurify#can-i-configure-dompurify"})},schema:[{type:"object",properties:{userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as template sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{userInputVariables:["req","request","body","query","params","input","data","userInput"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let sourceCode;let filename;let safetyChecker;let declaredUserInput;const namesUserInput=varName=>declaredUserInput.has(varName.toLowerCase());const memberChainNames=node=>{const names=[];let current=node;while(current.type==="MemberExpression"){const link=(0,eslint_devkit_1.propertyName)(current);if(link!==null){names.push(link)}current=current.object}if(current.type==="Identifier")names.push(current.name);return names};const resolvesToUserInput=(node,seen)=>{if(seen.has(node.name))return false;seen.add(node.name);let scope=sourceCode.getScope(node);while(scope){const variable=scope.variables.find(v=>v.name===node.name);if(variable){return variable.references.some(reference=>reference.writeExpr!==void 0&&reference.writeExpr!==null&&isUserInputExpression(reference.writeExpr,seen))}scope=scope.upper}return false};const isUnattributedParameter=raw=>{const node=(0,eslint_devkit_1.unwrapTypeSyntax)(raw);if(node.type!=="Identifier")return false;let scope=sourceCode.getScope(node);while(scope){const variable=scope.variables.find(v=>v.name===node.name);if(variable){return variable.defs.some(def=>def.type==="Parameter")}scope=scope.upper}return false};function isUserInputExpression(raw,seen=new Set){const node=(0,eslint_devkit_1.unwrapTypeSyntax)(raw);switch(node.type){case"Identifier":return namesUserInput(node.name)||resolvesToUserInput(node,seen);case"MemberExpression":return memberChainNames(node).some(namesUserInput);case"TemplateLiteral":return node.expressions.some(expr=>isUserInputExpression(expr,seen));case"BinaryExpression":return isUserInputExpression(node.left,seen)||isUserInputExpression(node.right,seen);case"ConditionalExpression":return isUserInputExpression(node.consequent,seen)||isUserInputExpression(node.alternate,seen);case"LogicalExpression":return isUserInputExpression(node.left,seen)||isUserInputExpression(node.right,seen);case"ObjectExpression":return node.properties.some(property=>property.type==="Property"&&isUserInputExpression(property.value,seen));default:return false}}return{before(){const options=context.options[0]||{};const{userInputVariables=["req","request","body","query","params","input","data","userInput"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});declaredUserInput=new Set(userInputVariables.map(name=>name.toLowerCase()))},JSXAttribute(node){const attrName=node.name;const attrValue=node.value;if(attrName.type==="JSXIdentifier"&&attrName.name==="dangerouslySetInnerHTML"){if(attrValue&&attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(isUserInputExpression(expression)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}const isNamespaceDirective=attrName.type==="JSXNamespacedName"&&(attrName.namespace.name==="v"||attrName.namespace.name==="ng")||attrName.type==="JSXIdentifier"&&(attrName.name.startsWith("ng:")||attrName.name.startsWith("v:"));if(isNamespaceDirective&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(isUserInputExpression(expression)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"directiveInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded directive values or validate user input"}})}}}if(attrName.type==="JSXIdentifier"){const attrNameStr=attrName.name;if(attrNameStr==="is"&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(isUserInputExpression(expression)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"unsafeComponentBinding",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},AssignmentExpression(node){const left=node.left;const right=node.right;if(left.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(left)==="innerHTML"){const isSanitizedValue=right.type==="CallExpression"&&right.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(right.callee)==="sanitize"&&findUnsafeSanitizerConfig(right)===null;if(isSanitizedValue){return}if(isUserInputExpression(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;const unsafeConfig=findUnsafeSanitizerConfig(node);if(unsafeConfig){context.report({node:unsafeConfig.node,messageId:"unsafeSanitizerConfig",data:{option:unsafeConfig.option,allowed:unsafeConfig.allowed}})}const methodName=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&methodName!==null){const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(["compile","template","$compile","$interpolate"].includes(methodName)||objectName==="Handlebars"&&methodName==="compile"||objectName==="_"&&methodName==="template"||objectName==="ejs"&&methodName==="render"||objectName==="pug"&&methodName==="render"||objectName==="mustache"&&methodName==="render"){const args=node.arguments;if(args.length>0){const templateArg=args[0];if(isUserInputExpression(templateArg)||isUnattributedParameter(templateArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:templateArg,messageId:"userControlledTemplate",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}if(objectName==="Vue"&&methodName==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(isUserInputExpression(directiveName)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"unsafeDirectiveName",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}if(callee.type==="Identifier"&&callee.name==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(isUserInputExpression(directiveName)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"dynamicDirectiveCreation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},TemplateLiteral(node){let current=node;let isInDangerousContext=false;while(current){if(current.type==="JSXExpressionContainer"){if(current.parent?.type==="JSXAttribute"&&current.parent.name.type==="JSXIdentifier"&&current.parent.name.name==="dangerouslySetInnerHTML"){if(current.expression&&isUserInputExpression(current.expression))return;isInDangerousContext=true;break}}else if(current.type==="AssignmentExpression"){const left=current.left;if(left.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(left)==="innerHTML"){if(current.right&&isUserInputExpression(current.right))return;isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext){const hasUserInput=node.expressions.some(expr=>isUserInputExpression(expr));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"templateInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Sanitize template input before insertion"}})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDirectiveInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");const DANGEROUS_TAGS=new Set(["script","iframe","object","embed","base"]);const DANGEROUS_ATTRS=new Set(["srcdoc","formaction","xlink:href"]);const TAG_OPTIONS=new Set(["ADD_TAGS","ALLOWED_TAGS"]);const ATTR_OPTIONS=new Set(["ADD_ATTR","ALLOWED_ATTR"]);const MARKUP_PROPERTIES=new Set(["innerHTML","outerHTML"]);function isMarkupSink(member){return MARKUP_PROPERTIES.has((0,eslint_devkit_1.propertyName)(member))}function staticStringArray(node){if(node.type!=="ArrayExpression")return null;const out=[];for(const element of node.elements){if(element?.type==="Literal"&&typeof element.value==="string"){out.push(element.value)}}return out}function findUnsafeSanitizerConfig(node){const callee=node.callee;if(callee.type!=="MemberExpression")return null;if((0,eslint_devkit_1.propertyName)(callee)!=="sanitize")return null;if(callee.object.type!=="Identifier")return null;if(!callee.object.name.toLowerCase().includes("purify"))return null;const config=node.arguments[1];if(!config||config.type!=="ObjectExpression")return null;for(const property of config.properties){if(property.type!=="Property")continue;if(property.computed)continue;const option=property.key.type==="Identifier"?property.key.name:(0,eslint_devkit_1.staticString)(property.key)!==null?(0,eslint_devkit_1.staticString)(property.key):null;if(option===null)continue;if(property.shorthand)continue;const values=staticStringArray(property.value);if(!values)continue;if(TAG_OPTIONS.has(option)){const bad=values.find(v=>DANGEROUS_TAGS.has(v.toLowerCase()));if(bad)return{node:property,option,allowed:`<${bad}>`}}if(ATTR_OPTIONS.has(option)){const bad=values.find(v=>v.toLowerCase().startsWith("on")||DANGEROUS_ATTRS.has(v.toLowerCase()));if(bad)return{node:property,option,allowed:`the "${bad}" attribute`}}}return null}exports.noDirectiveInjection=(0,eslint_devkit_1.createRule)({name:"no-directive-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-directive-injection.md",description:"Detects directive injection vulnerabilities in templates",cwe:"CWE-96"},messages:{directiveInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Directive Injection",cwe:"CWE-96",description:"User input injected into directive or template",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeDirectiveName:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Directive Name",cwe:"CWE-96",description:"Directive name controlled by user input",severity:"CRITICAL",fix:"Use hardcoded directive names or validate against whitelist",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dynamicDirectiveCreation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dynamic Directive Creation",cwe:"CWE-96",description:"Dynamic creation of directives from user input",severity:"HIGH",fix:"Validate directive names against trusted list",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),templateInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Template Injection",cwe:"CWE-96",description:"User input injected into template content",severity:"HIGH",fix:"Sanitize template input or use safe rendering",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),unsafeComponentBinding:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Component Binding",cwe:"CWE-96",description:"Dynamic component binding with user input",severity:"HIGH",fix:"Use component whitelist or validate component names",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),userControlledTemplate:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Template",cwe:"CWE-96",description:"Template content controlled by user input",severity:"CRITICAL",fix:"Sanitize template input before compilation",documentationLink:"https://cwe.mitre.org/data/definitions/96.html"}),dangerousInnerHTML:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous innerHTML",cwe:"CWE-96",description:"innerHTML set with user-controlled content",severity:"HIGH",fix:"Use textContent or sanitize HTML content",documentationLink:"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML"}),unsafeSanitizerConfig:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Sanitizer configured to allow {{allowed}}",cwe:"CWE-96",description:"DOMPurify was configured with {{option}} re-enabling {{allowed}}, which is exactly what the sanitizer removes by default. The call returns markup that can execute script, so the sanitization provides no protection.",severity:"HIGH",fix:"Drop {{allowed}} from {{option}}. If the markup genuinely needs it, render it outside the sanitized region rather than widening the allow-list.",documentationLink:"https://github.com/cure53/DOMPurify#can-i-configure-dompurify"})},schema:[{type:"object",properties:{userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as template sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{userInputVariables:["req","request","body","query","params","input","data","userInput"],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let sourceCode;let filename;let safetyChecker;let declaredUserInput;const namesUserInput=varName=>declaredUserInput.has(varName.toLowerCase());const memberChainNames=node=>{const names=[];let current=node;while(current.type==="MemberExpression"){const link=(0,eslint_devkit_1.propertyName)(current);if(link!==null){names.push(link)}current=current.object}if(current.type==="Identifier")names.push(current.name);return names};const resolvesToUserInput=(node,seen)=>{if(seen.has(node.name))return false;seen.add(node.name);let scope=sourceCode.getScope(node);while(scope){const variable=scope.variables.find(v=>v.name===node.name);if(variable){return variable.references.some(reference=>reference.writeExpr!==void 0&&reference.writeExpr!==null&&isUserInputExpression(reference.writeExpr,seen))}scope=scope.upper}return false};const isUnattributedParameter=raw=>{const node=(0,eslint_devkit_1.unwrapTypeSyntax)(raw);if(node.type!=="Identifier")return false;let scope=sourceCode.getScope(node);while(scope){const variable=scope.variables.find(v=>v.name===node.name);if(variable){return variable.defs.some(def=>def.type==="Parameter")}scope=scope.upper}return false};function isUserInputExpression(raw,seen=new Set){const node=(0,eslint_devkit_1.unwrapTypeSyntax)(raw);switch(node.type){case"Identifier":return namesUserInput(node.name)||resolvesToUserInput(node,seen);case"MemberExpression":return memberChainNames(node).some(namesUserInput);case"TemplateLiteral":return node.expressions.some(expr=>isUserInputExpression(expr,seen));case"BinaryExpression":return isUserInputExpression(node.left,seen)||isUserInputExpression(node.right,seen);case"ConditionalExpression":return isUserInputExpression(node.consequent,seen)||isUserInputExpression(node.alternate,seen);case"LogicalExpression":return isUserInputExpression(node.left,seen)||isUserInputExpression(node.right,seen);case"ObjectExpression":return node.properties.some(property=>property.type==="Property"&&isUserInputExpression(property.value,seen));default:return false}}return{before(){const options=context.options[0]||{};const{userInputVariables=["req","request","body","query","params","input","data","userInput"],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;sourceCode=context.sourceCode;filename=context.filename;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});declaredUserInput=new Set(userInputVariables.map(name=>name.toLowerCase()))},JSXAttribute(node){const attrName=node.name;const attrValue=node.value;if(attrName.type==="JSXIdentifier"&&attrName.name==="dangerouslySetInnerHTML"){if(attrValue&&attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(isUserInputExpression(expression)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}const isNamespaceDirective=attrName.type==="JSXNamespacedName"&&(attrName.namespace.name==="v"||attrName.namespace.name==="ng")||attrName.type==="JSXIdentifier"&&(attrName.name.startsWith("ng:")||attrName.name.startsWith("v:"));if(isNamespaceDirective&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(isUserInputExpression(expression)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"directiveInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded directive values or validate user input"}})}}}if(attrName.type==="JSXIdentifier"){const attrNameStr=attrName.name;if(attrNameStr==="is"&&attrValue){if(attrValue.type==="JSXExpressionContainer"){const expression=attrValue.expression;if(isUserInputExpression(expression)){if(safetyChecker.isSafe(node,context)){return}context.report({node:attrValue,messageId:"unsafeComponentBinding",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},AssignmentExpression(node){const left=node.left;const right=node.right;if(left.type==="MemberExpression"&&isMarkupSink(left)){const isSanitizedValue=right.type==="CallExpression"&&right.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(right.callee)==="sanitize"&&findUnsafeSanitizerConfig(right)===null;if(isSanitizedValue){return}if(isUserInputExpression(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"dangerousInnerHTML",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}},CallExpression(node){const callee=node.callee;const unsafeConfig=findUnsafeSanitizerConfig(node);if(unsafeConfig){context.report({node:unsafeConfig.node,messageId:"unsafeSanitizerConfig",data:{option:unsafeConfig.option,allowed:unsafeConfig.allowed}})}const methodName=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&methodName!==null){const objectName=callee.object.type==="Identifier"?callee.object.name:"";if(["compile","template","$compile","$interpolate"].includes(methodName)||objectName==="Handlebars"&&methodName==="compile"||objectName==="_"&&methodName==="template"||objectName==="ejs"&&methodName==="render"||objectName==="pug"&&methodName==="render"||objectName==="mustache"&&methodName==="render"){const args=node.arguments;if(args.length>0){const templateArg=args[0];if(isUserInputExpression(templateArg)||isUnattributedParameter(templateArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node:templateArg,messageId:"userControlledTemplate",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}if(objectName==="Vue"&&methodName==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(isUserInputExpression(directiveName)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"unsafeDirectiveName",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}if(callee.type==="Identifier"&&callee.name==="directive"){const args=node.arguments;if(args.length>=2){const directiveName=args[0];if(isUserInputExpression(directiveName)){if(safetyChecker.isSafe(node,context)){return}context.report({node:directiveName,messageId:"dynamicDirectiveCreation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}},TemplateLiteral(node){let current=node;let isInDangerousContext=false;while(current){if(current.type==="JSXExpressionContainer"){if(current.parent?.type==="JSXAttribute"&&current.parent.name.type==="JSXIdentifier"&&current.parent.name.name==="dangerouslySetInnerHTML"){if(current.expression&&isUserInputExpression(current.expression))return;isInDangerousContext=true;break}}else if(current.type==="AssignmentExpression"){const left=current.left;if(left.type==="MemberExpression"&&isMarkupSink(left)){if(current.right&&isUserInputExpression(current.right))return;isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext){const hasUserInput=node.expressions.some(expr=>isUserInputExpression(expr));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"templateInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Sanitize template input before insertion"}})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noFormatStringInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_USER_INPUT_ALIASES=["user","userinput","userdata","userparam","userparams","usermessage","usertemplate","userformat","uservar"];exports.noFormatStringInjection=(0,eslint_devkit_1.createRule)({name:"no-format-string-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-format-string-injection.md",description:"Detects format string injection vulnerabilities",cwe:"CWE-134"},fixable:"code",hasSuggestions:true,messages:{formatStringInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Format String Injection",cwe:"CWE-134",description:"Format string controlled by user input",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),userControlledFormatString:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Format String",cwe:"CWE-134",description:"Format string parameter comes from user input",severity:"CRITICAL",fix:"Use hardcoded format strings or validate user formats",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),missingFormatValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Format Validation",cwe:"CWE-134",description:"Format string not validated before use",severity:"HIGH",fix:"Validate format strings against allowed patterns",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),escapeFormatString:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Escape Format String",description:"Escape format specifiers in user input",severity:"LOW",fix:"Replace % with %% in user input",documentationLink:"https://nodejs.org/api/util.html#utilformatformat-args"})},schema:[{type:"object",properties:{formatFunctions:{type:"array",items:{type:"string"},default:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],description:"Functions whose first argument is a format string"},formatSpecifiers:{type:"array",items:{type:"string"},default:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],description:"Format specifiers recognised in a format string"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},userInputAliases:{type:"array",items:{type:"string"},default:DEFAULT_USER_INPUT_ALIASES,description:"The user-input name family recognised on top of `userInputVariables`, compared case-insensitively as a whole name or a whole dotted segment \u2014 never as a substring. Replaces the built-in list."},additionalUserInputAliases:{type:"array",items:{type:"string"},default:[],description:"Extra user-input aliases, on top of `userInputAliases`."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as format string sanitizers"}},additionalProperties:false}]},defaultOptions:[{formatFunctions:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],formatSpecifiers:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],userInputVariables:["req","request","body","query","params","input","data","userInput"],userInputAliases:DEFAULT_USER_INPUT_ALIASES,additionalUserInputAliases:[],trustedSanitizers:["validateFormat","sanitizeFormat","escapeFormat","cleanFormat","sanitizeFormatString","validate","sanitize","escape","clean"]}],createOnce(context){let options;let formatSpecifiers;let userInputVariables;let userInputAliases;let additionalUserInputAliases;let trustedSanitizers;let filename;let reportedTemplates;let safetyChecker;let declaredUserInput;let validatedVariables;let dangerousVariables;const isUserInput=varName=>declaredUserInput.has(varName.toLowerCase());const isUserInputPath=path=>path.split(".").some(segment=>isUserInput(segment));const isUserInputNode=rawNode=>{const node=(0,eslint_devkit_1.unwrapTypeSyntax)(rawNode);if(node.type==="ConditionalExpression"){return isUserInputNode(node.consequent)||isUserInputNode(node.alternate)}if(node.type==="LogicalExpression"){return isUserInputNode(node.left)||isUserInputNode(node.right)}if(node.type==="Identifier"){return isUserInput(node.name)||dangerousVariables.has(node.name)}if(node.type==="MemberExpression"){if(node.object.type==="MemberExpression"&&node.object.object.type==="Identifier"&&node.object.object.name==="req"&&["query","body","params","param"].includes((0,eslint_devkit_1.propertyName)(node.object)??"")){return true}if(node.object.type==="Identifier"&&node.object.name==="req"){return true}const fullName=getMemberExpressionName(node);return isUserInputPath(fullName)}return false};const getMemberExpressionName=node=>{const own=(0,eslint_devkit_1.propertyName)(node);if(node.object.type==="Identifier"){if(own!==null){return`${node.object.name}.${own}`}}else if(node.object.type==="MemberExpression"){const objectName=getMemberExpressionName(node.object);if(own!==null){return`${objectName}.${own}`}}return""};const containsFormatSpecifiers=text=>{return formatSpecifiers.some(specifier=>text.includes(specifier))};const isConsoleMethod=node=>{const callee=node.callee;return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="console"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["log","error","warn","info","debug"])};const isFormatFunctionCall=node=>{const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="util"&&(0,eslint_devkit_1.propertyName)(callee)==="format"){return true}if(callee.type==="Identifier"&&(0,eslint_devkit_1.isModuleBinding)(callee,context.sourceCode.getScope(callee),"util",["format"])){return true}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="console"&&["log","error","warn","info","debug"].includes((0,eslint_devkit_1.propertyName)(callee)??"")){return true}if(callee.type==="Identifier"&&["sprintf","printf","vsprintf"].includes(callee.name)){return true}return false};const isStaticFormatString=fmtNode=>(0,eslint_devkit_1.isStaticExpression)({node:fmtNode,scope:context.sourceCode.getScope(fmtNode)});const isInputValidated=inputNode=>{if(inputNode.type==="Identifier"&&validatedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&trustedSanitizers.includes(current.callee.name)){return true}current=current.parent}return false};const hasFormatSpecifiers=node=>{if(typeof node.value!=="string"){return false}return containsFormatSpecifiers(node.value)};function containsFormatSpecifiersInExpression(expr){const left=(0,eslint_devkit_1.staticString)(expr.left);if(left!==null&&containsFormatSpecifiers(left)){return true}const right=(0,eslint_devkit_1.staticString)(expr.right);if(right!==null&&containsFormatSpecifiers(right)){return true}if(expr.left.type==="BinaryExpression"&&containsFormatSpecifiersInExpression(expr.left)){return true}if(expr.right.type==="BinaryExpression"&&containsFormatSpecifiersInExpression(expr.right)){return true}return false}function hasUserInputInExpression(expr){if(isUserInputNode(expr.left)){return true}if(isUserInputNode(expr.right)){return true}if(expr.left.type==="BinaryExpression"&&hasUserInputInExpression(expr.left)){return true}if(expr.right.type==="BinaryExpression"&&hasUserInputInExpression(expr.right)){return true}return false}return{before(){const defaultOptions={formatFunctions:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],formatSpecifiers:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],userInputVariables:["req","request","body","query","params","input","data","userInput"],userInputAliases:DEFAULT_USER_INPUT_ALIASES,additionalUserInputAliases:[],trustedSanitizers:["validateFormat","sanitizeFormat","escapeFormat","cleanFormat","sanitizeFormatString","validate","sanitize","escape","clean"]};options={...defaultOptions,...context.options[0]};({formatSpecifiers,userInputVariables,userInputAliases,additionalUserInputAliases,trustedSanitizers}=options);filename=context.filename;reportedTemplates=new WeakSet;safetyChecker={isSafe:(safeNode,ruleCtx)=>{const comments=ruleCtx.sourceCode.getCommentsBefore(safeNode);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@safe-format")){return true}}if(safeNode.type==="CallExpression"&&safeNode.arguments.length>0){const firstArg=safeNode.arguments[0];if(firstArg.type==="Identifier"&&validatedVariables.has(firstArg.name)){return true}}return false}};declaredUserInput=new Set([...userInputVariables,...userInputAliases,...additionalUserInputAliases].map(name=>name.toLowerCase()));validatedVariables=new Set;dangerousVariables=new Set},CallExpression:function(node){if(!isFormatFunctionCall(node)){return}const args=node.arguments;if(args.length===0){return}const formatArg=args[0];const isFormatFromUserInput=isUserInputNode(formatArg)||formatArg.type==="Identifier"&&dangerousVariables.has(formatArg.name)||formatArg.type==="BinaryExpression"&&hasUserInputInExpression(formatArg);const consoleSubstitutes=isConsoleMethod(node)&&args.length>1;if(isFormatFromUserInput&&(!isConsoleMethod(node)||consoleSubstitutes)){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"userControlledFormatString",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(formatArg.type==="TemplateLiteral"){const hasUserInput=formatArg.expressions.some(expr=>isUserInputNode(expr));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded format strings or validate template input"}});return}}else if(formatArg.type==="BinaryExpression"&&formatArg.operator==="+"){const hasUserInput=hasUserInputInExpression(formatArg);if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Separate user input from format strings"}});return}}const fmtArg=args[0];const isFormatSafe=isInputValidated(fmtArg)||fmtArg.type==="Identifier"&&validatedVariables.has(fmtArg.name);if(!isFormatSafe){let hasUserInputInArgs=false;let hasSpecifiersInFormat=false;for(let i=1;i<args.length;i++){const arg=args[i];if(isUserInputNode(arg)&&!isInputValidated(arg)){hasUserInputInArgs=true;break}}const firstArg=args[0];const staticText=(0,eslint_devkit_1.staticString)(firstArg);if(staticText!==null){if(containsFormatSpecifiers(staticText)){hasSpecifiersInFormat=true}}else if(firstArg.type==="Identifier"){const varName=firstArg.name.toLowerCase();if(varName.includes("format")||varName.includes("template")||varName.includes("pattern")){hasSpecifiersInFormat=true}}if(!hasSpecifiersInFormat&&args.length===2&&isConsoleMethod(node)){}else if(hasSpecifiersInFormat&&hasUserInputInArgs&&!isStaticFormatString(firstArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingFormatValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"escapeFormatString",fix:fixer=>{const arg=node.arguments.slice(1).find(a=>isUserInputNode(a));return fixer.insertTextAfter(arg,'.replace(/%/g, "%%")')}}]})}}},Literal:function(node){if(!hasFormatSpecifiers(node)){return}const text=node.value;let current=node;let isFromUserInput=false;while(current){if(current.type==="BinaryExpression"&&current.operator==="+"&&(current.left===node||current.right===node)){const otherSide=current.left===node?current.right:current.left;if(otherSide.type==="Identifier"&&isUserInput(otherSide.name)){isFromUserInput=true;break}}if(current.type==="VariableDeclarator"&&current.init===node.parent&&current.id.type==="Identifier"){if(isUserInput(current.id.name)){isFromUserInput=true;break}}current=current.parent}if(!isFromUserInput){return}current=node;let isInDangerousContext=false;while(current){if(current.type==="CallExpression"&&isFormatFunctionCall(current)){const args=current.arguments;if(args.length>0&&args[0]===node){isInDangerousContext=true;break}}current=current.parent}if(isInDangerousContext&&containsFormatSpecifiers(text)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingFormatValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},TemplateLiteral:function(node){let templateCurrent=node;let isFormatString=false;while(templateCurrent){if(templateCurrent.type==="CallExpression"&&isFormatFunctionCall(templateCurrent)){const args=templateCurrent.arguments;if(args.length>0&&args[0]===node){isFormatString=true;break}}templateCurrent=templateCurrent.parent}if(isFormatString){return}const hasUserInput=node.expressions.some(expr=>isUserInputNode(expr));if(hasUserInput){let assignCurrent=node;let isAssignedToVariable=false;while(assignCurrent){if(assignCurrent.type==="VariableDeclarator"){isAssignedToVariable=true;break}assignCurrent=assignCurrent.parent}const carriesFormatSpecifier=node.quasis.some(quasi=>{const raw=quasi.value.raw;return options.formatSpecifiers.some(spec=>raw.includes(spec))});if(isAssignedToVariable&&carriesFormatSpecifier){if(safetyChecker.isSafe(node,context)||reportedTemplates.has(node)){return}context.report({node,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Extract user input from template and validate separately"}})}}},'VariableDeclarator[id.type!="Identifier"]':function(node){if(!node.init||!isUserInputNode(node.init))return;for(const variable of context.sourceCode.getDeclaredVariables(node)){dangerousVariables.add(variable.name)}},AssignmentExpression:function(node){if(node.left.type!=="Identifier")return;if(isUserInputNode(node.right)){dangerousVariables.add(node.left.name)}},VariableDeclarator:function(node){if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&trustedSanitizers.includes(node.init.callee.name)){validatedVariables.add(varName)}if(isUserInputNode(node.init)||node.init.type==="BinaryExpression"&&hasUserInputInExpression(node.init)||node.init.type==="TemplateLiteral"&&node.init.expressions.some(expr=>isUserInputNode(expr))){dangerousVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("format")&&!varNameLower.includes("template")&&!varNameLower.includes("fmt")&&!varNameLower.includes("str")){return}if(node.init.type==="TemplateLiteral"){const hasSpecifiers=node.init.quasis.some(quasi=>containsFormatSpecifiers(quasi.value.raw));const hasUserInput=node.init.expressions.some(expr=>isUserInputNode(expr));if(hasSpecifiers&&hasUserInput){if(safetyChecker.isSafe(node,context)){return}reportedTemplates.add(node.init);context.report({node:node.init,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Separate format string from user data"}})}}if(node.init.type==="BinaryExpression"&&node.init.operator==="+"){const hasSpecifiers=containsFormatSpecifiersInExpression(node.init);const hasUserInput=hasUserInputInExpression(node.init);if(hasSpecifiers&&hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.init,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Separate format string from user data"}})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noFormatStringInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_USER_INPUT_ALIASES=["user","userinput","userdata","userparam","userparams","usermessage","usertemplate","userformat","uservar"];exports.noFormatStringInjection=(0,eslint_devkit_1.createRule)({name:"no-format-string-injection",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-format-string-injection.md",description:"Detects format string injection vulnerabilities",cwe:"CWE-134"},fixable:"code",hasSuggestions:true,messages:{formatStringInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Format String Injection",cwe:"CWE-134",description:"Format string controlled by user input",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),userControlledFormatString:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Format String",cwe:"CWE-134",description:"Format string parameter comes from user input",severity:"CRITICAL",fix:"Use hardcoded format strings or validate user formats",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),missingFormatValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Format Validation",cwe:"CWE-134",description:"Format string not validated before use",severity:"HIGH",fix:"Validate format strings against allowed patterns",documentationLink:"https://cwe.mitre.org/data/definitions/134.html"}),escapeFormatString:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.INFO,issueName:"Escape Format String",description:"Escape format specifiers in user input",severity:"LOW",fix:"Replace % with %% in user input",documentationLink:"https://nodejs.org/api/util.html#utilformatformat-args"})},schema:[{type:"object",properties:{formatFunctions:{type:"array",items:{type:"string"},default:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],description:"Functions whose first argument is a format string"},formatSpecifiers:{type:"array",items:{type:"string"},default:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],description:"Format specifiers recognised in a format string"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data","userInput"],description:"Variable names treated as user-controlled input"},userInputAliases:{type:"array",items:{type:"string"},default:DEFAULT_USER_INPUT_ALIASES,description:"The user-input name family recognised on top of `userInputVariables`, compared case-insensitively as a whole name or a whole dotted segment \u2014 never as a substring. Replaces the built-in list."},additionalUserInputAliases:{type:"array",items:{type:"string"},default:[],description:"Extra user-input aliases, on top of `userInputAliases`."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as format string sanitizers"}},additionalProperties:false}]},defaultOptions:[{formatFunctions:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],formatSpecifiers:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],userInputVariables:["req","request","body","query","params","input","data","userInput"],userInputAliases:DEFAULT_USER_INPUT_ALIASES,additionalUserInputAliases:[],trustedSanitizers:["validateFormat","sanitizeFormat","escapeFormat","cleanFormat","sanitizeFormatString","validate","sanitize","escape","clean"]}],createOnce(context){let options;let formatSpecifiers;let userInputVariables;let userInputAliases;let additionalUserInputAliases;let trustedSanitizers;let filename;let reportedTemplates;let safetyChecker;let declaredUserInput;let validatedVariables;let dangerousVariables;const isUserInput=varName=>declaredUserInput.has(varName.toLowerCase());const isUserInputPath=path=>path.split(".").some(segment=>isUserInput(segment));const isUserInputNode=rawNode=>{const node=(0,eslint_devkit_1.unwrapTypeSyntax)(rawNode);if(node.type==="ConditionalExpression"){return isUserInputNode(node.consequent)||isUserInputNode(node.alternate)}if(node.type==="LogicalExpression"){return isUserInputNode(node.left)||isUserInputNode(node.right)}if(node.type==="Identifier"){return isUserInput(node.name)||dangerousVariables.has(node.name)}if(node.type==="MemberExpression"){if(node.object.type==="MemberExpression"&&node.object.object.type==="Identifier"&&node.object.object.name==="req"&&["query","body","params","param"].includes((0,eslint_devkit_1.propertyName)(node.object)??"")){return true}if(node.object.type==="Identifier"&&node.object.name==="req"){return true}const fullName=getMemberExpressionName(node);return isUserInputPath(fullName)}return false};const getMemberExpressionName=node=>{const own=(0,eslint_devkit_1.propertyName)(node);if(node.object.type==="Identifier"){if(own!==null){return`${node.object.name}.${own}`}}else if(node.object.type==="MemberExpression"){const objectName=getMemberExpressionName(node.object);if(own!==null){return`${objectName}.${own}`}}return""};const containsFormatSpecifiers=text=>{return formatSpecifiers.some(specifier=>text.includes(specifier))};const isConsoleMethod=node=>{const callee=node.callee;return callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="console"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["log","error","warn","info","debug"])};const isFormatFunctionCall=node=>{const callee=node.callee;if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="util"&&(0,eslint_devkit_1.propertyName)(callee)==="format"){return true}if(callee.type==="Identifier"&&(0,eslint_devkit_1.isModuleBinding)(callee,context.sourceCode.getScope(callee),"util",["format"])){return true}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="console"&&["log","error","warn","info","debug"].includes((0,eslint_devkit_1.propertyName)(callee)??"")){return true}if(callee.type==="Identifier"&&["sprintf","printf","vsprintf"].includes(callee.name)){return true}return false};const isStaticFormatString=fmtNode=>(0,eslint_devkit_1.isStaticExpression)({node:fmtNode,scope:context.sourceCode.getScope(fmtNode)});const isInputValidated=inputNode=>{if(inputNode.type==="Identifier"&&validatedVariables.has(inputNode.name)){return true}let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&trustedSanitizers.includes(current.callee.name)){return true}current=current.parent}return false};function containsFormatSpecifiersInExpression(expr){const left=(0,eslint_devkit_1.staticString)(expr.left);if(left!==null&&containsFormatSpecifiers(left)){return true}const right=(0,eslint_devkit_1.staticString)(expr.right);if(right!==null&&containsFormatSpecifiers(right)){return true}if(expr.left.type==="BinaryExpression"&&containsFormatSpecifiersInExpression(expr.left)){return true}if(expr.right.type==="BinaryExpression"&&containsFormatSpecifiersInExpression(expr.right)){return true}return false}function hasUserInputInExpression(expr){if(isUserInputNode(expr.left)){return true}if(isUserInputNode(expr.right)){return true}if(expr.left.type==="BinaryExpression"&&hasUserInputInExpression(expr.left)){return true}if(expr.right.type==="BinaryExpression"&&hasUserInputInExpression(expr.right)){return true}return false}return{before(){const defaultOptions={formatFunctions:["util.format","console.log","console.error","console.warn","sprintf","printf","vsprintf"],formatSpecifiers:["%s","%d","%i","%f","%j","%o","%O","%c","%%"],userInputVariables:["req","request","body","query","params","input","data","userInput"],userInputAliases:DEFAULT_USER_INPUT_ALIASES,additionalUserInputAliases:[],trustedSanitizers:["validateFormat","sanitizeFormat","escapeFormat","cleanFormat","sanitizeFormatString","validate","sanitize","escape","clean"]};options={...defaultOptions,...context.options[0]};({formatSpecifiers,userInputVariables,userInputAliases,additionalUserInputAliases,trustedSanitizers}=options);filename=context.filename;reportedTemplates=new WeakSet;safetyChecker={isSafe:(safeNode,ruleCtx)=>{const comments=ruleCtx.sourceCode.getCommentsBefore(safeNode);for(const comment of comments){if(comment.type==="Block"&&comment.value.includes("@safe-format")){return true}}if(safeNode.type==="CallExpression"){const firstArg=safeNode.arguments[0];if(firstArg.type==="Identifier"&&validatedVariables.has(firstArg.name)){return true}}return false}};declaredUserInput=new Set([...userInputVariables,...userInputAliases,...additionalUserInputAliases].map(name=>name.toLowerCase()));validatedVariables=new Set;dangerousVariables=new Set},CallExpression:function(node){if(!isFormatFunctionCall(node)){return}const args=node.arguments;if(args.length===0){return}const formatArg=args[0];const isFormatFromUserInput=isUserInputNode(formatArg)||formatArg.type==="BinaryExpression"&&hasUserInputInExpression(formatArg);const consoleSubstitutes=isConsoleMethod(node)&&args.length>1;if(isFormatFromUserInput&&(!isConsoleMethod(node)||consoleSubstitutes)){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"userControlledFormatString",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(formatArg.type==="TemplateLiteral"){const hasUserInput=formatArg.expressions.some(expr=>isUserInputNode(expr));if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Use hardcoded format strings or validate template input"}});return}}else if(formatArg.type==="BinaryExpression"&&formatArg.operator==="+"){const hasUserInput=hasUserInputInExpression(formatArg);if(hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:formatArg,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Separate user input from format strings"}});return}}const fmtArg=args[0];const isFormatSafe=isInputValidated(fmtArg);if(!isFormatSafe){let hasUserInputInArgs=false;let hasSpecifiersInFormat=false;for(let i=1;i<args.length;i++){const arg=args[i];if(isUserInputNode(arg)&&!isInputValidated(arg)){hasUserInputInArgs=true;break}}const firstArg=args[0];if(firstArg.type==="Identifier"){const varName=firstArg.name.toLowerCase();if(varName.includes("format")||varName.includes("template")||varName.includes("pattern")){hasSpecifiersInFormat=true}}if(hasSpecifiersInFormat&&hasUserInputInArgs&&!isStaticFormatString(firstArg)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingFormatValidation",data:{filePath:filename,line:String(node.loc?.start.line??0)},suggest:[{messageId:"escapeFormatString",fix:fixer=>{const arg=node.arguments.find(a=>isUserInputNode(a));return fixer.insertTextAfter(arg,'.replace(/%/g, "%%")')}}]})}}},TemplateLiteral:function(node){let templateCurrent=node;let isFormatString=false;while(templateCurrent){if(templateCurrent.type==="CallExpression"&&isFormatFunctionCall(templateCurrent)){const args=templateCurrent.arguments;if(args.length>0&&args[0]===node){isFormatString=true;break}}templateCurrent=templateCurrent.parent}if(isFormatString){return}const hasUserInput=node.expressions.some(expr=>isUserInputNode(expr));if(hasUserInput){let assignCurrent=node;let isAssignedToVariable=false;while(assignCurrent){if(assignCurrent.type==="VariableDeclarator"){isAssignedToVariable=true;break}assignCurrent=assignCurrent.parent}const carriesFormatSpecifier=node.quasis.some(quasi=>{const raw=quasi.value.raw;return options.formatSpecifiers.some(spec=>raw.includes(spec))});if(isAssignedToVariable&&carriesFormatSpecifier){if(safetyChecker.isSafe(node,context)||reportedTemplates.has(node)){return}context.report({node,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"HIGH",safeAlternative:"Extract user input from template and validate separately"}})}}},'VariableDeclarator[id.type!="Identifier"]':function(node){if(!node.init||!isUserInputNode(node.init))return;for(const variable of context.sourceCode.getDeclaredVariables(node)){dangerousVariables.add(variable.name)}},AssignmentExpression:function(node){if(node.left.type!=="Identifier")return;if(isUserInputNode(node.right)){dangerousVariables.add(node.left.name)}},VariableDeclarator:function(node){if(!node.init||node.id.type!=="Identifier"){return}const varName=node.id.name;if(node.init.type==="CallExpression"&&node.init.callee.type==="Identifier"&&trustedSanitizers.includes(node.init.callee.name)){validatedVariables.add(varName)}if(isUserInputNode(node.init)||node.init.type==="BinaryExpression"&&hasUserInputInExpression(node.init)||node.init.type==="TemplateLiteral"&&node.init.expressions.some(expr=>isUserInputNode(expr))){dangerousVariables.add(varName)}const varNameLower=varName.toLowerCase();if(!varNameLower.includes("format")&&!varNameLower.includes("template")&&!varNameLower.includes("fmt")&&!varNameLower.includes("str")){return}if(node.init.type==="TemplateLiteral"){const hasSpecifiers=node.init.quasis.some(quasi=>containsFormatSpecifiers(quasi.value.raw));const hasUserInput=node.init.expressions.some(expr=>isUserInputNode(expr));if(hasSpecifiers&&hasUserInput){reportedTemplates.add(node.init);if(safetyChecker.isSafe(node,context)){return}context.report({node:node.init,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Separate format string from user data"}})}}if(node.init.type==="BinaryExpression"&&node.init.operator==="+"){const hasSpecifiers=containsFormatSpecifiersInExpression(node.init);const hasUserInput=hasUserInputInExpression(node.init);if(hasSpecifiers&&hasUserInput){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.init,messageId:"formatStringInjection",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Separate format string from user data"}})}}}}}});