eslint-plugin-secure-coding 5.6.1 → 5.6.3

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
@@ -76,7 +76,7 @@ npm install eslint-plugin-secure-coding --save-dev
76
76
 
77
77
  <!-- AUTO-GENERATED:INSTALL:END -->
78
78
 
79
- **Add to your `eslint.config.mjs` — one line activates 16 security rules:**
79
+ **Add to your `eslint.config.mjs` — one line activates 18 security rules:**
80
80
 
81
81
  ```js
82
82
  import securePlugin from 'eslint-plugin-secure-coding';
@@ -85,7 +85,7 @@ export default [
85
85
  // Balanced: catches critical issues as errors, lower-confidence rules as warnings
86
86
  ...securePlugin.configs.recommended,
87
87
 
88
- // Zero-tolerance: same 16 rules, all promoted to error (good for CI gates)
88
+ // Zero-tolerance: same 18 rules, all promoted to error (good for CI gates)
89
89
  // ...securePlugin.configs['recommended-strict'],
90
90
  ];
91
91
  ```
@@ -120,8 +120,8 @@ The competitor's entropy-only detection catches the high-entropy API-key shape b
120
120
  ## ⚙️ Configuration Presets
121
121
  | Preset | Description |
122
122
  | :-------------------- | :-------------------------------------------------------------- |
123
- | `recommended` | 16 core rules — critical issues as `error`, lower-confidence as `warn` |
124
- | `recommended-strict` | Same 16 rules as `recommended`, all promoted to `error` — for CI gates |
123
+ | `recommended` | 18 core rules — critical issues as `error`, lower-confidence as `warn` |
124
+ | `recommended-strict` | Same 18 rules as `recommended`, all promoted to `error` — for CI gates |
125
125
  | `strict` | All rules as `error` — maximum coverage including experimental rules |
126
126
  | `owasp-top-10` | OWASP Top 10 Web 2021 compliance focused |
127
127
  | `owasp-mobile-top-10` | OWASP Mobile Top 10 2024 compliance focused |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-secure-coding",
3
- "version": "5.6.1",
3
+ "version": "5.6.3",
4
4
  "description": "ESLint plugin for secure coding — detects LDAP, XPath, XXE, GraphQL and template injection, unsafe deserialization, ReDoS, missing authentication, and PII in logs.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -78,14 +78,14 @@
78
78
  "node": ">=18.0.0"
79
79
  },
80
80
  "dependencies": {
81
- "@interlace/eslint-devkit": "^1.21.1",
81
+ "@interlace/eslint-devkit": "^1.21.2",
82
82
  "refa": "^0.12.0",
83
83
  "scslre": "^0.3.0",
84
84
  "@eslint-community/regexpp": "^4.10.0"
85
85
  },
86
86
  "peerDependencies": {
87
87
  "eslint": "^8.40.0 || ^9.0.0 || ^10.0.0",
88
- "recheck": "^4.5.0"
88
+ "recheck": "^4.6.2"
89
89
  },
90
90
  "funding": {
91
91
  "type": "github",
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.6.1"},rules:exports.rules};const recommendedRules={"secure-coding/no-graphql-injection":"warn","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-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.3"},rules:exports.rules};const recommendedRules={"secure-coding/no-graphql-injection":"warn","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-sql-injection":"error","secure-coding/no-log-injection":"error","secure-coding/no-fail-open-auth":"error","secure-coding/no-homoglyph-identifiers":"error","secure-coding/no-unsafe-deserialization":"warn","secure-coding/no-redos-vulnerable-regex":"error","secure-coding/no-unsafe-regex-construction":"error","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-template-injection":"error","secure-coding/no-improper-sanitization":"error","secure-coding/no-privilege-escalation":"warn","secure-coding/no-weak-password-recovery":"warn","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-unlimited-resource-allocation":"warn"};exports.configs={flagship:{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-hardcoded-credentials":"error","secure-coding/no-redos-vulnerable-regex":"error"}},recommended:{plugins:{"secure-coding":exports.plugin},rules:recommendedRules},"recommended-strict":{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(recommendedRules).map(rule=>[rule,"error"]))},strict:{plugins:{"secure-coding":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`secure-coding/${ruleName}`,"error"]))},"owasp-top-10":{plugins:{"secure-coding":exports.plugin},rules:{"secure-coding/no-privilege-escalation":"warn","secure-coding/no-hardcoded-credentials":"error","secure-coding/no-sensitive-data-exposure":"warn","secure-coding/no-graphql-injection":"error","secure-coding/no-xxe-injection":"error","secure-coding/no-xpath-injection":"error","secure-coding/no-ldap-injection":"error","secure-coding/no-weak-password-recovery":"error","secure-coding/no-unsafe-deserialization":"error"}}};exports.default=exports.plugin;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const resolve_reference_1=require("../../utils/resolve-reference");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noGraphqlInjection=(0,eslint_devkit_1.createRule)({name:"no-graphql-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-graphql-injection.md",description:"Detects GraphQL injection vulnerabilities and DoS attacks",cwe:"CWE-89"},messages:{graphqlInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"GraphQL Injection",cwe:"CWE-89",description:"GraphQL injection vulnerability detected",severity:"HIGH",fix:"Use GraphQL variables or query builders instead of string concatenation",documentationLink:"https://owasp.org/Top10/2025/A05_2025-Injection/"}),introspectionQuery:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Introspection Query",cwe:"CWE-200",description:"Introspection query may leak schema information",severity:"HIGH",fix:"Disable introspection in production",documentationLink:"https://graphql.org/learn/introspection/"}),complexQueryDos:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Complex Query DoS Risk",cwe:"CWE-400",description:"Complex query may cause DoS",severity:"MEDIUM",fix:"Limit query depth and complexity",documentationLink:"https://graphql.org/learn/queries/"}),unsafeVariableInterpolation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Variable Interpolation",cwe:"CWE-89",description:"Unsafe interpolation in GraphQL query",severity:"HIGH",fix:"Use GraphQL variables instead of string interpolation",documentationLink:"https://graphql.org/learn/queries/#variables"}),missingInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Input Validation",cwe:"CWE-20",description:"GraphQL input not validated",severity:"MEDIUM",fix:"Validate all user inputs before GraphQL execution",documentationLink:"https://graphql.org/learn/validation/"})},schema:[{type:"object",properties:{allowIntrospection:{type:"boolean",default:false,description:"Allow introspection queries"},maxQueryDepth:{type:"number",minimum:1,default:10,description:"Maximum query nesting depth before reporting a DoS risk"},trustedGraphqlLibraries:{type:"array",items:{type:"string"},default:["graphql","apollo-server","graphql-tools","graphql-tag"],description:"GraphQL libraries recognised as query builders"},validationFunctions:{type:"array",items:{type:"string"},default:["validate","sanitize","isValid","assertValid"],description:"Function names that count as query validation"},safeTemplateLiteralCallers:{type:"array",items:{type:"string"},default:[],description:"Additional callers where template literals are never GraphQL. Format: object.method or ClassName."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as GraphQL sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{allowIntrospection:false,maxQueryDepth:10,trustedGraphqlLibraries:["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions:["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let allowIntrospection;let maxQueryDepth;let trustedGraphqlLibraries;let validationFunctions;let safeTemplateLiteralCallers;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let safetyChecker;let safeMemberCallers;let safeConstructors;let GRAPHQL_OP_KEYWORDS;let GRAPHQL_SCHEMA_KEYWORDS;let GRAPHQL_TAG_NAMES;const GRAPHQL_SCHEMA_BINDING=/typedef|schema|sdl/i;const isGraphqlRelated=node=>{const callee=node.callee;if(callee.type==="Identifier"){return trustedGraphqlLibraries.some(lib=>callee.name.toLowerCase().includes(lib.toLowerCase()))}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){const objectName=callee.object.name;return trustedGraphqlLibraries.some(lib=>objectName.toLowerCase().includes(lib.toLowerCase()))}return false};const isInSafeCallerContext=node=>{let current=node.parent;while(current){if(current.type==="CallExpression"){const callee=current.callee;const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&method!==null){const key=`${callee.object.name}.${method}`;if(safeMemberCallers.has(key))return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){if(current.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&safeConstructors.has(current.callee.name)){return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){break}current=current.parent}return false};const isWordChar=ch=>/\w/.test(ch);const isWhitespace=ch=>/\s/.test(ch);const skip=(text,from,accept)=>{let at=from;while(accept(text.charAt(at)))at++;return at};const isAtLineStart=(text,idx)=>{for(let i=idx-1;i>=0;i--){const ch=text[i];if(ch==="\n")return true;if(!isWhitespace(ch))return false}return true};const maxBraceDepth=text=>{let depth=0;let open=0;for(const ch of text){if(ch==="{"){open++;depth=Math.max(depth,open)}else if(ch==="}"){open--}}return depth};const isStandaloneSelectionSet=text=>{const trimmed=text.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))return false;if(/\{\{|\}\}/.test(trimmed))return false;if(/"[^"]*"\s*:/.test(trimmed))return false;return maxBraceDepth(trimmed)>=2};const findKeywordAtBoundary=(text,keyword,startFrom=0)=>{let pos=startFrom;while(true){const idx=text.indexOf(keyword,pos);if(idx===-1)return-1;const beforeOk=idx===0||!isWordChar(text[idx-1]);const afterOk=!isWordChar(text.charAt(idx+keyword.length));if(beforeOk&&afterOk)return idx;pos=idx+1}};const keywordEndsAtLineStart=(text,keyword)=>{const ends=[];for(let idx=findKeywordAtBoundary(text,keyword);idx!==-1;idx=findKeywordAtBoundary(text,keyword,idx+1)){if(isAtLineStart(text,idx))ends.push(idx+keyword.length)}return ends};const hasGraphqlAttribution=node=>{let current=node;while(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){current=current.parent}const parent=current.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){const tag=parent.tag;const tagName=tag.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.name:tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(tag)??"":"";return GRAPHQL_TAG_NAMES.has(tagName.toLowerCase())}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.id.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.key.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isGraphqlRelated(parent)}return false};const templateText=node=>node.quasis.map(q=>q.value.cooked??q.value.raw).join("");const isGraphqlTemplate=node=>containsGraphqlText(templateText(node),hasGraphqlAttribution(node));const isGraphqlComposition=expr=>{const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(expr),expr);if(variable===null||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===null)return false;const literal=init.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression?init.expression:init;const text=literal.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?templateText(literal):(0,eslint_devkit_1.staticString)(literal);return text!==null&&containsGraphqlText(text,hasGraphqlAttribution(literal))};const hasIntrospectionField=text=>{const lower=text.toLowerCase();return findKeywordAtBoundary(lower,"__schema")!==-1||findKeywordAtBoundary(lower,"__type")!==-1};const containsGraphqlText=(text,attributed)=>{const lower=text.toLowerCase();for(const keyword of GRAPHQL_OP_KEYWORDS){for(const end of keywordEndsAtLineStart(lower,keyword)){const afterName=skip(lower,skip(lower,skip(lower,end,isWhitespace),isWordChar),isWhitespace);const next=lower.charAt(afterName);if(next==="(")return true;if(next==="{"&&(attributed||isWordChar(lower.charAt(skip(lower,afterName+1,isWhitespace))))){return true}}}for(const end of keywordEndsAtLineStart(lower,"fragment")){const on=skip(lower,skip(lower,skip(lower,end,isWhitespace),isWordChar),isWhitespace);if(lower.startsWith("on",on)&&!isWordChar(lower.charAt(on+2))){return true}}if(attributed&&lower.includes("{")){for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){for(const end of keywordEndsAtLineStart(lower,keyword)){if(isWordChar(lower.charAt(skip(lower,end,isWhitespace)))){return true}}}}return isStandaloneSelectionSet(text)};const concatenatedStaticText=node=>{if(node.type==="BinaryExpression"&&node.operator==="+"){return concatenatedStaticText(node.left)+concatenatedStaticText(node.right)}if(node.type==="TemplateLiteral"){return templateText(node)}return(0,eslint_devkit_1.staticString)(node)??""};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};return{before(){const options=context.options[0]||{};({allowIntrospection=false,maxQueryDepth=10,trustedGraphqlLibraries=["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions=["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const BUILTIN_SAFE_MEMBER_CALLERS=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.trace","logger.log","logger.info","logger.warn","logger.error","logger.debug"]);const BUILTIN_SAFE_CONSTRUCTORS=new Set(["URL","Error","TypeError","RangeError"]);safeMemberCallers=new Set(BUILTIN_SAFE_MEMBER_CALLERS);safeConstructors=new Set(BUILTIN_SAFE_CONSTRUCTORS);for(const caller of safeTemplateLiteralCallers){if(caller.includes(".")){safeMemberCallers.add(caller)}else{safeConstructors.add(caller)}}GRAPHQL_OP_KEYWORDS=["query","mutation","subscription"];GRAPHQL_SCHEMA_KEYWORDS=["type","interface","enum","scalar","input"];GRAPHQL_TAG_NAMES=new Set(["gql","graphql"])},TemplateLiteral(node){if(isInSafeCallerContext(node)){return}if(!isGraphqlTemplate(node)){return}if(!allowIntrospection&&node.quasis.some(q=>hasIntrospectionField(q.value.cooked??q.value.raw))){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery"});return}const allExpressionsSafe=node.expressions.every(expr=>isGraphqlComposition(expr)||isInputValidated(expr)||safetyChecker.isSafe(expr,context));if(!allExpressionsSafe){context.report({node,messageId:"unsafeVariableInterpolation"})}if(maxBraceDepth(templateText(node))>maxQueryDepth){context.report({node,messageId:"complexQueryDos"})}},Literal(node){const queryText=(0,eslint_devkit_1.staticString)(node);if(queryText===null)return;if(!containsGraphqlText(queryText,hasGraphqlAttribution(node))){return}if(!allowIntrospection&&hasIntrospectionField(queryText)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery"})}if(maxBraceDepth(queryText)>maxQueryDepth){context.report({node,messageId:"complexQueryDos"})}},BinaryExpression(node){const fullText=concatenatedStaticText(node);if(!containsGraphqlText(fullText,hasGraphqlAttribution(node))){return}if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"graphqlInjection"})},CallExpression(node){if(!isGraphqlRelated(node)){return}const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["execute","executeQuery","query","mutate","subscribe"])){for(const arg of node.arguments){if(arg.type==="Identifier"&&!isInputValidated(arg)){if(safetyChecker.isSafe(arg,context)){continue}context.report({node:arg,messageId:"missingInputValidation"})}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const resolve_reference_1=require("../../utils/resolve-reference");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noGraphqlInjection=(0,eslint_devkit_1.createRule)({name:"no-graphql-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-graphql-injection.md",description:"Detects GraphQL injection vulnerabilities and DoS attacks",cwe:"CWE-89"},messages:{graphqlInjection:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"GraphQL Injection",cwe:"CWE-89",description:"GraphQL injection vulnerability detected",severity:"CRITICAL",fix:"Use GraphQL variables or query builders instead of string concatenation",documentationLink:"https://owasp.org/Top10/2025/A05_2025-Injection/"}),introspectionQuery:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Dangerous Introspection Query",cwe:"CWE-200",description:"Introspection query may leak schema information",severity:"HIGH",fix:"Disable introspection in production",documentationLink:"https://graphql.org/learn/introspection/"}),complexQueryDos:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Complex Query DoS Risk",cwe:"CWE-400",description:"Complex query may cause DoS",severity:"MEDIUM",fix:"Limit query depth and complexity",documentationLink:"https://graphql.org/learn/queries/"}),unsafeVariableInterpolation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Variable Interpolation",cwe:"CWE-89",description:"Unsafe interpolation in GraphQL query",severity:"HIGH",fix:"Use GraphQL variables instead of string interpolation",documentationLink:"https://graphql.org/learn/queries/#variables"}),missingInputValidation:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Input Validation",cwe:"CWE-20",description:"GraphQL input not validated",severity:"MEDIUM",fix:"Validate all user inputs before GraphQL execution",documentationLink:"https://graphql.org/learn/validation/"})},schema:[{type:"object",properties:{allowIntrospection:{type:"boolean",default:false,description:"Allow introspection queries"},maxQueryDepth:{type:"number",minimum:1,default:10,description:"Maximum query nesting depth before reporting a DoS risk"},trustedGraphqlLibraries:{type:"array",items:{type:"string"},default:["graphql","apollo-server","graphql-tools","graphql-tag"],description:"GraphQL libraries recognised as query builders"},validationFunctions:{type:"array",items:{type:"string"},default:["validate","sanitize","isValid","assertValid"],description:"Function names that count as query validation"},safeTemplateLiteralCallers:{type:"array",items:{type:"string"},default:[],description:"Additional callers where template literals are never GraphQL. Format: object.method or ClassName."},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as GraphQL sanitizers"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{allowIntrospection:false,maxQueryDepth:10,trustedGraphqlLibraries:["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions:["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers:[],trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],createOnce(context){let allowIntrospection;let maxQueryDepth;let trustedGraphqlLibraries;let validationFunctions;let safeTemplateLiteralCallers;let trustedSanitizers;let trustedAnnotations;let strictMode;let sourceCode;let safetyChecker;let safeMemberCallers;let safeConstructors;let GRAPHQL_OP_KEYWORDS;let GRAPHQL_SCHEMA_KEYWORDS;let GRAPHQL_TAG_NAMES;const GRAPHQL_SCHEMA_BINDING=/typedef|schema|sdl/i;const isGraphqlRelated=node=>{const callee=node.callee;if(callee.type==="Identifier"){return trustedGraphqlLibraries.some(lib=>callee.name.toLowerCase().includes(lib.toLowerCase()))}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"){const objectName=callee.object.name;return trustedGraphqlLibraries.some(lib=>objectName.toLowerCase().includes(lib.toLowerCase()))}return false};const isInSafeCallerContext=node=>{let current=node.parent;while(current){if(current.type==="CallExpression"){const callee=current.callee;const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&method!==null){const key=`${callee.object.name}.${method}`;if(safeMemberCallers.has(key))return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){if(current.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&safeConstructors.has(current.callee.name)){return true}break}if(current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){break}current=current.parent}return false};const isWordChar=ch=>/\w/.test(ch);const isWhitespace=ch=>/\s/.test(ch);const skip=(text,from,accept)=>{let at=from;while(accept(text.charAt(at)))at++;return at};const isAtLineStart=(text,idx)=>{for(let i=idx-1;i>=0;i--){const ch=text[i];if(ch==="\n")return true;if(!isWhitespace(ch))return false}return true};const maxBraceDepth=text=>{let depth=0;let open=0;for(const ch of text){if(ch==="{"){open++;depth=Math.max(depth,open)}else if(ch==="}"){open--}}return depth};const isStandaloneSelectionSet=text=>{const trimmed=text.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))return false;if(/\{\{|\}\}/.test(trimmed))return false;if(/"[^"]*"\s*:/.test(trimmed))return false;return maxBraceDepth(trimmed)>=2};const findKeywordAtBoundary=(text,keyword,startFrom=0)=>{let pos=startFrom;while(true){const idx=text.indexOf(keyword,pos);if(idx===-1)return-1;const beforeOk=idx===0||!isWordChar(text[idx-1]);const afterOk=!isWordChar(text.charAt(idx+keyword.length));if(beforeOk&&afterOk)return idx;pos=idx+1}};const keywordEndsAtLineStart=(text,keyword)=>{const ends=[];for(let idx=findKeywordAtBoundary(text,keyword);idx!==-1;idx=findKeywordAtBoundary(text,keyword,idx+1)){if(isAtLineStart(text,idx))ends.push(idx+keyword.length)}return ends};const hasGraphqlAttribution=node=>{let current=node;while(current.parent?.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){current=current.parent}const parent=current.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression){const tag=parent.tag;const tagName=tag.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?tag.name:tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(tag)??"":"";return GRAPHQL_TAG_NAMES.has(tagName.toLowerCase())}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.id.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return GRAPHQL_SCHEMA_BINDING.test(parent.key.name)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return isGraphqlRelated(parent)}return false};const templateText=node=>node.quasis.map(q=>q.value.cooked??q.value.raw).join("");const isGraphqlTemplate=node=>containsGraphqlText(templateText(node),hasGraphqlAttribution(node));const isGraphqlComposition=expr=>{const variable=(0,resolve_reference_1.resolvedReference)(sourceCode.getScope(expr),expr);if(variable===null||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===null)return false;const literal=init.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression?init.expression:init;const text=literal.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?templateText(literal):(0,eslint_devkit_1.staticString)(literal);return text!==null&&containsGraphqlText(text,hasGraphqlAttribution(literal))};const hasIntrospectionField=text=>{const lower=text.toLowerCase();return findKeywordAtBoundary(lower,"__schema")!==-1||findKeywordAtBoundary(lower,"__type")!==-1};const containsGraphqlText=(text,attributed)=>{const lower=text.toLowerCase();for(const keyword of GRAPHQL_OP_KEYWORDS){for(const end of keywordEndsAtLineStart(lower,keyword)){const afterName=skip(lower,skip(lower,skip(lower,end,isWhitespace),isWordChar),isWhitespace);const next=lower.charAt(afterName);if(next==="(")return true;if(next==="{"&&(attributed||isWordChar(lower.charAt(skip(lower,afterName+1,isWhitespace))))){return true}}}for(const end of keywordEndsAtLineStart(lower,"fragment")){const on=skip(lower,skip(lower,skip(lower,end,isWhitespace),isWordChar),isWhitespace);if(lower.startsWith("on",on)&&!isWordChar(lower.charAt(on+2))){return true}}if(attributed&&lower.includes("{")){for(const keyword of GRAPHQL_SCHEMA_KEYWORDS){for(const end of keywordEndsAtLineStart(lower,keyword)){if(isWordChar(lower.charAt(skip(lower,end,isWhitespace)))){return true}}}}return isStandaloneSelectionSet(text)};const concatenatedStaticText=node=>{if(node.type==="BinaryExpression"&&node.operator==="+"){return concatenatedStaticText(node.left)+concatenatedStaticText(node.right)}if(node.type==="TemplateLiteral"){return templateText(node)}return(0,eslint_devkit_1.staticString)(node)??""};const isInputValidated=inputNode=>{let current=inputNode;while(current){if(current.type==="CallExpression"&&current.callee.type==="Identifier"&&validationFunctions.includes(current.callee.name)){return true}current=current.parent}return false};return{before(){const options=context.options[0]||{};({allowIntrospection=false,maxQueryDepth=10,trustedGraphqlLibraries=["graphql","apollo-server","graphql-tools","graphql-tag"],validationFunctions=["validate","sanitize","isValid","assertValid"],safeTemplateLiteralCallers=[],trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options);sourceCode=context.sourceCode;safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const BUILTIN_SAFE_MEMBER_CALLERS=new Set(["console.log","console.warn","console.error","console.info","console.debug","console.trace","logger.log","logger.info","logger.warn","logger.error","logger.debug"]);const BUILTIN_SAFE_CONSTRUCTORS=new Set(["URL","Error","TypeError","RangeError"]);safeMemberCallers=new Set(BUILTIN_SAFE_MEMBER_CALLERS);safeConstructors=new Set(BUILTIN_SAFE_CONSTRUCTORS);for(const caller of safeTemplateLiteralCallers){if(caller.includes(".")){safeMemberCallers.add(caller)}else{safeConstructors.add(caller)}}GRAPHQL_OP_KEYWORDS=["query","mutation","subscription"];GRAPHQL_SCHEMA_KEYWORDS=["type","interface","enum","scalar","input"];GRAPHQL_TAG_NAMES=new Set(["gql","graphql"])},TemplateLiteral(node){if(isInSafeCallerContext(node)){return}if(!isGraphqlTemplate(node)){return}if(!allowIntrospection&&node.quasis.some(q=>hasIntrospectionField(q.value.cooked??q.value.raw))){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery"});return}const allExpressionsSafe=node.expressions.every(expr=>isGraphqlComposition(expr)||isInputValidated(expr)||safetyChecker.isSafe(expr,context));if(!allExpressionsSafe){context.report({node,messageId:"unsafeVariableInterpolation"})}if(maxBraceDepth(templateText(node))>maxQueryDepth){context.report({node,messageId:"complexQueryDos"})}},Literal(node){const queryText=(0,eslint_devkit_1.staticString)(node);if(queryText===null)return;if(!containsGraphqlText(queryText,hasGraphqlAttribution(node))){return}if(!allowIntrospection&&hasIntrospectionField(queryText)){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"introspectionQuery"})}if(maxBraceDepth(queryText)>maxQueryDepth){context.report({node,messageId:"complexQueryDos"})}},BinaryExpression(node){const fullText=concatenatedStaticText(node);if(!containsGraphqlText(fullText,hasGraphqlAttribution(node))){return}if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"graphqlInjection"})},CallExpression(node){if(!isGraphqlRelated(node)){return}const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),["execute","executeQuery","query","mutate","subscribe"])){for(const arg of node.arguments){if(arg.type==="Identifier"&&!isInputValidated(arg)){if(safetyChecker.isSafe(arg,context)){continue}context.report({node:arg,messageId:"missingInputValidation"})}}}}}}});