eslint-plugin-mcp-sdk-security 1.0.0 → 1.1.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
@@ -48,10 +48,34 @@ That trade costs recall, and we measure it:
48
48
 
49
49
  - To check out the [guide](https://eslint.interlace.tools/docs/security/plugin-mcp-sdk-security?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-mcp-sdk-security), visit [eslint.interlace.tools](https://eslint.interlace.tools/?utm_source=github&utm_medium=referral&utm_campaign=eslint-plugin-mcp-sdk-security). 📚
50
50
 
51
+ <!-- AUTO-GENERATED:INSTALL:START - Do not edit manually -->
52
+
53
+ **oxlint / Vite+** — the same rules under the same `mcp-sdk-security/<rule>` IDs, without ESLint:
54
+
55
+ ```bash
56
+ npm install oxlint-plugin-mcp-sdk-security --save-dev
57
+ ```
58
+
59
+ ```jsonc
60
+ // .oxlintrc.json
61
+ { "jsPlugins": ["oxlint-plugin-mcp-sdk-security"] }
62
+ ```
63
+
64
+ ```ts
65
+ // vite.config.ts
66
+ import { defineConfig } from 'vite-plus';
67
+
68
+ export default defineConfig({ lint: { jsPlugins: ['oxlint-plugin-mcp-sdk-security'] } });
69
+ ```
70
+
71
+ **ESLint:**
72
+
51
73
  ```bash
52
74
  npm install eslint-plugin-mcp-sdk-security --save-dev
53
75
  ```
54
76
 
77
+ <!-- AUTO-GENERATED:INSTALL:END -->
78
+
55
79
  ## ⚙️ Configuration Presets
56
80
 
57
81
  | Preset | Rules (`error`, except `no-duplicate-tool-name` at `warn`) | Description |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-mcp-sdk-security",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "ESLint plugin for Model Context Protocol (MCP) SDK security — follows tool arguments into shells, file paths, URLs, SQL and eval; catches credential leaks, untrusted text in model-facing descriptions and prompts, unhardened HTTP transports, shared stateless servers, predictable session ids, untrusted stdio commands and schema/handler drift.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -69,12 +69,15 @@
69
69
  "@modelcontextprotocol/sdk": "^1.0.0"
70
70
  },
71
71
  "peerDependenciesMeta": {
72
+ "eslint": {
73
+ "optional": true
74
+ },
72
75
  "@modelcontextprotocol/sdk": {
73
76
  "optional": true
74
77
  }
75
78
  },
76
79
  "dependencies": {
77
- "@interlace/eslint-devkit": "^1.20.0"
80
+ "@interlace/eslint-devkit": "^1.21.0"
78
81
  },
79
82
  "funding": {
80
83
  "type": "github",
package/src/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=exports.requireToolInputSchema=exports.requireHttpTransportHardening=exports.noUnvalidatedToolArgs=exports.noUntrustedToolMetadataInPrompt=exports.noUntrustedStdioCommand=exports.noToolDescriptionInjection=exports.noSsrfInTool=exports.noSqlInjectionInTool=exports.noSharedStatelessTransport=exports.noPredictableSessionId=exports.noPathTraversalInTool=exports.noDuplicateToolName=exports.noCredentialLeakInTool=exports.noCommandInjectionInTool=exports.noCodeInjectionInTool=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");var no_code_injection_in_tool_2=require("./rules/no-code-injection-in-tool");Object.defineProperty(exports,"noCodeInjectionInTool",{enumerable:true,get:function(){return no_code_injection_in_tool_2.noCodeInjectionInTool}});var no_command_injection_in_tool_2=require("./rules/no-command-injection-in-tool");Object.defineProperty(exports,"noCommandInjectionInTool",{enumerable:true,get:function(){return no_command_injection_in_tool_2.noCommandInjectionInTool}});var no_credential_leak_in_tool_2=require("./rules/no-credential-leak-in-tool");Object.defineProperty(exports,"noCredentialLeakInTool",{enumerable:true,get:function(){return no_credential_leak_in_tool_2.noCredentialLeakInTool}});var no_duplicate_tool_name_2=require("./rules/no-duplicate-tool-name");Object.defineProperty(exports,"noDuplicateToolName",{enumerable:true,get:function(){return no_duplicate_tool_name_2.noDuplicateToolName}});var no_path_traversal_in_tool_2=require("./rules/no-path-traversal-in-tool");Object.defineProperty(exports,"noPathTraversalInTool",{enumerable:true,get:function(){return no_path_traversal_in_tool_2.noPathTraversalInTool}});var no_predictable_session_id_2=require("./rules/no-predictable-session-id");Object.defineProperty(exports,"noPredictableSessionId",{enumerable:true,get:function(){return no_predictable_session_id_2.noPredictableSessionId}});var no_shared_stateless_transport_2=require("./rules/no-shared-stateless-transport");Object.defineProperty(exports,"noSharedStatelessTransport",{enumerable:true,get:function(){return no_shared_stateless_transport_2.noSharedStatelessTransport}});var no_sql_injection_in_tool_2=require("./rules/no-sql-injection-in-tool");Object.defineProperty(exports,"noSqlInjectionInTool",{enumerable:true,get:function(){return no_sql_injection_in_tool_2.noSqlInjectionInTool}});var no_ssrf_in_tool_2=require("./rules/no-ssrf-in-tool");Object.defineProperty(exports,"noSsrfInTool",{enumerable:true,get:function(){return no_ssrf_in_tool_2.noSsrfInTool}});var no_tool_description_injection_2=require("./rules/no-tool-description-injection");Object.defineProperty(exports,"noToolDescriptionInjection",{enumerable:true,get:function(){return no_tool_description_injection_2.noToolDescriptionInjection}});var no_untrusted_stdio_command_2=require("./rules/no-untrusted-stdio-command");Object.defineProperty(exports,"noUntrustedStdioCommand",{enumerable:true,get:function(){return no_untrusted_stdio_command_2.noUntrustedStdioCommand}});var no_untrusted_tool_metadata_in_prompt_2=require("./rules/no-untrusted-tool-metadata-in-prompt");Object.defineProperty(exports,"noUntrustedToolMetadataInPrompt",{enumerable:true,get:function(){return no_untrusted_tool_metadata_in_prompt_2.noUntrustedToolMetadataInPrompt}});var no_unvalidated_tool_args_2=require("./rules/no-unvalidated-tool-args");Object.defineProperty(exports,"noUnvalidatedToolArgs",{enumerable:true,get:function(){return no_unvalidated_tool_args_2.noUnvalidatedToolArgs}});var require_http_transport_hardening_2=require("./rules/require-http-transport-hardening");Object.defineProperty(exports,"requireHttpTransportHardening",{enumerable:true,get:function(){return require_http_transport_hardening_2.requireHttpTransportHardening}});var require_tool_input_schema_2=require("./rules/require-tool-input-schema");Object.defineProperty(exports,"requireToolInputSchema",{enumerable:true,get:function(){return require_tool_input_schema_2.requireToolInputSchema}});exports.rules={get"no-code-injection-in-tool"(){return require("./rules/no-code-injection-in-tool").noCodeInjectionInTool},get"no-command-injection-in-tool"(){return require("./rules/no-command-injection-in-tool").noCommandInjectionInTool},get"no-credential-leak-in-tool"(){return require("./rules/no-credential-leak-in-tool").noCredentialLeakInTool},get"no-duplicate-tool-name"(){return require("./rules/no-duplicate-tool-name").noDuplicateToolName},get"no-path-traversal-in-tool"(){return require("./rules/no-path-traversal-in-tool").noPathTraversalInTool},get"no-predictable-session-id"(){return require("./rules/no-predictable-session-id").noPredictableSessionId},get"no-shared-stateless-transport"(){return require("./rules/no-shared-stateless-transport").noSharedStatelessTransport},get"no-sql-injection-in-tool"(){return require("./rules/no-sql-injection-in-tool").noSqlInjectionInTool},get"no-ssrf-in-tool"(){return require("./rules/no-ssrf-in-tool").noSsrfInTool},get"no-tool-description-injection"(){return require("./rules/no-tool-description-injection").noToolDescriptionInjection},get"no-untrusted-stdio-command"(){return require("./rules/no-untrusted-stdio-command").noUntrustedStdioCommand},get"no-untrusted-tool-metadata-in-prompt"(){return require("./rules/no-untrusted-tool-metadata-in-prompt").noUntrustedToolMetadataInPrompt},get"no-unvalidated-tool-args"(){return require("./rules/no-unvalidated-tool-args").noUnvalidatedToolArgs},get"require-http-transport-hardening"(){return require("./rules/require-http-transport-hardening").requireHttpTransportHardening},get"require-tool-input-schema"(){return require("./rules/require-tool-input-schema").requireToolInputSchema}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-mcp-sdk-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-mcp-sdk-security",version:"1.0.0"},rules:exports.rules};const minimalRules={"mcp-sdk-security/no-command-injection-in-tool":"error","mcp-sdk-security/require-tool-input-schema":"error"};const recommendedRules={"mcp-sdk-security/no-code-injection-in-tool":"error","mcp-sdk-security/no-command-injection-in-tool":"error","mcp-sdk-security/no-credential-leak-in-tool":"error","mcp-sdk-security/no-duplicate-tool-name":"warn","mcp-sdk-security/no-path-traversal-in-tool":"error","mcp-sdk-security/no-predictable-session-id":"error","mcp-sdk-security/no-shared-stateless-transport":"error","mcp-sdk-security/no-sql-injection-in-tool":"error","mcp-sdk-security/no-ssrf-in-tool":"error","mcp-sdk-security/no-tool-description-injection":"error","mcp-sdk-security/no-untrusted-stdio-command":"error","mcp-sdk-security/no-untrusted-tool-metadata-in-prompt":"error","mcp-sdk-security/no-unvalidated-tool-args":"error","mcp-sdk-security/require-http-transport-hardening":"error","mcp-sdk-security/require-tool-input-schema":"error"};const strictRules={...Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`mcp-sdk-security/${ruleName}`,"error"])),...recommendedRules};exports.configs={minimal:{plugins:{"mcp-sdk-security":exports.plugin},rules:minimalRules},recommended:{plugins:{"mcp-sdk-security":exports.plugin},rules:recommendedRules},strict:{plugins:{"mcp-sdk-security":exports.plugin},rules:strictRules}};exports.default={...exports.plugin,configs:exports.configs};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=exports.requireToolInputSchema=exports.requireHttpTransportHardening=exports.noUnvalidatedToolArgs=exports.noUntrustedToolMetadataInPrompt=exports.noUntrustedStdioCommand=exports.noToolDescriptionInjection=exports.noSsrfInTool=exports.noSqlInjectionInTool=exports.noSharedStatelessTransport=exports.noPredictableSessionId=exports.noPathTraversalInTool=exports.noDuplicateToolName=exports.noCredentialLeakInTool=exports.noCommandInjectionInTool=exports.noCodeInjectionInTool=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");var no_code_injection_in_tool_2=require("./rules/no-code-injection-in-tool");Object.defineProperty(exports,"noCodeInjectionInTool",{enumerable:true,get:function(){return no_code_injection_in_tool_2.noCodeInjectionInTool}});var no_command_injection_in_tool_2=require("./rules/no-command-injection-in-tool");Object.defineProperty(exports,"noCommandInjectionInTool",{enumerable:true,get:function(){return no_command_injection_in_tool_2.noCommandInjectionInTool}});var no_credential_leak_in_tool_2=require("./rules/no-credential-leak-in-tool");Object.defineProperty(exports,"noCredentialLeakInTool",{enumerable:true,get:function(){return no_credential_leak_in_tool_2.noCredentialLeakInTool}});var no_duplicate_tool_name_2=require("./rules/no-duplicate-tool-name");Object.defineProperty(exports,"noDuplicateToolName",{enumerable:true,get:function(){return no_duplicate_tool_name_2.noDuplicateToolName}});var no_path_traversal_in_tool_2=require("./rules/no-path-traversal-in-tool");Object.defineProperty(exports,"noPathTraversalInTool",{enumerable:true,get:function(){return no_path_traversal_in_tool_2.noPathTraversalInTool}});var no_predictable_session_id_2=require("./rules/no-predictable-session-id");Object.defineProperty(exports,"noPredictableSessionId",{enumerable:true,get:function(){return no_predictable_session_id_2.noPredictableSessionId}});var no_shared_stateless_transport_2=require("./rules/no-shared-stateless-transport");Object.defineProperty(exports,"noSharedStatelessTransport",{enumerable:true,get:function(){return no_shared_stateless_transport_2.noSharedStatelessTransport}});var no_sql_injection_in_tool_2=require("./rules/no-sql-injection-in-tool");Object.defineProperty(exports,"noSqlInjectionInTool",{enumerable:true,get:function(){return no_sql_injection_in_tool_2.noSqlInjectionInTool}});var no_ssrf_in_tool_2=require("./rules/no-ssrf-in-tool");Object.defineProperty(exports,"noSsrfInTool",{enumerable:true,get:function(){return no_ssrf_in_tool_2.noSsrfInTool}});var no_tool_description_injection_2=require("./rules/no-tool-description-injection");Object.defineProperty(exports,"noToolDescriptionInjection",{enumerable:true,get:function(){return no_tool_description_injection_2.noToolDescriptionInjection}});var no_untrusted_stdio_command_2=require("./rules/no-untrusted-stdio-command");Object.defineProperty(exports,"noUntrustedStdioCommand",{enumerable:true,get:function(){return no_untrusted_stdio_command_2.noUntrustedStdioCommand}});var no_untrusted_tool_metadata_in_prompt_2=require("./rules/no-untrusted-tool-metadata-in-prompt");Object.defineProperty(exports,"noUntrustedToolMetadataInPrompt",{enumerable:true,get:function(){return no_untrusted_tool_metadata_in_prompt_2.noUntrustedToolMetadataInPrompt}});var no_unvalidated_tool_args_2=require("./rules/no-unvalidated-tool-args");Object.defineProperty(exports,"noUnvalidatedToolArgs",{enumerable:true,get:function(){return no_unvalidated_tool_args_2.noUnvalidatedToolArgs}});var require_http_transport_hardening_2=require("./rules/require-http-transport-hardening");Object.defineProperty(exports,"requireHttpTransportHardening",{enumerable:true,get:function(){return require_http_transport_hardening_2.requireHttpTransportHardening}});var require_tool_input_schema_2=require("./rules/require-tool-input-schema");Object.defineProperty(exports,"requireToolInputSchema",{enumerable:true,get:function(){return require_tool_input_schema_2.requireToolInputSchema}});exports.rules={get"no-code-injection-in-tool"(){return require("./rules/no-code-injection-in-tool").noCodeInjectionInTool},get"no-command-injection-in-tool"(){return require("./rules/no-command-injection-in-tool").noCommandInjectionInTool},get"no-credential-leak-in-tool"(){return require("./rules/no-credential-leak-in-tool").noCredentialLeakInTool},get"no-duplicate-tool-name"(){return require("./rules/no-duplicate-tool-name").noDuplicateToolName},get"no-path-traversal-in-tool"(){return require("./rules/no-path-traversal-in-tool").noPathTraversalInTool},get"no-predictable-session-id"(){return require("./rules/no-predictable-session-id").noPredictableSessionId},get"no-shared-stateless-transport"(){return require("./rules/no-shared-stateless-transport").noSharedStatelessTransport},get"no-sql-injection-in-tool"(){return require("./rules/no-sql-injection-in-tool").noSqlInjectionInTool},get"no-ssrf-in-tool"(){return require("./rules/no-ssrf-in-tool").noSsrfInTool},get"no-tool-description-injection"(){return require("./rules/no-tool-description-injection").noToolDescriptionInjection},get"no-untrusted-stdio-command"(){return require("./rules/no-untrusted-stdio-command").noUntrustedStdioCommand},get"no-untrusted-tool-metadata-in-prompt"(){return require("./rules/no-untrusted-tool-metadata-in-prompt").noUntrustedToolMetadataInPrompt},get"no-unvalidated-tool-args"(){return require("./rules/no-unvalidated-tool-args").noUnvalidatedToolArgs},get"require-http-transport-hardening"(){return require("./rules/require-http-transport-hardening").requireHttpTransportHardening},get"require-tool-input-schema"(){return require("./rules/require-tool-input-schema").requireToolInputSchema}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-mcp-sdk-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-mcp-sdk-security",version:"1.1.0"},rules:exports.rules};const minimalRules={"mcp-sdk-security/no-command-injection-in-tool":"error","mcp-sdk-security/require-tool-input-schema":"error"};const recommendedRules={"mcp-sdk-security/no-code-injection-in-tool":"error","mcp-sdk-security/no-command-injection-in-tool":"error","mcp-sdk-security/no-credential-leak-in-tool":"error","mcp-sdk-security/no-duplicate-tool-name":"warn","mcp-sdk-security/no-path-traversal-in-tool":"error","mcp-sdk-security/no-predictable-session-id":"error","mcp-sdk-security/no-shared-stateless-transport":"error","mcp-sdk-security/no-sql-injection-in-tool":"error","mcp-sdk-security/no-ssrf-in-tool":"error","mcp-sdk-security/no-tool-description-injection":"error","mcp-sdk-security/no-untrusted-stdio-command":"error","mcp-sdk-security/no-untrusted-tool-metadata-in-prompt":"error","mcp-sdk-security/no-unvalidated-tool-args":"error","mcp-sdk-security/require-http-transport-hardening":"error","mcp-sdk-security/require-tool-input-schema":"error"};const strictRules={...Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`mcp-sdk-security/${ruleName}`,"error"])),...recommendedRules};exports.configs={minimal:{plugins:{"mcp-sdk-security":exports.plugin},rules:minimalRules},recommended:{plugins:{"mcp-sdk-security":exports.plugin},rules:recommendedRules},strict:{plugins:{"mcp-sdk-security":exports.plugin},rules:strictRules}};exports.default={...exports.plugin,configs:exports.configs};
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCodeInjectionInTool=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const CODE_GLOBALS=new Set(["eval","Function","setTimeout","setInterval"]);const VM_SINKS=new Set(["runInNewContext","runInThisContext","runInContext","compileFunction","Script","SourceTextModule"]);const VM2_CLASSES=new Set(["VM","NodeVM"]);function codeSinkOf(node,scope,builtBy){const{callee}=node;const first=node.arguments.slice(0,1);if(callee.type==="Identifier"&&CODE_GLOBALS.has(callee.name)&&!(0,tool_registration_1.lookupVariable)(callee.name,scope)?.defs.length){return{sink:callee.name,code:callee.name==="Function"?[...node.arguments]:first}}const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding?.module==="vm"){const name=binding.path.join(".");return VM_SINKS.has(name)?{sink:`vm.${name}`,code:first}:void 0}if(callee.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(callee)!=="run")return void 0;const instance=builtBy(callee.object);return instance?.module==="vm2"&&VM2_CLASSES.has(instance.path.join("."))?{sink:`vm2.${instance.path.join(".")}.run`,code:first}:void 0}exports.noCodeInjectionInTool=(0,eslint_devkit_1.createRule)({name:"no-code-injection-in-tool",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-code-injection-in-tool.md",description:"Disallow an MCP tool argument reaching eval, new Function or a vm context as code",cwe:"CWE-95",cvss:9.8},messages:{toolArgToCode:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Evaluated as Code",cwe:"CWE-95",owasp:"A03:2021",cvss:9.8,description:"Tool argument `{{arg}}` is evaluated as code by `{{sink}}`, so whatever steers the model runs arbitrary JavaScript with this server\u2019s privileges",severity:"CRITICAL",compliance:["SOC2","NIST-CSF"],fix:"Do not evaluate the argument. Parse it with a grammar that only accepts what the tool needs (an arithmetic expression parser such as mathjs\u2019 `evaluate` with a restricted scope, `JSON.parse` for data), or map it to a fixed set of operations. `node:vm` is not a sandbox; untrusted code needs a separate process or isolate with no host access.",documentationLink:"https://nodejs.org/api/vm.html#vm-executing-javascript"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const resolve=(0,module_resolver_1.valueResolverFor)(context);const builtBy=(0,instances_1.createInstanceResolver)(context);const handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");const candidates=[];const collect=node=>{const found=codeSinkOf(node,context.sourceCode.getScope(node),builtBy);for(const code of found?.code??[])candidates.push({node:code,sink:found.sink})};return{CallExpression(node){handlers.visit(node);collect(node)},NewExpression:collect,"Program:exit"(){const carries=(0,value_flow_1.createFlow)(context.sourceCode,fn=>handlers.roots.get(fn),void 0,(0,value_flow_1.flowOptionsFor)(context));for(const{node,sink}of candidates){const inner=node.type==="SpreadElement"?node.argument:node;const taint=carries(inner);if(taint?.kind!=="value")continue;context.report({node,messageId:"toolArgToCode",data:{arg:taint.text,sink}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCodeInjectionInTool=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const CODE_GLOBALS=new Set(["eval","Function","setTimeout","setInterval"]);const VM_SINKS=new Set(["runInNewContext","runInThisContext","runInContext","compileFunction","Script","SourceTextModule"]);const VM2_CLASSES=new Set(["VM","NodeVM"]);function codeSinkOf(node,scope,builtBy){const{callee}=node;const first=node.arguments.slice(0,1);if(callee.type==="Identifier"&&CODE_GLOBALS.has(callee.name)&&!(0,tool_registration_1.lookupVariable)(callee.name,scope)?.defs.length){return{sink:callee.name,code:callee.name==="Function"?[...node.arguments]:first}}const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding?.module==="vm"){const name=binding.path.join(".");return VM_SINKS.has(name)?{sink:`vm.${name}`,code:first}:void 0}if(callee.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(callee)!=="run")return void 0;const instance=builtBy(callee.object);return instance?.module==="vm2"&&VM2_CLASSES.has(instance.path.join("."))?{sink:`vm2.${instance.path.join(".")}.run`,code:first}:void 0}exports.noCodeInjectionInTool=(0,eslint_devkit_1.createRule)({name:"no-code-injection-in-tool",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-code-injection-in-tool.md",description:"Disallow an MCP tool argument reaching eval, new Function or a vm context as code",cwe:"CWE-95",cvss:9.8},messages:{toolArgToCode:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Evaluated as Code",cwe:"CWE-95",owasp:"A03:2021",cvss:9.8,description:"Tool argument `{{arg}}` is evaluated as code by `{{sink}}`, so whatever steers the model runs arbitrary JavaScript with this server\u2019s privileges",severity:"CRITICAL",compliance:["SOC2","NIST-CSF"],fix:"Do not evaluate the argument. Parse it with a grammar that only accepts what the tool needs (an arithmetic expression parser such as mathjs\u2019 `evaluate` with a restricted scope, `JSON.parse` for data), or map it to a fixed set of operations. `node:vm` is not a sandbox; untrusted code needs a separate process or isolate with no host access.",documentationLink:"https://nodejs.org/api/vm.html#vm-executing-javascript"})},schema:[]},defaultOptions:[],createOnce(context){let builtBy;let handlers;let candidates;const collect=node=>{const found=codeSinkOf(node,context.sourceCode.getScope(node),builtBy);for(const code of found?.code??[])candidates.push({node:code,sink:found.sink})};return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;const resolve=(0,module_resolver_1.valueResolverFor)(context);builtBy=(0,instances_1.createInstanceResolver)(context);handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");candidates=[];return true},CallExpression(node){handlers.visit(node);collect(node)},NewExpression:collect,"Program:exit"(){const carries=(0,value_flow_1.createFlow)(context.sourceCode,fn=>handlers.roots.get(fn),void 0,(0,value_flow_1.flowOptionsFor)(context));for(const{node,sink}of candidates){const inner=node.type==="SpreadElement"?node.argument:node;const taint=carries(inner);if(taint?.kind!=="value")continue;context.report({node,messageId:"toolArgToCode",data:{arg:taint.text,sink}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCommandInjectionInTool=void 0;exports.handlerArgNames=handlerArgNames;const eslint_devkit_1=require("@interlace/eslint-devkit");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const PROCESS_SINKS=new Set(["exec","execSync","execFile","execFileSync","spawn","spawnSync","fork"]);const EXECA_SINKS=new Set(["execa","execaSync","execaCommand","execaCommandSync","execaNode"]);const ARGV_SINKS=new Set(["spawn","spawnSync","execFile","execFileSync","execa","execaSync"]);const SHELLS=new Set(["sh","bash","zsh","dash","ksh","fish","cmd","cmd.exe","powershell","powershell.exe","pwsh","pwsh.exe"]);const SHELL_SCRIPT_FLAGS=new Set(["-c","-lc","-ic","/c","/C","-Command","-command"]);const TEMPLATE_SINKS={zx:new Set(["$"]),execa:new Set(["$","$sync","execa","execaSync"])};const SHELL_PREFIX=new RegExp(String.raw`^(?:\S*[\\/])?(\S+)\s+(\S+)\s*$`);function handlerArgNames(handler){const direct=new Set;const objects=new Set;const visit=(pattern,inside)=>{if(pattern.type==="AssignmentPattern")pattern=pattern.left;if(pattern.type==="Identifier"){(inside?direct:objects).add(pattern.name);return}if(pattern.type!=="ObjectPattern")return;for(const prop of pattern.properties){if(prop.type==="RestElement")visit(prop.argument,false);else if((0,tool_registration_1.propertyKey)(prop)!==void 0)visit(prop.value,true)}};if((handler.type==="ArrowFunctionExpression"||handler.type==="FunctionExpression"||handler.type==="FunctionDeclaration")&&handler.params[0]!==void 0){visit(handler.params[0],false)}return{direct,objects}}function enablesShell(node){if(node?.type!=="ObjectExpression")return false;return node.properties.some(prop=>prop.type==="Property"&&(0,tool_registration_1.propertyKey)(prop)==="shell"&&!(prop.value.type==="Literal"&&!prop.value.value))}exports.noCommandInjectionInTool=(0,eslint_devkit_1.createRule)({name:"no-command-injection-in-tool",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-command-injection-in-tool.md",description:"Disallow an MCP tool argument choosing the command a child_process call runs",cwe:"CWE-78",cvss:9.8},messages:{toolArgToShell:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Reaches a Process Sink",cwe:"CWE-78",owasp:"A03:2021",cvss:9.8,description:"Tool argument `{{arg}}` reaches the command of `{{sink}}()`, so whatever steers the model chooses what runs on this host",severity:"CRITICAL",compliance:["SOC2","NIST-CSF"],fix:"Do not let the argument name or build the command. Map it through a fixed allowlist of permitted operations (or declare it with z.enum), and pass user data as an argv array element \u2014 `execFile(ALLOWED[op], [value])` \u2014 with no shell.",documentationLink:"https://modelcontextprotocol.io/docs/concepts/tools"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const resolve=(0,module_resolver_1.valueResolverFor)(context);const handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");const candidates=[];function sinkOf(callee,scope,seen=new Set){if(seen.has(callee))return void 0;seen.add(callee);const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding!==void 0){const[name,extra]=binding.path;if(extra!==void 0)return void 0;if(binding.module==="child_process")return name!==void 0&&PROCESS_SINKS.has(name)?name:void 0;if(binding.module==="execa")return name===void 0?"execa":EXECA_SINKS.has(name)?name:void 0;return void 0}if(callee.type!=="Identifier")return void 0;const init=(0,tool_registration_1.constInitializer)(callee,scope);if(init?.type!=="CallExpression")return void 0;const wrapper=(0,eslint_devkit_1.resolveModuleBinding)(init.callee,scope);const wrapped=init.arguments[0];if(wrapper?.module!=="util"||wrapper.path.join(".")!=="promisify"||wrapped===void 0)return void 0;return sinkOf(wrapped,scope,seen)}function commandPositions(node,sink){const positions=[];const[file,argv,options]=node.arguments;if(file===void 0)return positions;positions.push(file);if(!ARGV_SINKS.has(sink)||argv?.type!=="ArrayExpression")return positions;const elements=argv.elements.filter(el=>el!==null&&el.type!=="SpreadElement");if(enablesShell(options))return[...positions,...elements];const shell=(0,eslint_devkit_1.staticString)(file)?.split(/[\\/]/).pop();if(shell!==void 0&&SHELLS.has(shell)){const flag=argv.elements.findIndex(el=>el!==null&&SHELL_SCRIPT_FLAGS.has((0,eslint_devkit_1.staticString)(el)??""));const script=flag===-1?void 0:argv.elements[flag+1];if(script&&script.type!=="SpreadElement")positions.push(script)}return positions}function templatePositions(node,scope){const tag=node.tag;const base=tag.type==="CallExpression"?tag.callee:tag;const binding=(0,eslint_devkit_1.resolveModuleBinding)(base,scope);const name=binding?.path.length===0?"execa":binding?.path[0];if(binding===void 0||binding.path.length>1||!TEMPLATE_SINKS[binding.module]?.has(name))return void 0;const{quasis,expressions}=node.quasi;if(tag.type==="CallExpression"&&enablesShell(tag.arguments[0]))return{sink:name,positions:[...expressions]};const lead=quasis[0].value.raw;const first=expressions[0];if(first===void 0)return void 0;if(lead.trim()==="")return{sink:name,positions:[first]};const shell=SHELL_PREFIX.exec(lead);if(shell!==null&&SHELLS.has(shell[1])&&SHELL_SCRIPT_FLAGS.has(shell[2]))return{sink:name,positions:[first]};return void 0}return{CallExpression(node){const scope=context.sourceCode.getScope(node);handlers.visit(node);const sink=sinkOf(node.callee,scope);if(sink===void 0)return;for(const position of commandPositions(node,sink))candidates.push({node:position,sink})},TaggedTemplateExpression(node){const found=templatePositions(node,context.sourceCode.getScope(node));for(const position of found?.positions??[])candidates.push({node:position,sink:found.sink})},"Program:exit"(){const carries=(0,value_flow_1.createFlow)(context.sourceCode,fn=>handlers.roots.get(fn),void 0,(0,value_flow_1.flowOptionsFor)(context));for(const candidate of candidates){const taint=carries(candidate.node);if(taint?.kind!=="value")continue;context.report({node:candidate.node,messageId:"toolArgToShell",data:{arg:taint.text,sink:candidate.sink}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCommandInjectionInTool=void 0;exports.handlerArgNames=handlerArgNames;const eslint_devkit_1=require("@interlace/eslint-devkit");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const PROCESS_SINKS=new Set(["exec","execSync","execFile","execFileSync","spawn","spawnSync","fork"]);const EXECA_SINKS=new Set(["execa","execaSync","execaCommand","execaCommandSync","execaNode"]);const ARGV_SINKS=new Set(["spawn","spawnSync","execFile","execFileSync","execa","execaSync"]);const SHELLS=new Set(["sh","bash","zsh","dash","ksh","fish","cmd","cmd.exe","powershell","powershell.exe","pwsh","pwsh.exe"]);const SHELL_SCRIPT_FLAGS=new Set(["-c","-lc","-ic","/c","/C","-Command","-command"]);const TEMPLATE_SINKS={zx:new Set(["$"]),execa:new Set(["$","$sync","execa","execaSync"])};const SHELL_PREFIX=new RegExp(String.raw`^(?:\S*[\\/])?(\S+)\s+(\S+)\s*$`);function handlerArgNames(handler){const direct=new Set;const objects=new Set;const visit=(pattern,inside)=>{if(pattern.type==="AssignmentPattern")pattern=pattern.left;if(pattern.type==="Identifier"){(inside?direct:objects).add(pattern.name);return}if(pattern.type!=="ObjectPattern")return;for(const prop of pattern.properties){if(prop.type==="RestElement")visit(prop.argument,false);else if((0,tool_registration_1.propertyKey)(prop)!==void 0)visit(prop.value,true)}};if((handler.type==="ArrowFunctionExpression"||handler.type==="FunctionExpression"||handler.type==="FunctionDeclaration")&&handler.params[0]!==void 0){visit(handler.params[0],false)}return{direct,objects}}function enablesShell(node){if(node?.type!=="ObjectExpression")return false;return node.properties.some(prop=>prop.type==="Property"&&(0,tool_registration_1.propertyKey)(prop)==="shell"&&!(prop.value.type==="Literal"&&!prop.value.value))}exports.noCommandInjectionInTool=(0,eslint_devkit_1.createRule)({name:"no-command-injection-in-tool",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-command-injection-in-tool.md",description:"Disallow an MCP tool argument choosing the command a child_process call runs",cwe:"CWE-78",cvss:9.8},messages:{toolArgToShell:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Reaches a Process Sink",cwe:"CWE-78",owasp:"A03:2021",cvss:9.8,description:"Tool argument `{{arg}}` reaches the command of `{{sink}}()`, so whatever steers the model chooses what runs on this host",severity:"CRITICAL",compliance:["SOC2","NIST-CSF"],fix:"Do not let the argument name or build the command. Map it through a fixed allowlist of permitted operations (or declare it with z.enum), and pass user data as an argv array element \u2014 `execFile(ALLOWED[op], [value])` \u2014 with no shell.",documentationLink:"https://modelcontextprotocol.io/docs/concepts/tools"})},schema:[]},defaultOptions:[],createOnce(context){let handlers;let candidates;function sinkOf(callee,scope,seen=new Set){if(seen.has(callee))return void 0;seen.add(callee);const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding!==void 0){const[name,extra]=binding.path;if(extra!==void 0)return void 0;if(binding.module==="child_process")return name!==void 0&&PROCESS_SINKS.has(name)?name:void 0;if(binding.module==="execa")return name===void 0?"execa":EXECA_SINKS.has(name)?name:void 0;return void 0}if(callee.type!=="Identifier")return void 0;const init=(0,tool_registration_1.constInitializer)(callee,scope);if(init?.type!=="CallExpression")return void 0;const wrapper=(0,eslint_devkit_1.resolveModuleBinding)(init.callee,scope);const wrapped=init.arguments[0];if(wrapper?.module!=="util"||wrapper.path.join(".")!=="promisify"||wrapped===void 0)return void 0;return sinkOf(wrapped,scope,seen)}function commandPositions(node,sink){const positions=[];const[file,argv,options]=node.arguments;if(file===void 0)return positions;positions.push(file);if(!ARGV_SINKS.has(sink)||argv?.type!=="ArrayExpression")return positions;const elements=argv.elements.filter(el=>el!==null&&el.type!=="SpreadElement");if(enablesShell(options))return[...positions,...elements];const shell=(0,eslint_devkit_1.staticString)(file)?.split(/[\\/]/).pop();if(shell!==void 0&&SHELLS.has(shell)){const flag=argv.elements.findIndex(el=>el!==null&&SHELL_SCRIPT_FLAGS.has((0,eslint_devkit_1.staticString)(el)??""));const script=flag===-1?void 0:argv.elements[flag+1];if(script&&script.type!=="SpreadElement")positions.push(script)}return positions}function templatePositions(node,scope){const tag=node.tag;const base=tag.type==="CallExpression"?tag.callee:tag;const binding=(0,eslint_devkit_1.resolveModuleBinding)(base,scope);const name=binding?.path.length===0?"execa":binding?.path[0];if(binding===void 0||binding.path.length>1||!TEMPLATE_SINKS[binding.module]?.has(name))return void 0;const{quasis,expressions}=node.quasi;if(tag.type==="CallExpression"&&enablesShell(tag.arguments[0]))return{sink:name,positions:[...expressions]};const lead=quasis[0].value.raw;const first=expressions[0];if(first===void 0)return void 0;if(lead.trim()==="")return{sink:name,positions:[first]};const shell=SHELL_PREFIX.exec(lead);if(shell!==null&&SHELLS.has(shell[1])&&SHELL_SCRIPT_FLAGS.has(shell[2]))return{sink:name,positions:[first]};return void 0}return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;const resolve=(0,module_resolver_1.valueResolverFor)(context);handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");candidates=[];return true},CallExpression(node){const scope=context.sourceCode.getScope(node);handlers.visit(node);const sink=sinkOf(node.callee,scope);if(sink===void 0)return;for(const position of commandPositions(node,sink))candidates.push({node:position,sink})},TaggedTemplateExpression(node){const found=templatePositions(node,context.sourceCode.getScope(node));for(const position of found?.positions??[])candidates.push({node:position,sink:found.sink})},"Program:exit"(){const carries=(0,value_flow_1.createFlow)(context.sourceCode,fn=>handlers.roots.get(fn),void 0,(0,value_flow_1.flowOptionsFor)(context));for(const candidate of candidates){const taint=carries(candidate.node);if(taint?.kind!=="value")continue;context.report({node:candidate.node,messageId:"toolArgToShell",data:{arg:taint.text,sink:candidate.sink}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCredentialLeakInTool=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const http_clients_1=require("../../utils/http-clients");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const TOKEN_KEY="token";const UPSTREAM_TRANSPORTS=new Set(["StreamableHTTPClientTransport","SSEClientTransport"]);const MAX_RESULT_DEPTH=8;const message=(issueName,cwe,description,fix)=>(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName,cwe,owasp:"A01:2021",cvss:7.5,description,severity:"HIGH",compliance:["SOC2","GDPR","NIST-CSF"],fix,documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices"});function children(node){const out=[];for(const[key,value]of Object.entries(node)){if(key==="parent")continue;for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string")out.push(child)}}return out}exports.noCredentialLeakInTool=(0,eslint_devkit_1.createRule)({name:"no-credential-leak-in-tool",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-credential-leak-in-tool.md",description:"Disallow an MCP tool returning the server's environment or the caller's token, or forwarding that token upstream",cwe:"CWE-200",cvss:7.5},messages:{envInResult:message("MCP Tool Returns the Server Environment","CWE-526","This tool result carries `{{what}}`, so every credential the server was started with reaches the model and anything that can steer it","Return only the specific, non-secret values the tool exists to report, each named in code. Never return `process.env` or let an argument choose which variable is read."),tokenInResult:message("MCP Tool Returns the Caller's Token","CWE-200","This tool result carries `{{arg}}` \u2014 the bearer token this request was authorised with \u2014 so the model, the host log and any later tool call can read it","Return what the token grants (the user id, the scopes) instead of the token itself."),tokenPassthrough:message("MCP Tool Forwards the Caller's Token","CWE-441","`{{arg}}` \u2014 the bearer token this MCP server received \u2014 is forwarded through `{{client}}`. The MCP spec forbids token passthrough: the downstream API trusts a token not issued for it, and the call is attributed to the wrong party","Authenticate to the downstream API with a credential issued to this server (OAuth token exchange / on-behalf-of, or the server\u2019s own client credentials). Never forward the inbound token.")},schema:[]},defaultOptions:[],skipTestFiles:true,create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const resolve=(0,module_resolver_1.valueResolverFor)(context);const builtBy=(0,instances_1.createInstanceResolver)(context);const argumentRoots=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");const contextRoots=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"context");const outbound=[];function isProcessEnv(node){if(node.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(node)!=="env")return false;const scope=sourceCode.getScope(node);if(node.object.type==="Identifier"&&node.object.name==="process"&&!(0,tool_registration_1.lookupVariable)("process",scope)?.defs.length)return true;const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,scope);return binding?.module==="process"&&binding.path.join(".")==="env"}function isObjectKeysOf(node){const call=node.parent;return call?.type==="CallExpression"&&call.arguments[0]===node&&call.callee.type==="MemberExpression"&&call.callee.object.type==="Identifier"&&call.callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(call.callee)==="keys"&&!(0,tool_registration_1.lookupVariable)("Object",sourceCode.getScope(call))?.defs.length}return{CallExpression(node){argumentRoots.visit(node);contextRoots.visit(node);const request=(0,http_clients_1.httpRequestOf)(node,sourceCode.getScope(node),builtBy);if(request!==void 0)for(const arg of node.arguments)outbound.push({node:arg,client:request.client})},NewExpression(node){const name=(0,tool_handlers_1.mcpExport)(node.callee,sourceCode.getScope(node));if(name!==void 0&&UPSTREAM_TRANSPORTS.has(name))for(const arg of node.arguments)outbound.push({node:arg,client:`new ${name}()`})},"Program:exit"(){const handlers=new Set([...argumentRoots.roots.keys(),...contextRoots.roots.keys()]);const fromArgs=(0,value_flow_1.createFlow)(sourceCode,fn=>argumentRoots.roots.get(fn),void 0,(0,value_flow_1.flowOptionsFor)(context));const fromContext=(0,value_flow_1.createFlow)(sourceCode,fn=>contextRoots.roots.get(fn),(node,follow)=>{if(node.type!=="CallExpression"||node.callee.type!=="MemberExpression"||node.callee.object.type!=="Identifier"||node.callee.object.name!=="JSON"||(0,eslint_devkit_1.propertyName)(node.callee)!=="stringify"||(0,tool_registration_1.lookupVariable)("JSON",sourceCode.getScope(node))?.defs.length||node.arguments[0]===void 0)return void 0;const t=follow(node.arguments[0]);return t?.kind==="object"?{kind:"value",text:t.text,key:TOKEN_KEY}:t},(0,value_flow_1.flowOptionsFor)(context));const tokenIn=(node,depth=0)=>{if(depth>MAX_RESULT_DEPTH)return null;if(node.type==="ObjectExpression"){for(const prop of node.properties){const value=prop.type==="Property"?prop.value:prop.argument;const t2=tokenIn(value,depth+1);if(t2)return t2}return null}if(node.type==="ArrayExpression"){for(const element of node.elements){const t2=element&&tokenIn(element,depth+1);if(t2)return t2}return null}if(node.type==="Identifier"){const variable=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node));const def=variable?.defs[0];if(def?.type==="Variable"&&def.node.id===def.name&&(def.node.init?.type==="ObjectExpression"||def.node.init?.type==="ArrayExpression"))return tokenIn(def.node.init,depth+1)}const t=fromContext(node);return t?.kind==="value"&&t.key===TOKEN_KEY?t:null};const envIn=root=>{const found=[];const seen=new Set;const visit=node=>{if((0,tool_registration_1.isFunctionNode)(node))return;if(isProcessEnv(node)){const parent=node.parent;if(isObjectKeysOf(node))return;if(parent?.type!=="MemberExpression"||parent.object!==node)found.push(node);else if(parent.computed&&fromArgs(parent.property)?.kind==="value")found.push(parent);return}if(node.type==="Identifier"){const variable=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node));if(variable===void 0||seen.has(variable))return;seen.add(variable);for(const def of variable.defs)if(def.type==="Variable"&&def.node.init)visit(def.node.init);return}for(const child of children(node))visit(child)};visit(root);return found};for(const fn of handlers){for(const result of(0,value_flow_1.returnedExpressions)(fn)){for(const env of envIn(result))context.report({node:env,messageId:"envInResult",data:{what:sourceCode.getText(env)}});const token=tokenIn(result);if(token)context.report({node:result,messageId:"tokenInResult",data:{arg:token.text}})}}for(const{node,client}of outbound){const inner=node.type==="SpreadElement"?node.argument:node;const token=tokenIn(inner);if(token)context.report({node,messageId:"tokenPassthrough",data:{arg:token.text,client}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCredentialLeakInTool=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const http_clients_1=require("../../utils/http-clients");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const TOKEN_KEY="token";const UPSTREAM_TRANSPORTS=new Set(["StreamableHTTPClientTransport","SSEClientTransport"]);const MAX_RESULT_DEPTH=8;const message=(issueName,cwe,description,fix)=>(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName,cwe,owasp:"A01:2021",cvss:7.5,description,severity:"HIGH",compliance:["SOC2","GDPR","NIST-CSF"],fix,documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices"});function children(node){const out=[];for(const[key,value]of Object.entries(node)){if(key==="parent")continue;for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string")out.push(child)}}return out}exports.noCredentialLeakInTool=(0,eslint_devkit_1.createRule)({name:"no-credential-leak-in-tool",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-credential-leak-in-tool.md",description:"Disallow an MCP tool returning the server's environment or the caller's token, or forwarding that token upstream",cwe:"CWE-200",cvss:7.5},messages:{envInResult:message("MCP Tool Returns the Server Environment","CWE-526","This tool result carries `{{what}}`, so every credential the server was started with reaches the model and anything that can steer it","Return only the specific, non-secret values the tool exists to report, each named in code. Never return `process.env` or let an argument choose which variable is read."),tokenInResult:message("MCP Tool Returns the Caller's Token","CWE-200","This tool result carries `{{arg}}` \u2014 the bearer token this request was authorised with \u2014 so the model, the host log and any later tool call can read it","Return what the token grants (the user id, the scopes) instead of the token itself."),tokenPassthrough:message("MCP Tool Forwards the Caller's Token","CWE-441","`{{arg}}` \u2014 the bearer token this MCP server received \u2014 is forwarded through `{{client}}`. The MCP spec forbids token passthrough: the downstream API trusts a token not issued for it, and the call is attributed to the wrong party","Authenticate to the downstream API with a credential issued to this server (OAuth token exchange / on-behalf-of, or the server\u2019s own client credentials). Never forward the inbound token.")},schema:[]},defaultOptions:[],skipTestFiles:true,createOnce(context){let sourceCode;let builtBy;let argumentRoots;let contextRoots;let outbound;function isProcessEnv(node){if(node.type!=="MemberExpression"||(0,eslint_devkit_1.propertyName)(node)!=="env")return false;const scope=sourceCode.getScope(node);if(node.object.type==="Identifier"&&node.object.name==="process"&&!(0,tool_registration_1.lookupVariable)("process",scope)?.defs.length)return true;const binding=(0,eslint_devkit_1.resolveModuleBinding)(node,scope);return binding?.module==="process"&&binding.path.join(".")==="env"}function isObjectKeysOf(node){const call=node.parent;return call?.type==="CallExpression"&&call.arguments[0]===node&&call.callee.type==="MemberExpression"&&call.callee.object.type==="Identifier"&&call.callee.object.name==="Object"&&(0,eslint_devkit_1.propertyName)(call.callee)==="keys"&&!(0,tool_registration_1.lookupVariable)("Object",sourceCode.getScope(call))?.defs.length}return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;sourceCode=context.sourceCode;const resolve=(0,module_resolver_1.valueResolverFor)(context);builtBy=(0,instances_1.createInstanceResolver)(context);argumentRoots=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");contextRoots=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"context");outbound=[];return true},CallExpression(node){argumentRoots.visit(node);contextRoots.visit(node);const request=(0,http_clients_1.httpRequestOf)(node,sourceCode.getScope(node),builtBy);if(request!==void 0)for(const arg of node.arguments)outbound.push({node:arg,client:request.client})},NewExpression(node){const name=(0,tool_handlers_1.mcpExport)(node.callee,sourceCode.getScope(node));if(name!==void 0&&UPSTREAM_TRANSPORTS.has(name))for(const arg of node.arguments)outbound.push({node:arg,client:`new ${name}()`})},"Program:exit"(){const handlers=new Set([...argumentRoots.roots.keys(),...contextRoots.roots.keys()]);const fromArgs=(0,value_flow_1.createFlow)(sourceCode,fn=>argumentRoots.roots.get(fn),void 0,(0,value_flow_1.flowOptionsFor)(context));const fromContext=(0,value_flow_1.createFlow)(sourceCode,fn=>contextRoots.roots.get(fn),(node,follow)=>{if(node.type!=="CallExpression"||node.callee.type!=="MemberExpression"||node.callee.object.type!=="Identifier"||node.callee.object.name!=="JSON"||(0,eslint_devkit_1.propertyName)(node.callee)!=="stringify"||(0,tool_registration_1.lookupVariable)("JSON",sourceCode.getScope(node))?.defs.length||node.arguments[0]===void 0)return void 0;const t=follow(node.arguments[0]);return t?.kind==="object"?{kind:"value",text:t.text,key:TOKEN_KEY}:t},(0,value_flow_1.flowOptionsFor)(context));const tokenIn=(node,depth=0)=>{if(depth>MAX_RESULT_DEPTH)return null;if(node.type==="ObjectExpression"){for(const prop of node.properties){const value=prop.type==="Property"?prop.value:prop.argument;const t2=tokenIn(value,depth+1);if(t2)return t2}return null}if(node.type==="ArrayExpression"){for(const element of node.elements){const t2=element&&tokenIn(element,depth+1);if(t2)return t2}return null}if(node.type==="Identifier"){const variable=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node));const def=variable?.defs[0];if(def?.type==="Variable"&&def.node.id===def.name&&(def.node.init?.type==="ObjectExpression"||def.node.init?.type==="ArrayExpression"))return tokenIn(def.node.init,depth+1)}const t=fromContext(node);return t?.kind==="value"&&t.key===TOKEN_KEY?t:null};const envIn=root=>{const found=[];const seen=new Set;const visit=node=>{if((0,tool_registration_1.isFunctionNode)(node))return;if(isProcessEnv(node)){const parent=node.parent;if(isObjectKeysOf(node))return;if(parent?.type!=="MemberExpression"||parent.object!==node)found.push(node);else if(parent.computed&&fromArgs(parent.property)?.kind==="value")found.push(parent);return}if(node.type==="Identifier"){const variable=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node));if(variable===void 0||seen.has(variable))return;seen.add(variable);for(const def of variable.defs)if(def.type==="Variable"&&def.node.init)visit(def.node.init);return}for(const child of children(node))visit(child)};visit(root);return found};for(const fn of handlers){for(const result of(0,value_flow_1.returnedExpressions)(fn)){for(const env of envIn(result))context.report({node:env,messageId:"envInResult",data:{what:sourceCode.getText(env)}});const token=tokenIn(result);if(token)context.report({node:result,messageId:"tokenInResult",data:{arg:token.text}})}}for(const{node,client}of outbound){const inner=node.type==="SpreadElement"?node.argument:node;const token=tokenIn(inner);if(token)context.report({node,messageId:"tokenPassthrough",data:{arg:token.text,client}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDuplicateToolName=void 0;exports.bothRun=bothRun;const eslint_devkit_1=require("@interlace/eslint-devkit");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const LOOPS=new Set(["ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement"]);function isBranch(child,parent){switch(parent.type){case"IfStatement":case"ConditionalExpression":return child!==parent.test;case"LogicalExpression":return child===parent.right;case"SwitchCase":case"CatchClause":return true;default:if(LOOPS.has(parent.type))return child===parent.body;return(0,tool_registration_1.isFunctionNode)(parent)}}function ancestry(node){const chain=[];for(let n=node;n;n=n.parent)chain.push(n);return chain}function bothRun(a,b){const above=new Set(ancestry(b));const lca=ancestry(a).find(n=>above.has(n));const straight=from=>{for(let n=from;n!==lca&&n.parent;n=n.parent)if(isBranch(n,n.parent))return false;return true};return straight(a)&&straight(b)}function unwrap(node){while(node.type==="TSAsExpression"||node.type==="TSSatisfiesExpression"||node.type==="TSNonNullExpression")node=node.expression;return node}exports.noDuplicateToolName=(0,eslint_devkit_1.createRule)({name:"no-duplicate-tool-name",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-duplicate-tool-name.md",description:"Disallow registering or listing two MCP tools with the same name on one server",cwe:"CWE-694",cvss:5.3},messages:{duplicateToolRegistration:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Duplicate MCP Tool Registration",cwe:"CWE-694",owasp:"A04:2021",cvss:5.3,description:"Tool `{{name}}` is already registered on this server at line {{line}}. McpServer throws on the second registration, so the server crashes at startup, or (behind a try/catch) keeps the first handler while this one never runs",severity:"MEDIUM",compliance:["SOC2"],fix:"Give each tool a unique name, or register only one of them (choose with if/else when they are alternatives).",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/server/tools"}),duplicateListedTool:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Duplicate Tool in tools/list",cwe:"CWE-694",owasp:"A04:2021",cvss:5.3,description:"Tool `{{name}}` is already listed at line {{line}}. Clients see two tools with one name, and which one a call reaches is decided by the call handler alone, not by the description the model chose from",severity:"MEDIUM",compliance:["SOC2"],fix:"Give each listed tool a unique name, and keep the tools/list response and the tools/call dispatch built from one table.",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/server/tools"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const resolve=(0,module_resolver_1.valueResolverFor)(context);const registered=new Map;const listed=new Set;function nameOf(node){const direct=(0,eslint_devkit_1.staticString)(node);if(direct!==null)return direct;const value=node.type==="Identifier"||node.type==="MemberExpression"?resolve(node):void 0;return value===void 0?null:(0,eslint_devkit_1.staticString)(value)}function inFile(node,scope){node=unwrap(node);return node.type==="Identifier"?(0,tool_registration_1.constInitializer)(node,scope):node}function checkRegistration(node){const registration=(0,tool_registration_1.readRegistration)(node,resolve);if(registration?.handler===void 0)return;const receiver=node.callee.object;if(receiver.type!=="Identifier")return;const variable=(0,tool_registration_1.lookupVariable)(receiver.name,sourceCode.getScope(node));const name=nameOf(node.arguments[0]);if(variable===void 0||name===null)return;let names=registered.get(variable);if(names===void 0)registered.set(variable,names=new Map);const earlier=names.get(name)??[];names.set(name,[...earlier,node]);const first=earlier.find(prev=>bothRun(prev,node));if(first===void 0)return;context.report({node:node.arguments[0],messageId:"duplicateToolRegistration",data:{name,line:String(first.loc.start.line)}})}function checkList(node){const scope=sourceCode.getScope(node);const[method,handler]=node.arguments;if(method===void 0||(0,eslint_devkit_1.staticString)(method)!=="tools/list"&&(0,tool_handlers_1.mcpExport)(method,scope)!=="ListToolsRequestSchema")return;const fn=(0,tool_registration_1.resolveFunction)(handler,scope);if(fn===void 0)return;for(const returned of(0,value_flow_1.returnedExpressions)(fn)){const result=unwrap(returned);if(result.type!=="ObjectExpression")continue;for(const prop of result.properties){if(prop.type!=="Property"||(0,tool_registration_1.propertyKey)(prop)!=="tools")continue;const array=inFile(prop.value,scope);if(array?.type==="ArrayExpression")checkArray(array,scope)}}}function checkArray(array,scope){if(listed.has(array))return;listed.add(array);const seen=new Map;for(const element of array.elements){if(element===null||element.type==="SpreadElement")continue;const tool=inFile(element,scope);if(tool?.type!=="ObjectExpression")continue;let name=null;for(const prop of tool.properties)if(prop.type==="Property"&&(0,tool_registration_1.propertyKey)(prop)==="name")name=nameOf(prop.value);if(name===null)continue;const first=seen.get(name);if(first===void 0){seen.set(name,element);continue}context.report({node:element,messageId:"duplicateListedTool",data:{name,line:String(first.loc.start.line)}})}}return{CallExpression(node){if(node.callee.type!=="MemberExpression")return;if((0,eslint_devkit_1.propertyName)(node.callee)==="setRequestHandler")checkList(node);else checkRegistration(node)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDuplicateToolName=void 0;exports.bothRun=bothRun;const eslint_devkit_1=require("@interlace/eslint-devkit");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const LOOPS=new Set(["ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement"]);function isBranch(child,parent){switch(parent.type){case"IfStatement":case"ConditionalExpression":return child!==parent.test;case"LogicalExpression":return child===parent.right;case"SwitchCase":case"CatchClause":return true;default:if(LOOPS.has(parent.type))return child===parent.body;return(0,tool_registration_1.isFunctionNode)(parent)}}function ancestry(node){const chain=[];for(let n=node;n;n=n.parent)chain.push(n);return chain}function bothRun(a,b){const above=new Set(ancestry(b));const lca=ancestry(a).find(n=>above.has(n));const straight=from=>{for(let n=from;n!==lca&&n.parent;n=n.parent)if(isBranch(n,n.parent))return false;return true};return straight(a)&&straight(b)}function unwrap(node){while(node.type==="TSAsExpression"||node.type==="TSSatisfiesExpression"||node.type==="TSNonNullExpression")node=node.expression;return node}exports.noDuplicateToolName=(0,eslint_devkit_1.createRule)({name:"no-duplicate-tool-name",meta:{interop:{runtimes:["eslint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-duplicate-tool-name.md",description:"Disallow registering or listing two MCP tools with the same name on one server",cwe:"CWE-694",cvss:5.3},messages:{duplicateToolRegistration:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Duplicate MCP Tool Registration",cwe:"CWE-694",owasp:"A04:2021",cvss:5.3,description:"Tool `{{name}}` is already registered on this server at line {{line}}. McpServer throws on the second registration, so the server crashes at startup, or (behind a try/catch) keeps the first handler while this one never runs",severity:"MEDIUM",compliance:["SOC2"],fix:"Give each tool a unique name, or register only one of them (choose with if/else when they are alternatives).",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/server/tools"}),duplicateListedTool:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Duplicate Tool in tools/list",cwe:"CWE-694",owasp:"A04:2021",cvss:5.3,description:"Tool `{{name}}` is already listed at line {{line}}. Clients see two tools with one name, and which one a call reaches is decided by the call handler alone, not by the description the model chose from",severity:"MEDIUM",compliance:["SOC2"],fix:"Give each listed tool a unique name, and keep the tools/list response and the tools/call dispatch built from one table.",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/server/tools"})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;let resolve;let registered;let listed;function nameOf(node){const direct=(0,eslint_devkit_1.staticString)(node);if(direct!==null)return direct;const value=node.type==="Identifier"||node.type==="MemberExpression"?resolve(node):void 0;return value===void 0?null:(0,eslint_devkit_1.staticString)(value)}function inFile(node,scope){node=unwrap(node);return node.type==="Identifier"?(0,tool_registration_1.constInitializer)(node,scope):node}function checkRegistration(node){const registration=(0,tool_registration_1.readRegistration)(node,resolve);if(registration?.handler===void 0)return;const receiver=node.callee.object;if(receiver.type!=="Identifier")return;const variable=(0,tool_registration_1.lookupVariable)(receiver.name,sourceCode.getScope(node));const name=nameOf(node.arguments[0]);if(variable===void 0||name===null)return;let names=registered.get(variable);if(names===void 0)registered.set(variable,names=new Map);const earlier=names.get(name)??[];names.set(name,[...earlier,node]);const first=earlier.find(prev=>bothRun(prev,node));if(first===void 0)return;context.report({node:node.arguments[0],messageId:"duplicateToolRegistration",data:{name,line:String(first.loc.start.line)}})}function checkList(node){const scope=sourceCode.getScope(node);const[method,handler]=node.arguments;if(method===void 0||(0,eslint_devkit_1.staticString)(method)!=="tools/list"&&(0,tool_handlers_1.mcpExport)(method,scope)!=="ListToolsRequestSchema")return;const fn=(0,tool_registration_1.resolveFunction)(handler,scope);if(fn===void 0)return;for(const returned of(0,value_flow_1.returnedExpressions)(fn)){const result=unwrap(returned);if(result.type!=="ObjectExpression")continue;for(const prop of result.properties){if(prop.type!=="Property"||(0,tool_registration_1.propertyKey)(prop)!=="tools")continue;const array=inFile(prop.value,scope);if(array?.type==="ArrayExpression")checkArray(array,scope)}}}function checkArray(array,scope){if(listed.has(array))return;listed.add(array);const seen=new Map;for(const element of array.elements){if(element===null||element.type==="SpreadElement")continue;const tool=inFile(element,scope);if(tool?.type!=="ObjectExpression")continue;let name=null;for(const prop of tool.properties)if(prop.type==="Property"&&(0,tool_registration_1.propertyKey)(prop)==="name")name=nameOf(prop.value);if(name===null)continue;const first=seen.get(name);if(first===void 0){seen.set(name,element);continue}context.report({node:element,messageId:"duplicateListedTool",data:{name,line:String(first.loc.start.line)}})}}return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;sourceCode=context.sourceCode;resolve=(0,module_resolver_1.valueResolverFor)(context);registered=new Map;listed=new Set;return true},CallExpression(node){if(node.callee.type!=="MemberExpression")return;if((0,eslint_devkit_1.propertyName)(node.callee)==="setRequestHandler")checkList(node);else checkRegistration(node)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPathTraversalInTool=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const fs_module_1=require("../../utils/fs-module");const guards_1=require("../../utils/guards");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const PATH_SINKS=new Set(["readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","createReadStream","createWriteStream","open","openSync","opendir","opendirSync","readdir","readdirSync","mkdir","mkdirSync","rm","rmSync","rmdir","rmdirSync","unlink","unlinkSync","truncate","truncateSync","chmod","chmodSync","chown","chownSync","readlink","readlinkSync"]);const TWO_PATH_SINKS=new Set(["copyFile","copyFileSync","cp","cpSync","rename","renameSync","symlink","symlinkSync","link","linkSync"]);const PATH_JOINERS=new Set(["join","resolve","normalize","dirname","toNamespacedPath"]);const PATH_CHECKS=new Set(["relative","isAbsolute"]);const CANONICALISERS=new Set(["realpath","realpathSync"]);const NOT_A_CHECK=new Set([...value_flow_1.STRING_DERIVING,"endsWith"]);function pathExport(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding?.module!=="path")return void 0;const rest=binding.path[0]==="posix"||binding.path[0]==="win32"?binding.path.slice(1):binding.path;return rest.length===1?rest[0]:void 0}exports.noPathTraversalInTool=(0,eslint_devkit_1.createRule)({name:"no-path-traversal-in-tool",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-path-traversal-in-tool.md",description:"Disallow an MCP tool argument choosing the file an fs call reads, writes or deletes without a containment check",cwe:"CWE-22",cvss:7.5},messages:{toolArgToPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Reaches a File Path",cwe:"CWE-22",owasp:"A01:2021",cvss:7.5,description:"Tool argument `{{arg}}` reaches the path of `{{sink}}()` with no containment check, so `../` or an absolute path reads or writes outside the directory this tool is meant to serve",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Resolve the path against a fixed root, canonicalise it (`fs.realpath`), and reject it unless `path.relative(root, target)` neither starts with `..` nor is absolute \u2014 before the fs call. Comparing with `startsWith(root)` alone also needs the trailing separator, or `/data-evil` passes for `/data`.",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const resolve=(0,module_resolver_1.valueResolverFor)(context);const handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");const candidates=[];return{CallExpression(node){handlers.visit(node);const sink=(0,fs_module_1.fsExport)(node.callee,context.sourceCode.getScope(node));if(sink===void 0)return;const count=TWO_PATH_SINKS.has(sink)?2:PATH_SINKS.has(sink)?1:0;for(const arg of node.arguments.slice(0,count))candidates.push({call:node,arg,sink})},"Program:exit"(){const sourceCode=context.sourceCode;const intercept=(node,follow)=>{if(node.type==="NewExpression"){const scope2=sourceCode.getScope(node);if(node.callee.type!=="Identifier"||node.callee.name!=="URL"||(0,tool_registration_1.lookupVariable)("URL",scope2)?.defs.length)return void 0;return firstValue(node.arguments,follow)}if(node.type!=="CallExpression")return void 0;const scope=sourceCode.getScope(node);const joiner=pathExport(node.callee,scope);if(joiner!==void 0)return PATH_JOINERS.has(joiner)?firstValue(node.arguments,follow):null;const fsName=(0,fs_module_1.fsExport)(node.callee,scope);if(fsName!==void 0)return CANONICALISERS.has(fsName)?firstValue(node.arguments.slice(0,1),follow):null;const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding?.module==="url"&&binding.path.join(".")==="fileURLToPath")return firstValue(node.arguments.slice(0,1),follow);const helper=(0,tool_registration_1.resolveFunction)(node.callee,scope);if(helper!==void 0&&guards.sanitizes(helper))return null;return void 0};const carries=(0,value_flow_1.createFlow)(sourceCode,fn=>handlers.roots.get(fn),intercept,(0,value_flow_1.flowOptionsFor)(context,(call,arg)=>guards.guarded(call,arg)));const guards=(0,guards_1.createGuards)(sourceCode,variable=>{const name=variable.defs[0]?.name;return name!==void 0&&carries(name)!==null},isContainmentCheck);function isContainmentCheck(node,involves,inHelper=false){if(node.type!=="CallExpression")return false;const scope=sourceCode.getScope(node);if((0,fs_module_1.fsExport)(node.callee,scope)!==void 0)return false;if((0,guards_1.isConversion)(node,scope))return false;const pathName=pathExport(node.callee,scope);if(pathName!==void 0&&!PATH_CHECKS.has(pathName))return false;if(node.callee.type==="MemberExpression"){const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method!==null&&NOT_A_CHECK.has(method))return false;if(involves(node.callee.object))return true}const helper=inHelper?void 0:(0,tool_registration_1.resolveFunction)(node.callee,scope);if(helper!==void 0&&!holdsCheck(helper))return false;return node.arguments.some(involves)}function holdsCheck(fn){const visit=node=>{if(isContainmentCheck(node,()=>true,true))return true;for(const[key,value]of Object.entries(node)){if(key==="parent")continue;for(const child of Array.isArray(value)?value:[value])if(child!==null&&typeof child==="object"&&typeof child.type==="string"&&visit(child))return true}return false};return visit(fn)}for(const{call,arg,sink}of candidates){const taint=carries(arg);if(taint?.kind!=="value")continue;if(guards.guarded(call,arg))continue;context.report({node:arg,messageId:"toolArgToPath",data:{arg:taint.text,sink}})}}}}});function firstValue(args,follow){for(const arg of args){const inner=arg.type==="SpreadElement"?arg.argument:arg;const t=follow(inner);if(t?.kind==="value")return t}return null}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPathTraversalInTool=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const fs_module_1=require("../../utils/fs-module");const guards_1=require("../../utils/guards");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const PATH_SINKS=new Set(["readFile","readFileSync","writeFile","writeFileSync","appendFile","appendFileSync","createReadStream","createWriteStream","open","openSync","opendir","opendirSync","readdir","readdirSync","mkdir","mkdirSync","rm","rmSync","rmdir","rmdirSync","unlink","unlinkSync","truncate","truncateSync","chmod","chmodSync","chown","chownSync","readlink","readlinkSync"]);const TWO_PATH_SINKS=new Set(["copyFile","copyFileSync","cp","cpSync","rename","renameSync","symlink","symlinkSync","link","linkSync"]);const PATH_JOINERS=new Set(["join","resolve","normalize","dirname","toNamespacedPath"]);const PATH_CHECKS=new Set(["relative","isAbsolute"]);const CANONICALISERS=new Set(["realpath","realpathSync"]);const NOT_A_CHECK=new Set([...value_flow_1.STRING_DERIVING,"endsWith"]);function pathExport(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding?.module!=="path")return void 0;const rest=binding.path[0]==="posix"||binding.path[0]==="win32"?binding.path.slice(1):binding.path;return rest.length===1?rest[0]:void 0}exports.noPathTraversalInTool=(0,eslint_devkit_1.createRule)({name:"no-path-traversal-in-tool",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-path-traversal-in-tool.md",description:"Disallow an MCP tool argument choosing the file an fs call reads, writes or deletes without a containment check",cwe:"CWE-22",cvss:7.5},messages:{toolArgToPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Reaches a File Path",cwe:"CWE-22",owasp:"A01:2021",cvss:7.5,description:"Tool argument `{{arg}}` reaches the path of `{{sink}}()` with no containment check, so `../` or an absolute path reads or writes outside the directory this tool is meant to serve",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Resolve the path against a fixed root, canonicalise it (`fs.realpath`), and reject it unless `path.relative(root, target)` neither starts with `..` nor is absolute \u2014 before the fs call. Comparing with `startsWith(root)` alone also needs the trailing separator, or `/data-evil` passes for `/data`.",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices"})},schema:[]},defaultOptions:[],createOnce(context){let handlers;let candidates;return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;const resolve=(0,module_resolver_1.valueResolverFor)(context);handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");candidates=[];return true},CallExpression(node){handlers.visit(node);const sink=(0,fs_module_1.fsExport)(node.callee,context.sourceCode.getScope(node));if(sink===void 0)return;const count=TWO_PATH_SINKS.has(sink)?2:PATH_SINKS.has(sink)?1:0;for(const arg of node.arguments.slice(0,count))candidates.push({call:node,arg,sink})},"Program:exit"(){const sourceCode=context.sourceCode;const intercept=(node,follow)=>{if(node.type==="NewExpression"){const scope2=sourceCode.getScope(node);if(node.callee.type!=="Identifier"||node.callee.name!=="URL"||(0,tool_registration_1.lookupVariable)("URL",scope2)?.defs.length)return void 0;return firstValue(node.arguments,follow)}if(node.type!=="CallExpression")return void 0;const scope=sourceCode.getScope(node);const joiner=pathExport(node.callee,scope);if(joiner!==void 0)return PATH_JOINERS.has(joiner)?firstValue(node.arguments,follow):null;const fsName=(0,fs_module_1.fsExport)(node.callee,scope);if(fsName!==void 0)return CANONICALISERS.has(fsName)?firstValue(node.arguments.slice(0,1),follow):null;const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding?.module==="url"&&binding.path.join(".")==="fileURLToPath")return firstValue(node.arguments.slice(0,1),follow);const helper=(0,tool_registration_1.resolveFunction)(node.callee,scope);if(helper!==void 0&&guards.sanitizes(helper))return null;return void 0};const carries=(0,value_flow_1.createFlow)(sourceCode,fn=>handlers.roots.get(fn),intercept,(0,value_flow_1.flowOptionsFor)(context,(call,arg)=>guards.guarded(call,arg)));const guards=(0,guards_1.createGuards)(sourceCode,variable=>{const name=variable.defs[0]?.name;return name!==void 0&&carries(name)!==null},isContainmentCheck);function isContainmentCheck(node,involves,inHelper=false){if(node.type!=="CallExpression")return false;const scope=sourceCode.getScope(node);if((0,fs_module_1.fsExport)(node.callee,scope)!==void 0)return false;if((0,guards_1.isConversion)(node,scope))return false;const pathName=pathExport(node.callee,scope);if(pathName!==void 0&&!PATH_CHECKS.has(pathName))return false;if(node.callee.type==="MemberExpression"){const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method!==null&&NOT_A_CHECK.has(method))return false;if(involves(node.callee.object))return true}const helper=inHelper?void 0:(0,tool_registration_1.resolveFunction)(node.callee,scope);if(helper!==void 0&&!holdsCheck(helper))return false;return node.arguments.some(involves)}function holdsCheck(fn){const visit=node=>{if(isContainmentCheck(node,()=>true,true))return true;for(const[key,value]of Object.entries(node)){if(key==="parent")continue;for(const child of Array.isArray(value)?value:[value])if(child!==null&&typeof child==="object"&&typeof child.type==="string"&&visit(child))return true}return false};return visit(fn)}for(const{call,arg,sink}of candidates){const taint=carries(arg);if(taint?.kind!=="value")continue;if(guards.guarded(call,arg))continue;context.report({node:arg,messageId:"toolArgToPath",data:{arg:taint.text,sink}})}}}}});function firstValue(args,follow){for(const arg of args){const inner=arg.type==="SpreadElement"?arg.argument:arg;const t=follow(inner);if(t?.kind==="value")return t}return null}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPredictableSessionId=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const mcp_evidence_1=require("../../utils/mcp-evidence");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const STREAMABLE_TRANSPORTS=new Set(["StreamableHTTPServerTransport","NodeStreamableHTTPServerTransport","WebStandardStreamableHTTPServerTransport"]);const CSPRNG_EXPORTS=new Map([["crypto",new Set(["randomUUID","randomBytes","getRandomValues"])],["uuid",new Set(["v4","v7"])],["nanoid",new Set(["nanoid"])]]);const GLOBAL_CSPRNG=new Set(["crypto.randomUUID","crypto.getRandomValues"]);const PREDICTABLE_GLOBALS=new Set(["Date.now","performance.now","Math.random","process.hrtime","process.hrtime.bigint"]);const DERIVING_GLOBALS=new Set(["String","Math.floor","Math.round","Math.trunc"]);const DERIVING_METHODS=new Set(["toString","toFixed","toISOString","getTime","valueOf","slice","substring","substr","padStart","padEnd","replace","replaceAll","toUpperCase","toLowerCase","trim","join"]);const MAX_DEPTH=8;function combine(kinds){if(kinds.includes("csprng"))return"csprng";if(kinds.includes("unknown"))return"unknown";if(kinds.includes("predictable"))return"predictable";return"constant"}function opaque(kinds){return kinds.includes("csprng")?"csprng":"unknown"}function insideFunction(node){for(let current=node.parent;current;current=current.parent){if((0,tool_registration_1.isFunctionNode)(current))return true}return false}function globalPath(node,scope){const path=(0,eslint_devkit_1.memberPath)(node);if(path===null||(0,tool_registration_1.lookupVariable)(path[0],scope)?.defs.length)return null;return path.join(".")}const SESSION_DOCS="https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices#session-hijacking";exports.noPredictableSessionId=(0,eslint_devkit_1.createRule)({name:"no-predictable-session-id",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-predictable-session-id.md",description:"Disallow an MCP sessionIdGenerator that returns a counter, a timestamp, Math.random() or a constant",cwe:"CWE-330",cvss:7.5},messages:{predictableSessionId:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Predictable MCP Session ID",cwe:"CWE-330",owasp:"A02:2021",cvss:7.5,description:"This sessionIdGenerator builds the session ID only from timestamps, counters or Math.random(), so a client that sees one ID can guess the IDs of other sessions and send requests into them",severity:"HIGH",compliance:["SOC2","PCI-DSS"],fix:"Return `randomUUID()` from 'node:crypto' (or the global `crypto.randomUUID()`): `sessionIdGenerator: () => randomUUID()`.",documentationLink:SESSION_DOCS}),constantSessionId:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Constant MCP Session ID",cwe:"CWE-330",owasp:"A02:2021",cvss:7.5,description:"This sessionIdGenerator returns the same value for every session, so every client shares one session and can read and drive the others' requests",severity:"HIGH",compliance:["SOC2","PCI-DSS"],fix:"Generate the ID per call: `sessionIdGenerator: () => randomUUID()`. A value computed once at module level is the same for every session.",documentationLink:SESSION_DOCS})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;function classify(node,depth){if(depth>MAX_DEPTH)return"unknown";const scope=sourceCode.getScope(node);switch(node.type){case"Literal":return"constant";case"UpdateExpression":return"predictable";case"TemplateLiteral":return combine(node.expressions.map(e=>classify(e,depth+1)));case"BinaryExpression":return combine([classify(node.left,depth+1),classify(node.right,depth+1)]);case"NewExpression":return globalPath(node.callee,scope)==="Date"?"predictable":"unknown";case"MemberExpression":return opaque([classify(node.object,depth+1)]);case"CallExpression":return classifyCall(node,scope,depth);case"Identifier":{const init=(0,tool_registration_1.constInitializer)(node,scope);if(init===void 0)return"unknown";if(!insideFunction(init))return"constant";return classify(init,depth+1)}default:return"unknown"}}function classifyCall(node,scope,depth){const args=node.arguments.map(arg=>classify(arg,depth+1));const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding!==void 0){const exported=binding.path.join(".");return CSPRNG_EXPORTS.get(binding.module)?.has(exported)?"csprng":opaque(args)}const global=globalPath(node.callee,scope);if(global!==null){if(GLOBAL_CSPRNG.has(global))return"csprng";if(PREDICTABLE_GLOBALS.has(global))return"predictable";if(DERIVING_GLOBALS.has(global))return combine(args);return opaque(args)}if(node.callee.type==="MemberExpression"){const receiver=classify(node.callee.object,depth+1);const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method!==null&&DERIVING_METHODS.has(method))return combine([receiver,...args]);return opaque([receiver,...args])}const helper=(0,tool_registration_1.resolveFunction)(node.callee,scope);if(helper===void 0)return opaque(args);return combine((0,value_flow_1.returnedExpressions)(helper).map(e=>classify(e,depth+1)))}function check(value){const scope=sourceCode.getScope(value);if(value.type==="MemberExpression"){const global=globalPath(value,scope);if(global!==null&&PREDICTABLE_GLOBALS.has(global))context.report({node:value,messageId:"predictableSessionId"});return}const fn=(0,tool_registration_1.resolveFunction)(value,scope);if(fn===void 0)return;const returned=(0,value_flow_1.returnedExpressions)(fn);if(returned.length===0)return;const kind=combine(returned.map(expression=>classify(expression,0)));if(kind==="predictable")context.report({node:value,messageId:"predictableSessionId"});else if(kind==="constant")context.report({node:value,messageId:"constantSessionId"})}return{NewExpression(node){const transport=(0,tool_handlers_1.mcpExport)(node.callee,sourceCode.getScope(node));if(transport===void 0||!STREAMABLE_TRANSPORTS.has(transport))return;const options=node.arguments[0];if(options?.type!=="ObjectExpression")return;let generator;for(const prop of options.properties){if(prop.type==="SpreadElement")return;const key=(0,tool_registration_1.propertyKey)(prop);if(key===void 0)return;if(key==="sessionIdGenerator")generator=prop.value}if(generator!==void 0)check(generator)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPredictableSessionId=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const mcp_evidence_1=require("../../utils/mcp-evidence");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const STREAMABLE_TRANSPORTS=new Set(["StreamableHTTPServerTransport","NodeStreamableHTTPServerTransport","WebStandardStreamableHTTPServerTransport"]);const CSPRNG_EXPORTS=new Map([["crypto",new Set(["randomUUID","randomBytes","getRandomValues"])],["uuid",new Set(["v4","v7"])],["nanoid",new Set(["nanoid"])]]);const GLOBAL_CSPRNG=new Set(["crypto.randomUUID","crypto.getRandomValues"]);const PREDICTABLE_GLOBALS=new Set(["Date.now","performance.now","Math.random","process.hrtime","process.hrtime.bigint"]);const DERIVING_GLOBALS=new Set(["String","Math.floor","Math.round","Math.trunc"]);const DERIVING_METHODS=new Set(["toString","toFixed","toISOString","getTime","valueOf","slice","substring","substr","padStart","padEnd","replace","replaceAll","toUpperCase","toLowerCase","trim","join"]);const MAX_DEPTH=8;function combine(kinds){if(kinds.includes("csprng"))return"csprng";if(kinds.includes("unknown"))return"unknown";if(kinds.includes("predictable"))return"predictable";return"constant"}function opaque(kinds){return kinds.includes("csprng")?"csprng":"unknown"}function insideFunction(node){for(let current=node.parent;current;current=current.parent){if((0,tool_registration_1.isFunctionNode)(current))return true}return false}function globalPath(node,scope){const path=(0,eslint_devkit_1.memberPath)(node);if(path===null||(0,tool_registration_1.lookupVariable)(path[0],scope)?.defs.length)return null;return path.join(".")}const SESSION_DOCS="https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices#session-hijacking";exports.noPredictableSessionId=(0,eslint_devkit_1.createRule)({name:"no-predictable-session-id",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-predictable-session-id.md",description:"Disallow an MCP sessionIdGenerator that returns a counter, a timestamp, Math.random() or a constant",cwe:"CWE-330",cvss:7.5},messages:{predictableSessionId:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Predictable MCP Session ID",cwe:"CWE-330",owasp:"A02:2021",cvss:7.5,description:"This sessionIdGenerator builds the session ID only from timestamps, counters or Math.random(), so a client that sees one ID can guess the IDs of other sessions and send requests into them",severity:"HIGH",compliance:["SOC2","PCI-DSS"],fix:"Return `randomUUID()` from 'node:crypto' (or the global `crypto.randomUUID()`): `sessionIdGenerator: () => randomUUID()`.",documentationLink:SESSION_DOCS}),constantSessionId:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Constant MCP Session ID",cwe:"CWE-330",owasp:"A02:2021",cvss:7.5,description:"This sessionIdGenerator returns the same value for every session, so every client shares one session and can read and drive the others' requests",severity:"HIGH",compliance:["SOC2","PCI-DSS"],fix:"Generate the ID per call: `sessionIdGenerator: () => randomUUID()`. A value computed once at module level is the same for every session.",documentationLink:SESSION_DOCS})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;function classify(node,depth){if(depth>MAX_DEPTH)return"unknown";const scope=sourceCode.getScope(node);switch(node.type){case"Literal":return"constant";case"UpdateExpression":return"predictable";case"TemplateLiteral":return combine(node.expressions.map(e=>classify(e,depth+1)));case"BinaryExpression":return combine([classify(node.left,depth+1),classify(node.right,depth+1)]);case"NewExpression":return globalPath(node.callee,scope)==="Date"?"predictable":"unknown";case"MemberExpression":return opaque([classify(node.object,depth+1)]);case"CallExpression":return classifyCall(node,scope,depth);case"Identifier":{const init=(0,tool_registration_1.constInitializer)(node,scope);if(init===void 0)return"unknown";if(!insideFunction(init))return"constant";return classify(init,depth+1)}default:return"unknown"}}function classifyCall(node,scope,depth){const args=node.arguments.map(arg=>classify(arg,depth+1));const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding!==void 0){const exported=binding.path.join(".");return CSPRNG_EXPORTS.get(binding.module)?.has(exported)?"csprng":opaque(args)}const global=globalPath(node.callee,scope);if(global!==null){if(GLOBAL_CSPRNG.has(global))return"csprng";if(PREDICTABLE_GLOBALS.has(global))return"predictable";if(DERIVING_GLOBALS.has(global))return combine(args);return opaque(args)}if(node.callee.type==="MemberExpression"){const receiver=classify(node.callee.object,depth+1);const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method!==null&&DERIVING_METHODS.has(method))return combine([receiver,...args]);return opaque([receiver,...args])}const helper=(0,tool_registration_1.resolveFunction)(node.callee,scope);if(helper===void 0)return opaque(args);return combine((0,value_flow_1.returnedExpressions)(helper).map(e=>classify(e,depth+1)))}function check(value){const scope=sourceCode.getScope(value);if(value.type==="MemberExpression"){const global=globalPath(value,scope);if(global!==null&&PREDICTABLE_GLOBALS.has(global))context.report({node:value,messageId:"predictableSessionId"});return}const fn=(0,tool_registration_1.resolveFunction)(value,scope);if(fn===void 0)return;const returned=(0,value_flow_1.returnedExpressions)(fn);if(returned.length===0)return;const kind=combine(returned.map(expression=>classify(expression,0)));if(kind==="predictable")context.report({node:value,messageId:"predictableSessionId"});else if(kind==="constant")context.report({node:value,messageId:"constantSessionId"})}return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;sourceCode=context.sourceCode;return true},NewExpression(node){const transport=(0,tool_handlers_1.mcpExport)(node.callee,sourceCode.getScope(node));if(transport===void 0||!STREAMABLE_TRANSPORTS.has(transport))return;const options=node.arguments[0];if(options?.type!=="ObjectExpression")return;let generator;for(const prop of options.properties){if(prop.type==="SpreadElement")return;const key=(0,tool_registration_1.propertyKey)(prop);if(key===void 0)return;if(key==="sessionIdGenerator")generator=prop.value}if(generator!==void 0)check(generator)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSharedStatelessTransport=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const STREAMABLE_TRANSPORTS=new Set(["StreamableHTTPServerTransport","NodeStreamableHTTPServerTransport","WebStandardStreamableHTTPServerTransport"]);const SERVER_CLASSES=new Set(["McpServer","Server"]);const ADVISORY="https://nvd.nist.gov/vuln/detail/CVE-2026-25536";function ownerOf(node){for(let current=node.parent;current;current=current.parent){if((0,tool_registration_1.isFunctionNode)(current)||current.type==="PropertyDefinition")return current}return void 0}function contains(owner,node){for(let current=node;current;current=current.parent){if(current===owner)return true}return false}exports.noSharedStatelessTransport=(0,eslint_devkit_1.createRule)({name:"no-shared-stateless-transport",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-shared-stateless-transport.md",description:"Disallow sharing one stateless Streamable HTTP transport or one MCP server across requests",cwe:"CWE-488",cvss:7.5},messages:{statelessTransportAtModuleLevel:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Stateless MCP Transport Shared Across Requests",cwe:"CWE-488",owasp:"A04:2021",cvss:7.5,description:"This stateless `{{transport}}` is created once at module level, so every request goes through one transport with no session to key responses by; JSON-RPC IDs from different clients collide and one client receives another's responses (CVE-2026-25536)",severity:"HIGH",compliance:["SOC2","GDPR"],fix:"Create the server and the transport inside the request handler, per request, and close both when the response closes, or switch to stateful mode with `sessionIdGenerator: () => randomUUID()` and a transport per session.",documentationLink:ADVISORY}),sharedServerAcrossRequests:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Server Shared Across Stateless Requests",cwe:"CWE-488",owasp:"A04:2021",cvss:7.5,description:"A per-request stateless transport is connected to an `{{server}}` built outside this handler, so one server instance serves every request and responses can be delivered to the wrong client (CVE-2026-25536)",severity:"HIGH",compliance:["SOC2","GDPR"],fix:"Build the server per request as well: call a `getServer()` factory (or `new McpServer(...)`) inside the handler, connect it to the new transport, and close both when the response closes.",documentationLink:ADVISORY})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const builtBy=(0,instances_1.createInstanceResolver)(context);const perRequest=new Map;const connects=[];function isStateless(node){const options=node.arguments[0];if(options===void 0)return true;if(options.type!=="ObjectExpression")return false;let generator;for(const prop of options.properties){if(prop.type==="SpreadElement")return false;const key=(0,tool_registration_1.propertyKey)(prop);if(key===void 0)return false;if(key==="sessionIdGenerator")generator=prop.value}if(generator===void 0)return true;return generator.type==="Identifier"&&generator.name==="undefined"&&!(0,tool_registration_1.lookupVariable)("undefined",sourceCode.getScope(generator))?.defs.length}return{NewExpression(node){const transport=(0,tool_handlers_1.mcpExport)(node.callee,sourceCode.getScope(node));if(transport===void 0||!STREAMABLE_TRANSPORTS.has(transport))return;if(!isStateless(node))return;const owner=ownerOf(node);if(owner===void 0){context.report({node,messageId:"statelessTransportAtModuleLevel",data:{transport}});return}perRequest.set(node,owner)},CallExpression(node){if(node.callee.type!=="MemberExpression")return;if((0,eslint_devkit_1.propertyName)(node.callee)!=="connect")return;connects.push(node)},"Program:exit"(){for(const call of connects){const arg=call.arguments[0];if(arg===void 0)continue;const transport=builtBy(arg);const owner=transport&&perRequest.get(transport.call);if(owner===void 0)continue;const server=builtBy(call.callee.object);if(server===void 0||!(0,mcp_evidence_1.isMcpModule)(server.module))continue;const name=server.path[server.path.length-1];if(!SERVER_CLASSES.has(name))continue;if(contains(owner,server.call))continue;context.report({node:call,messageId:"sharedServerAcrossRequests",data:{server:name}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSharedStatelessTransport=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const STREAMABLE_TRANSPORTS=new Set(["StreamableHTTPServerTransport","NodeStreamableHTTPServerTransport","WebStandardStreamableHTTPServerTransport"]);const SERVER_CLASSES=new Set(["McpServer","Server"]);const ADVISORY="https://nvd.nist.gov/vuln/detail/CVE-2026-25536";function ownerOf(node){for(let current=node.parent;current;current=current.parent){if((0,tool_registration_1.isFunctionNode)(current)||current.type==="PropertyDefinition")return current}return void 0}function contains(owner,node){for(let current=node;current;current=current.parent){if(current===owner)return true}return false}exports.noSharedStatelessTransport=(0,eslint_devkit_1.createRule)({name:"no-shared-stateless-transport",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-shared-stateless-transport.md",description:"Disallow sharing one stateless Streamable HTTP transport or one MCP server across requests",cwe:"CWE-488",cvss:7.5},messages:{statelessTransportAtModuleLevel:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Stateless MCP Transport Shared Across Requests",cwe:"CWE-488",owasp:"A04:2021",cvss:7.5,description:"This stateless `{{transport}}` is created once at module level, so every request goes through one transport with no session to key responses by; JSON-RPC IDs from different clients collide and one client receives another's responses (CVE-2026-25536)",severity:"HIGH",compliance:["SOC2","GDPR"],fix:"Create the server and the transport inside the request handler, per request, and close both when the response closes, or switch to stateful mode with `sessionIdGenerator: () => randomUUID()` and a transport per session.",documentationLink:ADVISORY}),sharedServerAcrossRequests:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Server Shared Across Stateless Requests",cwe:"CWE-488",owasp:"A04:2021",cvss:7.5,description:"A per-request stateless transport is connected to an `{{server}}` built outside this handler, so one server instance serves every request and responses can be delivered to the wrong client (CVE-2026-25536)",severity:"HIGH",compliance:["SOC2","GDPR"],fix:"Build the server per request as well: call a `getServer()` factory (or `new McpServer(...)`) inside the handler, connect it to the new transport, and close both when the response closes.",documentationLink:ADVISORY})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;let builtBy;let perRequest;let connects;function isStateless(node){const options=node.arguments[0];if(options===void 0)return true;if(options.type!=="ObjectExpression")return false;let generator;for(const prop of options.properties){if(prop.type==="SpreadElement")return false;const key=(0,tool_registration_1.propertyKey)(prop);if(key===void 0)return false;if(key==="sessionIdGenerator")generator=prop.value}if(generator===void 0)return true;return generator.type==="Identifier"&&generator.name==="undefined"&&!(0,tool_registration_1.lookupVariable)("undefined",sourceCode.getScope(generator))?.defs.length}return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;sourceCode=context.sourceCode;builtBy=(0,instances_1.createInstanceResolver)(context);perRequest=new Map;connects=[];return true},NewExpression(node){const transport=(0,tool_handlers_1.mcpExport)(node.callee,sourceCode.getScope(node));if(transport===void 0||!STREAMABLE_TRANSPORTS.has(transport))return;if(!isStateless(node))return;const owner=ownerOf(node);if(owner===void 0){context.report({node,messageId:"statelessTransportAtModuleLevel",data:{transport}});return}perRequest.set(node,owner)},CallExpression(node){if(node.callee.type!=="MemberExpression")return;if((0,eslint_devkit_1.propertyName)(node.callee)!=="connect")return;connects.push(node)},"Program:exit"(){for(const call of connects){const arg=call.arguments[0];if(arg===void 0)continue;const transport=builtBy(arg);const owner=transport&&perRequest.get(transport.call);if(owner===void 0)continue;const server=builtBy(call.callee.object);if(server===void 0||!(0,mcp_evidence_1.isMcpModule)(server.module))continue;const name=server.path[server.path.length-1];if(!SERVER_CLASSES.has(name))continue;if(contains(owner,server.call))continue;context.report({node:call,messageId:"sharedServerAcrossRequests",data:{server:name}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjectionInTool=exports.DRIVERS=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const value_flow_1=require("../../utils/value-flow");const MYSQL={builds:new Set(["createConnection","createPool","createPoolCluster"]),sinks:new Set(["query","execute"])};const SQLITE_SINKS=new Set(["run","get","all","each","exec","prepare"]);exports.DRIVERS={pg:{builds:new Set(["Pool","Client"]),sinks:new Set(["query"])},mysql:MYSQL,mysql2:MYSQL,"mysql2/promise":MYSQL,"better-sqlite3":{builds:new Set([""]),sinks:new Set(["prepare","exec"])},sqlite3:{builds:new Set(["Database"]),sinks:SQLITE_SINKS},sqlite:{builds:new Set(["open","DatabaseSync"]),sinks:SQLITE_SINKS},duckdb:{builds:new Set(["Database"]),sinks:SQLITE_SINKS},postgres:{builds:new Set([""]),sinks:new Set(["unsafe"])},"@neondatabase/serverless":{builds:new Set(["neon","Pool","Client"]),sinks:new Set(["query","unsafe"])},"@vercel/postgres":{builds:new Set(["createPool","createClient","sql","db"]),sinks:new Set(["query"])},mssql:{builds:new Set(["ConnectionPool","connect"]),sinks:new Set(["query","batch"])},"@libsql/client":{builds:new Set(["createClient"]),sinks:new Set(["execute","executeMultiple"])},"@prisma/client":{builds:new Set(["PrismaClient"]),sinks:new Set(["$queryRawUnsafe","$executeRawUnsafe"])},knex:{builds:new Set(["","knex"]),sinks:new Set(["raw"])},sequelize:{builds:new Set(["Sequelize"]),sinks:new Set(["query"])}};const TEXT_KEYS=new Set(["text","sql"]);function sqlSinkOf(node,scope,builtBy){if(node.callee.type!=="MemberExpression")return void 0;const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method===null)return void 0;const direct=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);const directDriver=direct&&exports.DRIVERS[direct.module];if(directDriver!==void 0)return directDriver.sinks.has(method)?`${direct.module}.${method}`:void 0;const instance=builtBy(node.callee.object);const driver=instance&&exports.DRIVERS[instance.module];if(driver===void 0||!driver.builds.has(instance.path.join("."))||!driver.sinks.has(method))return void 0;return`${instance.module}.${method}`}function sqlTextOf(node){const first=node.arguments[0];if(first===void 0)return[];if(first.type!=="ObjectExpression")return[first];return first.properties.flatMap(prop=>prop.type==="Property"&&TEXT_KEYS.has((0,eslint_devkit_1.objectKeyName)(prop)??"")?[prop.value]:[])}exports.noSqlInjectionInTool=(0,eslint_devkit_1.createRule)({name:"no-sql-injection-in-tool",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-sql-injection-in-tool.md",description:"Disallow an MCP tool argument reaching the text of a SQL query instead of its parameters",cwe:"CWE-89",cvss:9.8},messages:{toolArgToSql:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument in SQL Text",cwe:"CWE-89",owasp:"A03:2021",cvss:9.8,description:"Tool argument `{{arg}}` reaches the SQL text of `{{sink}}()`, so whatever steers the model can rewrite the query \u2014 read other rows, drop tables, or escalate through the database",severity:"CRITICAL",compliance:["SOC2","PCI-DSS","NIST-CSF"],fix:'Keep the SQL text a literal and pass the argument as a bound parameter \u2014 `pool.query("SELECT \u2026 WHERE name = $1", [name])`, `db.prepare("\u2026 WHERE id = ?").get(id)`. An identifier (table or column name) must come from an allowlist the code owns, never from the argument.',documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const resolve=(0,module_resolver_1.valueResolverFor)(context);const builtBy=(0,instances_1.createInstanceResolver)(context);const handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");const candidates=[];return{CallExpression(node){handlers.visit(node);const sink=sqlSinkOf(node,context.sourceCode.getScope(node),builtBy);if(sink===void 0)return;for(const text of sqlTextOf(node))candidates.push({node:text,sink})},"Program:exit"(){const carries=(0,value_flow_1.createFlow)(context.sourceCode,fn=>handlers.roots.get(fn),void 0,(0,value_flow_1.flowOptionsFor)(context));for(const{node,sink}of candidates){const taint=carries(node);if(taint?.kind!=="value")continue;context.report({node,messageId:"toolArgToSql",data:{arg:taint.text,sink}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjectionInTool=exports.DRIVERS=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const value_flow_1=require("../../utils/value-flow");const MYSQL={builds:new Set(["createConnection","createPool","createPoolCluster"]),sinks:new Set(["query","execute"])};const SQLITE_SINKS=new Set(["run","get","all","each","exec","prepare"]);exports.DRIVERS={pg:{builds:new Set(["Pool","Client"]),sinks:new Set(["query"])},mysql:MYSQL,mysql2:MYSQL,"mysql2/promise":MYSQL,"better-sqlite3":{builds:new Set([""]),sinks:new Set(["prepare","exec"])},sqlite3:{builds:new Set(["Database"]),sinks:SQLITE_SINKS},sqlite:{builds:new Set(["open","DatabaseSync"]),sinks:SQLITE_SINKS},duckdb:{builds:new Set(["Database"]),sinks:SQLITE_SINKS},postgres:{builds:new Set([""]),sinks:new Set(["unsafe"])},"@neondatabase/serverless":{builds:new Set(["neon","Pool","Client"]),sinks:new Set(["query","unsafe"])},"@vercel/postgres":{builds:new Set(["createPool","createClient","sql","db"]),sinks:new Set(["query"])},mssql:{builds:new Set(["ConnectionPool","connect"]),sinks:new Set(["query","batch"])},"@libsql/client":{builds:new Set(["createClient"]),sinks:new Set(["execute","executeMultiple"])},"@prisma/client":{builds:new Set(["PrismaClient"]),sinks:new Set(["$queryRawUnsafe","$executeRawUnsafe"])},knex:{builds:new Set(["","knex"]),sinks:new Set(["raw"])},sequelize:{builds:new Set(["Sequelize"]),sinks:new Set(["query"])}};const TEXT_KEYS=new Set(["text","sql"]);function sqlSinkOf(node,scope,builtBy){if(node.callee.type!=="MemberExpression")return void 0;const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method===null)return void 0;const direct=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);const directDriver=direct&&exports.DRIVERS[direct.module];if(directDriver!==void 0)return directDriver.sinks.has(method)?`${direct.module}.${method}`:void 0;const instance=builtBy(node.callee.object);const driver=instance&&exports.DRIVERS[instance.module];if(driver===void 0||!driver.builds.has(instance.path.join("."))||!driver.sinks.has(method))return void 0;return`${instance.module}.${method}`}function sqlTextOf(node){const first=node.arguments[0];if(first===void 0)return[];if(first.type!=="ObjectExpression")return[first];return first.properties.flatMap(prop=>prop.type==="Property"&&TEXT_KEYS.has((0,eslint_devkit_1.objectKeyName)(prop)??"")?[prop.value]:[])}exports.noSqlInjectionInTool=(0,eslint_devkit_1.createRule)({name:"no-sql-injection-in-tool",meta:{interop:{runtimes:["eslint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-sql-injection-in-tool.md",description:"Disallow an MCP tool argument reaching the text of a SQL query instead of its parameters",cwe:"CWE-89",cvss:9.8},messages:{toolArgToSql:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument in SQL Text",cwe:"CWE-89",owasp:"A03:2021",cvss:9.8,description:"Tool argument `{{arg}}` reaches the SQL text of `{{sink}}()`, so whatever steers the model can rewrite the query \u2014 read other rows, drop tables, or escalate through the database",severity:"CRITICAL",compliance:["SOC2","PCI-DSS","NIST-CSF"],fix:'Keep the SQL text a literal and pass the argument as a bound parameter \u2014 `pool.query("SELECT \u2026 WHERE name = $1", [name])`, `db.prepare("\u2026 WHERE id = ?").get(id)`. An identifier (table or column name) must come from an allowlist the code owns, never from the argument.',documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Query_Parameterization_Cheat_Sheet.html"})},schema:[]},defaultOptions:[],createOnce(context){let builtBy;let handlers;let candidates;return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;const resolve=(0,module_resolver_1.valueResolverFor)(context);builtBy=(0,instances_1.createInstanceResolver)(context);handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");candidates=[];return true},CallExpression(node){handlers.visit(node);const sink=sqlSinkOf(node,context.sourceCode.getScope(node),builtBy);if(sink===void 0)return;for(const text of sqlTextOf(node))candidates.push({node:text,sink})},"Program:exit"(){const carries=(0,value_flow_1.createFlow)(context.sourceCode,fn=>handlers.roots.get(fn),void 0,(0,value_flow_1.flowOptionsFor)(context));for(const{node,sink}of candidates){const taint=carries(node);if(taint?.kind!=="value")continue;context.report({node,messageId:"toolArgToSql",data:{arg:taint.text,sink}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSsrfInTool=void 0;exports.authorityOpen=authorityOpen;const eslint_devkit_1=require("@interlace/eslint-devkit");const guards_1=require("../../utils/guards");const http_clients_1=require("../../utils/http-clients");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const ORIGIN_MEMBERS=new Set(["hostname","host","origin"]);const COMPARISONS=new Set(["===","!==","==","!="]);const SCHEME=/^[a-z][a-z\d+.-]*:/i;function authorityOpen(prefix){const rest=prefix.replace(SCHEME,"").replace(/^\/\//,"");return!/[^/?#\\][/?#\\]/.test(rest)}const MAX_ORIGIN_DEPTH=12;const URL_TEXT_MEMBERS=new Set(["href","toString"]);const OPAQUE="x";exports.noSsrfInTool=(0,eslint_devkit_1.createRule)({name:"no-ssrf-in-tool",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-ssrf-in-tool.md",description:"Disallow an MCP tool argument choosing the host an outbound HTTP request is sent to",cwe:"CWE-918",cvss:8.6},messages:{toolArgToRequestHost:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Chooses a Request Host",cwe:"CWE-918",owasp:"A10:2021",cvss:8.6,description:"Tool argument `{{arg}}` decides where `{{client}}()` connects, so whatever steers the model can make this server request internal services or the cloud metadata endpoint and read the answer",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:'Keep the origin fixed in code and let the argument fill only a path or query segment (`new URL("/v1/" + encodeURIComponent(id), API_ORIGIN)`), or parse it with `new URL()` and reject it unless `url.hostname` is in an allowlist \u2014 before the request.',documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const resolve=(0,module_resolver_1.valueResolverFor)(context);const builtBy=(0,instances_1.createInstanceResolver)(context);const handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");const candidates=[];const isUrlConstructor=node=>node.type==="NewExpression"&&node.callee.type==="Identifier"&&node.callee.name==="URL"&&!(0,tool_registration_1.lookupVariable)("URL",sourceCode.getScope(node))?.defs.length;return{CallExpression(node){handlers.visit(node);const request=(0,http_clients_1.httpRequestOf)(node,sourceCode.getScope(node),builtBy);for(const target of request?.targets??[])candidates.push({call:node,target,client:request.client})},"Program:exit"(){const carries=(0,value_flow_1.createFlow)(sourceCode,fn=>handlers.roots.get(fn),(node,follow)=>{if(isUrlConstructor(node)){for(const arg of node.arguments){const t=follow(arg);if(t?.kind==="value")return t}return null}if(node.type!=="CallExpression")return void 0;const helper=(0,tool_registration_1.resolveFunction)(node.callee,sourceCode.getScope(node));return helper!==void 0&&guards.sanitizes(helper)?null:void 0},(0,value_flow_1.flowOptionsFor)(context,(call,arg)=>guards.guarded(call,arg)));const callsOf=(0,value_flow_1.callSitesIn)(sourceCode);const value=node=>{const t=carries(node);return t?.kind==="value"?t:null};const originOf=(node,depth)=>{if(depth>MAX_ORIGIN_DEPTH)return null;node=(0,module_resolver_1.unwrapTypeOnly)(node);if(node.type==="AwaitExpression"||node.type==="ChainExpression")return originOf(node.type==="AwaitExpression"?node.argument:node.expression,depth+1);const parts=textParts(node);if(parts!==void 0){let prefix="";for(const part of parts){if(typeof part==="string"){prefix+=part;continue}const t=value(part);if(t)return authorityOpen(prefix)?t:null;const fixed=resolve(part);prefix+=(fixed&&(0,eslint_devkit_1.staticString)(fixed))??OPAQUE}return null}if(isUrlConstructor(node)){const[input,base]=node.arguments;if(input===void 0)return null;const t=originOf(input,depth+1);if(t)return t;return(0,eslint_devkit_1.staticString)(input)!==null&&base!==void 0?originOf(base,depth+1):null}const scope=sourceCode.getScope(node);const same=inner=>cite(node,originOf(inner,depth+1));if(node.type==="MemberExpression"&&URL_TEXT_MEMBERS.has((0,eslint_devkit_1.propertyName)(node)??""))return same(node.object);if(node.type==="CallExpression"){const{callee}=node;const[first]=node.arguments;if((0,guards_1.isConversion)(node,scope)&&first!==void 0)return same(first);if(callee.type==="MemberExpression"&&node.arguments.length===0&&URL_TEXT_MEMBERS.has((0,eslint_devkit_1.propertyName)(callee)??""))return same(callee.object);const helper=(0,tool_registration_1.resolveFunction)(callee,scope);if(helper!==void 0){if(guards.sanitizes(helper))return null;for(const returned of(0,value_flow_1.returnedExpressions)(helper)){const t=cite(node,originOf(returned,depth+1));if(t)return t}return null}}if(node.type==="Identifier"){const init=(0,tool_registration_1.constInitializer)(node,scope);if(init!==void 0)return originOf(init,depth+1);const variable=(0,tool_registration_1.lookupVariable)(node.name,scope);const def=variable?.defs[0];const writes=def?.type==="Variable"?plainWrites(variable):void 0;if(writes!==void 0){for(const write of writes){const t=originOf(write,depth+1);if(t)return t}return null}const fn=def?.type==="Parameter"?def.node:void 0;if(fn!==void 0&&handlers.roots.get(fn)===void 0&&"params"in fn){const index=fn.params.indexOf(def.name);if(index<0)return value(node);for(const call of callsOf(fn)){const arg=call.arguments[index];if(arg===void 0||arg.type==="SpreadElement"||guards.guarded(call,arg))continue;const t=originOf(arg,depth+1);if(t)return t}if(callsOf(fn).length>0)return null}}return value(node)};const cite=(node,t)=>t&&[value(node),t].find(x=>x!==null);const plainWrites=variable=>{const def=variable.defs[0];if(def.node.type!=="VariableDeclarator"||def.node.id!==def.name)return void 0;const writes=def.node.init?[def.node.init]:[];for(const ref of variable.references){if(!ref.isWrite()||ref.identifier===def.name)continue;const parent=ref.identifier.parent;if(parent?.type!=="AssignmentExpression"||parent.operator!=="="||parent.left!==ref.identifier)return void 0;writes.push(parent.right)}return writes};const schemeOnly=arg=>{const text=(0,eslint_devkit_1.staticString)(resolve(arg)??arg);return text!==null&&authorityOpen(text)};const readsHost=fn=>{let found=false;const visit=node=>{if(found)return;if(node.type==="MemberExpression"&&ORIGIN_MEMBERS.has((0,eslint_devkit_1.propertyName)(node)??"")){found=true;return}if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node.callee)==="startsWith"&&node.arguments[0]!==void 0&&!schemeOnly(node.arguments[0])){found=true;return}for(const[key,value2]of Object.entries(node)){if(key==="parent")continue;for(const child of Array.isArray(value2)?value2:[value2])if(child!==null&&typeof child==="object"&&typeof child.type==="string")visit(child)}};visit(fn);return found};const guards=(0,guards_1.createGuards)(sourceCode,variable=>{const name=variable.defs[0]?.name;return name!==void 0&&carries(name)!==null},(node,involves)=>{if(node.type==="BinaryExpression"){if(!COMPARISONS.has(node.operator))return false;return[node.left,node.right].some(side=>{const member=side.type==="Identifier"?(0,tool_registration_1.constInitializer)(side,sourceCode.getScope(side)):side;return member?.type==="MemberExpression"&&ORIGIN_MEMBERS.has((0,eslint_devkit_1.propertyName)(member)??"")&&involves(member.object)})}if(node.type!=="CallExpression")return false;if((0,http_clients_1.httpRequestOf)(node,sourceCode.getScope(node),builtBy))return false;if((0,guards_1.isConversion)(node,sourceCode.getScope(node)))return false;if(node.callee.type==="MemberExpression"){const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method!==null&&value_flow_1.STRING_DERIVING.has(method))return false;const[prefix]=node.arguments;if(method==="startsWith"&&prefix&&schemeOnly(prefix))return false;if(involves(node.callee.object))return true}const helper=(0,tool_registration_1.resolveFunction)(node.callee,sourceCode.getScope(node));if(helper!==void 0&&!readsHost(helper))return false;return node.arguments.some(involves)});for(const{call,target,client}of candidates){const taint=originOf(target,0);if(taint===null||guards.guarded(call,target))continue;context.report({node:target,messageId:"toolArgToRequestHost",data:{arg:taint.text,client}})}}}}});function textParts(node){if(node.type==="TemplateLiteral"){const parts=[];node.quasis.forEach((quasi,i)=>{parts.push(quasi.value.raw);const expression=node.expressions[i];if(expression)parts.push(expression)});return parts}if(node.type==="BinaryExpression"&&node.operator==="+"){const side=n=>{const text=(0,eslint_devkit_1.staticString)(n);if(text!==null)return[text];return textParts(n)??[n]};return[...side(node.left),...side(node.right)]}return void 0}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSsrfInTool=void 0;exports.authorityOpen=authorityOpen;const eslint_devkit_1=require("@interlace/eslint-devkit");const guards_1=require("../../utils/guards");const http_clients_1=require("../../utils/http-clients");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const ORIGIN_MEMBERS=new Set(["hostname","host","origin"]);const COMPARISONS=new Set(["===","!==","==","!="]);const SCHEME=/^[a-z][a-z\d+.-]*:/i;function authorityOpen(prefix){const rest=prefix.replace(SCHEME,"").replace(/^\/\//,"");return!/[^/?#\\][/?#\\]/.test(rest)}const MAX_ORIGIN_DEPTH=12;const URL_TEXT_MEMBERS=new Set(["href","toString"]);const OPAQUE="x";exports.noSsrfInTool=(0,eslint_devkit_1.createRule)({name:"no-ssrf-in-tool",meta:{interop:{runtimes:["eslint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-ssrf-in-tool.md",description:"Disallow an MCP tool argument choosing the host an outbound HTTP request is sent to",cwe:"CWE-918",cvss:8.6},messages:{toolArgToRequestHost:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Chooses a Request Host",cwe:"CWE-918",owasp:"A10:2021",cvss:8.6,description:"Tool argument `{{arg}}` decides where `{{client}}()` connects, so whatever steers the model can make this server request internal services or the cloud metadata endpoint and read the answer",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:'Keep the origin fixed in code and let the argument fill only a path or query segment (`new URL("/v1/" + encodeURIComponent(id), API_ORIGIN)`), or parse it with `new URL()` and reject it unless `url.hostname` is in an allowlist \u2014 before the request.',documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices"})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;let resolve;let builtBy;let handlers;let candidates;const isUrlConstructor=node=>node.type==="NewExpression"&&node.callee.type==="Identifier"&&node.callee.name==="URL"&&!(0,tool_registration_1.lookupVariable)("URL",sourceCode.getScope(node))?.defs.length;return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;sourceCode=context.sourceCode;resolve=(0,module_resolver_1.valueResolverFor)(context);builtBy=(0,instances_1.createInstanceResolver)(context);handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");candidates=[];return true},CallExpression(node){handlers.visit(node);const request=(0,http_clients_1.httpRequestOf)(node,sourceCode.getScope(node),builtBy);for(const target of request?.targets??[])candidates.push({call:node,target,client:request.client})},"Program:exit"(){const carries=(0,value_flow_1.createFlow)(sourceCode,fn=>handlers.roots.get(fn),(node,follow)=>{if(isUrlConstructor(node)){for(const arg of node.arguments){const t=follow(arg);if(t?.kind==="value")return t}return null}if(node.type!=="CallExpression")return void 0;const helper=(0,tool_registration_1.resolveFunction)(node.callee,sourceCode.getScope(node));return helper!==void 0&&guards.sanitizes(helper)?null:void 0},(0,value_flow_1.flowOptionsFor)(context,(call,arg)=>guards.guarded(call,arg)));const callsOf=(0,value_flow_1.callSitesIn)(sourceCode);const value=node=>{const t=carries(node);return t?.kind==="value"?t:null};const originOf=(node,depth)=>{if(depth>MAX_ORIGIN_DEPTH)return null;node=(0,module_resolver_1.unwrapTypeOnly)(node);if(node.type==="AwaitExpression"||node.type==="ChainExpression")return originOf(node.type==="AwaitExpression"?node.argument:node.expression,depth+1);const parts=textParts(node);if(parts!==void 0){let prefix="";for(const part of parts){if(typeof part==="string"){prefix+=part;continue}const t=value(part);if(t)return authorityOpen(prefix)?t:null;const fixed=resolve(part);prefix+=(fixed&&(0,eslint_devkit_1.staticString)(fixed))??OPAQUE}return null}if(isUrlConstructor(node)){const[input,base]=node.arguments;if(input===void 0)return null;const t=originOf(input,depth+1);if(t)return t;return(0,eslint_devkit_1.staticString)(input)!==null&&base!==void 0?originOf(base,depth+1):null}const scope=sourceCode.getScope(node);const same=inner=>cite(node,originOf(inner,depth+1));if(node.type==="MemberExpression"&&URL_TEXT_MEMBERS.has((0,eslint_devkit_1.propertyName)(node)??""))return same(node.object);if(node.type==="CallExpression"){const{callee}=node;const[first]=node.arguments;if((0,guards_1.isConversion)(node,scope)&&first!==void 0)return same(first);if(callee.type==="MemberExpression"&&node.arguments.length===0&&URL_TEXT_MEMBERS.has((0,eslint_devkit_1.propertyName)(callee)??""))return same(callee.object);const helper=(0,tool_registration_1.resolveFunction)(callee,scope);if(helper!==void 0){if(guards.sanitizes(helper))return null;for(const returned of(0,value_flow_1.returnedExpressions)(helper)){const t=cite(node,originOf(returned,depth+1));if(t)return t}return null}}if(node.type==="Identifier"){const init=(0,tool_registration_1.constInitializer)(node,scope);if(init!==void 0)return originOf(init,depth+1);const variable=(0,tool_registration_1.lookupVariable)(node.name,scope);const def=variable?.defs[0];const writes=def?.type==="Variable"?plainWrites(variable):void 0;if(writes!==void 0){for(const write of writes){const t=originOf(write,depth+1);if(t)return t}return null}const fn=def?.type==="Parameter"?def.node:void 0;if(fn!==void 0&&handlers.roots.get(fn)===void 0&&"params"in fn){const index=fn.params.indexOf(def.name);if(index<0)return value(node);for(const call of callsOf(fn)){const arg=call.arguments[index];if(arg===void 0||arg.type==="SpreadElement"||guards.guarded(call,arg))continue;const t=originOf(arg,depth+1);if(t)return t}if(callsOf(fn).length>0)return null}}return value(node)};const cite=(node,t)=>t&&[value(node),t].find(x=>x!==null);const plainWrites=variable=>{const def=variable.defs[0];if(def.node.type!=="VariableDeclarator"||def.node.id!==def.name)return void 0;const writes=def.node.init?[def.node.init]:[];for(const ref of variable.references){if(!ref.isWrite()||ref.identifier===def.name)continue;const parent=ref.identifier.parent;if(parent?.type!=="AssignmentExpression"||parent.operator!=="="||parent.left!==ref.identifier)return void 0;writes.push(parent.right)}return writes};const schemeOnly=arg=>{const text=(0,eslint_devkit_1.staticString)(resolve(arg)??arg);return text!==null&&authorityOpen(text)};const readsHost=fn=>{let found=false;const visit=node=>{if(found)return;if(node.type==="MemberExpression"&&ORIGIN_MEMBERS.has((0,eslint_devkit_1.propertyName)(node)??"")){found=true;return}if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node.callee)==="startsWith"&&node.arguments[0]!==void 0&&!schemeOnly(node.arguments[0])){found=true;return}for(const[key,value2]of Object.entries(node)){if(key==="parent")continue;for(const child of Array.isArray(value2)?value2:[value2])if(child!==null&&typeof child==="object"&&typeof child.type==="string")visit(child)}};visit(fn);return found};const guards=(0,guards_1.createGuards)(sourceCode,variable=>{const name=variable.defs[0]?.name;return name!==void 0&&carries(name)!==null},(node,involves)=>{if(node.type==="BinaryExpression"){if(!COMPARISONS.has(node.operator))return false;return[node.left,node.right].some(side=>{const member=side.type==="Identifier"?(0,tool_registration_1.constInitializer)(side,sourceCode.getScope(side)):side;return member?.type==="MemberExpression"&&ORIGIN_MEMBERS.has((0,eslint_devkit_1.propertyName)(member)??"")&&involves(member.object)})}if(node.type!=="CallExpression")return false;if((0,http_clients_1.httpRequestOf)(node,sourceCode.getScope(node),builtBy))return false;if((0,guards_1.isConversion)(node,sourceCode.getScope(node)))return false;if(node.callee.type==="MemberExpression"){const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method!==null&&value_flow_1.STRING_DERIVING.has(method))return false;const[prefix]=node.arguments;if(method==="startsWith"&&prefix&&schemeOnly(prefix))return false;if(involves(node.callee.object))return true}const helper=(0,tool_registration_1.resolveFunction)(node.callee,sourceCode.getScope(node));if(helper!==void 0&&!readsHost(helper))return false;return node.arguments.some(involves)});for(const{call,target,client}of candidates){const taint=originOf(target,0);if(taint===null||guards.guarded(call,target))continue;context.report({node:target,messageId:"toolArgToRequestHost",data:{arg:taint.text,client}})}}}}});function textParts(node){if(node.type==="TemplateLiteral"){const parts=[];node.quasis.forEach((quasi,i)=>{parts.push(quasi.value.raw);const expression=node.expressions[i];if(expression)parts.push(expression)});return parts}if(node.type==="BinaryExpression"&&node.operator==="+"){const side=n=>{const text=(0,eslint_devkit_1.staticString)(n);if(text!==null)return[text];return textParts(n)??[n]};return[...side(node.left),...side(node.right)]}return void 0}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noToolDescriptionInjection=void 0;exports.textKind=textKind;exports.isStaticText=isStaticText;exports.modelFacingProperties=modelFacingProperties;const eslint_devkit_1=require("@interlace/eslint-devkit");const fs_module_1=require("../../utils/fs-module");const http_clients_1=require("../../utils/http-clients");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const MODEL_FACING_KEYS=["description","title"];const METADATA_CONFIG_INDEX=new Map([["registerPrompt",[1,"prompt"]],["registerResource",[2,"resource"]]]);function combine(kinds){if(kinds.includes("dynamic"))return"dynamic";return kinds.includes("unknown")?"unknown":"static"}function textKind(node,env,depth=0){node=(0,module_resolver_1.unwrapTypeOnly)(node);switch(node.type){case"Literal":return typeof node.value==="string"?"static":"dynamic";case"TemplateLiteral":return combine(node.expressions.map(e=>textKind(e,env,depth+1)));case"TaggedTemplateExpression":return combine(node.quasi.expressions.map(e=>textKind(e,env,depth+1)));case"BinaryExpression":return node.operator==="+"?combine([textKind(node.left,env,depth+1),textKind(node.right,env,depth+1)]):"dynamic";case"CallExpression":return joinKind(node,env,depth);case"Identifier":case"MemberExpression":{if(env===void 0)return"dynamic";const resolved=(0,module_resolver_1.resolveValue)(node,env.site,{parser:env.parser,depth});if(resolved.kind==="unknown")return"unknown";if(resolved.kind!=="value")return"dynamic";return textKind(resolved.node,{...env,site:resolved.site},depth+1)}default:return"dynamic"}}function joinKind(node,env,depth){if(node.callee.type!=="MemberExpression")return"dynamic";if((0,eslint_devkit_1.propertyName)(node.callee)!=="join")return"dynamic";const array=node.callee.object;if(array.type!=="ArrayExpression")return"dynamic";if(node.arguments.length>1)return"dynamic";const parts=node.arguments.map(a=>textKind(a,env,depth+1));for(const element of array.elements){if(element===null||element.type==="SpreadElement")return"dynamic";parts.push(textKind(element,env,depth+1))}return combine(parts)}function isStaticText(node){return textKind(node)==="static"}function modelFacingProperties(config,env){const found=[];for(const prop of config.properties){if(prop.type!=="Property"||prop.computed)continue;const key=prop.key.type==="Identifier"?prop.key.name:(0,eslint_devkit_1.staticString)(prop.key)??void 0;if(key===void 0)continue;if(!MODEL_FACING_KEYS.includes(key))continue;if(textKind(prop.value,env)!=="dynamic")continue;found.push({key,value:prop.value})}return found}const FILE_READS=new Set(["readFile","readFileSync"]);const BODY_READERS=new Set(["json","text"]);const HTTP_APPS={express:"",hono:"Hono",fastify:""};const ROUTE_METHODS=new Set(["get","post","put","patch","delete","all","route","on"]);const PATH_BUILDERS=new Set(["join","resolve"]);function isPackagePath(node,scopeOf,depth=0){if(node===void 0||depth>8)return false;const value=(0,module_resolver_1.unwrapTypeOnly)(node);const anchored=n=>isPackagePath(n,scopeOf,depth+1);switch(value.type){case"Identifier":{if(value.name==="__dirname"||value.name==="__filename")return!(0,tool_registration_1.lookupVariable)(value.name,scopeOf(value))?.defs.length;return anchored((0,tool_registration_1.constInitializer)(value,scopeOf(value)))}case"MemberExpression":return value.object.type==="MetaProperty";case"TemplateLiteral":return value.quasis[0].value.raw===""&&value.expressions.length===1&&anchored(value.expressions[0]);case"NewExpression":return value.callee.type==="Identifier"&&value.callee.name==="URL"&&!(0,tool_registration_1.lookupVariable)("URL",scopeOf(value))?.defs.length&&value.arguments.length===2&&(0,eslint_devkit_1.staticString)(value.arguments[0])!==null&&anchored(value.arguments[1]);case"CallExpression":{const binding=(0,eslint_devkit_1.resolveModuleBinding)(value.callee,scopeOf(value));const[first,...rest]=value.arguments;if(binding?.module==="url")return binding.path.join(".")==="fileURLToPath"&&anchored(first);return binding?.module==="path"&&PATH_BUILDERS.has(binding.path[binding.path.length-1]??"")&&anchored(first)&&rest.every(part=>(0,eslint_devkit_1.staticString)(part)!==null)}default:return false}}const REQUEST_ROOT={toArgs:[],closed:new Set};const PARAMS_ROOT={toArgs:["params"],closed:new Set};function registrationTexts(node,resolve,env){const tool=(0,tool_registration_1.toolNameOf)(node);const texts=[];const registration=(0,tool_registration_1.readRegistration)(node,resolve);if(registration!==void 0){const objects=[];if(registration.config)objects.push(registration.config);if(registration.annotations&&(0,tool_registration_1.classifyLegacyObject)(registration.annotations,resolve)!=="shape")objects.push(registration.annotations);for(const config2 of objects)for(const{key,value}of modelFacingProperties(config2,env))texts.push({value,messageId:"dynamicDescription",data:{tool,key}});if(registration.description&&textKind(registration.description,env)!=="static")texts.push({value:registration.description,messageId:"dynamicDescription",data:{tool,key:"description"}});return texts}const method=(0,tool_registration_1.calledMethod)(node);const slot=method===null?void 0:METADATA_CONFIG_INDEX.get(method);if(slot===void 0)return texts;const[index,kind]=slot;const config=node.arguments[index];if(config?.type!=="ObjectExpression")return texts;for(const{key,value}of modelFacingProperties(config,env))texts.push({value,messageId:"dynamicMetadata",data:{kind,name:tool,key}});return texts}function pathInPattern(pattern,target){if(pattern===target)return[];if(pattern.type==="AssignmentPattern")return pathInPattern(pattern.left,target);if(pattern.type!=="ObjectPattern")return void 0;for(const prop of pattern.properties){const key=(0,tool_registration_1.propertyKey)(prop);if(key===void 0)continue;const rest=pathInPattern(prop.value,target);if(rest)return[key,...rest]}return void 0}function paramPath(node,target,scopeOf,depth=0){if(depth>8)return void 0;const value=(0,module_resolver_1.unwrapTypeOnly)(node);if(value.type==="MemberExpression"){const key=(0,eslint_devkit_1.propertyName)(value);const base2=key===null?void 0:paramPath(value.object,target,scopeOf,depth+1);return base2&&{index:base2.index,path:[...base2.path,key]}}if(value.type==="TemplateLiteral"){for(const expression of value.expressions){const found=paramPath(expression,target,scopeOf,depth+1);if(found)return found}return void 0}if(value.type!=="Identifier")return void 0;const def=(0,tool_registration_1.lookupVariable)(value.name,scopeOf(value))?.defs[0];if(def?.type==="Parameter"&&def.node===target.fn){const index=target.fn.params.findIndex(param=>pathInPattern(param,def.name)!==void 0);if(index<0)return void 0;return{index,path:pathInPattern(target.fn.params[index],def.name)}}if(def?.type!=="Variable"||def.node.init===null)return void 0;const base=paramPath(def.node.init,target,scopeOf,depth+1);const rest=base&&pathInPattern(def.node.id,def.name);return rest&&{index:base.index,path:[...base.path,...rest]}}function forwardsOf(target,scopeOf){const found=[];const visit=node=>{if(node.type==="CallExpression")for(const text of registrationTexts(node)){const from=paramPath(text.value,target,scopeOf);if(from)found.push({...text,...from})}for(const[key,child]of Object.entries(node)){if(key==="parent")continue;for(const item of Array.isArray(child)?child:[child])if(item&&typeof item==="object"&&typeof item.type==="string")visit(item)}};visit(target.fn.body);return found}exports.noToolDescriptionInjection=(0,eslint_devkit_1.createRule)({name:"no-tool-description-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-tool-description-injection.md",description:"Disallow MCP tool, prompt and resource descriptions built from text a client, a remote service or a file controls",cwe:"CWE-1427",cvss:8.6},messages:{dynamicDescription:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Description From Untrusted Text",cwe:"CWE-1427",owasp:"A03:2021",cvss:8.6,description:'The `{{key}}` for tool "{{tool}}" is built from `{{source}}` \u2014 text a client, a remote service or a file controls \u2014 so whoever controls it writes part of the model\'s instructions',severity:"HIGH",compliance:["SOC2"],fix:"Write the {{key}} in code. If it must vary, choose among fixed texts the server owns (a map keyed by a validated enum) rather than interpolating the value \u2014 it lands in the model's instruction block, so whoever controls it controls the instructions.",documentationLink:"https://modelcontextprotocol.io/docs/concepts/tools"}),dynamicMetadata:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Prompt/Resource Description From Untrusted Text",cwe:"CWE-1427",owasp:"A03:2021",cvss:8.6,description:'The `{{key}}` for {{kind}} "{{name}}" is built from `{{source}}` \u2014 text a client, a remote service or a file controls \u2014 so whoever controls it writes what the model reads',severity:"HIGH",compliance:["SOC2"],fix:"Write the {{key}} in code, or choose among fixed texts the server owns; keep client- or file-supplied text in the resource CONTENTS, not its description.",documentationLink:"https://modelcontextprotocol.io/docs/concepts/prompts"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const parser=(0,module_resolver_1.activeParser)(context);const resolve=(0,module_resolver_1.valueResolverFor)(context);const builtBy=(0,instances_1.createInstanceResolver)(context);const handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");const requests=new Map;const candidates=[];const calls=[];function isHttpApp(node){const app=builtBy(node);return app!==void 0&&HTTP_APPS[app.module]===app.path.join(".")}function noteRequestHandlers(node,scope){if(node.callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method==="setRequestHandler"){const[schema,handler]=node.arguments;if((0,eslint_devkit_1.staticString)(schema)===null&&(schema===void 0||(0,tool_handlers_1.mcpExport)(schema,scope)===void 0))return;const fn=(0,tool_registration_1.resolveFunction)(handler,scope);if(fn)requests.set(fn,PARAMS_ROOT);return}if(!ROUTE_METHODS.has(method??"")||!isHttpApp(node.callee.object))return;for(const arg of node.arguments){const fn=(0,tool_registration_1.resolveFunction)(arg,scope);if(fn)requests.set(fn,REQUEST_ROOT)}}function sourceCall(node,scope,follow){if((0,http_clients_1.httpRequestOf)(node,scope,builtBy))return{kind:"object",text:"",toArgs:[]};const fsName=(0,fs_module_1.fsExport)(node.callee,scope);if(fsName!==void 0)return FILE_READS.has(fsName)&&!isPackagePath(node.arguments[0],n=>sourceCode.getScope(n))?{kind:"value",text:`${fsName}()`,key:void 0}:null;if(node.callee.type!=="MemberExpression")return void 0;const method=(0,eslint_devkit_1.propertyName)(node.callee);const object=node.callee.object;if(method==="parse"&&object.type==="Identifier"&&object.name==="JSON"&&!(0,tool_registration_1.lookupVariable)("JSON",scope)?.defs.length){const t=node.arguments[0]&&follow(node.arguments[0]);return t?{kind:"object",text:t.text,toArgs:[]}:null}if(method===null||!BODY_READERS.has(method))return void 0;const receiver=follow(object);return receiver&&{kind:"object",text:receiver.text,toArgs:[]}}function importedSource(node){const resolved=(0,module_resolver_1.resolveValue)(node,(0,module_resolver_1.siteOf)(context,node),{parser,depth:0});if(resolved.kind!=="value"||resolved.site.file===context.filename)return void 0;let value=resolved.node;while(value.type==="AwaitExpression")value=value.argument;if(value.type!=="CallExpression")return void 0;const fsName=(0,fs_module_1.fsExport)(value.callee,resolved.site.scope);const scopeOf=n=>(0,module_resolver_1.scopeAt)(resolved.site.scope,n);return fsName!==void 0&&FILE_READS.has(fsName)&&!isPackagePath(value.arguments[0],scopeOf)?{kind:"value",text:node.name,key:void 0}:void 0}return{CallExpression(node){const scope=sourceCode.getScope(node);handlers.visit(node);noteRequestHandlers(node,scope);calls.push(node);candidates.push(...registrationTexts(node,resolve,{site:(0,module_resolver_1.siteOf)(context,node),parser}))},"Program:exit"(){const carries=(0,value_flow_1.createFlow)(sourceCode,fn=>handlers.roots.get(fn)??requests.get(fn),(node,follow)=>{if(node.type==="Identifier")return importedSource(node);return node.type==="CallExpression"?sourceCall(node,sourceCode.getScope(node),follow):void 0},{...(0,value_flow_1.flowOptionsFor)(context),followCallers:false});const value=node=>{const t=carries(node);return t?.kind==="value"?t:null};for(const{value:node,messageId,data}of candidates){const taint=value(node);if(taint)context.report({node,messageId,data:{...data,source:taint.text}})}const along=(node,path)=>{let current=(0,module_resolver_1.unwrapTypeOnly)(node);if(current.type==="Identifier"){const init=(0,tool_registration_1.constInitializer)(current,sourceCode.getScope(current));if(init?.type==="ObjectExpression"||init?.type==="TSTypeAssertion")current=(0,module_resolver_1.unwrapTypeOnly)(init)}if(path.length>0&&current.type==="ObjectExpression"){const prop=current.properties.find(p=>p.type==="Property"&&(0,tool_registration_1.propertyKey)(p)===path[0]);return prop?along(prop.value,path.slice(1)):null}let taint=carries(current);for(const key of path)taint=taint&&(0,value_flow_1.memberStep)(taint,key);return taint?.kind==="value"?taint:null};const forwards=new Map;for(const call of calls){const target=(0,module_resolver_1.resolveCalleeFunction)(call.callee,(0,module_resolver_1.siteOf)(context,call),parser);if(target===void 0)continue;let list=forwards.get(target.fn);if(list===void 0){list=forwardsOf(target,target.site.file===context.filename?node=>sourceCode.getScope(node):node=>(0,module_resolver_1.scopeAt)(target.site.scope,node));forwards.set(target.fn,list)}for(const{index,path,messageId,data}of list){const arg=call.arguments[index];const taint=arg&&along(arg,path);if(taint)context.report({node:arg,messageId,data:{...data,source:taint.text}})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noToolDescriptionInjection=void 0;exports.textKind=textKind;exports.isStaticText=isStaticText;exports.modelFacingProperties=modelFacingProperties;const eslint_devkit_1=require("@interlace/eslint-devkit");const fs_module_1=require("../../utils/fs-module");const http_clients_1=require("../../utils/http-clients");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const MODEL_FACING_KEYS=["description","title"];const METADATA_CONFIG_INDEX=new Map([["registerPrompt",[1,"prompt"]],["registerResource",[2,"resource"]]]);function combine(kinds){if(kinds.includes("dynamic"))return"dynamic";return kinds.includes("unknown")?"unknown":"static"}function textKind(node,env,depth=0){node=(0,module_resolver_1.unwrapTypeOnly)(node);switch(node.type){case"Literal":return typeof node.value==="string"?"static":"dynamic";case"TemplateLiteral":return combine(node.expressions.map(e=>textKind(e,env,depth+1)));case"TaggedTemplateExpression":return combine(node.quasi.expressions.map(e=>textKind(e,env,depth+1)));case"BinaryExpression":return node.operator==="+"?combine([textKind(node.left,env,depth+1),textKind(node.right,env,depth+1)]):"dynamic";case"CallExpression":return joinKind(node,env,depth);case"Identifier":case"MemberExpression":{if(env===void 0)return"dynamic";const resolved=(0,module_resolver_1.resolveValue)(node,env.site,{parser:env.parser,depth});if(resolved.kind==="unknown")return"unknown";if(resolved.kind!=="value")return"dynamic";return textKind(resolved.node,{...env,site:resolved.site},depth+1)}default:return"dynamic"}}function joinKind(node,env,depth){if(node.callee.type!=="MemberExpression")return"dynamic";if((0,eslint_devkit_1.propertyName)(node.callee)!=="join")return"dynamic";const array=node.callee.object;if(array.type!=="ArrayExpression")return"dynamic";if(node.arguments.length>1)return"dynamic";const parts=node.arguments.map(a=>textKind(a,env,depth+1));for(const element of array.elements){if(element===null||element.type==="SpreadElement")return"dynamic";parts.push(textKind(element,env,depth+1))}return combine(parts)}function isStaticText(node){return textKind(node)==="static"}function modelFacingProperties(config,env){const found=[];for(const prop of config.properties){if(prop.type!=="Property"||prop.computed)continue;const key=prop.key.type==="Identifier"?prop.key.name:(0,eslint_devkit_1.staticString)(prop.key)??void 0;if(key===void 0)continue;if(!MODEL_FACING_KEYS.includes(key))continue;if(textKind(prop.value,env)!=="dynamic")continue;found.push({key,value:prop.value})}return found}const FILE_READS=new Set(["readFile","readFileSync"]);const BODY_READERS=new Set(["json","text"]);const HTTP_APPS={express:"",hono:"Hono",fastify:""};const ROUTE_METHODS=new Set(["get","post","put","patch","delete","all","route","on"]);const PATH_BUILDERS=new Set(["join","resolve"]);function isPackagePath(node,scopeOf,depth=0){if(node===void 0||depth>8)return false;const value=(0,module_resolver_1.unwrapTypeOnly)(node);const anchored=n=>isPackagePath(n,scopeOf,depth+1);switch(value.type){case"Identifier":{if(value.name==="__dirname"||value.name==="__filename")return!(0,tool_registration_1.lookupVariable)(value.name,scopeOf(value))?.defs.length;return anchored((0,tool_registration_1.constInitializer)(value,scopeOf(value)))}case"MemberExpression":return value.object.type==="MetaProperty";case"TemplateLiteral":return value.quasis[0].value.raw===""&&value.expressions.length===1&&anchored(value.expressions[0]);case"NewExpression":return value.callee.type==="Identifier"&&value.callee.name==="URL"&&!(0,tool_registration_1.lookupVariable)("URL",scopeOf(value))?.defs.length&&value.arguments.length===2&&(0,eslint_devkit_1.staticString)(value.arguments[0])!==null&&anchored(value.arguments[1]);case"CallExpression":{const binding=(0,eslint_devkit_1.resolveModuleBinding)(value.callee,scopeOf(value));const[first,...rest]=value.arguments;if(binding?.module==="url")return binding.path.join(".")==="fileURLToPath"&&anchored(first);return binding?.module==="path"&&PATH_BUILDERS.has(binding.path[binding.path.length-1]??"")&&anchored(first)&&rest.every(part=>(0,eslint_devkit_1.staticString)(part)!==null)}default:return false}}const REQUEST_ROOT={toArgs:[],closed:new Set};const PARAMS_ROOT={toArgs:["params"],closed:new Set};function registrationTexts(node,resolve,env){const tool=(0,tool_registration_1.toolNameOf)(node);const texts=[];const registration=(0,tool_registration_1.readRegistration)(node,resolve);if(registration!==void 0){const objects=[];if(registration.config)objects.push(registration.config);if(registration.annotations&&(0,tool_registration_1.classifyLegacyObject)(registration.annotations,resolve)!=="shape")objects.push(registration.annotations);for(const config2 of objects)for(const{key,value}of modelFacingProperties(config2,env))texts.push({value,messageId:"dynamicDescription",data:{tool,key}});if(registration.description&&textKind(registration.description,env)!=="static")texts.push({value:registration.description,messageId:"dynamicDescription",data:{tool,key:"description"}});return texts}const method=(0,tool_registration_1.calledMethod)(node);const slot=method===null?void 0:METADATA_CONFIG_INDEX.get(method);if(slot===void 0)return texts;const[index,kind]=slot;const config=node.arguments[index];if(config?.type!=="ObjectExpression")return texts;for(const{key,value}of modelFacingProperties(config,env))texts.push({value,messageId:"dynamicMetadata",data:{kind,name:tool,key}});return texts}function pathInPattern(pattern,target){if(pattern===target)return[];if(pattern.type==="AssignmentPattern")return pathInPattern(pattern.left,target);if(pattern.type!=="ObjectPattern")return void 0;for(const prop of pattern.properties){const key=(0,tool_registration_1.propertyKey)(prop);if(key===void 0)continue;const rest=pathInPattern(prop.value,target);if(rest)return[key,...rest]}return void 0}function paramPath(node,target,scopeOf,depth=0){if(depth>8)return void 0;const value=(0,module_resolver_1.unwrapTypeOnly)(node);if(value.type==="MemberExpression"){const key=(0,eslint_devkit_1.propertyName)(value);const base2=key===null?void 0:paramPath(value.object,target,scopeOf,depth+1);return base2&&{index:base2.index,path:[...base2.path,key]}}if(value.type==="TemplateLiteral"){for(const expression of value.expressions){const found=paramPath(expression,target,scopeOf,depth+1);if(found)return found}return void 0}if(value.type!=="Identifier")return void 0;const def=(0,tool_registration_1.lookupVariable)(value.name,scopeOf(value))?.defs[0];if(def?.type==="Parameter"&&def.node===target.fn){const index=target.fn.params.findIndex(param=>pathInPattern(param,def.name)!==void 0);if(index<0)return void 0;return{index,path:pathInPattern(target.fn.params[index],def.name)}}if(def?.type!=="Variable"||def.node.init===null)return void 0;const base=paramPath(def.node.init,target,scopeOf,depth+1);const rest=base&&pathInPattern(def.node.id,def.name);return rest&&{index:base.index,path:[...base.path,...rest]}}function forwardsOf(target,scopeOf){const found=[];const visit=node=>{if(node.type==="CallExpression")for(const text of registrationTexts(node)){const from=paramPath(text.value,target,scopeOf);if(from)found.push({...text,...from})}for(const[key,child]of Object.entries(node)){if(key==="parent")continue;for(const item of Array.isArray(child)?child:[child])if(item&&typeof item==="object"&&typeof item.type==="string")visit(item)}};visit(target.fn.body);return found}exports.noToolDescriptionInjection=(0,eslint_devkit_1.createRule)({name:"no-tool-description-injection",meta:{interop:{runtimes:["eslint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-tool-description-injection.md",description:"Disallow MCP tool, prompt and resource descriptions built from text a client, a remote service or a file controls",cwe:"CWE-1427",cvss:8.6},messages:{dynamicDescription:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Description From Untrusted Text",cwe:"CWE-1427",owasp:"A03:2021",cvss:8.6,description:'The `{{key}}` for tool "{{tool}}" is built from `{{source}}` \u2014 text a client, a remote service or a file controls \u2014 so whoever controls it writes part of the model\'s instructions',severity:"HIGH",compliance:["SOC2"],fix:"Write the {{key}} in code. If it must vary, choose among fixed texts the server owns (a map keyed by a validated enum) rather than interpolating the value \u2014 it lands in the model's instruction block, so whoever controls it controls the instructions.",documentationLink:"https://modelcontextprotocol.io/docs/concepts/tools"}),dynamicMetadata:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Prompt/Resource Description From Untrusted Text",cwe:"CWE-1427",owasp:"A03:2021",cvss:8.6,description:'The `{{key}}` for {{kind}} "{{name}}" is built from `{{source}}` \u2014 text a client, a remote service or a file controls \u2014 so whoever controls it writes what the model reads',severity:"HIGH",compliance:["SOC2"],fix:"Write the {{key}} in code, or choose among fixed texts the server owns; keep client- or file-supplied text in the resource CONTENTS, not its description.",documentationLink:"https://modelcontextprotocol.io/docs/concepts/prompts"})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;let parser;let resolve;let builtBy;let handlers;let requests;let candidates;let calls;function isHttpApp(node){const app=builtBy(node);return app!==void 0&&HTTP_APPS[app.module]===app.path.join(".")}function noteRequestHandlers(node,scope){if(node.callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method==="setRequestHandler"){const[schema,handler]=node.arguments;if((0,eslint_devkit_1.staticString)(schema)===null&&(schema===void 0||(0,tool_handlers_1.mcpExport)(schema,scope)===void 0))return;const fn=(0,tool_registration_1.resolveFunction)(handler,scope);if(fn)requests.set(fn,PARAMS_ROOT);return}if(!ROUTE_METHODS.has(method??"")||!isHttpApp(node.callee.object))return;for(const arg of node.arguments){const fn=(0,tool_registration_1.resolveFunction)(arg,scope);if(fn)requests.set(fn,REQUEST_ROOT)}}function sourceCall(node,scope,follow){if((0,http_clients_1.httpRequestOf)(node,scope,builtBy))return{kind:"object",text:"",toArgs:[]};const fsName=(0,fs_module_1.fsExport)(node.callee,scope);if(fsName!==void 0)return FILE_READS.has(fsName)&&!isPackagePath(node.arguments[0],n=>sourceCode.getScope(n))?{kind:"value",text:`${fsName}()`,key:void 0}:null;if(node.callee.type!=="MemberExpression")return void 0;const method=(0,eslint_devkit_1.propertyName)(node.callee);const object=node.callee.object;if(method==="parse"&&object.type==="Identifier"&&object.name==="JSON"&&!(0,tool_registration_1.lookupVariable)("JSON",scope)?.defs.length){const t=node.arguments[0]&&follow(node.arguments[0]);return t?{kind:"object",text:t.text,toArgs:[]}:null}if(method===null||!BODY_READERS.has(method))return void 0;const receiver=follow(object);return receiver&&{kind:"object",text:receiver.text,toArgs:[]}}function importedSource(node){const resolved=(0,module_resolver_1.resolveValue)(node,(0,module_resolver_1.siteOf)(context,node),{parser,depth:0});if(resolved.kind!=="value"||resolved.site.file===context.filename)return void 0;let value=resolved.node;while(value.type==="AwaitExpression")value=value.argument;if(value.type!=="CallExpression")return void 0;const fsName=(0,fs_module_1.fsExport)(value.callee,resolved.site.scope);const scopeOf=n=>(0,module_resolver_1.scopeAt)(resolved.site.scope,n);return fsName!==void 0&&FILE_READS.has(fsName)&&!isPackagePath(value.arguments[0],scopeOf)?{kind:"value",text:node.name,key:void 0}:void 0}return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;sourceCode=context.sourceCode;parser=(0,module_resolver_1.activeParser)(context);resolve=(0,module_resolver_1.valueResolverFor)(context);builtBy=(0,instances_1.createInstanceResolver)(context);handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");requests=new Map;candidates=[];calls=[];return true},CallExpression(node){const scope=sourceCode.getScope(node);handlers.visit(node);noteRequestHandlers(node,scope);calls.push(node);candidates.push(...registrationTexts(node,resolve,{site:(0,module_resolver_1.siteOf)(context,node),parser}))},"Program:exit"(){const carries=(0,value_flow_1.createFlow)(sourceCode,fn=>handlers.roots.get(fn)??requests.get(fn),(node,follow)=>{if(node.type==="Identifier")return importedSource(node);return node.type==="CallExpression"?sourceCall(node,sourceCode.getScope(node),follow):void 0},{...(0,value_flow_1.flowOptionsFor)(context),followCallers:false});const value=node=>{const t=carries(node);return t?.kind==="value"?t:null};for(const{value:node,messageId,data}of candidates){const taint=value(node);if(taint)context.report({node,messageId,data:{...data,source:taint.text}})}const along=(node,path)=>{let current=(0,module_resolver_1.unwrapTypeOnly)(node);if(current.type==="Identifier"){const init=(0,tool_registration_1.constInitializer)(current,sourceCode.getScope(current));if(init?.type==="ObjectExpression"||init?.type==="TSTypeAssertion")current=(0,module_resolver_1.unwrapTypeOnly)(init)}if(path.length>0&&current.type==="ObjectExpression"){const prop=current.properties.find(p=>p.type==="Property"&&(0,tool_registration_1.propertyKey)(p)===path[0]);return prop?along(prop.value,path.slice(1)):null}let taint=carries(current);for(const key of path)taint=taint&&(0,value_flow_1.memberStep)(taint,key);return taint?.kind==="value"?taint:null};const forwards=new Map;for(const call of calls){const target=(0,module_resolver_1.resolveCalleeFunction)(call.callee,(0,module_resolver_1.siteOf)(context,call),parser);if(target===void 0)continue;let list=forwards.get(target.fn);if(list===void 0){list=forwardsOf(target,target.site.file===context.filename?node=>sourceCode.getScope(node):node=>(0,module_resolver_1.scopeAt)(target.site.scope,node));forwards.set(target.fn,list)}for(const{index,path,messageId,data}of list){const arg=call.arguments[index];const taint=arg&&along(arg,path);if(taint)context.report({node:arg,messageId,data:{...data,source:taint.text}})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUntrustedStdioCommand=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const http_clients_1=require("../../utils/http-clients");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const SHELLS=new Set(["sh","bash","zsh","cmd","cmd.exe","powershell","pwsh"]);const SHELL_SCRIPT_FLAGS=new Set(["-c","-lc","/c","/C","-Command","-command"]);const RUNNERS=new Set(["npx","uvx","bunx","pnpx","pipx"]);const FILE_READS=new Set(["readFile","readFileSync"]);const PATH_BUILDERS=new Set(["join","resolve"]);const OBJECT_VIEWS=new Set(["entries","values","keys"]);const ELEMENT_CALLBACKS=new Set(["forEach","map","flatMap"]);const BODY_READERS=new Map([["json","object"],["text","value"]]);const SOURCES=["tool argument","network response","project config file"];function isAbsoluteSpelling(text){return/^(?:[/~\\]|[A-Za-z]:)/.test(text)}function untrusted(t){return t!==null&&(t.kind==="value"||t.toArgs.length===0)}function isGlobal(node,name,scope){return node.type==="Identifier"&&node.name===name&&!(0,tool_registration_1.lookupVariable)(name,scope)?.defs.length}function fieldOf(options,key){let found;for(const prop of options.properties){if(prop.type==="SpreadElement")found={node:prop.argument,via:key};else if((0,tool_registration_1.propertyKey)(prop)===key)found={node:prop.value}}return found}exports.noUntrustedStdioCommand=(0,eslint_devkit_1.createRule)({name:"no-untrusted-stdio-command",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-untrusted-stdio-command.md",description:"Disallow an MCP client spawning a stdio server whose command comes from a tool argument, a network response or a project config file",cwe:"CWE-78",cvss:8.8},messages:{untrustedStdioCommand:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Untrusted MCP Stdio Server Command",cwe:"CWE-78",owasp:"A03:2021",cvss:8.8,description:"The {{position}} of this StdioClientTransport comes from a {{source}} (`{{value}}`), so whoever writes that data chooses the process this client starts on the host",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Map the untrusted value to a server through a fixed allowlist the code owns (`ALLOWED[name]`); never pass it as the command, a shell script or a runner package. Read server definitions from the user\u2019s own config (under `os.homedir()`), or ask the user to approve each new or changed server before spawning it.",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const resolve=(0,module_resolver_1.valueResolverFor)(context);const builtBy=(0,instances_1.createInstanceResolver)(context);const handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");const transports=[];function local(node){if(node.type!=="Identifier"&&node.type!=="MemberExpression")return node;const value=resolve(node);let root=value;while(root?.parent)root=root.parent;return root===sourceCode.ast?value:void 0}function isCwd(node){return node?.type==="CallExpression"&&node.arguments.length===0&&node.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node.callee)==="cwd"&&isGlobal(node.callee.object,"process",sourceCode.getScope(node))}function isStaticRelative(node){const text=(0,eslint_devkit_1.staticString)(node);return text!==null&&!isAbsoluteSpelling(text)}function isProjectPath(node){if(node===void 0)return false;if(isStaticRelative(node))return true;if(node.type==="TemplateLiteral")return node.quasis[0].value.raw===""&&isCwd(node.expressions[0]);if(node.type==="CallExpression"){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,sourceCode.getScope(node));const[first,...rest]=node.arguments;return binding?.module==="path"&&PATH_BUILDERS.has(binding.path[binding.path.length-1]??"")&&first!==void 0&&(isCwd(first)||isStaticRelative(first))&&rest.every(isStaticRelative)}const value=local(node);return value!==void 0&&value!==node&&isProjectPath(value)}function fsExport(callee){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));if(binding?.module!=="fs"&&binding?.module!=="fs/promises")return void 0;const path=binding.path[0]==="promises"?binding.path.slice(1):binding.path;return path.length===1?path[0]:void 0}function ofElement(node,follow){const def=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node))?.defs[0];let pattern;let iterated;if(def?.type==="Variable"&&def.parent.parent.type==="ForOfStatement"&&def.parent.parent.left===def.parent){pattern=def.node.id;iterated=def.parent.parent.right}else if(def?.type==="Parameter"){const fn=def.node;const call=fn.parent;if(call?.type!=="CallExpression"||call.arguments[0]!==fn||call.callee.type!=="MemberExpression"||!ELEMENT_CALLBACKS.has((0,eslint_devkit_1.propertyName)(call.callee)??""))return void 0;pattern=fn.params[0];iterated=call.callee.object}else{return void 0}const element=follow(iterated);const t=(0,value_flow_1.throughPattern)(pattern,def.name,untrusted(element)?element:null);return t?{...t,text:node.name}:null}function interceptFor(source){return(node,follow)=>{if(node.type==="Identifier")return ofElement(node,follow);if(node.type!=="CallExpression")return void 0;const scope=sourceCode.getScope(node);const{callee}=node;const arg=node.arguments[0];if(callee.type==="MemberExpression"){const method=(0,eslint_devkit_1.propertyName)(callee)??"";if(method==="parse"&&isGlobal(callee.object,"JSON",scope)){const t=arg?follow(arg):null;return untrusted(t)?{kind:"object",text:`JSON.parse(${t.text})`,toArgs:[]}:null}if(OBJECT_VIEWS.has(method)&&isGlobal(callee.object,"Object",scope)){const t=arg?follow(arg):null;return untrusted(t)?{kind:"value",text:`Object.${method}(${t.text})`,key:void 0}:null}const kind=BODY_READERS.get(method);if(kind!==void 0){const t=follow(callee.object);if(!untrusted(t))return null;const text=`${t.text}.${method}()`;return kind==="object"?{kind,text,toArgs:[]}:{kind,text,key:void 0}}}if(source==="network response"){const request=(0,http_clients_1.httpRequestOf)(node,scope,builtBy);if(request!==void 0)return{kind:"object",text:`${request.client}()`,toArgs:[]}}if(source==="project config file"){const name=fsExport(callee);if(name!==void 0)return FILE_READS.has(name)&&isProjectPath(arg)?{kind:"value",text:`${name}()`,key:void 0}:null}const helper=(0,tool_registration_1.resolveFunction)(callee,scope);if(helper===void 0)return void 0;for(const expression of(0,value_flow_1.returnedExpressions)(helper)){const t=follow(expression);if(t?.kind==="object"&&untrusted(t))return t}return void 0}}return{CallExpression(node){handlers.visit(node)},NewExpression(node){if((0,tool_handlers_1.mcpExport)(node.callee,sourceCode.getScope(node))==="StdioClientTransport")transports.push(node)},"Program:exit"(){const roots=fn=>handlers.roots.get(fn);const flows=SOURCES.map(source=>({source,carries:(0,value_flow_1.createFlow)(sourceCode,source==="tool argument"?roots:()=>void 0,interceptFor(source),(0,value_flow_1.flowOptionsFor)(context))}));function check(field,position){for(const{source,carries}of flows){let t=carries(field.node);if(t&&field.via!==void 0)t=(0,value_flow_1.memberStep)(t,field.via);if(t?.kind!=="value")continue;context.report({node:field.node,messageId:"untrustedStdioCommand",data:{source,value:t.text,position}});return}}function checkArgs(field,name,isShell){const array=field.via===void 0?local(field.node):void 0;if(array?.type!=="ArrayExpression"){check(field,isShell?`\`${name}\` script`:`\`${name}\` package`);return}const elements=array.elements.map(el=>el?.type==="SpreadElement"?el.argument:el);if(isShell){const flag=elements.findIndex(el=>SHELL_SCRIPT_FLAGS.has((0,eslint_devkit_1.staticString)(el)??""));if(flag===-1)return;const label=`\`${name} ${(0,eslint_devkit_1.staticString)(elements[flag])}\` script`;for(const el of elements.slice(flag+1))if(el)check({node:el},label);return}let rest=elements.filter(el=>el!==null);if(name==="pipx"&&(0,eslint_devkit_1.staticString)(rest[0])==="run")rest=rest.slice(1);const pkg=rest.find(el=>!(0,eslint_devkit_1.staticString)(el)?.startsWith("-"));if(pkg)check({node:pkg},`\`${name}\` package`)}for(const transport of transports){const options=transport.arguments[0];if(options===void 0)continue;const object=local(options);if(object?.type!=="ObjectExpression"){check({node:options,via:"command"},"command");continue}const command=fieldOf(object,"command");if(command===void 0)continue;check(command,"command");const bin=command.via===void 0?local(command.node):void 0;const text=bin&&(0,eslint_devkit_1.staticString)(bin);if(!text)continue;const name=text.split(/[\\/]/).pop();const isShell=SHELLS.has(name);const args=fieldOf(object,"args");if((isShell||RUNNERS.has(name))&&args!==void 0)checkArgs(args,name,isShell)}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUntrustedStdioCommand=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const http_clients_1=require("../../utils/http-clients");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const SHELLS=new Set(["sh","bash","zsh","cmd","cmd.exe","powershell","pwsh"]);const SHELL_SCRIPT_FLAGS=new Set(["-c","-lc","/c","/C","-Command","-command"]);const RUNNERS=new Set(["npx","uvx","bunx","pnpx","pipx"]);const FILE_READS=new Set(["readFile","readFileSync"]);const PATH_BUILDERS=new Set(["join","resolve"]);const OBJECT_VIEWS=new Set(["entries","values","keys"]);const ELEMENT_CALLBACKS=new Set(["forEach","map","flatMap"]);const BODY_READERS=new Map([["json","object"],["text","value"]]);const SOURCES=["tool argument","network response","project config file"];function isAbsoluteSpelling(text){return/^(?:[/~\\]|[A-Za-z]:)/.test(text)}function untrusted(t){return t!==null&&(t.kind==="value"||t.toArgs.length===0)}function isGlobal(node,name,scope){return node.type==="Identifier"&&node.name===name&&!(0,tool_registration_1.lookupVariable)(name,scope)?.defs.length}function fieldOf(options,key){let found;for(const prop of options.properties){if(prop.type==="SpreadElement")found={node:prop.argument,via:key};else if((0,tool_registration_1.propertyKey)(prop)===key)found={node:prop.value}}return found}exports.noUntrustedStdioCommand=(0,eslint_devkit_1.createRule)({name:"no-untrusted-stdio-command",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-untrusted-stdio-command.md",description:"Disallow an MCP client spawning a stdio server whose command comes from a tool argument, a network response or a project config file",cwe:"CWE-78",cvss:8.8},messages:{untrustedStdioCommand:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Untrusted MCP Stdio Server Command",cwe:"CWE-78",owasp:"A03:2021",cvss:8.8,description:"The {{position}} of this StdioClientTransport comes from a {{source}} (`{{value}}`), so whoever writes that data chooses the process this client starts on the host",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Map the untrusted value to a server through a fixed allowlist the code owns (`ALLOWED[name]`); never pass it as the command, a shell script or a runner package. Read server definitions from the user\u2019s own config (under `os.homedir()`), or ask the user to approve each new or changed server before spawning it.",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices"})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;let resolve;let builtBy;let handlers;let transports;function local(node){if(node.type!=="Identifier"&&node.type!=="MemberExpression")return node;const value=resolve(node);let root=value;while(root?.parent)root=root.parent;return root===sourceCode.ast?value:void 0}function isCwd(node){return node?.type==="CallExpression"&&node.arguments.length===0&&node.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node.callee)==="cwd"&&isGlobal(node.callee.object,"process",sourceCode.getScope(node))}function isStaticRelative(node){const text=(0,eslint_devkit_1.staticString)(node);return text!==null&&!isAbsoluteSpelling(text)}function isProjectPath(node){if(node===void 0)return false;if(isStaticRelative(node))return true;if(node.type==="TemplateLiteral")return node.quasis[0].value.raw===""&&isCwd(node.expressions[0]);if(node.type==="CallExpression"){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,sourceCode.getScope(node));const[first,...rest]=node.arguments;return binding?.module==="path"&&PATH_BUILDERS.has(binding.path[binding.path.length-1]??"")&&first!==void 0&&(isCwd(first)||isStaticRelative(first))&&rest.every(isStaticRelative)}const value=local(node);return value!==void 0&&value!==node&&isProjectPath(value)}function fsExport(callee){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));if(binding?.module!=="fs"&&binding?.module!=="fs/promises")return void 0;const path=binding.path[0]==="promises"?binding.path.slice(1):binding.path;return path.length===1?path[0]:void 0}function ofElement(node,follow){const def=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node))?.defs[0];let pattern;let iterated;if(def?.type==="Variable"&&def.parent.parent.type==="ForOfStatement"&&def.parent.parent.left===def.parent){pattern=def.node.id;iterated=def.parent.parent.right}else if(def?.type==="Parameter"){const fn=def.node;const call=fn.parent;if(call?.type!=="CallExpression"||call.arguments[0]!==fn||call.callee.type!=="MemberExpression"||!ELEMENT_CALLBACKS.has((0,eslint_devkit_1.propertyName)(call.callee)??""))return void 0;pattern=fn.params[0];iterated=call.callee.object}else{return void 0}const element=follow(iterated);const t=(0,value_flow_1.throughPattern)(pattern,def.name,untrusted(element)?element:null);return t?{...t,text:node.name}:null}function interceptFor(source){return(node,follow)=>{if(node.type==="Identifier")return ofElement(node,follow);if(node.type!=="CallExpression")return void 0;const scope=sourceCode.getScope(node);const{callee}=node;const arg=node.arguments[0];if(callee.type==="MemberExpression"){const method=(0,eslint_devkit_1.propertyName)(callee)??"";if(method==="parse"&&isGlobal(callee.object,"JSON",scope)){const t=arg?follow(arg):null;return untrusted(t)?{kind:"object",text:`JSON.parse(${t.text})`,toArgs:[]}:null}if(OBJECT_VIEWS.has(method)&&isGlobal(callee.object,"Object",scope)){const t=arg?follow(arg):null;return untrusted(t)?{kind:"value",text:`Object.${method}(${t.text})`,key:void 0}:null}const kind=BODY_READERS.get(method);if(kind!==void 0){const t=follow(callee.object);if(!untrusted(t))return null;const text=`${t.text}.${method}()`;return kind==="object"?{kind,text,toArgs:[]}:{kind,text,key:void 0}}}if(source==="network response"){const request=(0,http_clients_1.httpRequestOf)(node,scope,builtBy);if(request!==void 0)return{kind:"object",text:`${request.client}()`,toArgs:[]}}if(source==="project config file"){const name=fsExport(callee);if(name!==void 0)return FILE_READS.has(name)&&isProjectPath(arg)?{kind:"value",text:`${name}()`,key:void 0}:null}const helper=(0,tool_registration_1.resolveFunction)(callee,scope);if(helper===void 0)return void 0;for(const expression of(0,value_flow_1.returnedExpressions)(helper)){const t=follow(expression);if(t?.kind==="object"&&untrusted(t))return t}return void 0}}return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;sourceCode=context.sourceCode;resolve=(0,module_resolver_1.valueResolverFor)(context);builtBy=(0,instances_1.createInstanceResolver)(context);handlers=(0,tool_handlers_1.createHandlerCollector)(context,resolve,"arguments");transports=[];return true},CallExpression(node){handlers.visit(node)},NewExpression(node){if((0,tool_handlers_1.mcpExport)(node.callee,sourceCode.getScope(node))==="StdioClientTransport")transports.push(node)},"Program:exit"(){const roots=fn=>handlers.roots.get(fn);const flows=SOURCES.map(source=>({source,carries:(0,value_flow_1.createFlow)(sourceCode,source==="tool argument"?roots:()=>void 0,interceptFor(source),(0,value_flow_1.flowOptionsFor)(context))}));function check(field,position){for(const{source,carries}of flows){let t=carries(field.node);if(t&&field.via!==void 0)t=(0,value_flow_1.memberStep)(t,field.via);if(t?.kind!=="value")continue;context.report({node:field.node,messageId:"untrustedStdioCommand",data:{source,value:t.text,position}});return}}function checkArgs(field,name,isShell){const array=field.via===void 0?local(field.node):void 0;if(array?.type!=="ArrayExpression"){check(field,isShell?`\`${name}\` script`:`\`${name}\` package`);return}const elements=array.elements.map(el=>el?.type==="SpreadElement"?el.argument:el);if(isShell){const flag=elements.findIndex(el=>SHELL_SCRIPT_FLAGS.has((0,eslint_devkit_1.staticString)(el)??""));if(flag===-1)return;const label=`\`${name} ${(0,eslint_devkit_1.staticString)(elements[flag])}\` script`;for(const el of elements.slice(flag+1))if(el)check({node:el},label);return}let rest=elements.filter(el=>el!==null);if(name==="pipx"&&(0,eslint_devkit_1.staticString)(rest[0])==="run")rest=rest.slice(1);const pkg=rest.find(el=>!(0,eslint_devkit_1.staticString)(el)?.startsWith("-"));if(pkg)check({node:pkg},`\`${name}\` package`)}for(const transport of transports){const options=transport.arguments[0];if(options===void 0)continue;const object=local(options);if(object?.type!=="ObjectExpression"){check({node:options,via:"command"},"command");continue}const command=fieldOf(object,"command");if(command===void 0)continue;check(command,"command");const bin=command.via===void 0?local(command.node):void 0;const text=bin&&(0,eslint_devkit_1.staticString)(bin);if(!text)continue;const name=text.split(/[\\/]/).pop();const isShell=SHELLS.has(name);const args=fieldOf(object,"args");if((isShell||RUNNERS.has(name))&&args!==void 0)checkArgs(args,name,isShell)}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUntrustedToolMetadataInPrompt=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const LISTINGS=new Set(["listTools","listPrompts","listResources","listResourceTemplates"]);const ELEMENT_CALLBACKS=new Set(["map","flatMap","filter","forEach","find","some","every"]);const MAPPERS=new Set(["map","flatMap"]);const SELECTORS=new Set(["filter","find","slice","concat","reverse","sort","flat"]);const ELEMENT={toArgs:[],closed:new Set};const OBJECT_SPREADERS=new Set(["values","entries"]);const LLM_CLIENTS={"@anthropic-ai/sdk":new Set(["","Anthropic","default"]),openai:new Set(["","OpenAI","AzureOpenAI","default"]),"@google/genai":new Set(["GoogleGenAI"])};const LLM_METHODS=new Set(["create","stream","parse","generateContent","generateContentStream"]);const AI_SDK_FUNCTIONS=new Set(["generateText","streamText","generateObject","streamObject"]);const TOOL_FIELDS=new Set(["tools","functions","toolChoice","tool_choice"]);function llmCallOf(node,scope,builtBy){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding?.module==="ai"&&AI_SDK_FUNCTIONS.has(binding.path.join(".")))return binding.path.join(".");if(node.callee.type!=="MemberExpression")return void 0;const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method===null||!LLM_METHODS.has(method))return void 0;let receiver=node.callee.object;const path=[method];while(receiver.type==="MemberExpression"){path.unshift((0,eslint_devkit_1.propertyName)(receiver)??"?");receiver=receiver.object}const client=builtBy(receiver);return client!==void 0&&LLM_CLIENTS[client.module]?.has(client.path.join("."))===true?`${client.module} ${path.join(".")}`:void 0}exports.noUntrustedToolMetadataInPrompt=(0,eslint_devkit_1.createRule)({name:"no-untrusted-tool-metadata-in-prompt",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-untrusted-tool-metadata-in-prompt.md",description:"Disallow an MCP client writing a server's tool, prompt or resource metadata into an LLM prompt instead of its tool definitions",cwe:"CWE-1427",cvss:8.6},messages:{toolMetadataInPrompt:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Server Metadata Written into a Prompt",cwe:"CWE-1427",owasp:"A03:2021",cvss:8.6,description:"`{{source}}` \u2014 text an MCP server supplied about itself \u2014 reaches the `{{field}}` of `{{sink}}`, so a malicious or compromised MCP server writes instructions with the authority of this host\u2019s own prompt (tool poisoning)",severity:"HIGH",compliance:["SOC2"],fix:"Pass the server\u2019s tools through the LLM API\u2019s `tools` parameter (name, description, input schema) rather than writing them into `system` or a message. Pin and review tool descriptions per server, and show changes to the user before they reach the model.",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const builtBy=(0,instances_1.createInstanceResolver)(context);const sinks=[];return{CallExpression(node){const sink=llmCallOf(node,sourceCode.getScope(node),builtBy);if(sink!==void 0)sinks.push({call:node,sink})},"Program:exit"(){const mappers=new Set;const callbackRoot=fn=>{if(mappers.has(fn))return ELEMENT;const call=fn.parent;if(call?.type!=="CallExpression"||call.arguments[0]!==fn||call.callee.type!=="MemberExpression"||!ELEMENT_CALLBACKS.has((0,eslint_devkit_1.propertyName)(call.callee)??""))return void 0;return carries(call.callee.object)?ELEMENT:void 0};const carries=(0,value_flow_1.createFlow)(sourceCode,callbackRoot,(node,follow)=>{if(node.type==="Identifier"){const def=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node))?.defs[0];const loop=def?.parent?.parent;if(def?.type!=="Variable"||loop?.type!=="ForOfStatement"||loop.left!==def.parent)return void 0;const iterated=follow(loop.right);if(iterated===null)return null;const element=iterated.kind==="value"?iterated:{kind:"value",text:iterated.text,key:void 0};return(0,value_flow_1.throughPattern)(def.node.id,def.name,element)}if(node.type!=="CallExpression")return void 0;const callee=node.callee;if(callee.type!=="MemberExpression")return void 0;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return void 0;if(LISTINGS.has(method)){const client=builtBy(callee.object);return client!==void 0&&(0,mcp_evidence_1.isMcpModule)(client.module)&&client.path[client.path.length-1]==="Client"?{kind:"object",text:`${sourceCode.getText(callee.object)}.${method}()`,toArgs:[]}:void 0}if(OBJECT_SPREADERS.has(method)&&callee.object.type==="Identifier"&&callee.object.name==="Object"&&!(0,tool_registration_1.lookupVariable)("Object",sourceCode.getScope(node))?.defs.length){const arg=node.arguments[0];return arg===void 0?null:follow(arg)}const receiver=MAPPERS.has(method)||SELECTORS.has(method)?follow(callee.object):null;if(receiver===null)return void 0;if(SELECTORS.has(method))return receiver;const fn=(0,tool_registration_1.resolveFunction)(node.arguments[0],sourceCode.getScope(node));if(fn===void 0)return null;mappers.add(fn);for(const expression of(0,value_flow_1.returnedExpressions)(fn)){const t=follow(expression);if(t?.kind==="value")return t}return null},(0,value_flow_1.flowOptionsFor)(context));const taintIn=(node,depth)=>{if(depth>8)return null;if(node.type==="ObjectExpression"){for(const prop of node.properties){const value=prop.type==="Property"?prop.value:prop.argument;const found=taintIn(value,depth+1);if(found)return found}return null}if(node.type==="ArrayExpression"){for(const element of node.elements){const found=element&&taintIn(element,depth+1);if(found)return found}return null}if(node.type==="Identifier"){const def=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node))?.defs[0];const init=def?.type==="Variable"?def.node.init:null;if(init?.type==="ObjectExpression"||init?.type==="ArrayExpression")return taintIn(init,depth+1)}const taint=carries(node);return taint?.kind==="value"?{node,taint}:null};for(const{call,sink}of sinks){const options=call.arguments[0];if(options?.type!=="ObjectExpression")continue;for(const prop of options.properties){if(prop.type!=="Property")continue;const field=(0,eslint_devkit_1.objectKeyName)(prop);if(field===null||TOOL_FIELDS.has(field))continue;const found=taintIn(prop.value,0);if(found===null)continue;context.report({node:found.node,messageId:"toolMetadataInPrompt",data:{source:found.taint.text,field,sink}})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUntrustedToolMetadataInPrompt=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const tool_registration_1=require("../../utils/tool-registration");const value_flow_1=require("../../utils/value-flow");const LISTINGS=new Set(["listTools","listPrompts","listResources","listResourceTemplates"]);const ELEMENT_CALLBACKS=new Set(["map","flatMap","filter","forEach","find","some","every"]);const MAPPERS=new Set(["map","flatMap"]);const SELECTORS=new Set(["filter","find","slice","concat","reverse","sort","flat"]);const ELEMENT={toArgs:[],closed:new Set};const OBJECT_SPREADERS=new Set(["values","entries"]);const LLM_CLIENTS={"@anthropic-ai/sdk":new Set(["","Anthropic","default"]),openai:new Set(["","OpenAI","AzureOpenAI","default"]),"@google/genai":new Set(["GoogleGenAI"])};const LLM_METHODS=new Set(["create","stream","parse","generateContent","generateContentStream"]);const AI_SDK_FUNCTIONS=new Set(["generateText","streamText","generateObject","streamObject"]);const TOOL_FIELDS=new Set(["tools","functions","toolChoice","tool_choice"]);function llmCallOf(node,scope,builtBy){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding?.module==="ai"&&AI_SDK_FUNCTIONS.has(binding.path.join(".")))return binding.path.join(".");if(node.callee.type!=="MemberExpression")return void 0;const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method===null||!LLM_METHODS.has(method))return void 0;let receiver=node.callee.object;const path=[method];while(receiver.type==="MemberExpression"){path.unshift((0,eslint_devkit_1.propertyName)(receiver)??"?");receiver=receiver.object}const client=builtBy(receiver);return client!==void 0&&LLM_CLIENTS[client.module]?.has(client.path.join("."))===true?`${client.module} ${path.join(".")}`:void 0}exports.noUntrustedToolMetadataInPrompt=(0,eslint_devkit_1.createRule)({name:"no-untrusted-tool-metadata-in-prompt",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-untrusted-tool-metadata-in-prompt.md",description:"Disallow an MCP client writing a server's tool, prompt or resource metadata into an LLM prompt instead of its tool definitions",cwe:"CWE-1427",cvss:8.6},messages:{toolMetadataInPrompt:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Server Metadata Written into a Prompt",cwe:"CWE-1427",owasp:"A03:2021",cvss:8.6,description:"`{{source}}` \u2014 text an MCP server supplied about itself \u2014 reaches the `{{field}}` of `{{sink}}`, so a malicious or compromised MCP server writes instructions with the authority of this host\u2019s own prompt (tool poisoning)",severity:"HIGH",compliance:["SOC2"],fix:"Pass the server\u2019s tools through the LLM API\u2019s `tools` parameter (name, description, input schema) rather than writing them into `system` or a message. Pin and review tool descriptions per server, and show changes to the user before they reach the model.",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/security_best_practices"})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;let builtBy;let sinks;return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;sourceCode=context.sourceCode;builtBy=(0,instances_1.createInstanceResolver)(context);sinks=[];return true},CallExpression(node){const sink=llmCallOf(node,sourceCode.getScope(node),builtBy);if(sink!==void 0)sinks.push({call:node,sink})},"Program:exit"(){const mappers=new Set;const callbackRoot=fn=>{if(mappers.has(fn))return ELEMENT;const call=fn.parent;if(call?.type!=="CallExpression"||call.arguments[0]!==fn||call.callee.type!=="MemberExpression"||!ELEMENT_CALLBACKS.has((0,eslint_devkit_1.propertyName)(call.callee)??""))return void 0;return carries(call.callee.object)?ELEMENT:void 0};const carries=(0,value_flow_1.createFlow)(sourceCode,callbackRoot,(node,follow)=>{if(node.type==="Identifier"){const def=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node))?.defs[0];const loop=def?.parent?.parent;if(def?.type!=="Variable"||loop?.type!=="ForOfStatement"||loop.left!==def.parent)return void 0;const iterated=follow(loop.right);if(iterated===null)return null;const element=iterated.kind==="value"?iterated:{kind:"value",text:iterated.text,key:void 0};return(0,value_flow_1.throughPattern)(def.node.id,def.name,element)}if(node.type!=="CallExpression")return void 0;const callee=node.callee;if(callee.type!=="MemberExpression")return void 0;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return void 0;if(LISTINGS.has(method)){const client=builtBy(callee.object);return client!==void 0&&(0,mcp_evidence_1.isMcpModule)(client.module)&&client.path[client.path.length-1]==="Client"?{kind:"object",text:`${sourceCode.getText(callee.object)}.${method}()`,toArgs:[]}:void 0}if(OBJECT_SPREADERS.has(method)&&callee.object.type==="Identifier"&&callee.object.name==="Object"&&!(0,tool_registration_1.lookupVariable)("Object",sourceCode.getScope(node))?.defs.length){const arg=node.arguments[0];return arg===void 0?null:follow(arg)}const receiver=MAPPERS.has(method)||SELECTORS.has(method)?follow(callee.object):null;if(receiver===null)return void 0;if(SELECTORS.has(method))return receiver;const fn=(0,tool_registration_1.resolveFunction)(node.arguments[0],sourceCode.getScope(node));if(fn===void 0)return null;mappers.add(fn);for(const expression of(0,value_flow_1.returnedExpressions)(fn)){const t=follow(expression);if(t?.kind==="value")return t}return null},(0,value_flow_1.flowOptionsFor)(context));const taintIn=(node,depth)=>{if(depth>8)return null;if(node.type==="ObjectExpression"){for(const prop of node.properties){const value=prop.type==="Property"?prop.value:prop.argument;const found=taintIn(value,depth+1);if(found)return found}return null}if(node.type==="ArrayExpression"){for(const element of node.elements){const found=element&&taintIn(element,depth+1);if(found)return found}return null}if(node.type==="Identifier"){const def=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node))?.defs[0];const init=def?.type==="Variable"?def.node.init:null;if(init?.type==="ObjectExpression"||init?.type==="ArrayExpression")return taintIn(init,depth+1)}const taint=carries(node);return taint?.kind==="value"?{node,taint}:null};for(const{call,sink}of sinks){const options=call.arguments[0];if(options?.type!=="ObjectExpression")continue;for(const prop of options.properties){if(prop.type!=="Property")continue;const field=(0,eslint_devkit_1.objectKeyName)(prop);if(field===null||TOOL_FIELDS.has(field))continue;const found=taintIn(prop.value,0);if(found===null)continue;context.report({node:found.node,messageId:"toolMetadataInPrompt",data:{source:found.taint.text,field,sink}})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnvalidatedToolArgs=exports.propertyKey=void 0;exports.declaredSchemaKeys=declaredSchemaKeys;exports.destructuredArgNames=destructuredArgNames;const eslint_devkit_1=require("@interlace/eslint-devkit");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_registration_1=require("../../utils/tool-registration");Object.defineProperty(exports,"propertyKey",{enumerable:true,get:function(){return tool_registration_1.propertyKey}});function declaredSchemaKeys(config){const schema=(0,tool_registration_1.configSchema)(config);if(schema.kind!=="schema")return void 0;const read=(0,tool_registration_1.schemaFields)(schema.node);return read===void 0?void 0:new Set(read.fields.keys())}function destructuredArgNames(handler){if(handler.type!=="ArrowFunctionExpression"&&handler.type!=="FunctionExpression"&&handler.type!=="FunctionDeclaration"){return[]}const first=handler.params[0];if(first===void 0||first.type!=="ObjectPattern")return[];const found=[];for(const prop of first.properties){if(prop.type==="RestElement")continue;const key=(0,tool_registration_1.propertyKey)(prop);if(key===void 0)continue;found.push({name:key,node:prop})}return found}exports.noUnvalidatedToolArgs=(0,eslint_devkit_1.createRule)({name:"no-unvalidated-tool-args",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-unvalidated-tool-args.md",description:"Disallow a tool handler reading an argument its declared input schema does not include",cwe:"CWE-20",cvss:7.5},messages:{undeclaredArg:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Outside the Declared Schema",cwe:"CWE-20",owasp:"A03:2021",cvss:7.5,description:'Tool "{{tool}}" reads `{{arg}}`, which its inputSchema does not declare \u2014 so the value either arrives unvalidated or never arrives at all',severity:"HIGH",compliance:["SOC2"],fix:"Declare `{{arg}}` in the inputSchema with the type and constraints it needs, or stop reading it. A key the schema does not mention is one nothing validated.",documentationLink:"https://modelcontextprotocol.io/docs/concepts/tools"}),undeclaredArgPassthrough:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Passed Through Unvalidated",cwe:"CWE-20",owasp:"A03:2021",cvss:7.5,description:'Tool "{{tool}}" reads `{{arg}}`, which its inputSchema does not declare, and the schema is loose (passthrough) \u2014 so the value reaches the handler exactly as the model sent it',severity:"HIGH",compliance:["SOC2"],fix:"Declare `{{arg}}` in the inputSchema with the type and constraints it needs. A loose schema validates the declared keys and waves every other key through.",documentationLink:"https://modelcontextprotocol.io/docs/concepts/tools"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const resolve=(0,module_resolver_1.valueResolverFor)(context);const candidates=[];return{CallExpression(node){const registration=(0,tool_registration_1.readRegistration)(node,resolve);if(registration?.schema.kind!=="schema")return;const declared=(0,tool_registration_1.schemaFields)(registration.schema.node);if(declared===void 0)return;const handler=(0,tool_registration_1.resolveFunction)(registration.handler,context.sourceCode.getScope(node));if(handler===void 0)return;for(const read of destructuredArgNames(handler)){if(declared.fields.has(read.name))continue;candidates.push({node:read.node,tool:(0,tool_registration_1.toolNameOf)(node),arg:read.name,messageId:declared.loose?"undeclaredArgPassthrough":"undeclaredArg"})}},"Program:exit"(){for(const{node,tool,arg,messageId}of candidates){context.report({node,messageId,data:{tool,arg}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnvalidatedToolArgs=exports.propertyKey=void 0;exports.declaredSchemaKeys=declaredSchemaKeys;exports.destructuredArgNames=destructuredArgNames;const eslint_devkit_1=require("@interlace/eslint-devkit");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_registration_1=require("../../utils/tool-registration");Object.defineProperty(exports,"propertyKey",{enumerable:true,get:function(){return tool_registration_1.propertyKey}});function declaredSchemaKeys(config){const schema=(0,tool_registration_1.configSchema)(config);if(schema.kind!=="schema")return void 0;const read=(0,tool_registration_1.schemaFields)(schema.node);return read===void 0?void 0:new Set(read.fields.keys())}function destructuredArgNames(handler){if(handler.type!=="ArrowFunctionExpression"&&handler.type!=="FunctionExpression"&&handler.type!=="FunctionDeclaration"){return[]}const first=handler.params[0];if(first===void 0||first.type!=="ObjectPattern")return[];const found=[];for(const prop of first.properties){if(prop.type==="RestElement")continue;const key=(0,tool_registration_1.propertyKey)(prop);if(key===void 0)continue;found.push({name:key,node:prop})}return found}exports.noUnvalidatedToolArgs=(0,eslint_devkit_1.createRule)({name:"no-unvalidated-tool-args",meta:{interop:{runtimes:["eslint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/no-unvalidated-tool-args.md",description:"Disallow a tool handler reading an argument its declared input schema does not include",cwe:"CWE-20",cvss:7.5},messages:{undeclaredArg:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Outside the Declared Schema",cwe:"CWE-20",owasp:"A03:2021",cvss:7.5,description:'Tool "{{tool}}" reads `{{arg}}`, which its inputSchema does not declare \u2014 so the value either arrives unvalidated or never arrives at all',severity:"HIGH",compliance:["SOC2"],fix:"Declare `{{arg}}` in the inputSchema with the type and constraints it needs, or stop reading it. A key the schema does not mention is one nothing validated.",documentationLink:"https://modelcontextprotocol.io/docs/concepts/tools"}),undeclaredArgPassthrough:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Argument Passed Through Unvalidated",cwe:"CWE-20",owasp:"A03:2021",cvss:7.5,description:'Tool "{{tool}}" reads `{{arg}}`, which its inputSchema does not declare, and the schema is loose (passthrough) \u2014 so the value reaches the handler exactly as the model sent it',severity:"HIGH",compliance:["SOC2"],fix:"Declare `{{arg}}` in the inputSchema with the type and constraints it needs. A loose schema validates the declared keys and waves every other key through.",documentationLink:"https://modelcontextprotocol.io/docs/concepts/tools"})},schema:[]},defaultOptions:[],createOnce(context){let resolve;let candidates;return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;resolve=(0,module_resolver_1.valueResolverFor)(context);candidates=[];return true},CallExpression(node){const registration=(0,tool_registration_1.readRegistration)(node,resolve);if(registration?.schema.kind!=="schema")return;const declared=(0,tool_registration_1.schemaFields)(registration.schema.node);if(declared===void 0)return;const handler=(0,tool_registration_1.resolveFunction)(registration.handler,context.sourceCode.getScope(node));if(handler===void 0)return;for(const read of destructuredArgNames(handler)){if(declared.fields.has(read.name))continue;candidates.push({node:read.node,tool:(0,tool_registration_1.toolNameOf)(node),arg:read.name,messageId:declared.loose?"undeclaredArgPassthrough":"undeclaredArg"})}},"Program:exit"(){for(const{node,tool,arg,messageId}of candidates){context.report({node,messageId,data:{tool,arg}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireHttpTransportHardening=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const guards_1=require("../../utils/guards");const tool_registration_1=require("../../utils/tool-registration");const HTTP_TRANSPORTS=new Map([["StreamableHTTPServerTransport",0],["SSEServerTransport",2],["NodeStreamableHTTPServerTransport",0],["WebStandardStreamableHTTPServerTransport",0]]);const TRANSPORT_OPTION_PACKAGES=["@modelcontextprotocol/sdk","@modelcontextprotocol/server-legacy"];const MCP_APP_FACTORIES=new Set(["createMcpExpressApp","createMcpHonoApp","createMcpFastifyApp"]);const RAW_APPS={express:"",hono:"Hono",fastify:""};const ROUTE_METHODS=new Set(["get","post","put","patch","delete","all","route","on"]);const HOST_VALIDATORS=new Set(["hostHeaderValidation","localhostHostValidation"]);const AUTH_EXPORTS=new Set(["requireBearerAuth","mcpAuthRouter","mcpAuthMetadataRouter"]);const LOOPBACK_HOSTS=new Set(["127.0.0.1","localhost","::1"]);const DEFAULT_ALL_INTERFACES={express:"",http:"createServer",https:"createServer"};const DEFAULT_LISTEN_HOST="::";const REQUEST_HEADER_READS=new Set(["headers","header","get"]);const ALL_INTERFACE_HOSTS=new Set(["0.0.0.0","::"]);const TRANSPORT_SECURITY_DOCS="https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#security-warning";exports.requireHttpTransportHardening=(0,eslint_devkit_1.createRule)({name:"require-http-transport-hardening",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/require-http-transport-hardening.md",description:"Require an MCP HTTP server transport to validate the Host header and a network-reachable MCP server to authenticate its callers",cwe:"CWE-346",cvss:8.1},messages:{missingRebindingProtection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP HTTP Transport Without DNS-Rebinding Protection",cwe:"CWE-346",owasp:"A05:2021",cvss:8.1,description:"`{{transport}}` is built without `enableDnsRebindingProtection: true` and a non-empty `allowedHosts`, and nothing in this file validates the Host header, so a web page the user opens can rebind its hostname to this server and call its tools",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Pass `enableDnsRebindingProtection: true, allowedHosts: ['127.0.0.1:3000', 'localhost:3000']` (the exact Host header values clients send; the transport compares them with the port), or serve the transport from `createMcpExpressApp()` or behind `hostHeaderValidation([...])`.",documentationLink:TRANSPORT_SECURITY_DOCS}),appWithoutHostValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP App Without Host Validation",cwe:"CWE-346",owasp:"A05:2021",cvss:8.1,description:"This {{framework}} app serves an SDK v2 MCP transport and nothing in this file validates the Host header \u2014 v2 transports leave DNS-rebinding protection to the app \u2014 so a web page the user opens can rebind its hostname to this server and call its tools",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Build the app with `createMcpExpressApp()` / `createMcpHonoApp()` (localhost validation by default, `allowedHosts` for other hosts), or mount `hostHeaderValidation(['mcp.example.com'])` / `localhostHostValidation()` before the MCP route.",documentationLink:TRANSPORT_SECURITY_DOCS}),allInterfacesWithoutAllowedHosts:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Express App on All Interfaces Without allowedHosts",cwe:"CWE-346",owasp:"A05:2021",cvss:8.1,description:"`{{factory}}({ host: '{{host}}' })` binds every interface and, with no `allowedHosts`, installs no Host validation; the SDK only logs a warning",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Pass `allowedHosts: ['mcp.example.com']` with the host names clients use, or bind to `127.0.0.1` when the server is local-only.",documentationLink:TRANSPORT_SECURITY_DOCS}),missingAuth:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Network-Reachable MCP Server Without Authentication",cwe:"CWE-306",owasp:"A05:2021",cvss:8.1,description:"This MCP HTTP server binds every interface ('{{host}}') and nothing in this file authenticates its callers (no SDK auth middleware, no custom `.use()` middleware, no middleware in front of the route that calls `handleRequest`), so anyone who can reach the port can call every tool",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Mount `requireBearerAuth({ verifier })` or your own auth middleware on the MCP route in this file (`app.post('/mcp', requireBearerAuth({ verifier }), handler)`), or bind to `127.0.0.1`.",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization"})},schema:[]},defaultOptions:[],skipTestFiles:true,create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const resolve=(0,module_resolver_1.valueResolverFor)(context);const builtBy=(0,instances_1.createInstanceResolver)(context);function appVariables(bind){const found=[];const add=node=>{if(node?.type==="CallExpression"){for(const arg of node.arguments)add(arg);return}if(node?.type!=="Identifier")return;const variable=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node));if(variable===void 0||found.includes(variable))return;found.push(variable);const def=variable.defs[0];if(def?.type==="Variable")add(def.node.init)};if(bind.type==="CallExpression"&&bind.callee.type==="MemberExpression")add(bind.callee.object);else if(bind.parent?.type==="VariableDeclarator")add(bind.parent.id);return found}function appEscapes(bind){return appVariables(bind).some(variable=>variable.references.some(ref=>{const call=ref.identifier.parent;if(call?.type!=="CallExpression"||!call.arguments.includes(ref.identifier))return false;if((0,tool_registration_1.resolveFunction)(call.callee,sourceCode.getScope(call)))return false;const callee=(0,eslint_devkit_1.resolveModuleBinding)(call.callee,sourceCode.getScope(call));return!(callee!==void 0&&DEFAULT_ALL_INTERFACES[callee.module]===callee.path.join("."))}))}function listensOnAllByDefault(receiver){const app=builtBy(receiver);if(app===void 0)return false;if((0,mcp_evidence_1.isMcpModule)(app.module))return app.path[app.path.length-1]==="createMcpExpressApp";return DEFAULT_ALL_INTERFACES[app.module]===app.path.join(".")}const unhardened=[];let constructsTransport=false;let servesV2=false;const rawApps=[];let validatesHost=false;let authenticates=false;let customUse=false;const binds=[];const openFactories=[];const handleRequestCalls=[];const serveCalls=[];function rootedAt(node,request){let current=node;while(current.type==="MemberExpression")current=current.object;return current.type==="Identifier"&&(0,tool_registration_1.lookupVariable)(current.name,sourceCode.getScope(current))===request}function readsHeader(test,request){const seen=new Set;const visit=node=>{if((0,tool_registration_1.isFunctionNode)(node)&&node.parent?.type!=="CallExpression")return false;if(node.type==="MemberExpression"&&REQUEST_HEADER_READS.has((0,eslint_devkit_1.propertyName)(node)??"")&&rootedAt(node.object,request))return true;if(node.type==="Identifier"){const variable=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node));if(variable===void 0||seen.has(variable))return false;seen.add(variable);return variable.defs.some(def=>def.type==="Variable"&&def.node.init!==null&&visit(def.node.init))}for(const[key,value]of Object.entries(node)){if(key==="parent")continue;for(const child of Array.isArray(value)?value:[value])if(child!==null&&typeof child==="object"&&typeof child.type==="string"&&visit(child))return true}return false};return visit(test)}function gatedInline(call){const requests=[];for(let node=call.parent;node;node=node.parent){if(!(0,tool_registration_1.isFunctionNode)(node))continue;if(registrationsOf(node).some(behindSdkAuth))return true;const param=node.params[0];if(param?.type!=="Identifier")continue;requests.push(sourceCode.getDeclaredVariables(node).find(v=>v.defs[0]?.name===param))}let child=call;for(let node=call.parent;node;node=node.parent){if(node.type==="BlockStatement")for(const statement of node.body){if(statement===child)break;if(statement.type==="IfStatement"&&(0,guards_1.exits)(statement.consequent)&&requests.some(request=>readsHeader(statement.test,request)))return true}child=node}return false}function behindSdkAuth(route){return route.arguments.some(arg=>arg.type==="CallExpression"&&AUTH_EXPORTS.has((0,tool_handlers_1.mcpExport)(arg.callee,sourceCode.getScope(arg))??""))}function servedBehindCredentialCheck(){return serveCalls.length>0&&serveCalls.every(gatedInline)}function hostOf(node){return(0,eslint_devkit_1.staticString)(resolve(node))}function readOptions(node){if(node.type==="SpreadElement")return null;const object=resolve(node);if(object?.type!=="ObjectExpression")return null;const options=new Map;for(const prop of object.properties){if(prop.type==="SpreadElement")return null;const key=(0,tool_registration_1.propertyKey)(prop);if(key===void 0)return null;options.set(key,prop.value)}return options}function rebindingProtection(options){const flag=options.get("enableDnsRebindingProtection");if(flag===void 0)return"no";const value=resolve(flag);if(value?.type!=="Literal"||typeof value.value!=="boolean")return"unknown";return value.value?"yes":"no"}function nonEmptyHosts(options){const hosts=options.get("allowedHosts");if(hosts===void 0)return"no";const value=resolve(hosts);if(value?.type!=="ArrayExpression")return"unknown";return value.elements.length>0?"yes":"no"}function expressAppState(call){const arg=call.arguments[0];if(arg===void 0)return{kind:"guarded"};const options=readOptions(arg);if(options===null||options.has("allowedHosts"))return{kind:"guarded"};const hostNode=options.get("host");if(hostNode===void 0)return{kind:"guarded"};const host=hostOf(hostNode);if(host===null||LOOPBACK_HOSTS.has(host))return{kind:"guarded"};return ALL_INTERFACE_HOSTS.has(host)?{kind:"allInterfaces",host}:{kind:"other"}}function registrationsOf(fn){const parent=fn.parent;if(parent.type==="CallExpression"&&parent.arguments.includes(fn))return[parent];const declared=fn.type==="FunctionDeclaration"?fn:parent.type==="VariableDeclarator"?parent:void 0;if(declared===void 0)return[];const calls=[];for(const variable of sourceCode.getDeclaredVariables(declared)){for(const ref of variable.references){const site=ref.identifier.parent;if(site.type==="CallExpression"&&site.arguments.includes(ref.identifier))calls.push(site)}}return calls}function routeHasMiddleware(){for(const call of handleRequestCalls){for(let node=call.parent;node;node=node.parent){if(!(0,tool_registration_1.isFunctionNode)(node))continue;if(registrationsOf(node).some(route=>route.arguments.length>2))return true}}return false}function noteRawApp(node,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding!==void 0&&RAW_APPS[binding.module]===binding.path.join("."))rawApps.push({node,framework:binding.module})}function registersRoute(node){const declarator=node.parent;if(declarator?.type!=="VariableDeclarator")return false;return sourceCode.getDeclaredVariables(declarator).some(variable=>variable.references.some(ref=>{const member=ref.identifier.parent;return member.type==="MemberExpression"&&member.object===ref.identifier&&member.parent.type==="CallExpression"&&member.parent.callee===member&&ROUTE_METHODS.has((0,eslint_devkit_1.propertyName)(member)??"")}))}return{NewExpression(node){const scope=sourceCode.getScope(node);noteRawApp(node,scope);const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding===void 0||!(0,mcp_evidence_1.isMcpModule)(binding.module))return;const transport=String(binding.path[binding.path.length-1]);const index=HTTP_TRANSPORTS.get(transport);if(index===void 0)return;constructsTransport=true;if(transport==="SSEServerTransport")serveCalls.push(node);if(!TRANSPORT_OPTION_PACKAGES.some(pkg=>binding.module===pkg||binding.module.startsWith(`${pkg}/`))){servesV2=true;return}const arg=node.arguments[index];if(arg===void 0){unhardened.push({node,transport});return}const options=readOptions(arg);if(options===null)return;if(rebindingProtection(options)==="no"||nonEmptyHosts(options)==="no")unhardened.push({node,transport})},CallExpression(node){const scope=sourceCode.getScope(node);noteRawApp(node,scope);if(node.callee.type==="Identifier"){const init=(0,tool_registration_1.constInitializer)(node.callee,scope);if(init?.type==="CallExpression"&&(0,tool_handlers_1.mcpExport)(init.callee,scope)!==void 0)serveCalls.push(node)}const name=(0,tool_handlers_1.mcpExport)(node.callee,scope);if(name!==void 0){if(HOST_VALIDATORS.has(name))validatesHost=true;else if(AUTH_EXPORTS.has(name))authenticates=true;else if(name==="createMcpHandler")servesV2=true;else if(MCP_APP_FACTORIES.has(name)){const state=expressAppState(node);if(state.kind==="guarded")validatesHost=true;else if(state.kind==="allInterfaces"){openFactories.push({node,factory:name,host:state.host});binds.push({node,host:state.host})}}return}if(node.callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method==="use"){if(node.arguments.some(arg=>arg.type==="Identifier"||(0,tool_registration_1.isFunctionNode)(arg)))customUse=true}else if(method==="handleRequest"){handleRequestCalls.push(node);serveCalls.push(node)}else if(method==="handlePostMessage"){serveCalls.push(node)}else if(method==="listen"){const[first,second]=node.arguments;const options=first?.type==="ObjectExpression"?readOptions(first):null;const hostNode=first?.type==="ObjectExpression"?options?.get("host"):second!==void 0&&!(0,tool_registration_1.isFunctionNode)(second)?second:void 0;const host=hostNode===void 0?null:hostOf(hostNode);if(host!==null&&ALL_INTERFACE_HOSTS.has(host))binds.push({node,host});else if(hostNode===void 0&&(first?.type!=="ObjectExpression"||options!==null)&&listensOnAllByDefault(node.callee.object))binds.push({node,host:DEFAULT_LISTEN_HOST})}},"Program:exit"(){const gated=servedBehindCredentialCheck();if(!gated)for(const{node,factory,host}of openFactories)context.report({node,messageId:"allInterfacesWithoutAllowedHosts",data:{factory,host}});if(!validatesHost&&!gated){for(const{node,transport}of unhardened)context.report({node,messageId:"missingRebindingProtection",data:{transport}});if(servesV2){for(const{node,framework}of rawApps)if(registersRoute(node))context.report({node,messageId:"appWithoutHostValidation",data:{framework}})}}if(!constructsTransport||binds.length===0||authenticates||gated||customUse||routeHasMiddleware())return;for(const{node,host}of binds)if(!appEscapes(node))context.report({node,messageId:"missingAuth",data:{host}})}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireHttpTransportHardening=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const instances_1=require("../../utils/instances");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_handlers_1=require("../../utils/tool-handlers");const guards_1=require("../../utils/guards");const tool_registration_1=require("../../utils/tool-registration");const HTTP_TRANSPORTS=new Map([["StreamableHTTPServerTransport",0],["SSEServerTransport",2],["NodeStreamableHTTPServerTransport",0],["WebStandardStreamableHTTPServerTransport",0]]);const TRANSPORT_OPTION_PACKAGES=["@modelcontextprotocol/sdk","@modelcontextprotocol/server-legacy"];const MCP_APP_FACTORIES=new Set(["createMcpExpressApp","createMcpHonoApp","createMcpFastifyApp"]);const RAW_APPS={express:"",hono:"Hono",fastify:""};const ROUTE_METHODS=new Set(["get","post","put","patch","delete","all","route","on"]);const HOST_VALIDATORS=new Set(["hostHeaderValidation","localhostHostValidation"]);const AUTH_EXPORTS=new Set(["requireBearerAuth","mcpAuthRouter","mcpAuthMetadataRouter"]);const LOOPBACK_HOSTS=new Set(["127.0.0.1","localhost","::1"]);const DEFAULT_ALL_INTERFACES={express:"",http:"createServer",https:"createServer"};const DEFAULT_LISTEN_HOST="::";const REQUEST_HEADER_READS=new Set(["headers","header","get"]);const ALL_INTERFACE_HOSTS=new Set(["0.0.0.0","::"]);const TRANSPORT_SECURITY_DOCS="https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#security-warning";exports.requireHttpTransportHardening=(0,eslint_devkit_1.createRule)({name:"require-http-transport-hardening",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/require-http-transport-hardening.md",description:"Require an MCP HTTP server transport to validate the Host header and a network-reachable MCP server to authenticate its callers",cwe:"CWE-346",cvss:8.1},messages:{missingRebindingProtection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP HTTP Transport Without DNS-Rebinding Protection",cwe:"CWE-346",owasp:"A05:2021",cvss:8.1,description:"`{{transport}}` is built without `enableDnsRebindingProtection: true` and a non-empty `allowedHosts`, and nothing in this file validates the Host header, so a web page the user opens can rebind its hostname to this server and call its tools",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Pass `enableDnsRebindingProtection: true, allowedHosts: ['127.0.0.1:3000', 'localhost:3000']` (the exact Host header values clients send; the transport compares them with the port), or serve the transport from `createMcpExpressApp()` or behind `hostHeaderValidation([...])`.",documentationLink:TRANSPORT_SECURITY_DOCS}),appWithoutHostValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP App Without Host Validation",cwe:"CWE-346",owasp:"A05:2021",cvss:8.1,description:"This {{framework}} app serves an SDK v2 MCP transport and nothing in this file validates the Host header \u2014 v2 transports leave DNS-rebinding protection to the app \u2014 so a web page the user opens can rebind its hostname to this server and call its tools",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Build the app with `createMcpExpressApp()` / `createMcpHonoApp()` (localhost validation by default, `allowedHosts` for other hosts), or mount `hostHeaderValidation(['mcp.example.com'])` / `localhostHostValidation()` before the MCP route.",documentationLink:TRANSPORT_SECURITY_DOCS}),allInterfacesWithoutAllowedHosts:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Express App on All Interfaces Without allowedHosts",cwe:"CWE-346",owasp:"A05:2021",cvss:8.1,description:"`{{factory}}({ host: '{{host}}' })` binds every interface and, with no `allowedHosts`, installs no Host validation; the SDK only logs a warning",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Pass `allowedHosts: ['mcp.example.com']` with the host names clients use, or bind to `127.0.0.1` when the server is local-only.",documentationLink:TRANSPORT_SECURITY_DOCS}),missingAuth:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Network-Reachable MCP Server Without Authentication",cwe:"CWE-306",owasp:"A05:2021",cvss:8.1,description:"This MCP HTTP server binds every interface ('{{host}}') and nothing in this file authenticates its callers (no SDK auth middleware, no custom `.use()` middleware, no middleware in front of the route that calls `handleRequest`), so anyone who can reach the port can call every tool",severity:"HIGH",compliance:["SOC2","NIST-CSF"],fix:"Mount `requireBearerAuth({ verifier })` or your own auth middleware on the MCP route in this file (`app.post('/mcp', requireBearerAuth({ verifier }), handler)`), or bind to `127.0.0.1`.",documentationLink:"https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization"})},schema:[]},defaultOptions:[],skipTestFiles:true,createOnce(context){let sourceCode;let resolve;let builtBy;let unhardened;let constructsTransport;let servesV2;let rawApps;let validatesHost;let authenticates;let customUse;let binds;let openFactories;let handleRequestCalls;let serveCalls;function appVariables(bind){const found=[];const add=node=>{if(node?.type==="CallExpression"){for(const arg of node.arguments)add(arg);return}if(node?.type!=="Identifier")return;const variable=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node));if(variable===void 0||found.includes(variable))return;found.push(variable);const def=variable.defs[0];if(def?.type==="Variable")add(def.node.init)};if(bind.type==="CallExpression"&&bind.callee.type==="MemberExpression")add(bind.callee.object);else if(bind.parent?.type==="VariableDeclarator")add(bind.parent.id);return found}function appEscapes(bind){return appVariables(bind).some(variable=>variable.references.some(ref=>{const call=ref.identifier.parent;if(call?.type!=="CallExpression"||!call.arguments.includes(ref.identifier))return false;if((0,tool_registration_1.resolveFunction)(call.callee,sourceCode.getScope(call)))return false;const callee=(0,eslint_devkit_1.resolveModuleBinding)(call.callee,sourceCode.getScope(call));return!(callee!==void 0&&DEFAULT_ALL_INTERFACES[callee.module]===callee.path.join("."))}))}function listensOnAllByDefault(receiver){const app=builtBy(receiver);if(app===void 0)return false;if((0,mcp_evidence_1.isMcpModule)(app.module))return app.path[app.path.length-1]==="createMcpExpressApp";return DEFAULT_ALL_INTERFACES[app.module]===app.path.join(".")}function rootedAt(node,request){let current=node;while(current.type==="MemberExpression")current=current.object;return current.type==="Identifier"&&(0,tool_registration_1.lookupVariable)(current.name,sourceCode.getScope(current))===request}function readsHeader(test,request){const seen=new Set;const visit=node=>{if((0,tool_registration_1.isFunctionNode)(node)&&node.parent?.type!=="CallExpression")return false;if(node.type==="MemberExpression"&&REQUEST_HEADER_READS.has((0,eslint_devkit_1.propertyName)(node)??"")&&rootedAt(node.object,request))return true;if(node.type==="Identifier"){const variable=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node));if(variable===void 0||seen.has(variable))return false;seen.add(variable);return variable.defs.some(def=>def.type==="Variable"&&def.node.init!==null&&visit(def.node.init))}for(const[key,value]of Object.entries(node)){if(key==="parent")continue;for(const child of Array.isArray(value)?value:[value])if(child!==null&&typeof child==="object"&&typeof child.type==="string"&&visit(child))return true}return false};return visit(test)}function gatedInline(call){const requests=[];for(let node=call.parent;node;node=node.parent){if(!(0,tool_registration_1.isFunctionNode)(node))continue;if(registrationsOf(node).some(behindSdkAuth))return true;const param=node.params[0];if(param?.type!=="Identifier")continue;requests.push(sourceCode.getDeclaredVariables(node).find(v=>v.defs[0]?.name===param))}let child=call;for(let node=call.parent;node;node=node.parent){if(node.type==="BlockStatement")for(const statement of node.body){if(statement===child)break;if(statement.type==="IfStatement"&&(0,guards_1.exits)(statement.consequent)&&requests.some(request=>readsHeader(statement.test,request)))return true}child=node}return false}function behindSdkAuth(route){return route.arguments.some(arg=>arg.type==="CallExpression"&&AUTH_EXPORTS.has((0,tool_handlers_1.mcpExport)(arg.callee,sourceCode.getScope(arg))??""))}function servedBehindCredentialCheck(){return serveCalls.length>0&&serveCalls.every(gatedInline)}function hostOf(node){return(0,eslint_devkit_1.staticString)(resolve(node))}function readOptions(node){if(node.type==="SpreadElement")return null;const object=resolve(node);if(object?.type!=="ObjectExpression")return null;const options=new Map;for(const prop of object.properties){if(prop.type==="SpreadElement")return null;const key=(0,tool_registration_1.propertyKey)(prop);if(key===void 0)return null;options.set(key,prop.value)}return options}function rebindingProtection(options){const flag=options.get("enableDnsRebindingProtection");if(flag===void 0)return"no";const value=resolve(flag);if(value?.type!=="Literal"||typeof value.value!=="boolean")return"unknown";return value.value?"yes":"no"}function nonEmptyHosts(options){const hosts=options.get("allowedHosts");if(hosts===void 0)return"no";const value=resolve(hosts);if(value?.type!=="ArrayExpression")return"unknown";return value.elements.length>0?"yes":"no"}function expressAppState(call){const arg=call.arguments[0];if(arg===void 0)return{kind:"guarded"};const options=readOptions(arg);if(options===null||options.has("allowedHosts"))return{kind:"guarded"};const hostNode=options.get("host");if(hostNode===void 0)return{kind:"guarded"};const host=hostOf(hostNode);if(host===null||LOOPBACK_HOSTS.has(host))return{kind:"guarded"};return ALL_INTERFACE_HOSTS.has(host)?{kind:"allInterfaces",host}:{kind:"other"}}function registrationsOf(fn){const parent=fn.parent;if(parent.type==="CallExpression"&&parent.arguments.includes(fn))return[parent];const declared=fn.type==="FunctionDeclaration"?fn:parent.type==="VariableDeclarator"?parent:void 0;if(declared===void 0)return[];const calls=[];for(const variable of sourceCode.getDeclaredVariables(declared)){for(const ref of variable.references){const site=ref.identifier.parent;if(site.type==="CallExpression"&&site.arguments.includes(ref.identifier))calls.push(site)}}return calls}function routeHasMiddleware(){for(const call of handleRequestCalls){for(let node=call.parent;node;node=node.parent){if(!(0,tool_registration_1.isFunctionNode)(node))continue;if(registrationsOf(node).some(route=>route.arguments.length>2))return true}}return false}function noteRawApp(node,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding!==void 0&&RAW_APPS[binding.module]===binding.path.join("."))rawApps.push({node,framework:binding.module})}function registersRoute(node){const declarator=node.parent;if(declarator?.type!=="VariableDeclarator")return false;return sourceCode.getDeclaredVariables(declarator).some(variable=>variable.references.some(ref=>{const member=ref.identifier.parent;return member.type==="MemberExpression"&&member.object===ref.identifier&&member.parent.type==="CallExpression"&&member.parent.callee===member&&ROUTE_METHODS.has((0,eslint_devkit_1.propertyName)(member)??"")}))}return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;sourceCode=context.sourceCode;resolve=(0,module_resolver_1.valueResolverFor)(context);builtBy=(0,instances_1.createInstanceResolver)(context);unhardened=[];constructsTransport=false;servesV2=false;rawApps=[];validatesHost=false;authenticates=false;customUse=false;binds=[];openFactories=[];handleRequestCalls=[];serveCalls=[];return true},NewExpression(node){const scope=sourceCode.getScope(node);noteRawApp(node,scope);const binding=(0,eslint_devkit_1.resolveModuleBinding)(node.callee,scope);if(binding===void 0||!(0,mcp_evidence_1.isMcpModule)(binding.module))return;const transport=String(binding.path[binding.path.length-1]);const index=HTTP_TRANSPORTS.get(transport);if(index===void 0)return;constructsTransport=true;if(transport==="SSEServerTransport")serveCalls.push(node);if(!TRANSPORT_OPTION_PACKAGES.some(pkg=>binding.module===pkg||binding.module.startsWith(`${pkg}/`))){servesV2=true;return}const arg=node.arguments[index];if(arg===void 0){unhardened.push({node,transport});return}const options=readOptions(arg);if(options===null)return;if(rebindingProtection(options)==="no"||nonEmptyHosts(options)==="no")unhardened.push({node,transport})},CallExpression(node){const scope=sourceCode.getScope(node);noteRawApp(node,scope);if(node.callee.type==="Identifier"){const init=(0,tool_registration_1.constInitializer)(node.callee,scope);if(init?.type==="CallExpression"&&(0,tool_handlers_1.mcpExport)(init.callee,scope)!==void 0)serveCalls.push(node)}const name=(0,tool_handlers_1.mcpExport)(node.callee,scope);if(name!==void 0){if(HOST_VALIDATORS.has(name))validatesHost=true;else if(AUTH_EXPORTS.has(name))authenticates=true;else if(name==="createMcpHandler")servesV2=true;else if(MCP_APP_FACTORIES.has(name)){const state=expressAppState(node);if(state.kind==="guarded")validatesHost=true;else if(state.kind==="allInterfaces"){openFactories.push({node,factory:name,host:state.host});binds.push({node,host:state.host})}}return}if(node.callee.type!=="MemberExpression")return;const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method==="use"){if(node.arguments.some(arg=>arg.type==="Identifier"||(0,tool_registration_1.isFunctionNode)(arg)))customUse=true}else if(method==="handleRequest"){handleRequestCalls.push(node);serveCalls.push(node)}else if(method==="handlePostMessage"){serveCalls.push(node)}else if(method==="listen"){const[first,second]=node.arguments;const options=first?.type==="ObjectExpression"?readOptions(first):null;const hostNode=first?.type==="ObjectExpression"?options?.get("host"):second!==void 0&&!(0,tool_registration_1.isFunctionNode)(second)?second:void 0;const host=hostNode===void 0?null:hostOf(hostNode);if(host!==null&&ALL_INTERFACE_HOSTS.has(host))binds.push({node,host});else if(hostNode===void 0&&(first?.type!=="ObjectExpression"||options!==null)&&listensOnAllByDefault(node.callee.object))binds.push({node,host:DEFAULT_LISTEN_HOST})}},"Program:exit"(){const gated=servedBehindCredentialCheck();if(!gated)for(const{node,factory,host}of openFactories)context.report({node,messageId:"allInterfacesWithoutAllowedHosts",data:{factory,host}});if(!validatesHost&&!gated){for(const{node,transport}of unhardened)context.report({node,messageId:"missingRebindingProtection",data:{transport}});if(servesV2){for(const{node,framework}of rawApps)if(registersRoute(node))context.report({node,messageId:"appWithoutHostValidation",data:{framework}})}}if(!constructsTransport||binds.length===0||authenticates||gated||customUse||routeHasMiddleware())return;for(const{node,host}of binds)if(!appEscapes(node))context.report({node,messageId:"missingAuth",data:{host}})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireToolInputSchema=void 0;exports.argumentRead=argumentRead;const eslint_devkit_1=require("@interlace/eslint-devkit");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_registration_1=require("../../utils/tool-registration");function argumentRead(fn,declaredVariables){let first=fn.params[0];if(first?.type==="AssignmentPattern")first=first.left;if(fn.params.length>=2){return first?.type==="Identifier"?first.name:"args"}if(first?.type==="ObjectPattern"){for(const prop of first.properties){const key=(0,tool_registration_1.propertyKey)(prop);if(key!==void 0&&!tool_registration_1.HANDLER_CONTEXT_KEYS.has(key))return key}return void 0}if(first?.type!=="Identifier")return void 0;const variable=declaredVariables(fn).find(v=>v.name===first.name);for(const ref of variable.references){const parent=ref.identifier.parent;if(parent?.type!=="MemberExpression"||parent.object!==ref.identifier)continue;const key=(0,eslint_devkit_1.propertyName)(parent);if(key!==null&&!tool_registration_1.HANDLER_CONTEXT_KEYS.has(key))return`${first.name}.${key}`}return void 0}exports.requireToolInputSchema=(0,eslint_devkit_1.createRule)({name:"require-tool-input-schema",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/require-tool-input-schema.md",description:"Require an input schema when an MCP tool handler reads arguments",cwe:"CWE-20",cvss:5.3},messages:{missingInputSchema:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Handler Reads Arguments No Schema Declares",cwe:"CWE-20",owasp:"A03:2021",cvss:5.3,description:'Tool "{{tool}}" declares no inputSchema, yet its handler reads `{{arg}}`. Without a schema the SDK passes the request context there, not the client\'s arguments \u2014 nothing declared or validated what the handler expects',severity:"MEDIUM",compliance:["SOC2"],fix:'Declare the arguments the handler reads: registerTool("{{tool}}", { inputSchema: { path: z.string() } }, handler)',documentationLink:"https://modelcontextprotocol.io/docs/concepts/tools"})},schema:[]},defaultOptions:[],create(context){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return{};const resolve=(0,module_resolver_1.valueResolverFor)(context);const candidates=[];return{CallExpression(node){const registration=(0,tool_registration_1.readRegistration)(node,resolve);if(registration?.schema.kind!=="none")return;const fn=(0,tool_registration_1.resolveFunction)(registration.handler,context.sourceCode.getScope(node));if(fn===void 0)return;const arg=argumentRead(fn,n=>context.sourceCode.getDeclaredVariables(n));if(arg!==void 0)candidates.push({node,tool:(0,tool_registration_1.toolNameOf)(node),arg})},"Program:exit"(){for(const{node,tool,arg}of candidates){context.report({node,messageId:"missingInputSchema",data:{tool,arg}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireToolInputSchema=void 0;exports.argumentRead=argumentRead;const eslint_devkit_1=require("@interlace/eslint-devkit");const mcp_evidence_1=require("../../utils/mcp-evidence");const module_resolver_1=require("../../utils/module-resolver");const tool_registration_1=require("../../utils/tool-registration");function argumentRead(fn,declaredVariables){let first=fn.params[0];if(first?.type==="AssignmentPattern")first=first.left;if(fn.params.length>=2){return first?.type==="Identifier"?first.name:"args"}if(first?.type==="ObjectPattern"){for(const prop of first.properties){const key=(0,tool_registration_1.propertyKey)(prop);if(key!==void 0&&!tool_registration_1.HANDLER_CONTEXT_KEYS.has(key))return key}return void 0}if(first?.type!=="Identifier")return void 0;const variable=declaredVariables(fn).find(v=>v.name===first.name);for(const ref of variable.references){const parent=ref.identifier.parent;if(parent?.type!=="MemberExpression"||parent.object!==ref.identifier)continue;const key=(0,eslint_devkit_1.propertyName)(parent);if(key!==null&&!tool_registration_1.HANDLER_CONTEXT_KEYS.has(key))return`${first.name}.${key}`}return void 0}exports.requireToolInputSchema=(0,eslint_devkit_1.createRule)({name:"require-tool-input-schema",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-mcp-sdk-security/docs/rules/require-tool-input-schema.md",description:"Require an input schema when an MCP tool handler reads arguments",cwe:"CWE-20",cvss:5.3},messages:{missingInputSchema:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"MCP Tool Handler Reads Arguments No Schema Declares",cwe:"CWE-20",owasp:"A03:2021",cvss:5.3,description:'Tool "{{tool}}" declares no inputSchema, yet its handler reads `{{arg}}`. Without a schema the SDK passes the request context there, not the client\'s arguments \u2014 nothing declared or validated what the handler expects',severity:"MEDIUM",compliance:["SOC2"],fix:'Declare the arguments the handler reads: registerTool("{{tool}}", { inputSchema: { path: z.string() } }, handler)',documentationLink:"https://modelcontextprotocol.io/docs/concepts/tools"})},schema:[]},defaultOptions:[],createOnce(context){let resolve;let candidates;return{before(){if(!(0,mcp_evidence_1.fileUsesMcpSdk)(context.sourceCode.ast))return false;resolve=(0,module_resolver_1.valueResolverFor)(context);candidates=[];return true},CallExpression(node){const registration=(0,tool_registration_1.readRegistration)(node,resolve);if(registration?.schema.kind!=="none")return;const fn=(0,tool_registration_1.resolveFunction)(registration.handler,context.sourceCode.getScope(node));if(fn===void 0)return;const arg=argumentRead(fn,n=>context.sourceCode.getDeclaredVariables(n));if(arg!==void 0)candidates.push({node,tool:(0,tool_registration_1.toolNameOf)(node),arg})},"Program:exit"(){for(const{node,tool,arg}of candidates){context.report({node,messageId:"missingInputSchema",data:{tool,arg}})}}}}});
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __setModuleDefault=this&&this.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}):function(o,v){o["default"]=v});var __importStar=this&&this.__importStar||(function(){var ownKeys=function(o){ownKeys=Object.getOwnPropertyNames||function(o2){var ar=[];for(var k in o2)if(Object.prototype.hasOwnProperty.call(o2,k))ar[ar.length]=k;return ar};return ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null){for(var k=ownKeys(mod),i=0;i<k.length;i++)if(k[i]!=="default")__createBinding(result,mod,k[i])}__setModuleDefault(result,mod);return result}})();Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_RESOLVE_DEPTH=void 0;exports.resolveRelative=resolveRelative;exports.parseModule=parseModule;exports.resolveIdentifier=resolveIdentifier;exports.resolveExport=resolveExport;exports.resolveValue=resolveValue;exports.unwrapTypeOnly=unwrapTypeOnly;exports.siteOf=siteOf;exports.activeParser=activeParser;exports.valueResolverFor=valueResolverFor;exports.resolveCalleeFunction=resolveCalleeFunction;exports.scopeAt=scopeAt;const fs=__importStar(require("node:fs"));const path=__importStar(require("node:path"));const eslint_devkit_1=require("@interlace/eslint-devkit");const tool_registration_1=require("./tool-registration");exports.MAX_RESOLVE_DEPTH=12;const SOURCE_EXTENSIONS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];const TS_FOR_JS={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};const UNKNOWN={kind:"unknown"};const DYNAMIC={kind:"dynamic"};function isFile(file){try{return fs.statSync(file).isFile()}catch{return false}}function resolveRelative(fromFile,specifier){if(!specifier.startsWith("./")&&!specifier.startsWith("../"))return void 0;const base=path.resolve(path.dirname(fromFile),specifier);const ext=path.extname(base);const stem=base.slice(0,base.length-ext.length);const candidates=[base,...(TS_FOR_JS[ext]??[]).map(e=>stem+e),...SOURCE_EXTENSIONS.map(e=>base+e),...SOURCE_EXTENSIONS.map(e=>path.join(base,`index${e}`))];return candidates.find(isFile)}const caches=new WeakMap;function parseModule(file,parser){const parse=parser?.parseForESLint;if(typeof parse!=="function")return void 0;let mtimeMs;try{mtimeMs=fs.statSync(file).mtimeMs}catch{return void 0}let cache=caches.get(parser);if(cache===void 0){cache=new Map;caches.set(parser,cache)}const cached=cache.get(file);if(cached?.mtimeMs===mtimeMs)return cached.parsed;let parsed;try{const result=parse(fs.readFileSync(file,"utf8"),{sourceType:"module",ecmaVersion:"latest",range:true,loc:true,filePath:file});const scope=result.scopeManager?.scopes.find(s=>s.type==="module");if(scope)parsed={ast:result.ast,scope}}catch{parsed=void 0}cache.set(file,{mtimeMs,parsed});return parsed}function specName(node){return node.type==="Identifier"?node.name:node.value}function resolveIdentifier(node,site,options){const{depth}=options;if(depth>exports.MAX_RESOLVE_DEPTH)return UNKNOWN;const variable=(0,tool_registration_1.lookupVariable)(node.name,site.scope);const def=variable?.defs[0];if(def===void 0)return{kind:"global"};if(def.type==="ImportBinding"){const declaration=def.parent;if(declaration.type!=="ImportDeclaration")return UNKNOWN;const file=resolveRelative(site.file,declaration.source.value);if(file===void 0)return UNKNOWN;const spec=def.node;if(spec.type==="ImportNamespaceSpecifier")return{kind:"namespace",file};const imported=spec.type==="ImportDefaultSpecifier"?"default":specName(spec.imported);return resolveExport(file,imported,{...options,depth:depth+1})??UNKNOWN}if(def.type==="Variable"&&def.parent.kind==="const"&&def.node.id.type==="Identifier"&&def.node.init){return{kind:"value",node:def.node.init,site}}return DYNAMIC}function resolveExport(file,name,options){const{depth}=options;if(depth>exports.MAX_RESOLVE_DEPTH)return UNKNOWN;const parsed=parseModule(file,options.parser);if(parsed===void 0)return UNKNOWN;const site={scope:parsed.scope,file};const next={...options,depth:depth+1};for(const statement of parsed.ast.body){if(statement.type==="ExportDefaultDeclaration"){if(name!=="default")continue;const declaration2=statement.declaration;if(declaration2.type==="Identifier")return resolveIdentifier(declaration2,site,next);return declaration2.type.endsWith("Declaration")?DYNAMIC:{kind:"value",node:declaration2,site}}if(statement.type==="ExportAllDeclaration"){const target=resolveRelative(file,statement.source.value);if(statement.exported!==null){if(specName(statement.exported)!==name)continue;return target===void 0?UNKNOWN:{kind:"namespace",file:target}}const found=target&&resolveExport(target,name,next);if(found)return found;continue}if(statement.type!=="ExportNamedDeclaration")continue;const declaration=statement.declaration;if(declaration?.type==="VariableDeclaration"){for(const declarator of declaration.declarations){if(declarator.id.type!=="Identifier"||declarator.id.name!==name)continue;return declaration.kind==="const"&&declarator.init?{kind:"value",node:declarator.init,site}:DYNAMIC}}else if(declaration&&"id"in declaration&&declaration.id?.type==="Identifier"&&declaration.id.name===name){return DYNAMIC}for(const spec of statement.specifiers){if(specName(spec.exported)!==name)continue;if(statement.source===null)return resolveIdentifier(spec.local,site,next);const target=resolveRelative(file,statement.source.value);return target===void 0?UNKNOWN:resolveExport(target,specName(spec.local),next)??UNKNOWN}}return void 0}function resolveValue(node,site,options){const next={...options,depth:options.depth+1};const unwrapped=unwrapTypeOnly(node);if(unwrapped.type==="Identifier"){const found=resolveIdentifier(unwrapped,site,next);return found.kind==="value"?resolveValue(found.node,found.site,next):found}if(unwrapped.type==="MemberExpression"){const key=(0,eslint_devkit_1.propertyName)(unwrapped);if(key===null)return DYNAMIC;const base=resolveValue(unwrapped.object,site,next);if(base.kind==="namespace"){const found=resolveExport(base.file,key,next)??UNKNOWN;return found.kind==="value"?resolveValue(found.node,found.site,next):found}if(base.kind!=="value")return base;const object=unwrapTypeOnly(base.node);if(object.type!=="ObjectExpression")return DYNAMIC;let value=DYNAMIC;for(const prop of object.properties){if(prop.type==="SpreadElement"){value=DYNAMIC;continue}if(prop.computed)continue;const name=prop.key.type==="Identifier"?prop.key.name:(0,eslint_devkit_1.staticString)(prop.key);if(name===key)value={kind:"value",node:prop.value,site:base.site}}return value.kind==="value"?resolveValue(value.node,value.site,next):value}return{kind:"value",node:unwrapped,site}}function unwrapTypeOnly(node){let current=node;while(current.type==="TSAsExpression"||current.type==="TSSatisfiesExpression"||current.type==="TSTypeAssertion"||current.type==="TSNonNullExpression"){current=current.expression}return current}function siteOf(context,node){return{scope:context.sourceCode.getScope(node),file:context.filename}}function activeParser(context){return context.languageOptions?.parser}function valueResolverFor(context){const parser=activeParser(context);return node=>{const resolved=resolveValue(node,siteOf(context,node),{parser,depth:0});return resolved.kind==="value"?resolved.node:void 0}}function asFunction(node){const value=node?unwrapTypeOnly(node):void 0;return value?.type==="ArrowFunctionExpression"||value?.type==="FunctionExpression"||value?.type==="FunctionDeclaration"?value:void 0}function exportedFunction(file,name,parser){const parsed=parseModule(file,parser);if(parsed===void 0)return void 0;const site={scope:parsed.scope,file};for(const statement of parsed.ast.body){if(statement.type==="ExportDefaultDeclaration"){const fn=name==="default"?asFunction(statement.declaration):void 0;if(fn)return{fn,site};continue}if(statement.type!=="ExportNamedDeclaration")continue;const declaration=statement.declaration;if(declaration?.type==="FunctionDeclaration"&&declaration.id?.name===name)return{fn:declaration,site};if(declaration?.type!=="VariableDeclaration")continue;for(const declarator of declaration.declarations){const fn=asFunction(declarator.init);if(fn&&declaration.kind==="const"&&declarator.id.type==="Identifier"&&declarator.id.name===name)return{fn,site}}}return void 0}function resolveCalleeFunction(callee,site,parser){if(callee.type!=="Identifier")return void 0;const variable=(0,tool_registration_1.lookupVariable)(callee.name,site.scope);const def=variable?.defs[0];if(def?.type==="FunctionName"){for(const each of variable.defs){const fn=asFunction(each.node);if(fn)return{fn,site}}return void 0}if(def?.type==="Variable"){const fn=def.parent.kind==="const"?asFunction(def.node.init):void 0;return fn&&{fn,site}}if(def?.type!=="ImportBinding"||def.parent.type!=="ImportDeclaration")return void 0;const file=resolveRelative(site.file,def.parent.source.value);if(file===void 0)return void 0;const spec=def.node;const imported=spec.type==="ImportDefaultSpecifier"?"default":spec.type==="ImportSpecifier"?specName(spec.imported):void 0;return imported===void 0?void 0:exportedFunction(file,imported,parser)}function scopeAt(root,node){for(const child of root.childScopes){const[start,end]=child.block.range;if(start<=node.range[0]&&node.range[1]<=end)return scopeAt(child,node)}return root}
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __setModuleDefault=this&&this.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}):function(o,v){o["default"]=v});var __importStar=this&&this.__importStar||(function(){var ownKeys=function(o){ownKeys=Object.getOwnPropertyNames||function(o2){var ar=[];for(var k in o2)if(Object.prototype.hasOwnProperty.call(o2,k))ar[ar.length]=k;return ar};return ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null){for(var k=ownKeys(mod),i=0;i<k.length;i++)if(k[i]!=="default")__createBinding(result,mod,k[i])}__setModuleDefault(result,mod);return result}})();Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_CACHED_MODULES=exports.MAX_RESOLVE_DEPTH=void 0;exports.resolveRelative=resolveRelative;exports.cachedModuleCount=cachedModuleCount;exports.parseModule=parseModule;exports.resolveIdentifier=resolveIdentifier;exports.resolveExport=resolveExport;exports.resolveValue=resolveValue;exports.unwrapTypeOnly=unwrapTypeOnly;exports.siteOf=siteOf;exports.activeParser=activeParser;exports.valueResolverFor=valueResolverFor;exports.resolveCalleeFunction=resolveCalleeFunction;exports.scopeAt=scopeAt;const fs=__importStar(require("node:fs"));const path=__importStar(require("node:path"));const eslint_devkit_1=require("@interlace/eslint-devkit");const tool_registration_1=require("./tool-registration");exports.MAX_RESOLVE_DEPTH=12;const SOURCE_EXTENSIONS=[".ts",".tsx",".mts",".cts",".js",".jsx",".mjs",".cjs"];const TS_FOR_JS={".js":[".ts",".tsx"],".jsx":[".tsx"],".mjs":[".mts"],".cjs":[".cts"]};const UNKNOWN={kind:"unknown"};const DYNAMIC={kind:"dynamic"};function isFile(file){try{return fs.statSync(file).isFile()}catch{return false}}function resolveRelative(fromFile,specifier){if(!specifier.startsWith("./")&&!specifier.startsWith("../"))return void 0;const base=path.resolve(path.dirname(fromFile),specifier);const ext=path.extname(base);const stem=base.slice(0,base.length-ext.length);const candidates=[base,...(TS_FOR_JS[ext]??[]).map(e=>stem+e),...SOURCE_EXTENSIONS.map(e=>base+e),...SOURCE_EXTENSIONS.map(e=>path.join(base,`index${e}`))];return candidates.find(isFile)}exports.MAX_CACHED_MODULES=512;const caches=new WeakMap;function cachedModuleCount(parser){return caches.get(parser)?.size??0}function parseModule(file,parser){const parse=parser?.parseForESLint;if(typeof parse!=="function")return void 0;let mtimeMs;try{mtimeMs=fs.statSync(file).mtimeMs}catch{return void 0}let cache=caches.get(parser);if(cache===void 0){cache=(0,eslint_devkit_1.createLRUCache)(exports.MAX_CACHED_MODULES);caches.set(parser,cache)}const cached=cache.get(file);if(cached?.mtimeMs===mtimeMs)return cached.parsed;let parsed;try{const result=parse(fs.readFileSync(file,"utf8"),{sourceType:"module",ecmaVersion:"latest",range:true,loc:true,filePath:file});const scope=result.scopeManager?.scopes.find(s=>s.type==="module");if(scope)parsed={ast:result.ast,scope}}catch{parsed=void 0}cache.set(file,{mtimeMs,parsed});return parsed}function specName(node){return node.type==="Identifier"?node.name:node.value}function resolveIdentifier(node,site,options){const{depth}=options;if(depth>exports.MAX_RESOLVE_DEPTH)return UNKNOWN;const variable=(0,tool_registration_1.lookupVariable)(node.name,site.scope);const def=variable?.defs[0];if(def===void 0)return{kind:"global"};if(def.type==="ImportBinding"){const declaration=def.parent;if(declaration.type!=="ImportDeclaration")return UNKNOWN;const file=resolveRelative(site.file,declaration.source.value);if(file===void 0)return UNKNOWN;const spec=def.node;if(spec.type==="ImportNamespaceSpecifier")return{kind:"namespace",file};const imported=spec.type==="ImportDefaultSpecifier"?"default":specName(spec.imported);return resolveExport(file,imported,{...options,depth:depth+1})??UNKNOWN}if(def.type==="Variable"&&def.parent.kind==="const"&&def.node.id.type==="Identifier"&&def.node.init){return{kind:"value",node:def.node.init,site}}return DYNAMIC}function resolveExport(file,name,options){const{depth}=options;if(depth>exports.MAX_RESOLVE_DEPTH)return UNKNOWN;const parsed=parseModule(file,options.parser);if(parsed===void 0)return UNKNOWN;const site={scope:parsed.scope,file};const next={...options,depth:depth+1};for(const statement of parsed.ast.body){if(statement.type==="ExportDefaultDeclaration"){if(name!=="default")continue;const declaration2=statement.declaration;if(declaration2.type==="Identifier")return resolveIdentifier(declaration2,site,next);return declaration2.type.endsWith("Declaration")?DYNAMIC:{kind:"value",node:declaration2,site}}if(statement.type==="ExportAllDeclaration"){const target=resolveRelative(file,statement.source.value);if(statement.exported!==null){if(specName(statement.exported)!==name)continue;return target===void 0?UNKNOWN:{kind:"namespace",file:target}}const found=target&&resolveExport(target,name,next);if(found)return found;continue}if(statement.type!=="ExportNamedDeclaration")continue;const declaration=statement.declaration;if(declaration?.type==="VariableDeclaration"){for(const declarator of declaration.declarations){if(declarator.id.type!=="Identifier"||declarator.id.name!==name)continue;return declaration.kind==="const"&&declarator.init?{kind:"value",node:declarator.init,site}:DYNAMIC}}else if(declaration&&"id"in declaration&&declaration.id?.type==="Identifier"&&declaration.id.name===name){return DYNAMIC}for(const spec of statement.specifiers){if(specName(spec.exported)!==name)continue;if(statement.source===null)return resolveIdentifier(spec.local,site,next);const target=resolveRelative(file,statement.source.value);return target===void 0?UNKNOWN:resolveExport(target,specName(spec.local),next)??UNKNOWN}}return void 0}function resolveValue(node,site,options){const next={...options,depth:options.depth+1};const unwrapped=unwrapTypeOnly(node);if(unwrapped.type==="Identifier"){const found=resolveIdentifier(unwrapped,site,next);return found.kind==="value"?resolveValue(found.node,found.site,next):found}if(unwrapped.type==="MemberExpression"){const key=(0,eslint_devkit_1.propertyName)(unwrapped);if(key===null)return DYNAMIC;const base=resolveValue(unwrapped.object,site,next);if(base.kind==="namespace"){const found=resolveExport(base.file,key,next)??UNKNOWN;return found.kind==="value"?resolveValue(found.node,found.site,next):found}if(base.kind!=="value")return base;const object=unwrapTypeOnly(base.node);if(object.type!=="ObjectExpression")return DYNAMIC;let value=DYNAMIC;for(const prop of object.properties){if(prop.type==="SpreadElement"){value=DYNAMIC;continue}if(prop.computed)continue;const name=prop.key.type==="Identifier"?prop.key.name:(0,eslint_devkit_1.staticString)(prop.key);if(name===key)value={kind:"value",node:prop.value,site:base.site}}return value.kind==="value"?resolveValue(value.node,value.site,next):value}return{kind:"value",node:unwrapped,site}}function unwrapTypeOnly(node){let current=node;while(current.type==="TSAsExpression"||current.type==="TSSatisfiesExpression"||current.type==="TSTypeAssertion"||current.type==="TSNonNullExpression"){current=current.expression}return current}function siteOf(context,node){return{scope:context.sourceCode.getScope(node),file:context.filename}}function activeParser(context){return context.languageOptions?.parser}function valueResolverFor(context){const parser=activeParser(context);return node=>{const resolved=resolveValue(node,siteOf(context,node),{parser,depth:0});return resolved.kind==="value"?resolved.node:void 0}}function asFunction(node){const value=node?unwrapTypeOnly(node):void 0;return value?.type==="ArrowFunctionExpression"||value?.type==="FunctionExpression"||value?.type==="FunctionDeclaration"?value:void 0}function exportedFunction(file,name,parser){const parsed=parseModule(file,parser);if(parsed===void 0)return void 0;const site={scope:parsed.scope,file};for(const statement of parsed.ast.body){if(statement.type==="ExportDefaultDeclaration"){const fn=name==="default"?asFunction(statement.declaration):void 0;if(fn)return{fn,site};continue}if(statement.type!=="ExportNamedDeclaration")continue;const declaration=statement.declaration;if(declaration?.type==="FunctionDeclaration"&&declaration.id?.name===name)return{fn:declaration,site};if(declaration?.type!=="VariableDeclaration")continue;for(const declarator of declaration.declarations){const fn=asFunction(declarator.init);if(fn&&declaration.kind==="const"&&declarator.id.type==="Identifier"&&declarator.id.name===name)return{fn,site}}}return void 0}function resolveCalleeFunction(callee,site,parser){if(callee.type!=="Identifier")return void 0;const variable=(0,tool_registration_1.lookupVariable)(callee.name,site.scope);const def=variable?.defs[0];if(def?.type==="FunctionName"){for(const each of variable.defs){const fn=asFunction(each.node);if(fn)return{fn,site}}return void 0}if(def?.type==="Variable"){const fn=def.parent.kind==="const"?asFunction(def.node.init):void 0;return fn&&{fn,site}}if(def?.type!=="ImportBinding"||def.parent.type!=="ImportDeclaration")return void 0;const file=resolveRelative(site.file,def.parent.source.value);if(file===void 0)return void 0;const spec=def.node;const imported=spec.type==="ImportDefaultSpecifier"?"default":spec.type==="ImportSpecifier"?specName(spec.imported):void 0;return imported===void 0?void 0:exportedFunction(file,imported,parser)}function scopeAt(root,node){for(const child of root.childScopes){const[start,end]=child.block.range;if(start<=node.range[0]&&node.range[1]<=end)return scopeAt(child,node)}return root}