eslint-plugin-mcp-sdk-security 0.6.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/index.js +1 -1
- package/src/rules/no-code-injection-in-tool/index.js +1 -1
- package/src/rules/no-command-injection-in-tool/index.js +1 -1
- package/src/rules/no-credential-leak-in-tool/index.js +1 -1
- package/src/rules/no-path-traversal-in-tool/index.js +1 -1
- package/src/rules/no-sql-injection-in-tool/index.js +1 -1
- package/src/rules/no-ssrf-in-tool/index.js +1 -1
- package/src/rules/no-tool-description-injection/index.js +1 -1
- package/src/rules/no-untrusted-stdio-command/index.js +1 -1
- package/src/rules/no-untrusted-tool-metadata-in-prompt/index.js +1 -1
- package/src/rules/require-http-transport-hardening/index.js +1 -1
- package/src/utils/guards.js +1 -1
- package/src/utils/module-resolver.js +1 -1
- package/src/utils/tool-registration.js +1 -1
- package/src/utils/value-flow.js +1 -1
- package/src/utils/zod.js +1 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "eslint-plugin-mcp-sdk-security",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.1",
|
|
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",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
}
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
77
|
-
"@interlace/eslint-devkit": "^1.
|
|
77
|
+
"@interlace/eslint-devkit": "^1.20.2"
|
|
78
78
|
},
|
|
79
79
|
"funding": {
|
|
80
80
|
"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:"0.
|
|
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.1"},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));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:{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 +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));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:{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 +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));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});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:{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 +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);const guards=(0,guards_1.createGuards)(sourceCode,variable=>{const name=variable.defs[0]?.name;return name!==void 0&&carries(name)!==null},(node,involves)
|
|
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 +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"])}};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));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:{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 +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 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});const value=node=>{const t=carries(node);return t?.kind==="value"?t:null};const originOf=(node,depth)=>{if(depth>
|
|
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 +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 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)?{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);return fsName!==void 0&&FILE_READS.has(fsName)?{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});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&¤t.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:{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&¤t.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))}));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:{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 +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});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:{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 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireHttpTransportHardening=void 0;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 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 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 unhardened=[];let constructsTransport=false;let servesV2=false;const rawApps=[];let validatesHost=false;let authenticates=false;let customUse=false;const binds=[];const handleRequestCalls=[];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_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);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"){context.report({node,messageId:"allInterfacesWithoutAllowedHosts",data:{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)}else if(method==="listen"){const[first,second]=node.arguments;const options=first?.type==="ObjectExpression"?readOptions(first):null;const hostNode=options===null?second:options.get("host");const host=hostNode===void 0?null:hostOf(hostNode);if(host!==null&&ALL_INTERFACE_HOSTS.has(host))binds.push({node,host})}},"Program:exit"(){if(!validatesHost){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||customUse||routeHasMiddleware())return;for(const{node,host}of binds)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:{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}})}}}});
|
package/src/utils/guards.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_GUARD_DEPTH=void 0;exports.exits=exits;exports.createGuards=createGuards;const tool_registration_1=require("./tool-registration");exports.MAX_GUARD_DEPTH=6;function exits(node){if(node.type==="ThrowStatement"||node.type==="ReturnStatement")return true;return node.type==="BlockStatement"&&node.body.some(s=>s.type==="ThrowStatement"||s.type==="ReturnStatement")}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}function isReference(node){const parent=node.parent;if(parent?.type==="MemberExpression")return parent.object===node||parent.computed;if(parent?.type==="Property"&&parent.key===node)return parent.computed||parent.shorthand;return true}function createGuards(sourceCode,isTainted,isCheck){function lineage(node){const seen=new Set;const visit=current=>{if((0,tool_registration_1.isFunctionNode)(current))return;if(current.type==="Identifier"){if(!isReference(current))return;const variable=(0,tool_registration_1.lookupVariable)(current.name,sourceCode.getScope(current));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)}for(const ref of variable.references){const parent=ref.identifier.parent;if(ref.isWrite()&&parent?.type==="AssignmentExpression"&&parent.left===ref.identifier)visit(parent.right)}return}for(const child of children(current))visit(child)};visit(node);return seen}function checks(test,targets){const involves=n=>{for(const variable of lineage(n))if(targets.has(variable))return true;return false};const visited=new Set;const visit=(current,depth)=>{if((0,tool_registration_1.isFunctionNode)(current))return false;if(isCheck(current,involves))return true;if(current.type==="Identifier"){const variable=(0,tool_registration_1.lookupVariable)(current.name,sourceCode.getScope(current));if(variable===void 0||visited.has(variable)||depth>=exports.MAX_GUARD_DEPTH)return false;visited.add(variable);return variable.defs.some(def=>def.type==="Variable"&&def.node.init!==null&&visit(def.node.init,depth+1))}return children(current).some(child=>visit(child,depth))};return visit(test,0)}function guarded(sink,arg){const targets=new Set([...lineage(arg)].filter(isTainted));let child=sink;for(let parent=sink.parent;parent;parent=parent.parent){if(parent.type==="IfStatement"&&parent.consequent===child&&checks(parent.test,targets))return true;if(parent.type==="BlockStatement"||parent.type==="Program"){for(const statement of parent.body){if(statement===child)break;if(statement.type==="IfStatement"&&exits(statement.consequent)&&checks(statement.test,targets))return true}}child=parent}return false}function sanitizes(fn){const params=new Set(sourceCode.getDeclaredVariables(fn).filter(v=>v.defs.some(d=>d.type==="Parameter")));if(params.size===0||fn.body.type!=="BlockStatement")return false;const visit=
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_GUARD_DEPTH=void 0;exports.isConversion=isConversion;exports.exits=exits;exports.createGuards=createGuards;const tool_registration_1=require("./tool-registration");exports.MAX_GUARD_DEPTH=6;const CONVERSIONS=new Set(["String","Number","Boolean"]);function isConversion(node,scope){const{callee}=node;return callee.type==="Identifier"&&CONVERSIONS.has(callee.name)&&!(0,tool_registration_1.lookupVariable)(callee.name,scope)?.defs.length}function exits(node){if(node.type==="ThrowStatement"||node.type==="ReturnStatement")return true;return node.type==="BlockStatement"&&node.body.some(s=>s.type==="ThrowStatement"||s.type==="ReturnStatement")}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}function isReference(node){const parent=node.parent;if(parent?.type==="MemberExpression")return parent.object===node||parent.computed;if(parent?.type==="Property"&&parent.key===node)return parent.computed||parent.shorthand;return true}function createGuards(sourceCode,isTainted,isCheck){function lineage(node){const seen=new Set;const visit=current=>{if((0,tool_registration_1.isFunctionNode)(current))return;if(current.type==="Identifier"){if(!isReference(current))return;const variable=(0,tool_registration_1.lookupVariable)(current.name,sourceCode.getScope(current));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)}for(const ref of variable.references){const parent=ref.identifier.parent;if(ref.isWrite()&&parent?.type==="AssignmentExpression"&&parent.left===ref.identifier)visit(parent.right)}return}for(const child of children(current))visit(child)};visit(node);return seen}function checks(test,targets){const involves=n=>{for(const variable of lineage(n))if(targets.has(variable))return true;return false};const visited=new Set;const visit=(current,depth)=>{if((0,tool_registration_1.isFunctionNode)(current)&¤t.parent?.type!=="CallExpression")return false;if(isCheck(current,involves))return true;if(current.type==="CallExpression"&&!isConversion(current,sourceCode.getScope(current)))return current.arguments.some(arg=>(0,tool_registration_1.isFunctionNode)(arg)&&visit(arg,depth));if(current.type==="Identifier"){const variable=(0,tool_registration_1.lookupVariable)(current.name,sourceCode.getScope(current));if(variable===void 0||visited.has(variable)||depth>=exports.MAX_GUARD_DEPTH)return false;visited.add(variable);return variable.defs.some(def=>def.type==="Variable"&&def.node.init!==null&&visit(def.node.init,depth+1))}return children(current).some(child=>visit(child,depth))};return visit(test,0)}function guarded(sink,arg){const targets=new Set([...lineage(arg)].filter(isTainted));let child=sink;for(let parent=sink.parent;parent;parent=parent.parent){if(parent.type==="IfStatement"&&parent.consequent===child&&checks(parent.test,targets))return true;if(parent.type==="BlockStatement"||parent.type==="Program"){for(const statement of parent.body){if(statement===child)break;if(statement.type==="IfStatement"&&exits(statement.consequent)&&checks(statement.test,targets))return true}}child=parent}return false}function sanitizes(fn){const params=new Set(sourceCode.getDeclaredVariables(fn).filter(v=>v.defs.some(d=>d.type==="Parameter")));if(params.size===0||fn.body.type!=="BlockStatement")return false;const visit=statements=>statements.some(node=>node.type==="IfStatement"&&exits(node.consequent)&&checks(node.test,params)||node.type==="TryStatement"&&visit(node.block.body)||node.type==="BlockStatement"&&visit(node.body));return visit(fn.body.body)}return{lineage,guarded,sanitizes}}
|
|
@@ -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=
|
|
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}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HANDLER_CONTEXT_KEYS=exports.LEGACY_TOOL=exports.REGISTER_TOOL=void 0;exports.isFunctionNode=isFunctionNode;exports.lookupVariable=lookupVariable;exports.constInitializer=constInitializer;exports.resolveFunction=resolveFunction;exports.classifyLegacyObject=classifyLegacyObject;exports.calledMethod=calledMethod;exports.toolNameOf=toolNameOf;exports.readRegistration=readRegistration;exports.configSchema=configSchema;exports.propertyKey=propertyKey;exports.schemaFields=schemaFields;exports.isClosedSetSchema=isClosedSetSchema;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.REGISTER_TOOL="registerTool";exports.LEGACY_TOOL="tool";function isFunctionNode(node){return node?.type==="ArrowFunctionExpression"||node?.type==="FunctionExpression"||node?.type==="FunctionDeclaration"}function lookupVariable(name,scope){for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable)return variable}return void 0}function constInitializer(node,scope){const def=lookupVariable(node.name,scope)?.defs[0];if(def?.type!=="Variable")return void 0;if(def.parent.kind!=="const")return void 0;if(def.node.id.type!=="Identifier")return void 0;return def.node.init??void 0}function resolveFunction(node,scope){if(node===void 0)return void 0;if(isFunctionNode(node))return node;if(node.type!=="Identifier")return void 0;const variable=lookupVariable(node.name,scope);if(variable?.defs[0]?.type==="FunctionName")return variable.defs.map(def=>def.node).find(isFunctionNode);const init=constInitializer(node,scope);return isFunctionNode(init)?init:void 0}function classifyLegacyObject(node,resolve){if(node.properties.length===0)return"shape";let calls=0;let literals=0;for(const prop of node.properties){if(prop.type!=="Property"||prop.computed)return"unknown";let value=prop.value;if(resolve&&(value.type==="Identifier"||value.type==="MemberExpression"))value=resolve(value)??value;if(value.type==="CallExpression")calls++;else if(value.type==="Literal"||value.type==="TemplateLiteral")literals++}if(calls===node.properties.length)return"shape";if(literals===node.properties.length)return"annotations";return"unknown"}function isStringShaped(node){return node.type==="Literal"&&typeof node.value==="string"||node.type==="TemplateLiteral"||node.type==="TaggedTemplateExpression"||node.type==="BinaryExpression"&&node.operator==="+"}function calledMethod(node){if(node.callee.type!=="MemberExpression")return null;return(0,eslint_devkit_1.propertyName)(node.callee)}function toolNameOf(node){return(0,eslint_devkit_1.staticString)(node.arguments[0])??"unknown"}function readRegistration(node,resolve){const method=calledMethod(node);const args=node.arguments;if(method===exports.REGISTER_TOOL){const config=args[1];const handler2=args.length>=3?args[args.length-1]:void 0;if(config?.type!=="ObjectExpression"){return{method,call:node,schema:{kind:"unknown"},handler:handler2}}return{method,call:node,config,schema:configSchema(config),handler:handler2}}if(method!==exports.LEGACY_TOOL||args.length<2)return void 0;const handler=args[args.length-1];const last=args.length-1;const registration={method,call:node,schema:{kind:"none"},handler};let index=1;const first=args[1];if(index<last&&first.type!=="ObjectExpression"&&!isFunctionNode(first)&&(isStringShaped(first)||args.length>=4)){registration.description=first;index=2}if(index<last){const slot=args[index];if(slot.type!=="ObjectExpression"){registration.schema={kind:"unknown"}}else{const kind=classifyLegacyObject(slot,resolve);if(kind==="shape"){registration.schema={kind:"schema",node:slot};const next=args[index+1];if(index+1<last&&next.type==="ObjectExpression")registration.annotations=next}else if(kind==="annotations"){registration.annotations=slot}else{registration.schema={kind:"unknown"}}}}return registration}function configSchema(config){let state={kind:"none"};for(const prop of config.properties){if(prop.type==="SpreadElement"){state={kind:"unknown"};continue}if((0,eslint_devkit_1.objectKeyName)(prop)==="inputSchema")state={kind:"schema",node:prop.value}}return state}function propertyKey(prop){if(prop.type!=="Property")return void 0;return(0,eslint_devkit_1.objectKeyName)(prop)??void 0}const KEY_PRESERVING=new Set(["strict","strip","describe","partial","required","readonly","meta"]);const LOOSENING=new Set(["passthrough","loose"]);const OBJECT_CONSTRUCTORS=new Set(["object","strictObject"]);const LOOSE_CONSTRUCTORS=new Set(["looseObject"]);function schemaFields(node){let loose=false;let current=node;while(current.type==="CallExpression"){if(current.callee.type!=="MemberExpression")return void 0;const method=(0,eslint_devkit_1.propertyName)(current.callee);if(method===null)return void 0;if(OBJECT_CONSTRUCTORS.has(method)||LOOSE_CONSTRUCTORS.has(method)){if(LOOSE_CONSTRUCTORS.has(method))loose=true;const shape=current.arguments[0];if(current.arguments.length!==1||shape?.type!=="ObjectExpression")return void 0;current=shape;break}if(LOOSENING.has(method))loose=true;else if(!KEY_PRESERVING.has(method))return void 0;current=current.callee.object}if(current.type!=="ObjectExpression")return void 0;const fields=new Map;for(const entry of current.properties){if(entry.type==="SpreadElement")return void 0;const key=propertyKey(entry);if(key===void 0)return void 0;fields.set(key,entry.value)}return{fields,loose}}function isClosedSetSchema(node){let current=node;let innermost=null;while(current.type==="CallExpression"&¤t.callee.type==="MemberExpression"){innermost=(0,eslint_devkit_1.propertyName)(current.callee);current=current.callee.object}return innermost==="enum"||innermost==="literal"||innermost==="nativeEnum"}exports.HANDLER_CONTEXT_KEYS=new Set(["signal","authInfo","sessionId","_meta","requestId","requestInfo","sendNotification","sendRequest","taskStore","taskId","taskRequestedTtl","closeSSEStream","closeStandaloneSSEStream","mcpReq","http"]);
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.HANDLER_CONTEXT_KEYS=exports.LEGACY_TOOL=exports.REGISTER_TOOL=void 0;exports.isFunctionNode=isFunctionNode;exports.lookupVariable=lookupVariable;exports.constInitializer=constInitializer;exports.resolveFunction=resolveFunction;exports.classMethodOf=classMethodOf;exports.classifyLegacyObject=classifyLegacyObject;exports.calledMethod=calledMethod;exports.toolNameOf=toolNameOf;exports.readRegistration=readRegistration;exports.configSchema=configSchema;exports.propertyKey=propertyKey;exports.schemaFields=schemaFields;exports.isClosedSetSchema=isClosedSetSchema;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.REGISTER_TOOL="registerTool";exports.LEGACY_TOOL="tool";function isFunctionNode(node){return node?.type==="ArrowFunctionExpression"||node?.type==="FunctionExpression"||node?.type==="FunctionDeclaration"}function lookupVariable(name,scope){for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable)return variable}return void 0}function constInitializer(node,scope){const def=lookupVariable(node.name,scope)?.defs[0];if(def?.type!=="Variable")return void 0;if(def.parent.kind!=="const")return void 0;if(def.node.id.type!=="Identifier")return void 0;return def.node.init??void 0}function resolveFunction(node,scope){if(node===void 0)return void 0;if(isFunctionNode(node))return node;if(node.type==="MemberExpression")return classMethodOf(node);if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&memberKey(node.callee.property,node.callee.computed)==="bind")return resolveFunction(node.callee.object,scope);if(node.type!=="Identifier")return void 0;const variable=lookupVariable(node.name,scope);if(variable?.defs[0]?.type==="FunctionName")return variable.defs.map(def=>def.node).find(isFunctionNode);const init=constInitializer(node,scope);return isFunctionNode(init)?init:void 0}function thisClass(node){for(let current=node.parent;current;current=current.parent){if(current.type==="ClassBody")return current;if((current.type==="FunctionExpression"||current.type==="FunctionDeclaration")&¤t.parent?.type!=="MethodDefinition"&¤t.parent?.type!=="PropertyDefinition")return void 0}return void 0}function memberKey(key,computed){if(computed)return void 0;if(key.type==="PrivateIdentifier")return`#${key.name}`;return key.type==="Identifier"?key.name:void 0}function classMethodOf(node){if(node.object.type!=="ThisExpression")return void 0;const name=memberKey(node.property,node.computed);const body=name===void 0?void 0:thisClass(node);for(const member of body?.body??[]){if(member.type!=="MethodDefinition"&&member.type!=="PropertyDefinition"||memberKey(member.key,member.computed)!==name)continue;return isFunctionNode(member.value)?member.value:void 0}return void 0}function classifyLegacyObject(node,resolve){if(node.properties.length===0)return"shape";let calls=0;let literals=0;for(const prop of node.properties){if(prop.type!=="Property"||prop.computed)return"unknown";let value=prop.value;if(resolve&&(value.type==="Identifier"||value.type==="MemberExpression"))value=resolve(value)??value;if(value.type==="CallExpression")calls++;else if(value.type==="Literal"||value.type==="TemplateLiteral")literals++}if(calls===node.properties.length)return"shape";if(literals===node.properties.length)return"annotations";return"unknown"}function isStringShaped(node){return node.type==="Literal"&&typeof node.value==="string"||node.type==="TemplateLiteral"||node.type==="TaggedTemplateExpression"||node.type==="BinaryExpression"&&node.operator==="+"}function calledMethod(node){if(node.callee.type!=="MemberExpression")return null;return(0,eslint_devkit_1.propertyName)(node.callee)}function toolNameOf(node){return(0,eslint_devkit_1.staticString)(node.arguments[0])??"unknown"}function readRegistration(node,resolve){const method=calledMethod(node);const args=node.arguments;if(method===exports.REGISTER_TOOL){const config=args[1];const handler2=args.length>=3?args[args.length-1]:void 0;if(config?.type!=="ObjectExpression"){return{method,call:node,schema:{kind:"unknown"},handler:handler2}}return{method,call:node,config,schema:configSchema(config),handler:handler2}}if(method!==exports.LEGACY_TOOL||args.length<2)return void 0;const handler=args[args.length-1];const last=args.length-1;const registration={method,call:node,schema:{kind:"none"},handler};let index=1;const first=args[1];if(index<last&&first.type!=="ObjectExpression"&&!isFunctionNode(first)&&(isStringShaped(first)||args.length>=4)){registration.description=first;index=2}if(index<last){const slot=args[index];if(slot.type!=="ObjectExpression"){registration.schema={kind:"unknown"}}else{const kind=classifyLegacyObject(slot,resolve);if(kind==="shape"){registration.schema={kind:"schema",node:slot};const next=args[index+1];if(index+1<last&&next.type==="ObjectExpression")registration.annotations=next}else if(kind==="annotations"){registration.annotations=slot}else{registration.schema={kind:"unknown"}}}}return registration}function configSchema(config){let state={kind:"none"};for(const prop of config.properties){if(prop.type==="SpreadElement"){state={kind:"unknown"};continue}if((0,eslint_devkit_1.objectKeyName)(prop)==="inputSchema")state={kind:"schema",node:prop.value}}return state}function propertyKey(prop){if(prop.type!=="Property")return void 0;return(0,eslint_devkit_1.objectKeyName)(prop)??void 0}const KEY_PRESERVING=new Set(["strict","strip","describe","partial","required","readonly","meta"]);const LOOSENING=new Set(["passthrough","loose"]);const OBJECT_CONSTRUCTORS=new Set(["object","strictObject"]);const LOOSE_CONSTRUCTORS=new Set(["looseObject"]);function schemaFields(node){let loose=false;let current=node;while(current.type==="CallExpression"){if(current.callee.type!=="MemberExpression")return void 0;const method=(0,eslint_devkit_1.propertyName)(current.callee);if(method===null)return void 0;if(OBJECT_CONSTRUCTORS.has(method)||LOOSE_CONSTRUCTORS.has(method)){if(LOOSE_CONSTRUCTORS.has(method))loose=true;const shape=current.arguments[0];if(current.arguments.length!==1||shape?.type!=="ObjectExpression")return void 0;current=shape;break}if(LOOSENING.has(method))loose=true;else if(!KEY_PRESERVING.has(method))return void 0;current=current.callee.object}if(current.type!=="ObjectExpression")return void 0;const fields=new Map;for(const entry of current.properties){if(entry.type==="SpreadElement")return void 0;const key=propertyKey(entry);if(key===void 0)return void 0;fields.set(key,entry.value)}return{fields,loose}}function isClosedSetSchema(node){let current=node;let innermost=null;while(current.type==="CallExpression"&¤t.callee.type==="MemberExpression"){innermost=(0,eslint_devkit_1.propertyName)(current.callee);current=current.callee.object}return innermost==="enum"||innermost==="literal"||innermost==="nativeEnum"}exports.HANDLER_CONTEXT_KEYS=new Set(["signal","authInfo","sessionId","_meta","requestId","requestInfo","sendNotification","sendRequest","taskStore","taskId","taskRequestedTtl","closeSSEStream","closeStandaloneSSEStream","mcpReq","http"]);
|
package/src/utils/value-flow.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.STRING_DERIVING=exports.MAX_FLOW_DEPTH=void 0;exports.memberStep=memberStep;exports.throughPattern=throughPattern;exports.returnedExpressions=returnedExpressions;exports.createFlow=createFlow;const eslint_devkit_1=require("@interlace/eslint-devkit");const tool_registration_1=require("./tool-registration");exports.MAX_FLOW_DEPTH=16;exports.STRING_DERIVING=new Set(["trim","trimStart","trimEnd","split","slice","substring","substr","toLowerCase","toUpperCase","toLocaleLowerCase","toLocaleUpperCase","replace","replaceAll","padStart","padEnd","normalize","at","toString","valueOf","concat","join","repeat"]);function memberStep(t,key){if(t.kind==="value")return key===null?t:{...t,text:`${t.text}.${key}`};if(key===null)return null;const text=t.text===""?key:`${t.text}.${key}`;if(t.toArgs.length===0){if(t.closed?.has(key))return null;return{kind:"value",text,key}}return t.toArgs[0]===key?{kind:"object",text,toArgs:t.toArgs.slice(1),closed:t.closed}:null}function throughPattern(pattern,target,source){if(pattern===target)return source;if(pattern.type==="AssignmentPattern")return throughPattern(pattern.left,target,source);if(pattern.type==="ObjectPattern"){for(const prop of pattern.properties){let found;if(prop.type==="RestElement"){const rest=source?.kind==="object"&&source.toArgs.length>0?null:source;found=throughPattern(prop.argument,target,rest)}else{const key=(0,tool_registration_1.propertyKey)(prop)??null;found=throughPattern(prop.value,target,source&&memberStep(source,key))}if(found!==void 0)return found}return void 0}if(pattern.type==="ArrayPattern"){for(const element of pattern.elements){if(element===null)continue;const inner=element.type==="RestElement"?element.argument:element;const found=throughPattern(inner,target,source&&memberStep(source,null));if(found!==void 0)return found}}return void 0}function returnedExpressions(fn){if(fn.body.type!=="BlockStatement")return[fn.body];const found=[];const visit=node=>{if(node.type==="ReturnStatement"){if(node.argument)found.push(node.argument);return}if((0,tool_registration_1.isFunctionNode)(node))return;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)}}};for(const statement of fn.body.body)visit(statement);return found}const PATTERN_PARTS=new Set(["Property","ObjectPattern","ArrayPattern","RestElement","AssignmentPattern"]);function createFlow(sourceCode,handlerRoot,intercept){const active=new Set;function ofIdentifier(node,depth,env){const variable=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node));if(variable===void 0)return null;if(env.has(variable))return env.get(variable);const def=variable.defs[0];if(def?.type==="Parameter"){const fn=def.node;const root=handlerRoot(fn);const param=root&&fn.params[root.param??0];if(param===void 0)return null;const t=throughPattern(param,def.name,{kind:"object",text:"",toArgs:root.toArgs,closed:root.closed});return t?{...t,text:node.name}:null}if(def?.type!=="Variable")return null;const sources=[];const declarator=def.node;if(declarator.init){sources.push(throughPattern(declarator.id,def.name,taint(declarator.init,depth+1,env)))}for(const ref of variable.references){if(!ref.isWrite()||ref.identifier===def.name)continue;let assignment=ref.identifier.parent;while(assignment&&PATTERN_PARTS.has(assignment.type))assignment=assignment.parent;if(assignment?.type!=="AssignmentExpression")continue;sources.push(throughPattern(assignment.left,ref.identifier,taint(assignment.right,depth+1,env)))}const found=sources.find(t=>t)??null;return found?.kind==="object"?{...found,text:node.name}:found}function ofCall(node,depth,env){const{callee}=node;if(callee.type==="Identifier"&&callee.name==="String"&&!(0,tool_registration_1.lookupVariable)("String",sourceCode.getScope(node))?.defs.length){const arg=node.arguments[0];return arg?asValue(taint(arg,depth+1,env)):null}if(callee.type==="MemberExpression"){const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null||!exports.STRING_DERIVING.has(method))return null;const receiver=asValue(taint(callee.object,depth+1,env));if(receiver||method!=="concat")return receiver;for(const arg of node.arguments){const t=asValue(taint(arg,depth+1,env));if(t)return t}return null}const fn=(0,tool_registration_1.resolveFunction)(callee,sourceCode.getScope(node));if(fn===void 0)return null;const bound=new Map(env);const params=sourceCode.getDeclaredVariables(fn);fn.params.forEach((param,i)=>{const variable=params.find(v=>v.defs[0]?.name===param);const arg=node.arguments[i];if(variable&&arg)bound.set(variable,taint(arg,depth+1,env))});let object=null;for(const expression of returnedExpressions(fn)){const t=taint(expression,depth+1,bound);if(t?.kind==="value")return t;object??=t}return object}function taint(node,depth,env){if(depth>exports.MAX_FLOW_DEPTH||active.has(node))return null;active.add(node);try{return compute(node,depth,env)}finally{active.delete(node)}}function firstOf(nodes,depth,env,valuesOnly){for(const node of nodes){if(node===null)continue;const inner=node.type==="SpreadElement"?node.argument:node;const t=taint(inner,depth+1,env);const kept=valuesOnly?asValue(t):t;if(kept)return kept}return null}function compute(node,depth,env){const decided=intercept?.(node,next=>taint(next,depth+1,env));if(decided!==void 0)return decided;switch(node.type){case"Identifier":return ofIdentifier(node,depth,env);case"MemberExpression":{const object=taint(node.object,depth+1,env);return object&&memberStep(object,(0,eslint_devkit_1.propertyName)(node))}case"CallExpression":return ofCall(node,depth,env);case"TemplateLiteral":return firstOf(node.expressions,depth,env,true);case"ArrayExpression":return firstOf(node.elements,depth,env,true);case"BinaryExpression":return node.operator==="+"?firstOf([node.left,node.right],depth,env,true):null;case"LogicalExpression":return firstOf([node.left,node.right],depth,env,false);case"ConditionalExpression":return firstOf([node.consequent,node.alternate],depth,env,false);case"SequenceExpression":return taint(node.expressions[node.expressions.length-1],depth+1,env);case"AwaitExpression":case"ChainExpression":case"TSAsExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"TSSatisfiesExpression":{const inner=node.type==="AwaitExpression"?node.argument:node.expression;return taint(inner,depth+1,env)}default:return null}}return node=>taint(node,0,new Map)}function asValue(t){return t?.kind==="value"?t:null}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.STRING_DERIVING=exports.MAX_FLOW_DEPTH=void 0;exports.memberStep=memberStep;exports.throughPattern=throughPattern;exports.returnedExpressions=returnedExpressions;exports.flowOptionsFor=flowOptionsFor;exports.callSitesIn=callSitesIn;exports.createFlow=createFlow;const eslint_devkit_1=require("@interlace/eslint-devkit");const tool_registration_1=require("./tool-registration");const zod_1=require("./zod");exports.MAX_FLOW_DEPTH=16;exports.STRING_DERIVING=new Set(["trim","trimStart","trimEnd","split","slice","substring","substr","toLowerCase","toUpperCase","toLocaleLowerCase","toLocaleUpperCase","replace","replaceAll","padStart","padEnd","normalize","at","toString","valueOf","concat","join","repeat"]);const ELEMENT_CALLBACKS=new Set(["map","flatMap","forEach","filter","find","findLast","findIndex","some","every"]);const ARRAY_SELECTORS=new Set(["filter","find","findLast","sort","reverse","flat","toSorted","toReversed"]);const ARRAY_MAPPERS=new Set(["map","flatMap"]);function memberStep(t,key){if(t.kind==="value")return key===null?t:{...t,text:`${t.text}.${key}`};if(key===null)return null;const text=t.text===""?key:`${t.text}.${key}`;if(t.toArgs.length===0){if(t.closed?.has(key))return null;return{kind:"value",text,key}}return t.toArgs[0]===key?{kind:"object",text,toArgs:t.toArgs.slice(1),closed:t.closed}:null}function throughPattern(pattern,target,source){if(pattern===target)return source;if(pattern.type==="AssignmentPattern")return throughPattern(pattern.left,target,source);if(pattern.type==="ObjectPattern"){for(const prop of pattern.properties){let found;if(prop.type==="RestElement"){const rest=source?.kind==="object"&&source.toArgs.length>0?null:source;found=throughPattern(prop.argument,target,rest)}else{const key=(0,tool_registration_1.propertyKey)(prop)??null;found=throughPattern(prop.value,target,source&&memberStep(source,key))}if(found!==void 0)return found}return void 0}if(pattern.type==="ArrayPattern"){for(const element of pattern.elements){if(element===null)continue;const inner=element.type==="RestElement"?element.argument:element;const found=throughPattern(inner,target,source&&memberStep(source,null));if(found!==void 0)return found}}return void 0}function returnedExpressions(fn){if(fn.body.type!=="BlockStatement")return[fn.body];const found=[];const visit=node=>{if(node.type==="ReturnStatement"){if(node.argument)found.push(node.argument);return}if((0,tool_registration_1.isFunctionNode)(node))return;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)}}};for(const statement of fn.body.body)visit(statement);return found}const PATTERN_PARTS=new Set(["Property","ObjectPattern","ArrayPattern","RestElement","AssignmentPattern"]);function flowOptionsFor(context,blocksCallSite){return{parser:context.languageOptions?.parser,file:context.filename,blocksCallSite}}function childNodes(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}const callIndexes=new WeakMap;function callSitesIn(sourceCode){return fn=>{let index=callIndexes.get(sourceCode.ast);if(index===void 0){const built=new Map;const visit=node=>{if(node.type==="CallExpression"){const target=(0,tool_registration_1.resolveFunction)(node.callee,sourceCode.getScope(node));if(target!==void 0){const calls=built.get(target)??[];calls.push(node);built.set(target,calls)}}for(const child of childNodes(node))visit(child)};visit(sourceCode.ast);callIndexes.set(sourceCode.ast,built);index=built}return index.get(fn)??[]}}function keyPath(pattern,target){if(pattern===target)return[];if(pattern.type==="AssignmentPattern")return keyPath(pattern.left,target);if(pattern.type!=="ObjectPattern")return void 0;for(const prop of pattern.properties){if(prop.type==="RestElement")continue;const key=(0,tool_registration_1.propertyKey)(prop);const rest=key===void 0?void 0:keyPath(prop.value,target);if(rest)return[key,...rest]}return void 0}function binds(pattern,target){if(pattern===target)return true;return childNodes(pattern).some(child=>binds(child,target))}function createFlow(sourceCode,handlerRoot,intercept,options){const active=new Set;const callsOf=callSitesIn(sourceCode);function fieldOf(node,path,depth,env){if(path.length===0)return taint(node,depth+1,env);let literal=node;if(literal.type==="Identifier"){const def=(0,tool_registration_1.lookupVariable)(literal.name,sourceCode.getScope(literal))?.defs[0];if(def?.type==="Variable"&&def.node.id===def.name&&def.node.init?.type==="ObjectExpression")literal=def.node.init}if(literal.type==="ObjectExpression"){let found=null;for(const prop of literal.properties){if(prop.type==="SpreadElement")found=fieldOf(prop.argument,path,depth+1,env);else if((0,tool_registration_1.propertyKey)(prop)===path[0])found=fieldOf(prop.value,path.slice(1),depth+1,env)}return found}let t=taint(node,depth+1,env);for(const key of path)t=t&&memberStep(t,key);return t}function ofCallers(fn,name,depth,env){const index=fn.params.findIndex(param2=>binds(param2,name));const param=fn.params[index];if(param===void 0||param.type==="RestElement")return null;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)??"")){const iterated=taint(call.callee.object,depth+1,env);const element=iterated&&memberStep(iterated,null);return index===0?throughPattern(param,name,element):null}if(options.followCallers===false)return null;const path=keyPath(param,name);let object=null;for(const site of callsOf(fn)){const arg=site.arguments[index];if(arg===void 0||arg.type==="SpreadElement")continue;if(options.blocksCallSite?.(site,arg))continue;const t=path!==void 0?fieldOf(arg,path,depth,env):throughPattern(param,name,taint(arg,depth+1,env));if(t?.kind==="value")return t;object??=t}return object}function literalField(node,depth,env){const key=(0,eslint_devkit_1.propertyName)(node);if(key===null||node.object.type!=="Identifier")return void 0;const variable=(0,tool_registration_1.lookupVariable)(node.object.name,sourceCode.getScope(node.object));const def=variable?.defs[0];if(def?.type==="Variable"&&def.parent.kind==="const"&&def.node.id===def.name&&def.node.init?.type==="ObjectExpression")return fieldOf(def.node.init,[key],depth,env);if(def?.type!=="Parameter"||env.has(variable)||options.followCallers===false)return void 0;const fn=def.node;if(handlerRoot(fn)!==void 0)return void 0;const param=fn.params.find(p=>binds(p,def.name));const index=fn.params.indexOf(param);const path=keyPath(param,def.name);if(path===void 0)return void 0;let found=null;for(const site of callsOf(fn)){const arg=site.arguments[index];if(arg===void 0||arg.type==="SpreadElement")continue;if(options.blocksCallSite?.(site,arg))continue;const t=fieldOf(arg,[...path,key],depth,env);if(t?.kind==="value")return t;found??=t}return found??void 0}function ofIdentifier(node,depth,env){const variable=(0,tool_registration_1.lookupVariable)(node.name,sourceCode.getScope(node));if(variable===void 0)return null;if(env.has(variable))return env.get(variable);const def=variable.defs[0];if(def?.type==="Parameter"){const fn=def.node;const root=handlerRoot(fn);if(root===void 0){const t2=ofCallers(fn,def.name,depth,env);return t2?{...t2,text:node.name}:null}const param=fn.params[root.param??0];if(param===void 0)return null;const t=throughPattern(param,def.name,{kind:"object",text:"",toArgs:root.toArgs,closed:root.closed});return t?{...t,text:node.name}:null}if(def?.type!=="Variable")return null;const sources=[];const declarator=def.node;const loop=def.parent.parent;if(loop?.type==="ForOfStatement"&&loop.left===def.parent){const iterated=taint(loop.right,depth+1,env);sources.push(throughPattern(declarator.id,def.name,iterated&&memberStep(iterated,null)))}if(declarator.init){sources.push(throughPattern(declarator.id,def.name,taint(declarator.init,depth+1,env)))}for(const ref of variable.references){if(!ref.isWrite()||ref.identifier===def.name)continue;let assignment=ref.identifier.parent;while(assignment&&PATTERN_PARTS.has(assignment.type))assignment=assignment.parent;if(assignment?.type!=="AssignmentExpression")continue;sources.push(throughPattern(assignment.left,ref.identifier,taint(assignment.right,depth+1,env)))}const found=sources.find(t=>t)??null;return found?.kind==="object"?{...found,text:node.name}:found}function ofCall(node,depth,env){const{callee}=node;if(callee.type==="Identifier"&&callee.name==="String"&&!(0,tool_registration_1.lookupVariable)("String",sourceCode.getScope(node))?.defs.length){const arg=node.arguments[0];return arg?asValue(taint(arg,depth+1,env)):null}if(callee.type==="MemberExpression"){const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return null;if(zod_1.ZOD_PARSERS.has(method)||zod_1.ZOD_SAFE_PARSERS.has(method))return ofParse(node,callee,method,depth,env);if(ARRAY_MAPPERS.has(method)){const fn2=(0,tool_registration_1.resolveFunction)(node.arguments[0],sourceCode.getScope(node));for(const expression of fn2?returnedExpressions(fn2):[]){const t=asValue(taint(expression,depth+1,env));if(t)return t}return null}if(ARRAY_SELECTORS.has(method))return asValue(taint(callee.object,depth+1,env));if(!exports.STRING_DERIVING.has(method))return null;const receiver=asValue(taint(callee.object,depth+1,env));if(receiver||method!=="concat")return receiver;for(const arg of node.arguments){const t=asValue(taint(arg,depth+1,env));if(t)return t}return null}const fn=(0,tool_registration_1.resolveFunction)(callee,sourceCode.getScope(node));if(fn===void 0)return null;const bound=new Map(env);const params=sourceCode.getDeclaredVariables(fn);fn.params.forEach((param,i)=>{const variable=params.find(v=>v.defs[0]?.name===param);const arg=node.arguments[i];if(variable&&arg)bound.set(variable,taint(arg,depth+1,env))});let object=null;for(const expression of returnedExpressions(fn)){const t=taint(expression,depth+1,bound);if(t?.kind==="value")return t;object??=t}return object}function ofParse(node,callee,method,depth,env){const schema=(0,zod_1.zodSchemaOf)(callee.object,{scope:sourceCode.getScope(callee.object),file:options.file},options.parser);const input=node.arguments[0];if(schema===void 0||input===void 0)return null;const t=taint(input,depth+1,env);if(t===null||t.kind==="value"&&schema.closedValue)return null;if(t.kind==="value")return t;const closed=new Set(t.closed);if(t.toArgs.length===0)for(const key of schema.closed)closed.add(key);return{...t,closed,toArgs:zod_1.ZOD_SAFE_PARSERS.has(method)?["data",...t.toArgs]:t.toArgs}}function taint(node,depth,env){if(depth>exports.MAX_FLOW_DEPTH||active.has(node))return null;active.add(node);try{return compute(node,depth,env)}finally{active.delete(node)}}function firstOf(nodes,depth,env,valuesOnly){for(const node of nodes){if(node===null)continue;const inner=node.type==="SpreadElement"?node.argument:node;const t=taint(inner,depth+1,env);const kept=valuesOnly?asValue(t):t;if(kept)return kept}return null}function compute(node,depth,env){const decided=intercept?.(node,next=>taint(next,depth+1,env));if(decided!==void 0)return decided;switch(node.type){case"Identifier":return ofIdentifier(node,depth,env);case"MemberExpression":{const field=literalField(node,depth,env);if(field!==void 0)return field;const object=taint(node.object,depth+1,env);return object&&memberStep(object,(0,eslint_devkit_1.propertyName)(node))}case"CallExpression":return ofCall(node,depth,env);case"TemplateLiteral":return firstOf(node.expressions,depth,env,true);case"ArrayExpression":return firstOf(node.elements,depth,env,true);case"BinaryExpression":return node.operator==="+"?firstOf([node.left,node.right],depth,env,true):null;case"LogicalExpression":return firstOf([node.left,node.right],depth,env,false);case"ConditionalExpression":return firstOf([node.consequent,node.alternate],depth,env,false);case"SequenceExpression":return taint(node.expressions[node.expressions.length-1],depth+1,env);case"AwaitExpression":case"ChainExpression":case"TSAsExpression":case"TSNonNullExpression":case"TSTypeAssertion":case"TSSatisfiesExpression":{const inner=node.type==="AwaitExpression"?node.argument:node.expression;return taint(inner,depth+1,env)}default:return null}}return node=>taint(node,0,new Map)}function asValue(t){return t?.kind==="value"?t:null}
|
package/src/utils/zod.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ZOD_SAFE_PARSERS=exports.ZOD_PARSERS=void 0;exports.zodSchemaOf=zodSchemaOf;const eslint_devkit_1=require("@interlace/eslint-devkit");const module_resolver_1=require("./module-resolver");const tool_registration_1=require("./tool-registration");exports.ZOD_PARSERS=new Set(["parse","parseAsync"]);exports.ZOD_SAFE_PARSERS=new Set(["safeParse","safeParseAsync","spa"]);const MAX_ZOD_DEPTH=8;function isZodModule(module){return module==="zod"||module.startsWith("zod/")}function closedFacts(node,site,parser){const closed=new Set;for(const[key,value]of(0,tool_registration_1.schemaFields)(node)?.fields??[]){const resolved=(0,module_resolver_1.resolveValue)(value,site,{parser,depth:0});const field=resolved.kind==="value"?resolved.node:value;if((0,tool_registration_1.isClosedSetSchema)(field))closed.add(key)}return{closed,closedValue:(0,tool_registration_1.isClosedSetSchema)(node)}}function zodSchemaOf(node,site,parser,depth=0){const value=(0,module_resolver_1.unwrapTypeOnly)(node);if(depth>MAX_ZOD_DEPTH)return void 0;if(value.type==="Identifier"||value.type==="MemberExpression"){const resolved=(0,module_resolver_1.resolveValue)(value,site,{parser,depth:0});if(resolved.kind!=="value"||resolved.node===value)return void 0;return zodSchemaOf(resolved.node,resolved.site,parser,depth+1)}if(value.type!=="CallExpression")return void 0;const binding=(0,eslint_devkit_1.resolveModuleBinding)(value.callee,(0,module_resolver_1.scopeAt)(site.scope,value));const isZod=binding!==void 0?isZodModule(binding.module):value.callee.type==="MemberExpression"&&zodSchemaOf(value.callee.object,site,parser,depth+1)!==void 0;return isZod?closedFacts(value,site,parser):void 0}
|