eslint-plugin-express-security 3.2.1 → 3.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-express-security",
3
- "version": "3.2.1",
3
+ "version": "3.2.2",
4
4
  "description": "ESLint plugin for Express.js security — detects permissive CORS, missing CSRF protection, missing helmet headers, insecure cookies, and GraphQL introspection in production.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -76,7 +76,7 @@
76
76
  "node": ">=18.0.0"
77
77
  },
78
78
  "dependencies": {
79
- "@interlace/eslint-devkit": "^1.18.2"
79
+ "@interlace/eslint-devkit": "^1.19.0"
80
80
  },
81
81
  "peerDependencies": {
82
82
  "eslint": "^8.40.0 || ^9.0.0 || ^10.0.0",
package/src/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"require-helmet"(){return require("./rules/require-helmet").requireHelmet},get"no-permissive-cors"(){return require("./rules/no-permissive-cors").noPermissiveCors},get"require-csrf-protection"(){return require("./rules/require-csrf-protection").requireCsrfProtection},get"no-insecure-cookie-options"(){return require("./rules/no-insecure-cookie-options").noInsecureCookieOptions},get"require-rate-limiting"(){return require("./rules/require-rate-limiting").requireRateLimiting},get"no-graphql-introspection-production"(){return require("./rules/no-graphql-introspection-production").noGraphqlIntrospectionProduction},get"no-cors-credentials-wildcard"(){return require("./rules/no-cors-credentials-wildcard").noCorsCredentialsWildcard},get"require-express-body-parser-limits"(){return require("./rules/require-express-body-parser-limits").requireExpressBodyParserLimits},get"no-express-unsafe-regex-route"(){return require("./rules/no-express-unsafe-regex-route").noExpressUnsafeRegexRoute},get"no-exposed-debug-endpoints"(){return require("./rules/no-exposed-debug-endpoints").noExposedDebugEndpoints},get"no-missing-cors-check"(){return require("./rules/no-missing-cors-check").noMissingCorsCheck},get"no-missing-csrf-protection"(){return require("./rules/no-missing-csrf-protection").noMissingCsrfProtection},get"no-missing-security-headers"(){return require("./rules/no-missing-security-headers").noMissingSecurityHeaders},get"no-user-controlled-redirect"(){return require("./rules/no-user-controlled-redirect").noUserControlledRedirect},get"no-host-header-in-links"(){return require("./rules/no-host-header-in-links").noHostHeaderInLinks},get"no-error-details-in-response"(){return require("./rules/no-error-details-in-response").noErrorDetailsInResponse},get"no-sensitive-data-in-query"(){return require("./rules/no-sensitive-data-in-query").noSensitiveDataInQuery},get"no-user-controlled-render-locals"(){return require("./rules/no-user-controlled-render-locals").noUserControlledRenderLocals},get"no-static-root-exposure"(){return require("./rules/no-static-root-exposure").noStaticRootExposure},get"require-case-insensitive-path-guard"(){return require("./rules/require-case-insensitive-path-guard").requireCaseInsensitivePathGuard},get"require-query-type-guard"(){return require("./rules/require-query-type-guard").requireQueryTypeGuard},get"no-disabled-helmet-protections"(){return require("./rules/no-disabled-helmet-protections").noDisabledHelmetProtections},get"require-strict-transport-security"(){return require("./rules/require-strict-transport-security").requireStrictTransportSecurity},get"no-unsafe-csp-directives"(){return require("./rules/no-unsafe-csp-directives").noUnsafeCspDirectives},get"no-permissive-trust-proxy"(){return require("./rules/no-permissive-trust-proxy").noPermissiveTrustProxy},get"require-route-authentication"(){return require("./rules/require-route-authentication").requireRouteAuthentication},get"no-client-controlled-authorization"(){return require("./rules/no-client-controlled-authorization").noClientControlledAuthorization},get"no-idor-resource-access"(){return require("./rules/no-idor-resource-access").noIdorResourceAccess}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-express-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-express-security",version:"3.2.1"},rules:exports.rules};const recommendedRules={"express-security/require-helmet":"error","express-security/no-permissive-cors":"error","express-security/require-csrf-protection":"warn","express-security/no-insecure-cookie-options":"error","express-security/require-rate-limiting":"error","express-security/no-graphql-introspection-production":"warn","express-security/no-cors-credentials-wildcard":"error","express-security/require-express-body-parser-limits":"warn","express-security/no-express-unsafe-regex-route":"error","express-security/no-exposed-debug-endpoints":"error","express-security/no-user-controlled-redirect":"error","express-security/no-host-header-in-links":"error","express-security/no-error-details-in-response":"error","express-security/no-sensitive-data-in-query":"warn","express-security/no-user-controlled-render-locals":"error","express-security/no-static-root-exposure":"error","express-security/require-case-insensitive-path-guard":"warn","express-security/require-query-type-guard":"warn","express-security/no-disabled-helmet-protections":"error","express-security/require-strict-transport-security":"error","express-security/no-unsafe-csp-directives":"error","express-security/no-permissive-trust-proxy":"error","express-security/require-route-authentication":"warn","express-security/no-client-controlled-authorization":"warn","express-security/no-idor-resource-access":"warn"};exports.configs={recommended:{plugins:{"express-security":exports.plugin},rules:recommendedRules},strict:{plugins:{"express-security":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`express-security/${ruleName}`,"error"]))},api:{plugins:{"express-security":exports.plugin},rules:{"express-security/require-helmet":"error","express-security/no-disabled-helmet-protections":"error","express-security/require-strict-transport-security":"error","express-security/no-unsafe-csp-directives":"error","express-security/no-permissive-trust-proxy":"error","express-security/no-permissive-cors":"error","express-security/require-csrf-protection":"error","express-security/no-insecure-cookie-options":"error","express-security/require-rate-limiting":"error"}},graphql:{plugins:{"express-security":exports.plugin},rules:{"express-security/no-graphql-introspection-production":"error"}}};exports.default=exports.plugin;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.configs=exports.plugin=exports.rules=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");exports.rules={get"require-helmet"(){return require("./rules/require-helmet").requireHelmet},get"no-permissive-cors"(){return require("./rules/no-permissive-cors").noPermissiveCors},get"require-csrf-protection"(){return require("./rules/require-csrf-protection").requireCsrfProtection},get"no-insecure-cookie-options"(){return require("./rules/no-insecure-cookie-options").noInsecureCookieOptions},get"require-rate-limiting"(){return require("./rules/require-rate-limiting").requireRateLimiting},get"no-graphql-introspection-production"(){return require("./rules/no-graphql-introspection-production").noGraphqlIntrospectionProduction},get"no-cors-credentials-wildcard"(){return require("./rules/no-cors-credentials-wildcard").noCorsCredentialsWildcard},get"require-express-body-parser-limits"(){return require("./rules/require-express-body-parser-limits").requireExpressBodyParserLimits},get"no-express-unsafe-regex-route"(){return require("./rules/no-express-unsafe-regex-route").noExpressUnsafeRegexRoute},get"no-exposed-debug-endpoints"(){return require("./rules/no-exposed-debug-endpoints").noExposedDebugEndpoints},get"no-missing-cors-check"(){return require("./rules/no-missing-cors-check").noMissingCorsCheck},get"no-missing-csrf-protection"(){return require("./rules/no-missing-csrf-protection").noMissingCsrfProtection},get"no-missing-security-headers"(){return require("./rules/no-missing-security-headers").noMissingSecurityHeaders},get"no-user-controlled-redirect"(){return require("./rules/no-user-controlled-redirect").noUserControlledRedirect},get"no-host-header-in-links"(){return require("./rules/no-host-header-in-links").noHostHeaderInLinks},get"no-error-details-in-response"(){return require("./rules/no-error-details-in-response").noErrorDetailsInResponse},get"no-sensitive-data-in-query"(){return require("./rules/no-sensitive-data-in-query").noSensitiveDataInQuery},get"no-user-controlled-render-locals"(){return require("./rules/no-user-controlled-render-locals").noUserControlledRenderLocals},get"no-static-root-exposure"(){return require("./rules/no-static-root-exposure").noStaticRootExposure},get"require-case-insensitive-path-guard"(){return require("./rules/require-case-insensitive-path-guard").requireCaseInsensitivePathGuard},get"require-query-type-guard"(){return require("./rules/require-query-type-guard").requireQueryTypeGuard},get"no-disabled-helmet-protections"(){return require("./rules/no-disabled-helmet-protections").noDisabledHelmetProtections},get"require-strict-transport-security"(){return require("./rules/require-strict-transport-security").requireStrictTransportSecurity},get"no-unsafe-csp-directives"(){return require("./rules/no-unsafe-csp-directives").noUnsafeCspDirectives},get"no-permissive-trust-proxy"(){return require("./rules/no-permissive-trust-proxy").noPermissiveTrustProxy},get"require-route-authentication"(){return require("./rules/require-route-authentication").requireRouteAuthentication},get"no-client-controlled-authorization"(){return require("./rules/no-client-controlled-authorization").noClientControlledAuthorization},get"no-idor-resource-access"(){return require("./rules/no-idor-resource-access").noIdorResourceAccess}};(0,eslint_devkit_1.withCanonicalDocsUrls)("plugin-express-security",exports.rules);exports.plugin={meta:{name:"eslint-plugin-express-security",version:"3.2.2"},rules:exports.rules};const recommendedRules={"express-security/require-helmet":"error","express-security/no-permissive-cors":"error","express-security/require-csrf-protection":"warn","express-security/no-insecure-cookie-options":"error","express-security/require-rate-limiting":"error","express-security/no-graphql-introspection-production":"warn","express-security/no-cors-credentials-wildcard":"error","express-security/require-express-body-parser-limits":"warn","express-security/no-express-unsafe-regex-route":"error","express-security/no-exposed-debug-endpoints":"error","express-security/no-user-controlled-redirect":"error","express-security/no-host-header-in-links":"error","express-security/no-error-details-in-response":"error","express-security/no-sensitive-data-in-query":"warn","express-security/no-user-controlled-render-locals":"error","express-security/no-static-root-exposure":"error","express-security/require-case-insensitive-path-guard":"warn","express-security/require-query-type-guard":"warn","express-security/no-disabled-helmet-protections":"error","express-security/require-strict-transport-security":"error","express-security/no-unsafe-csp-directives":"error","express-security/no-permissive-trust-proxy":"error","express-security/require-route-authentication":"warn","express-security/no-client-controlled-authorization":"warn","express-security/no-idor-resource-access":"warn"};exports.configs={recommended:{plugins:{"express-security":exports.plugin},rules:recommendedRules},strict:{plugins:{"express-security":exports.plugin},rules:Object.fromEntries(Object.keys(exports.rules).map(ruleName=>[`express-security/${ruleName}`,"error"]))},api:{plugins:{"express-security":exports.plugin},rules:{"express-security/require-helmet":"error","express-security/no-disabled-helmet-protections":"error","express-security/require-strict-transport-security":"error","express-security/no-unsafe-csp-directives":"error","express-security/no-permissive-trust-proxy":"error","express-security/no-permissive-cors":"error","express-security/require-csrf-protection":"error","express-security/no-insecure-cookie-options":"error","express-security/require-rate-limiting":"error"}},graphql:{plugins:{"express-security":exports.plugin},rules:{"express-security/no-graphql-introspection-production":"error"}}};exports.default=exports.plugin;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noClientControlledAuthorization=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const CLIENT_CONTAINERS=new Set(["body","query","params","headers","cookies"]);const REQUEST_RECEIVER=/^(req|request)$/i;const AUTHZ_PROPERTIES=new Set(["role","roles","admin","isadmin","is_admin","superuser","issuperuser","permission","permissions","scope","scopes","privilege","privileges","usertype","user_type","accesslevel","access_level","acl","claims","grants","userid","user_id","ownerid","owner_id","owner","accountid","account_id","tenantid","tenant_id","orgid","org_id"]);const AUTHZ_HEADER=/^x-.*(role|admin|user|auth|permission|scope|tenant|account|owner)/i;function staticPropertyName(node){if(!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.property.name}if(node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.property.value==="string"){return node.property.value}return null}function clientContainerOf(node){const{object}=node;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const container=staticPropertyName(object);if(!container||!CLIENT_CONTAINERS.has(container))return null;const root=object.object;if(root.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_RECEIVER.test(root.name)){return container}if(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_RECEIVER.test(root.property.name)){return container}return null}function isAuthorizationDecision(node){let current=node;let parent=node.parent;for(let depth=0;parent&&depth<4;depth+=1){switch(parent.type){case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:if(parent.operator==="==="||parent.operator==="=="||parent.operator==="!=="||parent.operator==="!="){return true}break;case eslint_devkit_1.AST_NODE_TYPES.IfStatement:case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:if(parent.test===current)return true;break;case eslint_devkit_1.AST_NODE_TYPES.SwitchStatement:if(parent.discriminant===current)return true;break;case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:if(parent.operator==="??")break;return true;case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:if(parent.operator==="!")return true;break;case eslint_devkit_1.AST_NODE_TYPES.CallExpression:if(parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(parent.callee.property.name==="includes"||parent.callee.property.name==="some")){return true}return false;default:break}current=parent;parent=parent.parent}return false}exports.noClientControlledAuthorization=(0,eslint_devkit_1.createRule)({name:"no-client-controlled-authorization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-client-controlled-authorization.md",description:"Disallow authorization decisions taken on request-supplied role, permission or identity values",cwe:"CWE-863",cvss:8.1,confidence:"medium"},messages:{clientControlledAuthorization:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Authorization Decided On Client Input (CWE-863)",cwe:"CWE-863",cvss:8.1,description:"The access decision reads {{expression}} \u2014 a value the caller sends. The check runs, and passes for anyone who sets the field.",severity:"HIGH",fix:"Read the attribute from the server-side session or verified token instead: req.user.{{property}} / req.auth.{{property}}.",documentationLink:"https://cwe.mitre.org/data/definitions/863.html"})},schema:[{type:"object",properties:{extraProperties:{type:"array",items:{type:"string"},description:"Extra property names treated as authorization attributes"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{extraProperties}=options;const extra=new Set((extraProperties??[]).map(name=>name.toLowerCase()));function isAuthorizationAttribute(property,container){const normalized=property.toLowerCase();if(AUTHZ_PROPERTIES.has(normalized))return true;if(extra.has(normalized))return true;return container==="headers"&&AUTHZ_HEADER.test(property)}return{MemberExpression(node){const property=staticPropertyName(node);if(!property)return;const container=clientContainerOf(node);if(!container)return;if(!isAuthorizationAttribute(property,container))return;if(!isAuthorizationDecision(node))return;context.report({node,messageId:"clientControlledAuthorization",data:{expression:context.sourceCode.getText(node),property}})}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noClientControlledAuthorization=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const CLIENT_CONTAINERS=new Set(["body","query","params","headers","cookies"]);const REQUEST_RECEIVER=/^(req|request)$/i;const AUTHZ_PROPERTIES=new Set(["role","roles","admin","isadmin","is_admin","superuser","issuperuser","permission","permissions","scope","scopes","privilege","privileges","usertype","user_type","accesslevel","access_level","acl","claims","grants","userid","user_id","ownerid","owner_id","owner","accountid","account_id","tenantid","tenant_id","orgid","org_id"]);const AUTHZ_HEADER=/^x-.*(role|admin|user|auth|permission|scope|tenant|account|owner)/i;function staticPropertyName(node){if(!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.property.name}if(node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.property.value==="string"){return node.property.value}return null}function clientContainerOf(node){const{object}=node;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const container=staticPropertyName(object);if(!container||!CLIENT_CONTAINERS.has(container))return null;const root=object.object;if(root.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_RECEIVER.test(root.name)){return container}if(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&REQUEST_RECEIVER.test((0,eslint_devkit_1.propertyName)(root))){return container}return null}function isAuthorizationDecision(node){let current=node;let parent=node.parent;for(let depth=0;parent&&depth<4;depth+=1){switch(parent.type){case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:if(parent.operator==="==="||parent.operator==="=="||parent.operator==="!=="||parent.operator==="!="){return true}break;case eslint_devkit_1.AST_NODE_TYPES.IfStatement:case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:if(parent.test===current)return true;break;case eslint_devkit_1.AST_NODE_TYPES.SwitchStatement:if(parent.discriminant===current)return true;break;case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:if(parent.operator==="??")break;return true;case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:if(parent.operator==="!")return true;break;case eslint_devkit_1.AST_NODE_TYPES.CallExpression:if(parent.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(parent.callee)==="includes"||(0,eslint_devkit_1.propertyName)(parent.callee)==="some")){return true}return false;default:break}current=parent;parent=parent.parent}return false}exports.noClientControlledAuthorization=(0,eslint_devkit_1.createRule)({name:"no-client-controlled-authorization",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-client-controlled-authorization.md",description:"Disallow authorization decisions taken on request-supplied role, permission or identity values",cwe:"CWE-863",cvss:8.1,confidence:"medium"},messages:{clientControlledAuthorization:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Authorization Decided On Client Input (CWE-863)",cwe:"CWE-863",cvss:8.1,description:"The access decision reads {{expression}} \u2014 a value the caller sends. The check runs, and passes for anyone who sets the field.",severity:"HIGH",fix:"Read the attribute from the server-side session or verified token instead: req.user.{{property}} / req.auth.{{property}}.",documentationLink:"https://cwe.mitre.org/data/definitions/863.html"})},schema:[{type:"object",properties:{extraProperties:{type:"array",items:{type:"string"},description:"Extra property names treated as authorization attributes"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{extraProperties}=options;const extra=new Set((extraProperties??[]).map(name=>name.toLowerCase()));function isAuthorizationAttribute(property,container){const normalized=property.toLowerCase();if(AUTHZ_PROPERTIES.has(normalized))return true;if(extra.has(normalized))return true;return container==="headers"&&AUTHZ_HEADER.test(property)}return{MemberExpression(node){const property=staticPropertyName(node);if(!property)return;const container=clientContainerOf(node);if(!container)return;if(!isAuthorizationAttribute(property,container))return;if(!isAuthorizationDecision(node))return;context.report({node,messageId:"clientControlledAuthorization",data:{expression:context.sourceCode.getText(node),property}})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCorsCredentialsWildcard=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");function hasWildcardOrigin(node,sourceCode){const text=sourceCode.getText(node);if(/\borigin\s*:\s*['"`]\*['"`]/.test(text)){return true}if(/\borigin\s*:\s*true\b/.test(text)){return true}return false}function hasCredentialsTrue(node,sourceCode){const text=sourceCode.getText(node);return/\bcredentials\s*:\s*true\b/.test(text)}function getCorsConfigNode(node){const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="cors"){const parent=node.parent;if(parent&&parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"&&parent.callee.property.name==="use"){return null}if(node.arguments[0]?.type==="ObjectExpression"){return node.arguments[0]}return null}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="use"){const firstArg=node.arguments[0];if(firstArg?.type==="CallExpression"&&firstArg.callee.type==="Identifier"&&firstArg.callee.name==="cors"&&firstArg.arguments[0]?.type==="ObjectExpression"){return firstArg.arguments[0]}}return null}exports.noCorsCredentialsWildcard=(0,eslint_devkit_1.createRule)({name:"no-cors-credentials-wildcard",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-cors-credentials-wildcard.md",description:"Disallow credentials: true with wildcard CORS origin (CVE-2024-25124)",cwe:"CWE-942",cvss:7.5},messages:{credentialsWildcard:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CORS Credentials with Wildcard Origin",cwe:"CWE-942",description:'Using credentials: true with origin: "*" or origin: true allows any domain to send credentials to your API. This is a critical vulnerability (CVE-2024-25124, CVSS 9.1).',severity:"CRITICAL",fix:'Specify explicit allowed origins: origin: ["https://trusted-domain.com"]',documentationLink:"https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2024-25124"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;return{CallExpression(node){const corsConfigNode=getCorsConfigNode(node);if(corsConfigNode){const hasWildcard=hasWildcardOrigin(corsConfigNode,sourceCode);const hasCredentials=hasCredentialsTrue(corsConfigNode,sourceCode);if(hasWildcard&&hasCredentials){context.report({node:corsConfigNode,messageId:"credentialsWildcard"})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCorsCredentialsWildcard=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");function hasWildcardOrigin(node,sourceCode){const text=sourceCode.getText(node);if(/\borigin\s*:\s*['"`]\*['"`]/.test(text)){return true}if(/\borigin\s*:\s*true\b/.test(text)){return true}return false}function hasCredentialsTrue(node,sourceCode){const text=sourceCode.getText(node);return/\bcredentials\s*:\s*true\b/.test(text)}function getCorsConfigNode(node){const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="cors"){const parent=node.parent;if(parent&&parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(parent.callee)==="use"){return null}if(node.arguments[0]?.type==="ObjectExpression"){return node.arguments[0]}return null}if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="use"){const firstArg=node.arguments[0];if(firstArg?.type==="CallExpression"&&firstArg.callee.type==="Identifier"&&firstArg.callee.name==="cors"&&firstArg.arguments[0]?.type==="ObjectExpression"){return firstArg.arguments[0]}}return null}exports.noCorsCredentialsWildcard=(0,eslint_devkit_1.createRule)({name:"no-cors-credentials-wildcard",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-cors-credentials-wildcard.md",description:"Disallow credentials: true with wildcard CORS origin (CVE-2024-25124)",cwe:"CWE-942",cvss:7.5},messages:{credentialsWildcard:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CORS Credentials with Wildcard Origin",cwe:"CWE-942",description:'Using credentials: true with origin: "*" or origin: true allows any domain to send credentials to your API. This is a critical vulnerability (CVE-2024-25124, CVSS 9.1).',severity:"CRITICAL",fix:'Specify explicit allowed origins: origin: ["https://trusted-domain.com"]',documentationLink:"https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2024-25124"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;return{CallExpression(node){const corsConfigNode=getCorsConfigNode(node);if(corsConfigNode){const hasWildcard=hasWildcardOrigin(corsConfigNode,sourceCode);const hasCredentials=hasCredentialsTrue(corsConfigNode,sourceCode);if(hasWildcard&&hasCredentials){context.report({node:corsConfigNode,messageId:"credentialsWildcard"})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noExposedDebugEndpoints=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const express_evidence_1=require("../../utils/express-evidence");const DEFAULT_DEBUG_PATHS=["/debug","/__debug__","/admin","/_admin","/test","/health"];const HTTP_METHODS=new Set(["get","post","put","patch","delete","head","options","all","use","route"]);exports.noExposedDebugEndpoints=(0,eslint_devkit_1.createRule)({name:"no-exposed-debug-endpoints",skipTestFiles:true,meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-exposed-debug-endpoints.md",description:"Detect debug endpoints without auth in Express applications",cwe:"CWE-489",cvss:7.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Exposed Debug Endpoint",cwe:"CWE-489",description:"Debug endpoint exposed without authentication",severity:"HIGH",fix:"Remove debug endpoints from production or add authentication",documentationLink:"https://cwe.mitre.org/data/definitions/489.html"})},schema:[{type:"object",properties:{endpoints:{type:"array",items:{type:"string"},description:"Custom list of debug/admin endpoints to flag"},ignoreFiles:{type:"array",items:{type:"string"},description:"List of files or patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{}],create(context){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const options=context.options[0]||{};const debugPaths=options.endpoints||DEFAULT_DEBUG_PATHS;const ignoreFiles=options.ignoreFiles||[];const filename=context.filename;if(ignoreFiles.some(pattern=>filename.includes(pattern))){return{}}const isExpressRouteCall=node=>{return node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&["app","router","express"].includes(node.callee.object.name)&&node.callee.property.type==="Identifier"&&HTTP_METHODS.has(node.callee.property.name)};return{CallExpression(node){if(!isExpressRouteCall(node)){return}const isSettingLookup=node.callee.type==="MemberExpression"&&node.callee.property.type==="Identifier"&&node.callee.property.name==="get"&&node.arguments.length===1;if(isSettingLookup){return}const pathArg=node.arguments[0];if(pathArg&&pathArg.type==="Literal"&&typeof pathArg.value==="string"){const path=pathArg.value.toLowerCase();if(debugPaths.some(dp=>path.includes(dp.toLowerCase()))){context.report({node:pathArg,messageId:"violationDetected"})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noExposedDebugEndpoints=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const express_evidence_1=require("../../utils/express-evidence");const DEFAULT_DEBUG_PATHS=["/debug","/__debug__","/admin","/_admin","/test","/health"];const HTTP_METHODS=new Set(["get","post","put","patch","delete","head","options","all","use","route"]);exports.noExposedDebugEndpoints=(0,eslint_devkit_1.createRule)({name:"no-exposed-debug-endpoints",skipTestFiles:true,meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-exposed-debug-endpoints.md",description:"Detect debug endpoints without auth in Express applications",cwe:"CWE-489",cvss:7.5},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Exposed Debug Endpoint",cwe:"CWE-489",description:"Debug endpoint exposed without authentication",severity:"HIGH",fix:"Remove debug endpoints from production or add authentication",documentationLink:"https://cwe.mitre.org/data/definitions/489.html"})},schema:[{type:"object",properties:{endpoints:{type:"array",items:{type:"string"},description:"Custom list of debug/admin endpoints to flag"},ignoreFiles:{type:"array",items:{type:"string"},description:"List of files or patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{}],create(context){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const options=context.options[0]||{};const debugPaths=options.endpoints||DEFAULT_DEBUG_PATHS;const ignoreFiles=options.ignoreFiles||[];const filename=context.filename;if(ignoreFiles.some(pattern=>filename.includes(pattern))){return{}}const isExpressRouteCall=node=>{return node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&["app","router","express"].includes(node.callee.object.name)&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),HTTP_METHODS)};return{CallExpression(node){if(!isExpressRouteCall(node)){return}const isSettingLookup=node.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node.callee)==="get"&&node.arguments.length===1;if(isSettingLookup){return}const pathArg=node.arguments[0];if(pathArg&&pathArg.type==="Literal"&&typeof pathArg.value==="string"){const path=pathArg.value.toLowerCase();if(debugPaths.some(dp=>path.includes(dp.toLowerCase()))){context.report({node:pathArg,messageId:"violationDetected"})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHostHeaderInLinks=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const HOST_HEADER_NAMES=new Set(["host","x-forwarded-host"]);const HOST_GETTER_METHODS=new Set(["get","header"]);exports.noHostHeaderInLinks=(0,eslint_devkit_1.createRule)({name:"no-host-header-in-links",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-host-header-in-links.md",description:"Disallow building absolute URLs (reset/verification links) from the Host or X-Forwarded-Host request header",cwe:"CWE-640",cvss:8.1},messages:{hostHeaderInLink:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Host-Header Poisoning (CWE-640)",cwe:"CWE-640",description:"A URL is built from {{source}}, which the client controls. Reset/verification links built this way can be redirected to an attacker-owned host, leaking the token.",severity:"HIGH",fix:"Build absolute links from a server-side constant (e.g. process.env.PUBLIC_ORIGIN), never from request headers.",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"})},schema:[{type:"object",properties:{allowedHosts:{type:"array",items:{type:"string"},description:"Trusted literal hosts \u2014 an if-guard comparing against one of these suppresses the report"},checkMailCallees:{type:"array",items:{type:"string"},description:'Callee names treated as mail-send sinks (default: ["sendMail", "send"])'}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowedHosts,checkMailCallees}=options;const allowed=allowedHosts??[];const mailCallees=new Set(checkMailCallees??["sendMail","send"]);const sourceCode=context.sourceCode;const hostVars=new Map;function isRequestIdent(name){const lower=name.toLowerCase();return lower==="req"||lower==="request"||lower==="ctx"}function propName(node){if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!node.computed){return node.property.name}if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.property.value==="string"){return node.property.value}return null}function getHostHeaderSource(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return getHostHeaderSource(node.left)??getHostHeaderSource(node.right)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&HOST_GETTER_METHODS.has(callee.property.name)&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isRequestIdent(callee.object.name)){const arg=node.arguments[0];if(arg!==void 0&&arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&HOST_HEADER_NAMES.has(arg.value.toLowerCase())){return`req.${callee.property.name}('${arg.value}')`}}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const obj=node.object;if(obj.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&obj.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&obj.property.name==="headers"&&obj.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isRequestIdent(obj.object.name)){const name=propName(node);if(name!==null&&HOST_HEADER_NAMES.has(name.toLowerCase())){return`req.headers['${name}']`}}}return null}function resolveHostSource(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){let scope=sourceCode.getScope(node);while(scope){const variable=scope.variables.find(v=>v.name===node.name);if(variable)return hostVars.get(variable)??null;scope=scope.upper}return null}return getHostHeaderSource(node)}function isUrlish(text){return text.includes("://")||text.startsWith("//")}function isInMailCall(node){let current=node.parent;while(current!=null){if(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=current.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&mailCallees.has(callee.name)){return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&mailCallees.has(callee.property.name)){return true}}current=current.parent}return false}function isValidatedByAllowlist(node){if(allowed.length===0)return false;let current=node.parent;while(current!=null){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){const testText=sourceCode.getText(current.test);if(allowed.some(host=>testText.includes(host)))return true}current=current.parent}return false}function reportHostUse(node,source){if(isValidatedByAllowlist(node))return;context.report({node,messageId:"hostHeaderInLink",data:{source}})}return{VariableDeclarator(node){if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.init==null){return}const source=getHostHeaderSource(node.init);if(source===null)return;for(const variable of sourceCode.getDeclaredVariables(node)){hostVars.set(variable,source)}},TemplateLiteral(node){const urlish=node.quasis.some(q=>isUrlish(q.value.raw));for(const expr of node.expressions){const source=resolveHostSource(expr);if(source!==null&&(urlish||isInMailCall(node))){reportHostUse(expr,source)}}},BinaryExpression(node){if(node.operator!=="+")return;if(node.parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.parent.operator==="+"){return}const operands=[];const stack=[node];while(stack.length>0){const current=stack.pop();if(current.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&current.operator==="+"){stack.push(current.left,current.right)}else{operands.push(current)}}let urlish=false;let hostNode=null;let hostSource=null;for(const operand of operands){if(operand.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof operand.value==="string"&&isUrlish(operand.value)){urlish=true}if(hostSource===null){const source=resolveHostSource(operand);if(source!==null){hostSource=source;hostNode=operand}}}if(hostNode!==null&&(urlish||isInMailCall(node))){reportHostUse(hostNode,hostSource)}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHostHeaderInLinks=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const HOST_HEADER_NAMES=new Set(["host","x-forwarded-host"]);const HOST_GETTER_METHODS=new Set(["get","header"]);exports.noHostHeaderInLinks=(0,eslint_devkit_1.createRule)({name:"no-host-header-in-links",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-host-header-in-links.md",description:"Disallow building absolute URLs (reset/verification links) from the Host or X-Forwarded-Host request header",cwe:"CWE-640",cvss:8.1},messages:{hostHeaderInLink:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Host-Header Poisoning (CWE-640)",cwe:"CWE-640",description:"A URL is built from {{source}}, which the client controls. Reset/verification links built this way can be redirected to an attacker-owned host, leaking the token.",severity:"HIGH",fix:"Build absolute links from a server-side constant (e.g. process.env.PUBLIC_ORIGIN), never from request headers.",documentationLink:"https://cwe.mitre.org/data/definitions/640.html"})},schema:[{type:"object",properties:{allowedHosts:{type:"array",items:{type:"string"},description:"Trusted literal hosts \u2014 an if-guard comparing against one of these suppresses the report"},checkMailCallees:{type:"array",items:{type:"string"},description:'Callee names treated as mail-send sinks (default: ["sendMail", "send"])'}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowedHosts,checkMailCallees}=options;const allowed=allowedHosts??[];const mailCallees=new Set(checkMailCallees??["sendMail","send"]);const sourceCode=context.sourceCode;const hostVars=new Map;function isRequestIdent(name){const lower=name.toLowerCase();return lower==="req"||lower==="request"||lower==="ctx"}function propName(node){if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!node.computed){return node.property.name}if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.property.value==="string"){return node.property.value}return null}function getHostHeaderSource(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return getHostHeaderSource(node.left)??getHostHeaderSource(node.right)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;const getter=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&getter!==null&&HOST_GETTER_METHODS.has(getter)&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isRequestIdent(callee.object.name)){const arg=node.arguments[0];if(arg!==void 0&&arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&HOST_HEADER_NAMES.has(arg.value.toLowerCase())){return`req.${getter}('${arg.value}')`}}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const obj=node.object;if(obj.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(obj)==="headers"&&obj.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isRequestIdent(obj.object.name)){const name=propName(node);if(name!==null&&HOST_HEADER_NAMES.has(name.toLowerCase())){return`req.headers['${name}']`}}}return null}function resolveHostSource(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){let scope=sourceCode.getScope(node);while(scope){const variable=scope.variables.find(v=>v.name===node.name);if(variable)return hostVars.get(variable)??null;scope=scope.upper}return null}return getHostHeaderSource(node)}function isUrlish(text){return text.includes("://")||text.startsWith("//")}function isInMailCall(node){let current=node.parent;while(current!=null){if(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=current.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&mailCallees.has(callee.name)){return true}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),mailCallees)){return true}}current=current.parent}return false}function isValidatedByAllowlist(node){if(allowed.length===0)return false;let current=node.parent;while(current!=null){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){const testText=sourceCode.getText(current.test);if(allowed.some(host=>testText.includes(host)))return true}current=current.parent}return false}function reportHostUse(node,source){if(isValidatedByAllowlist(node))return;context.report({node,messageId:"hostHeaderInLink",data:{source}})}return{VariableDeclarator(node){if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.init==null){return}const source=getHostHeaderSource(node.init);if(source===null)return;for(const variable of sourceCode.getDeclaredVariables(node)){hostVars.set(variable,source)}},TemplateLiteral(node){const urlish=node.quasis.some(q=>isUrlish(q.value.raw));for(const expr of node.expressions){const source=resolveHostSource(expr);if(source!==null&&(urlish||isInMailCall(node))){reportHostUse(expr,source)}}},BinaryExpression(node){if(node.operator!=="+")return;if(node.parent.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.parent.operator==="+"){return}const operands=[];const stack=[node];while(stack.length>0){const current=stack.pop();if(current.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&current.operator==="+"){stack.push(current.left,current.right)}else{operands.push(current)}}let urlish=false;let hostNode=null;let hostSource=null;for(const operand of operands){if(operand.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof operand.value==="string"&&isUrlish(operand.value)){urlish=true}if(hostSource===null){const source=resolveHostSource(operand);if(source!==null){hostSource=source;hostNode=operand}}}if(hostNode!==null&&(urlish||isInMailCall(node))){reportHostUse(hostNode,hostSource)}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureCookieOptions=void 0;exports.checkCookieOptions=checkCookieOptions;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");function propertyName(property){if(property.type!=="Property")return void 0;if(property.key.type==="Identifier"&&!property.computed){return property.key.name.toLowerCase()}const staticText=(0,eslint_devkit_1.staticString)(property.key);if(staticText!==null){return staticText.toLowerCase()}return void 0}function flagState(node,name,hasSpread){const property=[...node.properties].reverse().find(p=>propertyName(p)===name);if(property===void 0)return hasSpread?"unknown":"absent";const value=property.value;if(value.type!=="Literal")return"unknown";return value.value===true?"on":"off"}function checkCookieOptions(node,options){const issues=[];const hasSpread=node.properties.some(p=>p.type==="SpreadElement");if(options.requireHttpOnly!==false){const state=flagState(node,"httponly",hasSpread);if(state==="absent"||state==="off"){issues.push("missing httpOnly flag (prevents XSS access to cookie)")}}if(options.requireSecure!==false){const state=flagState(node,"secure",hasSpread);if(state==="absent"||state==="off"){issues.push("missing secure flag (cookie sent over HTTPS only)")}}if(options.requireSameSite!==false){const acceptableValues=options.acceptableSameSiteValues||["strict","lax"];const property=[...node.properties].reverse().find(p=>propertyName(p)==="samesite");if(property===void 0){if(!hasSpread)issues.push("missing sameSite flag (prevents CSRF)")}else if(property.value.type==="Literal"&&typeof property.value.value==="string"){const value=property.value.value;if(!acceptableValues.includes(value.toLowerCase())){issues.push(`sameSite should be 'strict' or 'lax', not '${value}'`)}}}return{issues,hasSuggestions:issues.length>0}}exports.noInsecureCookieOptions=(0,eslint_devkit_1.createRule)({name:"no-insecure-cookie-options",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-insecure-cookie-options.md",description:"Require secure cookie flags (httpOnly, secure, sameSite) in Express.js",cwe:"CWE-614",cvss:5.3},hasSuggestions:true,messages:{insecureCookie:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure Cookie Configuration",cwe:"CWE-614",description:"{{issues}}",severity:"HIGH",fix:'Set httpOnly: true, secure: true, sameSite: "strict"',documentationLink:"https://owasp.org/www-community/controls/SecureCookieAttribute"}),addSecureFlags:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Secure Cookie Flags",description:"Add missing security flags to cookie options",severity:"LOW",fix:'{ httpOnly: true, secure: true, sameSite: "strict" }',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#security"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false},requireHttpOnly:{type:"boolean",default:true},requireSecure:{type:"boolean",default:true},requireSameSite:{type:"boolean",default:true},acceptableSameSiteValues:{type:"array",items:{type:"string"},default:["strict","lax"]}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,requireHttpOnly:true,requireSecure:true,requireSameSite:true,acceptableSameSiteValues:["strict","lax"]}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}return{CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="cookie"){const optionsArg=node.arguments[2];if(!optionsArg){context.report({node,messageId:"insecureCookie",data:{issues:"Cookie set without options - missing httpOnly, secure, sameSite flags"},suggest:[{messageId:"addSecureFlags",fix:fixer=>{const lastArg=node.arguments[node.arguments.length-1];return fixer.insertTextAfter(lastArg,', { httpOnly: true, secure: true, sameSite: "strict" }')}}]});return}if(optionsArg.type==="ObjectExpression"){const{issues}=checkCookieOptions(optionsArg,options);if(issues.length>0){context.report({node:optionsArg,messageId:"insecureCookie",data:{issues:issues.join("; ")}})}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureCookieOptions=void 0;exports.checkCookieOptions=checkCookieOptions;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");function cookieOptionKey(property){if(property.type!=="Property")return void 0;if(property.key.type==="Identifier"&&!property.computed){return property.key.name.toLowerCase()}const staticText=(0,eslint_devkit_1.staticString)(property.key);if(staticText!==null){return staticText.toLowerCase()}return void 0}function flagState(node,name,hasSpread){const property=[...node.properties].reverse().find(p=>cookieOptionKey(p)===name);if(property===void 0)return hasSpread?"unknown":"absent";const value=property.value;if(value.type!=="Literal")return"unknown";return value.value===true?"on":"off"}function checkCookieOptions(node,options){const issues=[];const hasSpread=node.properties.some(p=>p.type==="SpreadElement");if(options.requireHttpOnly!==false){const state=flagState(node,"httponly",hasSpread);if(state==="absent"||state==="off"){issues.push("missing httpOnly flag (prevents XSS access to cookie)")}}if(options.requireSecure!==false){const state=flagState(node,"secure",hasSpread);if(state==="absent"||state==="off"){issues.push("missing secure flag (cookie sent over HTTPS only)")}}if(options.requireSameSite!==false){const acceptableValues=options.acceptableSameSiteValues||["strict","lax"];const property=[...node.properties].reverse().find(p=>cookieOptionKey(p)==="samesite");if(property===void 0){if(!hasSpread)issues.push("missing sameSite flag (prevents CSRF)")}else if(property.value.type==="Literal"&&typeof property.value.value==="string"){const value=property.value.value;if(!acceptableValues.includes(value.toLowerCase())){issues.push(`sameSite should be 'strict' or 'lax', not '${value}'`)}}}return{issues,hasSuggestions:issues.length>0}}exports.noInsecureCookieOptions=(0,eslint_devkit_1.createRule)({name:"no-insecure-cookie-options",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-insecure-cookie-options.md",description:"Require secure cookie flags (httpOnly, secure, sameSite) in Express.js",cwe:"CWE-614",cvss:5.3},hasSuggestions:true,messages:{insecureCookie:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Insecure Cookie Configuration",cwe:"CWE-614",description:"{{issues}}",severity:"HIGH",fix:'Set httpOnly: true, secure: true, sameSite: "strict"',documentationLink:"https://owasp.org/www-community/controls/SecureCookieAttribute"}),addSecureFlags:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Secure Cookie Flags",description:"Add missing security flags to cookie options",severity:"LOW",fix:'{ httpOnly: true, secure: true, sameSite: "strict" }',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#security"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false},requireHttpOnly:{type:"boolean",default:true},requireSecure:{type:"boolean",default:true},requireSameSite:{type:"boolean",default:true},acceptableSameSiteValues:{type:"array",items:{type:"string"},default:["strict","lax"]}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,requireHttpOnly:true,requireSecure:true,requireSameSite:true,acceptableSameSiteValues:["strict","lax"]}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}return{CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="cookie"){const optionsArg=node.arguments[2];if(!optionsArg){context.report({node,messageId:"insecureCookie",data:{issues:"Cookie set without options - missing httpOnly, secure, sameSite flags"},suggest:[{messageId:"addSecureFlags",fix:fixer=>{const lastArg=node.arguments[node.arguments.length-1];return fixer.insertTextAfter(lastArg,', { httpOnly: true, secure: true, sameSite: "strict" }')}}]});return}if(optionsArg.type==="ObjectExpression"){const{issues}=checkCookieOptions(optionsArg,options);if(issues.length>0){context.report({node:optionsArg,messageId:"insecureCookie",data:{issues:issues.join("; ")}})}}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveCors=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");function readsBooleanTrue(node,name){return node.properties.some(property=>property.type==="Property"&&!property.computed&&(property.key.type==="Identifier"&&property.key.name===name||property.key.type==="Literal"&&property.key.value===name)&&property.value.type==="Literal"&&property.value.value===true)}function isPermissiveOrigin(node){return node.properties.some(property=>property.type==="Property"&&!property.computed&&(property.key.type==="Identifier"&&property.key.name==="origin"||property.key.type==="Literal"&&property.key.value==="origin")&&property.value.type==="Literal"&&(property.value.value===true||property.value.value==="*"))}function isPermissiveCorsConfig(node,sourceCode,options){const text=sourceCode.getText(node);if(readsBooleanTrue(node,"credentials")&&isPermissiveOrigin(node)){return{isPermissive:false,reason:""}}if(/\borigin\s*:\s*['"`]\*['"`]/.test(text)){return{isPermissive:true,reason:"origin: '*' allows any domain to access your API"}}if(!options.allowOriginTrue&&/\borigin\s*:\s*true\b/.test(text)){return{isPermissive:true,reason:"origin: true reflects the request origin, allowing any domain"}}return{isPermissive:false,reason:""}}function isStandaloneCorsCall(node){const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="cors"){const parent=node.parent;if(parent&&parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&parent.callee.property.type==="Identifier"&&parent.callee.property.name==="use"){return false}return true}return false}function isAppUseCors(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="use"){const firstArg=node.arguments[0];if(firstArg&&firstArg.type==="CallExpression"&&firstArg.callee.type==="Identifier"&&firstArg.callee.name==="cors"){return true}}return false}exports.noPermissiveCors=(0,eslint_devkit_1.createRule)({name:"no-permissive-cors",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-permissive-cors.md",description:"Disallow overly permissive CORS configurations (wildcard origin, origin: true)",cwe:"CWE-942",cvss:7.5},messages:{permissiveCors:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Permissive CORS Configuration",cwe:"CWE-942",description:"{{reason}}",severity:"HIGH",fix:'Specify an explicit whitelist of allowed origins: origin: ["https://trusted-domain.com"]',documentationLink:"https://owasp.org/www-community/attacks/CORS_OriginHeaderScrutiny"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow permissive CORS in test files"},allowOriginTrue:{type:"boolean",default:false,description:"Allow origin: true for development"},allowedOrigins:{type:"array",items:{type:"string"},default:[],description:"Allowed origins that should not trigger warnings"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,allowOriginTrue:false,allowedOrigins:[]}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false,allowOriginTrue=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;return{CallExpression(node){if(isStandaloneCorsCall(node)||isAppUseCors(node)){let corsConfigNode=null;if(isStandaloneCorsCall(node)&&node.arguments[0]?.type==="ObjectExpression"){corsConfigNode=node.arguments[0]}else if(isAppUseCors(node)){const corsCall=node.arguments[0];if(corsCall.arguments[0]?.type==="ObjectExpression"){corsConfigNode=corsCall.arguments[0]}}let corsCallNode=null;if(isStandaloneCorsCall(node)){corsCallNode=node}else{corsCallNode=node.arguments[0]}if(corsCallNode&&corsCallNode.arguments.length===0){context.report({node:corsCallNode,messageId:"permissiveCors",data:{reason:"cors() with no options uses permissive defaults"}});return}if(corsConfigNode){const{isPermissive,reason}=isPermissiveCorsConfig(corsConfigNode,sourceCode,{allowOriginTrue});if(isPermissive){context.report({node:corsConfigNode,messageId:"permissiveCors",data:{reason}})}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveCors=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");function readsBooleanTrue(node,name){return node.properties.some(property=>property.type==="Property"&&!property.computed&&(property.key.type==="Identifier"&&property.key.name===name||property.key.type==="Literal"&&property.key.value===name)&&property.value.type==="Literal"&&property.value.value===true)}function isPermissiveOrigin(node){return node.properties.some(property=>property.type==="Property"&&!property.computed&&(property.key.type==="Identifier"&&property.key.name==="origin"||property.key.type==="Literal"&&property.key.value==="origin")&&property.value.type==="Literal"&&(property.value.value===true||property.value.value==="*"))}function isPermissiveCorsConfig(node,sourceCode,options){const text=sourceCode.getText(node);if(readsBooleanTrue(node,"credentials")&&isPermissiveOrigin(node)){return{isPermissive:false,reason:""}}if(/\borigin\s*:\s*['"`]\*['"`]/.test(text)){return{isPermissive:true,reason:"origin: '*' allows any domain to access your API"}}if(!options.allowOriginTrue&&/\borigin\s*:\s*true\b/.test(text)){return{isPermissive:true,reason:"origin: true reflects the request origin, allowing any domain"}}return{isPermissive:false,reason:""}}function isStandaloneCorsCall(node){const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="cors"){const parent=node.parent;if(parent&&parent.type==="CallExpression"&&parent.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(parent.callee)==="use"){return false}return true}return false}function isAppUseCors(node){const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="use"){const firstArg=node.arguments[0];if(firstArg&&firstArg.type==="CallExpression"&&firstArg.callee.type==="Identifier"&&firstArg.callee.name==="cors"){return true}}return false}exports.noPermissiveCors=(0,eslint_devkit_1.createRule)({name:"no-permissive-cors",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-permissive-cors.md",description:"Disallow overly permissive CORS configurations (wildcard origin, origin: true)",cwe:"CWE-942",cvss:7.5},messages:{permissiveCors:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Permissive CORS Configuration",cwe:"CWE-942",description:"{{reason}}",severity:"HIGH",fix:'Specify an explicit whitelist of allowed origins: origin: ["https://trusted-domain.com"]',documentationLink:"https://owasp.org/www-community/attacks/CORS_OriginHeaderScrutiny"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow permissive CORS in test files"},allowOriginTrue:{type:"boolean",default:false,description:"Allow origin: true for development"},allowedOrigins:{type:"array",items:{type:"string"},default:[],description:"Allowed origins that should not trigger warnings"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,allowOriginTrue:false,allowedOrigins:[]}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false,allowOriginTrue=false}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;return{CallExpression(node){if(isStandaloneCorsCall(node)||isAppUseCors(node)){let corsConfigNode=null;if(isStandaloneCorsCall(node)&&node.arguments[0]?.type==="ObjectExpression"){corsConfigNode=node.arguments[0]}else if(isAppUseCors(node)){const corsCall=node.arguments[0];if(corsCall.arguments[0]?.type==="ObjectExpression"){corsConfigNode=corsCall.arguments[0]}}let corsCallNode=null;if(isStandaloneCorsCall(node)){corsCallNode=node}else{corsCallNode=node.arguments[0]}if(corsCallNode&&corsCallNode.arguments.length===0){context.report({node:corsCallNode,messageId:"permissiveCors",data:{reason:"cors() with no options uses permissive defaults"}});return}if(corsConfigNode){const{isPermissive,reason}=isPermissiveCorsConfig(corsConfigNode,sourceCode,{allowOriginTrue});if(isPermissive){context.report({node:corsConfigNode,messageId:"permissiveCors",data:{reason}})}}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveTrustProxy=void 0;const express_evidence_1=require("../../utils/express-evidence");const app_receiver_1=require("../../utils/app-receiver");const eslint_devkit_1=require("@interlace/eslint-devkit");const TRUST_PROXY="trust proxy";function isAppMethodCall(node,method,appReceiverNames){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(callee.computed)return false;if(callee.property.name!==method)return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return(0,app_receiver_1.isAppReceiver)(callee.object.name,appReceiverNames)}function isTrustProxyLiteral(node){return node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&node.value===TRUST_PROXY}exports.noPermissiveTrustProxy=(0,eslint_devkit_1.createRule)({name:"no-permissive-trust-proxy",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-permissive-trust-proxy.md",description:"Disallow unconditional 'trust proxy' \u2014 it makes req.ip client-controlled",cwe:"CWE-348",cvss:5.3,confidence:"high"},messages:{permissiveTrustProxy:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unconditional Proxy Trust (CWE-348)",cwe:"CWE-348",cvss:5.3,description:"'trust proxy' is enabled unconditionally, so Express takes the left-most X-Forwarded-For entry as req.ip. A client can send any address it likes \u2014 rate-limit buckets, IP allowlists and audit logs all follow the forged value.",severity:"MEDIUM",fix:"Set the number of proxies you actually run behind \u2014 app.set('trust proxy', {{hops}}) \u2014 or a subnet/'loopback'/predicate that names them.",documentationLink:"https://expressjs.com/en/guide/behind-proxies.html"}),useHopCount:"Trust exactly {{hops}} proxy hop(s) instead"},schema:[{type:"object",properties:{...app_receiver_1.APP_RECEIVER_SCHEMA,hopCount:{type:"number",minimum:1,description:"Number of reverse proxies used in the suggested fix"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{hopCount,appReceiverNames}=options;const hops=hopCount??1;function report(node,replacement){context.report({node,messageId:"permissiveTrustProxy",data:{hops:String(hops)},suggest:[{messageId:"useHopCount",data:{hops:String(hops)},fix:fixer=>fixer.replaceText(node,replacement)}]})}return{CallExpression(node){if(isAppMethodCall(node,"enable",appReceiverNames)){if(!isTrustProxyLiteral(node.arguments[0]))return;const receiver=context.sourceCode.getText(node.callee.object);report(node,`${receiver}.set('trust proxy', ${hops})`);return}if(!isAppMethodCall(node,"set",appReceiverNames))return;if(!isTrustProxyLiteral(node.arguments[0]))return;const value=node.arguments[1];if(!value||value.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||value.value!==true){return}report(value,String(hops))}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveTrustProxy=void 0;const express_evidence_1=require("../../utils/express-evidence");const app_receiver_1=require("../../utils/app-receiver");const eslint_devkit_1=require("@interlace/eslint-devkit");const TRUST_PROXY="trust proxy";function isAppMethodCall(node,method,appReceiverNames){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if((0,eslint_devkit_1.propertyName)(callee)!==method)return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return(0,app_receiver_1.isAppReceiver)(callee.object.name,appReceiverNames)}function isTrustProxyLiteral(node){return node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&node.value===TRUST_PROXY}exports.noPermissiveTrustProxy=(0,eslint_devkit_1.createRule)({name:"no-permissive-trust-proxy",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-permissive-trust-proxy.md",description:"Disallow unconditional 'trust proxy' \u2014 it makes req.ip client-controlled",cwe:"CWE-348",cvss:5.3,confidence:"high"},messages:{permissiveTrustProxy:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unconditional Proxy Trust (CWE-348)",cwe:"CWE-348",cvss:5.3,description:"'trust proxy' is enabled unconditionally, so Express takes the left-most X-Forwarded-For entry as req.ip. A client can send any address it likes \u2014 rate-limit buckets, IP allowlists and audit logs all follow the forged value.",severity:"MEDIUM",fix:"Set the number of proxies you actually run behind \u2014 app.set('trust proxy', {{hops}}) \u2014 or a subnet/'loopback'/predicate that names them.",documentationLink:"https://expressjs.com/en/guide/behind-proxies.html"}),useHopCount:"Trust exactly {{hops}} proxy hop(s) instead"},schema:[{type:"object",properties:{...app_receiver_1.APP_RECEIVER_SCHEMA,hopCount:{type:"number",minimum:1,description:"Number of reverse proxies used in the suggested fix"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{hopCount,appReceiverNames}=options;const hops=hopCount??1;function report(node,replacement){context.report({node,messageId:"permissiveTrustProxy",data:{hops:String(hops)},suggest:[{messageId:"useHopCount",data:{hops:String(hops)},fix:fixer=>fixer.replaceText(node,replacement)}]})}return{CallExpression(node){if(isAppMethodCall(node,"enable",appReceiverNames)){if(!isTrustProxyLiteral(node.arguments[0]))return;const receiver=context.sourceCode.getText(node.callee.object);report(node,`${receiver}.set('trust proxy', ${hops})`);return}if(!isAppMethodCall(node,"set",appReceiverNames))return;if(!isTrustProxyLiteral(node.arguments[0]))return;const value=node.arguments[1];if(!value||value.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||value.value!==true){return}report(value,String(hops))}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataInQuery=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_SENSITIVE=["password","token","secret","apiKey","api_key","auth","credential","ssn","card"];const MAX_PARAM_NAME_LENGTH=128;function tokenize(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(token=>token.length>0)}function containsSubsequence(tokens,term){for(let i=0;i+term.length<=tokens.length;i++){let match=true;for(let j=0;j<term.length;j++){if(tokens[i+j]!==term[j]){match=false;break}}if(match)return true}return false}exports.noSensitiveDataInQuery=(0,eslint_devkit_1.createRule)({name:"no-sensitive-data-in-query",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-sensitive-data-in-query.md",description:"Disallow reading sensitive-named parameters (password, token, secret, ...) from req.query",cwe:"CWE-598",cvss:6.5},messages:{sensitiveQueryParam:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Data in Query String (CWE-598)",cwe:"CWE-598",description:"Query parameter '{{name}}' is sensitive. Query strings are stored in access logs, proxy logs, browser history and leak via the Referer header.",severity:"MEDIUM",fix:"Move the value to the POST request body (req.body) or an Authorization header; never accept secrets via the query string.",documentationLink:"https://cwe.mitre.org/data/definitions/598.html"})},schema:[{type:"object",properties:{sensitiveParams:{type:"array",items:{type:"string"},description:"Additional sensitive parameter names (extends the defaults)"},extraPatterns:{type:"array",items:{type:"string"},description:"Additional regex patterns (case-insensitive) matched against the raw parameter name"},allowedParams:{type:"array",items:{type:"string"},description:"Parameter names explicitly allowed in the query string (exact, case-insensitive)"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{sensitiveParams,extraPatterns,allowedParams}=options;const terms=[...DEFAULT_SENSITIVE,...sensitiveParams??[]].map(term=>tokenize(term));const patterns=[];for(const pattern of extraPatterns??[]){try{patterns.push(new RegExp(pattern,"i"))}catch{}}const allowedSet=new Set((allowedParams??[]).map(name=>name.toLowerCase()));function isRequestIdent(name){const lower=name.toLowerCase();return lower==="req"||lower==="request"||lower==="ctx"}function isReqQuery(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isRequestIdent(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="query"}function isSensitive(name){if(allowedSet.has(name.toLowerCase()))return false;const tokens=tokenize(name);for(const term of terms){if(term.length===1){const single=term[0];if(tokens.some(token=>token===single||token===`${single}s`)){return true}}else if(containsSubsequence(tokens,term)){return true}}if(name.length>MAX_PARAM_NAME_LENGTH)return false;return patterns.some(pattern=>pattern.test(name))}function report(node,name){context.report({node,messageId:"sensitiveQueryParam",data:{name}})}return{MemberExpression(node){if(!isReqQuery(node.object))return;let name=null;if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!node.computed){name=node.property.name}else if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.property.value==="string"){name=node.property.value}if(name!==null&&isSensitive(name))report(node,name)},VariableDeclarator(node){if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return;if(node.init===null||!isReqQuery(node.init))return;for(const prop of node.id.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;let name=null;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed){name=prop.key.name}else if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){name=prop.key.value}if(name!==null&&isSensitive(name))report(prop,name)}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataInQuery=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_SENSITIVE=["password","token","secret","apiKey","api_key","auth","credential","ssn","card"];const MAX_PARAM_NAME_LENGTH=128;function tokenize(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(token=>token.length>0)}function containsSubsequence(tokens,term){for(let i=0;i+term.length<=tokens.length;i++){let match=true;for(let j=0;j<term.length;j++){if(tokens[i+j]!==term[j]){match=false;break}}if(match)return true}return false}exports.noSensitiveDataInQuery=(0,eslint_devkit_1.createRule)({name:"no-sensitive-data-in-query",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-sensitive-data-in-query.md",description:"Disallow reading sensitive-named parameters (password, token, secret, ...) from req.query",cwe:"CWE-598",cvss:6.5},messages:{sensitiveQueryParam:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive Data in Query String (CWE-598)",cwe:"CWE-598",description:"Query parameter '{{name}}' is sensitive. Query strings are stored in access logs, proxy logs, browser history and leak via the Referer header.",severity:"MEDIUM",fix:"Move the value to the POST request body (req.body) or an Authorization header; never accept secrets via the query string.",documentationLink:"https://cwe.mitre.org/data/definitions/598.html"})},schema:[{type:"object",properties:{sensitiveParams:{type:"array",items:{type:"string"},description:"Additional sensitive parameter names (extends the defaults)"},extraPatterns:{type:"array",items:{type:"string"},description:"Additional regex patterns (case-insensitive) matched against the raw parameter name"},allowedParams:{type:"array",items:{type:"string"},description:"Parameter names explicitly allowed in the query string (exact, case-insensitive)"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{sensitiveParams,extraPatterns,allowedParams}=options;const terms=[...DEFAULT_SENSITIVE,...sensitiveParams??[]].map(term=>tokenize(term));const patterns=[];for(const pattern of extraPatterns??[]){try{patterns.push(new RegExp(pattern,"i"))}catch{}}const allowedSet=new Set((allowedParams??[]).map(name=>name.toLowerCase()));function isRequestIdent(name){const lower=name.toLowerCase();return lower==="req"||lower==="request"||lower==="ctx"}function isReqQuery(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isRequestIdent(node.object.name)&&(0,eslint_devkit_1.propertyName)(node)==="query"}function isSensitive(name){if(allowedSet.has(name.toLowerCase()))return false;const tokens=tokenize(name);for(const term of terms){if(term.length===1){const single=term[0];if(tokens.some(token=>token===single||token===`${single}s`)){return true}}else if(containsSubsequence(tokens,term)){return true}}if(name.length>MAX_PARAM_NAME_LENGTH)return false;return patterns.some(pattern=>pattern.test(name))}function report(node,name){context.report({node,messageId:"sensitiveQueryParam",data:{name}})}return{MemberExpression(node){if(!isReqQuery(node.object))return;let name=null;if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!node.computed){name=node.property.name}else if(node.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.property.value==="string"){name=node.property.value}if(name!==null&&isSensitive(name))report(node,name)},VariableDeclarator(node){if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return;if(node.init===null||!isReqQuery(node.init))return;for(const prop of node.id.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;let name=null;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!prop.computed){name=prop.key.name}else if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){name=prop.key.value}if(name!==null&&isSensitive(name))report(prop,name)}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noStaticRootExposure=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_ALLOWED_ROOTS=[];const JOIN_METHODS=new Set(["join","resolve"]);function quoteLiteral(value){const json=JSON.stringify(value);const inner=json.slice(1,-1);return/['\\]/.test(inner)?json:`'${inner}'`}exports.noStaticRootExposure=(0,eslint_devkit_1.createRule)({name:"no-static-root-exposure",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-static-root-exposure.md",description:"Disallow express.static() roots that expose the application directory and any serve-index usage",cwe:"CWE-548",cvss:7.5},messages:{staticRoot:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Application Root Served Statically (CWE-548)",cwe:"CWE-548",description:"express.static() serves {{exposed}} \u2014 the application root. This publishes .env, package-lock.json, .git metadata and the server source itself.",severity:"HIGH",fix:"Serve a dedicated asset directory instead: express.static(path.join(__dirname, 'public')).",documentationLink:"https://cwe.mitre.org/data/definitions/548.html"}),traversalSegments:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Static Root Escapes the Application Directory (CWE-548)",cwe:"CWE-548",description:'The static root contains a ".." segment, so files OUTSIDE the intended directory become publicly reachable.',severity:"HIGH",fix:'Point express.static() at a dedicated asset directory inside the project, with no ".." segments.',documentationLink:"https://cwe.mitre.org/data/definitions/548.html"}),nonLiteralPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic Static-Root Segment (CWE-548)",cwe:"CWE-548",description:"The static root is built from a non-literal segment, so the served directory cannot be verified at lint time and may expose unintended files.",severity:"MEDIUM",fix:"Use a string literal for every path segment: path.join(__dirname, 'public').",documentationLink:"https://cwe.mitre.org/data/definitions/548.html"}),unknownRoot:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unrecognized Static-Assets Directory (CWE-548)",cwe:"CWE-548",description:'"{{root}}" is not an allowlisted static-assets directory. Serving arbitrary directories risks exposing files that were never meant to be public.',severity:"MEDIUM",fix:"Serve a dedicated asset directory (public/, static/, dist/, build/, assets/) or add the directory to the allowedRoots option.",documentationLink:"https://cwe.mitre.org/data/definitions/548.html"}),directoryListing:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Directory Listing Enabled (CWE-548)",cwe:"CWE-548",description:"serve-index exposes a browsable listing of every file in the served directory, giving attackers a map of the filesystem.",severity:"HIGH",fix:"Remove the serve-index middleware; serve an explicit index file or a curated file list instead.",documentationLink:"https://cwe.mitre.org/data/definitions/548.html"}),scopeToSubdir:"Serve path.join(__dirname, '{{root}}') instead"},schema:[{type:"object",properties:{allowedRoots:{type:"array",items:{type:"string"},description:"Directory names accepted as the first path segment of a static root"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowedRoots}=options;const roots=new Set(allowedRoots??DEFAULT_ALLOWED_ROOTS);const suggestionRoot=(allowedRoots??DEFAULT_ALLOWED_ROOTS)[0]??"public";const serveIndexNames=new Set(["serveIndex"]);function isDirnameNode(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.name==="__dirname"}function isProcessCwdCall(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(callee.object.name!=="process")return false;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return callee.property.name==="cwd"}function isPathJoinCall(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(callee.object.name!=="path")return false;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return JOIN_METHODS.has(callee.property.name)}function isExpressStaticCall(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(callee.property.name!=="static")return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return callee.object.name.toLowerCase()==="express"}function segmentsOf(value){return value.split(/[\\/]+/).filter(seg=>seg!==""&&seg!==".")}function reportRoot(node,exposed){context.report({node,messageId:"staticRoot",data:{exposed},suggest:[{messageId:"scopeToSubdir",data:{root:suggestionRoot},fix:fixer=>fixer.replaceText(node,`path.join(__dirname, ${quoteLiteral(suggestionRoot)})`)}]})}function checkJoinRoot(call){const literalSegments=[];let hasNonLiteral=false;let hasTraversal=false;for(const arg of call.arguments){if(isDirnameNode(arg)||isProcessCwdCall(arg))continue;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"){const segments=segmentsOf(arg.value);if(segments.includes(".."))hasTraversal=true;literalSegments.push(...segments);continue}hasNonLiteral=true}if(hasTraversal){context.report({node:call,messageId:"traversalSegments"});return}if(hasNonLiteral&&literalSegments.length===0){context.report({node:call,messageId:"nonLiteralPath"});return}if(literalSegments.length===0){reportRoot(call,context.sourceCode.getText(call));return}if(roots.size>0&&!roots.has(literalSegments[0])){context.report({node:call,messageId:"unknownRoot",data:{root:literalSegments[0]}})}}function checkStaticRoot(node){if(isDirnameNode(node)){reportRoot(node,"__dirname");return}if(isProcessCwdCall(node)){reportRoot(node,"process.cwd()");return}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){if(typeof node.value!=="string")return;const segments=segmentsOf(node.value);if(segments.includes("..")){context.report({node,messageId:"traversalSegments"});return}if(segments.length===0){reportRoot(node,`'${node.value}'`);return}if(roots.size>0&&!roots.has(segments[0])){context.report({node,messageId:"unknownRoot",data:{root:segments[0]}})}return}if(isPathJoinCall(node)){checkJoinRoot(node)}}return{ImportDeclaration(node){if(node.source.value!=="serve-index")return;for(const specifier of node.specifiers){serveIndexNames.add(specifier.local.name)}},VariableDeclarator(node){if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(!node.init)return;if(node.init.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return;const callee=node.init.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(callee.name!=="require")return;const requiredModule=node.init.arguments[0];if(!requiredModule)return;if(requiredModule.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return;if(requiredModule.value!=="serve-index")return;serveIndexNames.add(node.id.name)},CallExpression(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&serveIndexNames.has(callee.name)){context.report({node,messageId:"directoryListing"});return}if(!isExpressStaticCall(node))return;const rootArg=node.arguments[0];if(!rootArg)return;checkStaticRoot(rootArg)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noStaticRootExposure=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_ALLOWED_ROOTS=[];const JOIN_METHODS=new Set(["join","resolve"]);function quoteLiteral(value){const json=JSON.stringify(value);const inner=json.slice(1,-1);return/['\\]/.test(inner)?json:`'${inner}'`}exports.noStaticRootExposure=(0,eslint_devkit_1.createRule)({name:"no-static-root-exposure",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-static-root-exposure.md",description:"Disallow express.static() roots that expose the application directory and any serve-index usage",cwe:"CWE-548",cvss:7.5},messages:{staticRoot:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Application Root Served Statically (CWE-548)",cwe:"CWE-548",description:"express.static() serves {{exposed}} \u2014 the application root. This publishes .env, package-lock.json, .git metadata and the server source itself.",severity:"HIGH",fix:"Serve a dedicated asset directory instead: express.static(path.join(__dirname, 'public')).",documentationLink:"https://cwe.mitre.org/data/definitions/548.html"}),traversalSegments:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Static Root Escapes the Application Directory (CWE-548)",cwe:"CWE-548",description:'The static root contains a ".." segment, so files OUTSIDE the intended directory become publicly reachable.',severity:"HIGH",fix:'Point express.static() at a dedicated asset directory inside the project, with no ".." segments.',documentationLink:"https://cwe.mitre.org/data/definitions/548.html"}),nonLiteralPath:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic Static-Root Segment (CWE-548)",cwe:"CWE-548",description:"The static root is built from a non-literal segment, so the served directory cannot be verified at lint time and may expose unintended files.",severity:"MEDIUM",fix:"Use a string literal for every path segment: path.join(__dirname, 'public').",documentationLink:"https://cwe.mitre.org/data/definitions/548.html"}),unknownRoot:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unrecognized Static-Assets Directory (CWE-548)",cwe:"CWE-548",description:'"{{root}}" is not an allowlisted static-assets directory. Serving arbitrary directories risks exposing files that were never meant to be public.',severity:"MEDIUM",fix:"Serve a dedicated asset directory (public/, static/, dist/, build/, assets/) or add the directory to the allowedRoots option.",documentationLink:"https://cwe.mitre.org/data/definitions/548.html"}),directoryListing:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Directory Listing Enabled (CWE-548)",cwe:"CWE-548",description:"serve-index exposes a browsable listing of every file in the served directory, giving attackers a map of the filesystem.",severity:"HIGH",fix:"Remove the serve-index middleware; serve an explicit index file or a curated file list instead.",documentationLink:"https://cwe.mitre.org/data/definitions/548.html"}),scopeToSubdir:"Serve path.join(__dirname, '{{root}}') instead"},schema:[{type:"object",properties:{allowedRoots:{type:"array",items:{type:"string"},description:"Directory names accepted as the first path segment of a static root"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowedRoots}=options;const roots=new Set(allowedRoots??DEFAULT_ALLOWED_ROOTS);const suggestionRoot=(allowedRoots??DEFAULT_ALLOWED_ROOTS)[0]??"public";const serveIndexNames=new Set(["serveIndex"]);function isDirnameNode(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.name==="__dirname"}function isProcessCwdCall(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(callee.object.name!=="process")return false;return(0,eslint_devkit_1.propertyName)(callee)==="cwd"}function isPathJoinCall(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(callee.object.name!=="path")return false;return(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),JOIN_METHODS)}function isExpressStaticCall(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if((0,eslint_devkit_1.propertyName)(callee)!=="static")return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return callee.object.name.toLowerCase()==="express"}function segmentsOf(value){return value.split(/[\\/]+/).filter(seg=>seg!==""&&seg!==".")}function reportRoot(node,exposed){context.report({node,messageId:"staticRoot",data:{exposed},suggest:[{messageId:"scopeToSubdir",data:{root:suggestionRoot},fix:fixer=>fixer.replaceText(node,`path.join(__dirname, ${quoteLiteral(suggestionRoot)})`)}]})}function checkJoinRoot(call){const literalSegments=[];let hasNonLiteral=false;let hasTraversal=false;for(const arg of call.arguments){if(isDirnameNode(arg)||isProcessCwdCall(arg))continue;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"){const segments=segmentsOf(arg.value);if(segments.includes(".."))hasTraversal=true;literalSegments.push(...segments);continue}hasNonLiteral=true}if(hasTraversal){context.report({node:call,messageId:"traversalSegments"});return}if(hasNonLiteral&&literalSegments.length===0){context.report({node:call,messageId:"nonLiteralPath"});return}if(literalSegments.length===0){reportRoot(call,context.sourceCode.getText(call));return}if(roots.size>0&&!roots.has(literalSegments[0])){context.report({node:call,messageId:"unknownRoot",data:{root:literalSegments[0]}})}}function checkStaticRoot(node){if(isDirnameNode(node)){reportRoot(node,"__dirname");return}if(isProcessCwdCall(node)){reportRoot(node,"process.cwd()");return}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){if(typeof node.value!=="string")return;const segments=segmentsOf(node.value);if(segments.includes("..")){context.report({node,messageId:"traversalSegments"});return}if(segments.length===0){reportRoot(node,`'${node.value}'`);return}if(roots.size>0&&!roots.has(segments[0])){context.report({node,messageId:"unknownRoot",data:{root:segments[0]}})}return}if(isPathJoinCall(node)){checkJoinRoot(node)}}return{ImportDeclaration(node){if(node.source.value!=="serve-index")return;for(const specifier of node.specifiers){serveIndexNames.add(specifier.local.name)}},VariableDeclarator(node){if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(!node.init)return;if(node.init.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return;const callee=node.init.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(callee.name!=="require")return;const requiredModule=node.init.arguments[0];if(!requiredModule)return;if(requiredModule.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return;if(requiredModule.value!=="serve-index")return;serveIndexNames.add(node.id.name)},CallExpression(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&serveIndexNames.has(callee.name)){context.report({node,messageId:"directoryListing"});return}if(!isExpressStaticCall(node))return;const rootArg=node.arguments[0];if(!rootArg)return;checkStaticRoot(rootArg)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUserControlledRedirect=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const USER_SOURCE_PROPS=new Set(["query","body","params","headers","cookies"]);const REDIRECT_METHODS=new Set(["redirect","location"]);const ORIGIN_PROPS=new Set(["host","hostname","origin"]);exports.noUserControlledRedirect=(0,eslint_devkit_1.createRule)({name:"no-user-controlled-redirect",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-user-controlled-redirect.md",description:"Disallow res.redirect() with values directly from req.query / req.body / req.params",cwe:"CWE-601",cvss:6.1},messages:{openRedirect:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Open Redirect (CWE-601)",cwe:"CWE-601",description:"res.redirect() receives a value directly from {{source}}, which is user-controlled. An attacker can redirect victims to a malicious site.",severity:"HIGH",fix:"Validate the redirect target against an allowlist of trusted paths/origins, or use a relative path that cannot be redirected off-domain.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html"})},schema:[{type:"object",properties:{responseObjects:{type:"array",items:{type:"string"},description:'Additional response object names (e.g. ["reply"] for Fastify)'},requestObjects:{type:"array",items:{type:"string"},description:"Additional request object names"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{responseObjects,requestObjects}=options;const extraResNames=new Set(responseObjects??[]);const extraReqNames=new Set(requestObjects??[]);function isRedirectCall(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(!REDIRECT_METHODS.has(callee.property.name))return false;const obj=callee.object;if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const name=obj.name.toLowerCase();return name==="res"||name==="response"||name==="reply"||extraResNames.has(obj.name)}function getUserSourceDescription(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const obj=node.object;if(obj.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const root=obj.object;const sourceProp=obj.property;if(root.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&sourceProp.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&USER_SOURCE_PROPS.has(sourceProp.name)&&isRequestIdent(root.name)){return`req.${sourceProp.name}`}}const prop=node.property;if(obj.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&USER_SOURCE_PROPS.has(prop.name)&&isRequestIdent(obj.name)){return`req.${prop.name}`}return null}function sameMemberPath(a,b){if(a.type!==b.type)return false;if(a.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&b.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return a.name===b.name}if(a.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&b.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return a.value===b.value}if(a.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&b.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return a.computed===b.computed&&sameMemberPath(a.object,b.object)&&sameMemberPath(a.property,b.property)}return false}function isUrlParseOf(node,source){return node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="URL"&&node.arguments.length>0&&sameMemberPath(node.arguments[0],source)}function search(root,hit,stopAtFn){let found=false;const visit=n=>{if(found||n===null||typeof n!=="object")return;const candidate=n;if(typeof candidate.type!=="string"){if(Array.isArray(n))n.forEach(visit);return}if(hit(candidate)){found=true;return}if(stopAtFn&&(candidate.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||candidate.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||candidate.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration)){return}for(const key of Object.keys(candidate)){if(key==="parent")continue;const value=candidate[key];if(Array.isArray(value))value.forEach(visit);else if(value&&typeof value==="object")visit(value)}};visit(root);return found}function containsOriginCheck(node,source){return search(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&n.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&ORIGIN_PROPS.has(n.property.name)&&isUrlParseOf(n.object,source),false)}function exitsHandler(node){return search(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||n.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement,true)}function hasOriginGuard(source,from){let scope=context.sourceCode.ast;for(let candidate=from;candidate;candidate=candidate.parent){if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||candidate.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||candidate.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||candidate.type===eslint_devkit_1.AST_NODE_TYPES.Program){scope=candidate;break}}const body=scope.type===eslint_devkit_1.AST_NODE_TYPES.Program?scope.body:scope.body;return search(body,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&containsOriginCheck(n.test,source)&&exitsHandler(n.consequent),true)}function isRequestIdent(name){const lower=name.toLowerCase();return lower==="req"||lower==="request"||lower==="ctx"||extraReqNames.has(name)}return{CallExpression(node){if(!isRedirectCall(node))return;const firstArg=node.arguments[0];if(!firstArg)return;const source=getUserSourceDescription(firstArg);if(!source)return;if(hasOriginGuard(firstArg,node))return;context.report({node:firstArg,messageId:"openRedirect",data:{source}})}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUserControlledRedirect=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const USER_SOURCE_PROPS=new Set(["query","body","params","headers","cookies"]);const REDIRECT_METHODS=new Set(["redirect","location"]);const ORIGIN_PROPS=new Set(["host","hostname","origin"]);exports.noUserControlledRedirect=(0,eslint_devkit_1.createRule)({name:"no-user-controlled-redirect",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-user-controlled-redirect.md",description:"Disallow res.redirect() with values directly from req.query / req.body / req.params",cwe:"CWE-601",cvss:6.1},messages:{openRedirect:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Open Redirect (CWE-601)",cwe:"CWE-601",description:"res.redirect() receives a value directly from {{source}}, which is user-controlled. An attacker can redirect victims to a malicious site.",severity:"HIGH",fix:"Validate the redirect target against an allowlist of trusted paths/origins, or use a relative path that cannot be redirected off-domain.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html"})},schema:[{type:"object",properties:{responseObjects:{type:"array",items:{type:"string"},description:'Additional response object names (e.g. ["reply"] for Fastify)'},requestObjects:{type:"array",items:{type:"string"},description:"Additional request object names"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{responseObjects,requestObjects}=options;const extraResNames=new Set(responseObjects??[]);const extraReqNames=new Set(requestObjects??[]);function isRedirectCall(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(!REDIRECT_METHODS.has(callee.property.name))return false;const obj=callee.object;if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const name=obj.name.toLowerCase();return name==="res"||name==="response"||name==="reply"||extraResNames.has(obj.name)}function getUserSourceDescription(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const obj=node.object;if(obj.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const root=obj.object;const sourceProp=obj.property;if(root.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&sourceProp.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&USER_SOURCE_PROPS.has(sourceProp.name)&&isRequestIdent(root.name)){return`req.${sourceProp.name}`}}const prop=node.property;if(obj.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&USER_SOURCE_PROPS.has(prop.name)&&isRequestIdent(obj.name)){return`req.${prop.name}`}return null}function sameMemberPath(a,b){if(a.type!==b.type)return false;if(a.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&b.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return a.name===b.name}if(a.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&b.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return a.value===b.value}if(a.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&b.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return a.computed===b.computed&&sameMemberPath(a.object,b.object)&&sameMemberPath(a.property,b.property)}return false}function isUrlParseOf(node,source){return node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="URL"&&node.arguments.length>0&&sameMemberPath(node.arguments[0],source)}function search(root,hit,stopAtFn){let found=false;const visit=n=>{if(found||n===null||typeof n!=="object")return;const candidate=n;if(typeof candidate.type!=="string"){if(Array.isArray(n))n.forEach(visit);return}if(hit(candidate)){found=true;return}if(stopAtFn&&(candidate.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||candidate.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||candidate.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration)){return}for(const key of Object.keys(candidate)){if(key==="parent")continue;const value=candidate[key];if(Array.isArray(value))value.forEach(visit);else if(value&&typeof value==="object")visit(value)}};visit(root);return found}function containsOriginCheck(node,source){return search(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(n),ORIGIN_PROPS)&&isUrlParseOf(n.object,source),false)}function exitsHandler(node){return search(node,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||n.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement,true)}function hasOriginGuard(source,from){let scope=context.sourceCode.ast;for(let candidate=from;candidate;candidate=candidate.parent){if(candidate.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||candidate.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||candidate.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||candidate.type===eslint_devkit_1.AST_NODE_TYPES.Program){scope=candidate;break}}const body=scope.type===eslint_devkit_1.AST_NODE_TYPES.Program?scope.body:scope.body;return search(body,n=>n.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&containsOriginCheck(n.test,source)&&exitsHandler(n.consequent),true)}function isRequestIdent(name){const lower=name.toLowerCase();return lower==="req"||lower==="request"||lower==="ctx"||extraReqNames.has(name)}return{CallExpression(node){if(!isRedirectCall(node))return;const firstArg=node.arguments[0];if(!firstArg)return;const source=getUserSourceDescription(firstArg);if(!source)return;if(hasOriginGuard(firstArg,node))return;context.report({node:firstArg,messageId:"openRedirect",data:{source}})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUserControlledRenderLocals=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const USER_SOURCE_PROPS=new Set(["body","query","params"]);exports.noUserControlledRenderLocals=(0,eslint_devkit_1.createRule)({name:"no-user-controlled-render-locals",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-user-controlled-render-locals.md",description:"Disallow res.render() with locals or view names sourced wholesale from req.body / req.query / req.params",cwe:"CWE-73",cvss:7.3},messages:{unsafeRenderLocals:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Template Object Injection (CWE-73)",cwe:"CWE-73",description:'res.render() receives locals wholly controlled by {{source}}. Express merges locals into the view-engine options, so keys like "layout", "settings" or "cache" can point the engine at an attacker-chosen file.',severity:"HIGH",fix:"Pick only the fields the template needs into an explicit object literal ({ title: req.body.title }) instead of forwarding the whole request object.",documentationLink:"https://cwe.mitre.org/data/definitions/73.html"}),userControlledView:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"User-Controlled View Path (CWE-73)",cwe:"CWE-73",description:"The view name passed to res.render() derives from {{source}}. An attacker can traverse into unintended templates or files within the views directory.",severity:"HIGH",fix:"Map user input to a fixed set of view names via an allowlist; never build the template path from request data.",documentationLink:"https://cwe.mitre.org/data/definitions/73.html"}),pickFieldsExplicitly:"Remove the request-object spread and pick the required fields explicitly"},schema:[{type:"object",properties:{allowSanitizers:{type:"array",items:{type:"string"},description:'Callee names that sanitize locals (e.g. ["pick", "sanitizeLocals"]); calls to them are not flagged'}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowSanitizers}=options;const sanitizers=new Set(allowSanitizers??[]);const trackedVars=new Map;function resolveVariable(node){let scope=context.sourceCode.getScope(node);while(scope){const found=scope.variables.find(v=>v.name===node.name);if(found)return found;scope=scope.upper}return null}function getTracked(node){const variable=resolveVariable(node);return variable?trackedVars.get(variable):void 0}function isParameter(node){const variable=resolveVariable(node);return variable?.defs.some(d=>d.type==="Parameter")??false}function getWholeSource(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const{object,property}=node;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(node.computed)return null;if(!USER_SOURCE_PROPS.has(property.name))return null;if(!(0,eslint_devkit_1.readsRequestShape)(node,context.sourceCode,{bodyNeedsDepth:false})){return null}return`req.${property.name}`}function isSanitizerCall(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return sanitizers.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return sanitizers.has(callee.property.name)}return false}function getUnsafeLocalsSource(node){const direct=getWholeSource(node);if(direct)return direct;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const tracked=getTracked(node);if(tracked&&tracked.whole)return tracked.source;return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(isSanitizerCall(node))return null;for(const arg of node.arguments){const argSource=getWholeSource(arg);if(argSource)return argSource}}return null}function getDerivedSource(node){const whole=getWholeSource(node);if(whole)return whole;if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return getDerivedSource(node.object)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expr of node.expressions){const inner=getDerivedSource(expr);if(inner)return inner}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){if(node.operator!=="+")return null;const left=getDerivedSource(node.left);if(left)return left;return getDerivedSource(node.right)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const tracked=getTracked(node);if(tracked)return tracked.source;return null}return null}function isRenderCall(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(callee.property.name!=="render")return false;const obj=callee.object;if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return isParameter(obj)}function buildRemoveSpreadFix(spread){return fixer=>{const sourceCode=context.sourceCode;const tokenAfter=sourceCode.getTokenAfter(spread);const tokenBefore=sourceCode.getTokenBefore(spread);if(tokenAfter.value===","){return fixer.removeRange([spread.range[0],tokenAfter.range[1]])}if(tokenBefore.value===","){return fixer.removeRange([tokenBefore.range[0],spread.range[1]])}return fixer.remove(spread)}}function checkLocalsArg(node){const source=getUnsafeLocalsSource(node);if(source){context.report({node,messageId:"unsafeRenderLocals",data:{source}});return}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;for(const prop of node.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const spreadSource=getUnsafeLocalsSource(prop.argument);if(!spreadSource)continue;context.report({node:prop,messageId:"unsafeRenderLocals",data:{source:spreadSource},suggest:[{messageId:"pickFieldsExplicitly",fix:buildRemoveSpreadFix(prop)}]})}}function trackDeclarator(declared,init){const unsafe=getUnsafeLocalsSource(init);if(unsafe){trackedVars.set(declared,{source:unsafe,whole:true});return}if(init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of init.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const spreadSource=getUnsafeLocalsSource(prop.argument);if(spreadSource){trackedVars.set(declared,{source:spreadSource,whole:true});return}}return}const derived=getDerivedSource(init);if(derived){trackedVars.set(declared,{source:derived,whole:false})}}return{VariableDeclarator(node){if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const init=node.init;if(!init)return;for(const declared of context.sourceCode.getDeclaredVariables(node)){trackDeclarator(declared,init)}},CallExpression(node){if(!isRenderCall(node))return;const viewArg=node.arguments[0];if(!viewArg)return;const viewSource=getDerivedSource(viewArg);if(viewSource){context.report({node:viewArg,messageId:"userControlledView",data:{source:viewSource}})}const localsArg=node.arguments[1];if(!localsArg)return;checkLocalsArg(localsArg)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUserControlledRenderLocals=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const USER_SOURCE_PROPS=new Set(["body","query","params"]);exports.noUserControlledRenderLocals=(0,eslint_devkit_1.createRule)({name:"no-user-controlled-render-locals",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-user-controlled-render-locals.md",description:"Disallow res.render() with locals or view names sourced wholesale from req.body / req.query / req.params",cwe:"CWE-73",cvss:7.3},messages:{unsafeRenderLocals:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Template Object Injection (CWE-73)",cwe:"CWE-73",description:'res.render() receives locals wholly controlled by {{source}}. Express merges locals into the view-engine options, so keys like "layout", "settings" or "cache" can point the engine at an attacker-chosen file.',severity:"HIGH",fix:"Pick only the fields the template needs into an explicit object literal ({ title: req.body.title }) instead of forwarding the whole request object.",documentationLink:"https://cwe.mitre.org/data/definitions/73.html"}),userControlledView:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"User-Controlled View Path (CWE-73)",cwe:"CWE-73",description:"The view name passed to res.render() derives from {{source}}. An attacker can traverse into unintended templates or files within the views directory.",severity:"HIGH",fix:"Map user input to a fixed set of view names via an allowlist; never build the template path from request data.",documentationLink:"https://cwe.mitre.org/data/definitions/73.html"}),pickFieldsExplicitly:"Remove the request-object spread and pick the required fields explicitly"},schema:[{type:"object",properties:{allowSanitizers:{type:"array",items:{type:"string"},description:'Callee names that sanitize locals (e.g. ["pick", "sanitizeLocals"]); calls to them are not flagged'}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowSanitizers}=options;const sanitizers=new Set(allowSanitizers??[]);const trackedVars=new Map;function resolveVariable(node){let scope=context.sourceCode.getScope(node);while(scope){const found=scope.variables.find(v=>v.name===node.name);if(found)return found;scope=scope.upper}return null}function getTracked(node){const variable=resolveVariable(node);return variable?trackedVars.get(variable):void 0}function isParameter(node){const variable=resolveVariable(node);return variable?.defs.some(d=>d.type==="Parameter")??false}function getWholeSource(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const{object}=node;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const source=(0,eslint_devkit_1.propertyName)(node);if(source===null||!USER_SOURCE_PROPS.has(source))return null;if(!(0,eslint_devkit_1.readsRequestShape)(node,context.sourceCode,{bodyNeedsDepth:false})){return null}return`req.${source}`}function isSanitizerCall(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return sanitizers.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),sanitizers)}return false}function getUnsafeLocalsSource(node){const direct=getWholeSource(node);if(direct)return direct;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const tracked=getTracked(node);if(tracked&&tracked.whole)return tracked.source;return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){if(isSanitizerCall(node))return null;for(const arg of node.arguments){const argSource=getWholeSource(arg);if(argSource)return argSource}}return null}function getDerivedSource(node){const whole=getWholeSource(node);if(whole)return whole;if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return getDerivedSource(node.object)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expr of node.expressions){const inner=getDerivedSource(expr);if(inner)return inner}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){if(node.operator!=="+")return null;const left=getDerivedSource(node.left);if(left)return left;return getDerivedSource(node.right)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const tracked=getTracked(node);if(tracked)return tracked.source;return null}return null}function isRenderCall(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if((0,eslint_devkit_1.propertyName)(callee)!=="render")return false;const obj=callee.object;if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return isParameter(obj)}function buildRemoveSpreadFix(spread){return fixer=>{const sourceCode=context.sourceCode;const tokenAfter=sourceCode.getTokenAfter(spread);const tokenBefore=sourceCode.getTokenBefore(spread);if(tokenAfter.value===","){return fixer.removeRange([spread.range[0],tokenAfter.range[1]])}if(tokenBefore.value===","){return fixer.removeRange([tokenBefore.range[0],spread.range[1]])}return fixer.remove(spread)}}function checkLocalsArg(node){const source=getUnsafeLocalsSource(node);if(source){context.report({node,messageId:"unsafeRenderLocals",data:{source}});return}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;for(const prop of node.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const spreadSource=getUnsafeLocalsSource(prop.argument);if(!spreadSource)continue;context.report({node:prop,messageId:"unsafeRenderLocals",data:{source:spreadSource},suggest:[{messageId:"pickFieldsExplicitly",fix:buildRemoveSpreadFix(prop)}]})}}function trackDeclarator(declared,init){const unsafe=getUnsafeLocalsSource(init);if(unsafe){trackedVars.set(declared,{source:unsafe,whole:true});return}if(init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const prop of init.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const spreadSource=getUnsafeLocalsSource(prop.argument);if(spreadSource){trackedVars.set(declared,{source:spreadSource,whole:true});return}}return}const derived=getDerivedSource(init);if(derived){trackedVars.set(declared,{source:derived,whole:false})}}return{VariableDeclarator(node){if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const init=node.init;if(!init)return;for(const declared of context.sourceCode.getDeclaredVariables(node)){trackDeclarator(declared,init)}},CallExpression(node){if(!isRenderCall(node))return;const viewArg=node.arguments[0];if(!viewArg)return;const viewSource=getDerivedSource(viewArg);if(viewSource){context.report({node:viewArg,messageId:"userControlledView",data:{source:viewSource}})}const localsArg=node.arguments[1];if(!localsArg)return;checkLocalsArg(localsArg)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireCaseInsensitivePathGuard=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const PATH_PROPS=new Set(["path","url","originalUrl"]);const GUARD_METHODS=new Set(["startsWith","endsWith","includes","indexOf","match"]);const EQUALITY_OPS=new Set(["===","==","!==","!="]);function quoteLiteral(value){const json=JSON.stringify(value.toLowerCase());const inner=json.slice(1,-1);return/['\\]/.test(inner)?json:`'${inner}'`}const DEFAULT_PROTECTED_PATHS=["admin","api","dashboard","internal","private"];exports.requireCaseInsensitivePathGuard=(0,eslint_devkit_1.createRule)({name:"require-case-insensitive-path-guard",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-case-insensitive-path-guard.md",description:"Require case-insensitive comparison when guarding protected paths via req.path / req.url / req.originalUrl",cwe:"CWE-178",cvss:7.3},messages:{caseSensitivePathGuard:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Case-Sensitive Path Guard (CWE-178)",cwe:"CWE-178",description:"{{pathExpr}} is compared case-sensitively against '{{value}}', but Express routes can match case-insensitively. A request to an upper-cased variant (e.g. /Admin) reaches the handler without ever hitting this guard.",severity:"HIGH",fix:"Normalize the path with .toLowerCase() before comparing (and lower-case the compared literal), or add the /i flag to the guard regex.",documentationLink:"https://cwe.mitre.org/data/definitions/178.html"}),addToLowerCase:"Normalize with .toLowerCase() before comparing",addIgnoreCaseFlag:"Add the i flag to the guard regex"},schema:[{type:"object",properties:{protectedPaths:{type:"array",items:{type:"string"},description:"Substrings that mark a compared value as a protected path"},checkAllPaths:{type:"boolean",description:"Flag every case-sensitive path guard regardless of the compared value"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{protectedPaths,checkAllPaths}=options;const patterns=(protectedPaths??DEFAULT_PROTECTED_PATHS).map(p=>p.toLowerCase());const flagAll=checkAllPaths??false;const sourceCode=context.sourceCode;function isRequestIdent(name){const lower=name.toLowerCase();return lower==="req"||lower==="request"}function isPathAccess(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isRequestIdent(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&PATH_PROPS.has(node.property.name)}function isProtectedValue(value){if(flagAll)return true;const lower=value.toLowerCase();return patterns.some(p=>lower.includes(p))}function isStringLiteral(node){return(0,eslint_devkit_1.staticString)(node)!==null}function reportWithLowerCaseSuggestion(node,pathNode,literalNode){const value=literalNode.value;context.report({node,messageId:"caseSensitivePathGuard",data:{pathExpr:sourceCode.getText(pathNode),value},suggest:[{messageId:"addToLowerCase",fix(fixer){const fixes=[fixer.insertTextAfter(pathNode,".toLowerCase()")];if(/[A-Z]/.test(value)){fixes.push(fixer.replaceText(literalNode,quoteLiteral(value)))}return fixes}}]})}return{CallExpression(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(!GUARD_METHODS.has(callee.property.name))return;if(!isPathAccess(callee.object))return;const arg=node.arguments[0];if(!arg)return;if(arg.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return;if("regex"in arg){if(arg.regex.flags.includes("i"))return;if(!isProtectedValue(arg.regex.pattern))return;context.report({node,messageId:"caseSensitivePathGuard",data:{pathExpr:sourceCode.getText(callee.object),value:arg.regex.pattern},suggest:[{messageId:"addIgnoreCaseFlag",fix:fixer=>fixer.insertTextAfter(arg,"i")}]});return}if(typeof arg.value!=="string")return;if(!isProtectedValue(arg.value))return;reportWithLowerCaseSuggestion(node,callee.object,arg)},BinaryExpression(node){if(!EQUALITY_OPS.has(node.operator))return;let pathNode;let literalNode;if(isPathAccess(node.left)&&isStringLiteral(node.right)){pathNode=node.left;literalNode=node.right}else if(isPathAccess(node.right)&&isStringLiteral(node.left)){pathNode=node.right;literalNode=node.left}else{return}if(!isProtectedValue(literalNode.value))return;reportWithLowerCaseSuggestion(node,pathNode,literalNode)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireCaseInsensitivePathGuard=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const PATH_PROPS=new Set(["path","url","originalUrl"]);const GUARD_METHODS=new Set(["startsWith","endsWith","includes","indexOf","match"]);const EQUALITY_OPS=new Set(["===","==","!==","!="]);function quoteLiteral(value){const json=JSON.stringify(value.toLowerCase());const inner=json.slice(1,-1);return/['\\]/.test(inner)?json:`'${inner}'`}const DEFAULT_PROTECTED_PATHS=["admin","api","dashboard","internal","private"];exports.requireCaseInsensitivePathGuard=(0,eslint_devkit_1.createRule)({name:"require-case-insensitive-path-guard",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-case-insensitive-path-guard.md",description:"Require case-insensitive comparison when guarding protected paths via req.path / req.url / req.originalUrl",cwe:"CWE-178",cvss:7.3},messages:{caseSensitivePathGuard:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Case-Sensitive Path Guard (CWE-178)",cwe:"CWE-178",description:"{{pathExpr}} is compared case-sensitively against '{{value}}', but Express routes can match case-insensitively. A request to an upper-cased variant (e.g. /Admin) reaches the handler without ever hitting this guard.",severity:"HIGH",fix:"Normalize the path with .toLowerCase() before comparing (and lower-case the compared literal), or add the /i flag to the guard regex.",documentationLink:"https://cwe.mitre.org/data/definitions/178.html"}),addToLowerCase:"Normalize with .toLowerCase() before comparing",addIgnoreCaseFlag:"Add the i flag to the guard regex"},schema:[{type:"object",properties:{protectedPaths:{type:"array",items:{type:"string"},description:"Substrings that mark a compared value as a protected path"},checkAllPaths:{type:"boolean",description:"Flag every case-sensitive path guard regardless of the compared value"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{protectedPaths,checkAllPaths}=options;const patterns=(protectedPaths??DEFAULT_PROTECTED_PATHS).map(p=>p.toLowerCase());const flagAll=checkAllPaths??false;const sourceCode=context.sourceCode;function isRequestIdent(name){const lower=name.toLowerCase();return lower==="req"||lower==="request"}function isPathAccess(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isRequestIdent(node.object.name)&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),PATH_PROPS)}function isProtectedValue(value){if(flagAll)return true;const lower=value.toLowerCase();return patterns.some(p=>lower.includes(p))}function isStringLiteral(node){return(0,eslint_devkit_1.staticString)(node)!==null}function reportWithLowerCaseSuggestion(node,pathNode,literalNode){const value=literalNode.value;context.report({node,messageId:"caseSensitivePathGuard",data:{pathExpr:sourceCode.getText(pathNode),value},suggest:[{messageId:"addToLowerCase",fix(fixer){const fixes=[fixer.insertTextAfter(pathNode,".toLowerCase()")];if(/[A-Z]/.test(value)){fixes.push(fixer.replaceText(literalNode,quoteLiteral(value)))}return fixes}}]})}return{CallExpression(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(!GUARD_METHODS.has(callee.property.name))return;if(!isPathAccess(callee.object))return;const arg=node.arguments[0];if(!arg)return;if(arg.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)return;if("regex"in arg){if(arg.regex.flags.includes("i"))return;if(!isProtectedValue(arg.regex.pattern))return;context.report({node,messageId:"caseSensitivePathGuard",data:{pathExpr:sourceCode.getText(callee.object),value:arg.regex.pattern},suggest:[{messageId:"addIgnoreCaseFlag",fix:fixer=>fixer.insertTextAfter(arg,"i")}]});return}if(typeof arg.value!=="string")return;if(!isProtectedValue(arg.value))return;reportWithLowerCaseSuggestion(node,callee.object,arg)},BinaryExpression(node){if(!EQUALITY_OPS.has(node.operator))return;let pathNode;let literalNode;if(isPathAccess(node.left)&&isStringLiteral(node.right)){pathNode=node.left;literalNode=node.right}else if(isPathAccess(node.right)&&isStringLiteral(node.left)){pathNode=node.right;literalNode=node.left}else{return}if(!isProtectedValue(literalNode.value))return;reportWithLowerCaseSuggestion(node,pathNode,literalNode)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireCsrfProtection=void 0;const express_evidence_1=require("../../utils/express-evidence");const app_composition_1=require("../../utils/app-composition");const auth_evidence_1=require("../../utils/auth-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_PROTECTED_METHODS=["post","put","patch","delete"];const EMPTY=new Set;function isCsrfMiddleware(node){const callee=node.callee;if(callee.type==="Identifier"){const name=callee.name.toLowerCase();return name==="csrf"||name==="csurf"||name==="csrfprotection"}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="lusca"&&callee.property.type==="Identifier"&&callee.property.name==="csrf"){return true}return false}function isCsrfReference(node){if(node.type==="Identifier")return/csrf|csurf/i.test(node.name);if(node.type==="MemberExpression"){return isCsrfReference(node.object)||node.property.type==="Identifier"&&isCsrfReference(node.property)}if(node.type==="CallExpression")return isCsrfReference(node.callee);return false}function hasCsrfInMiddlewareChain(chain){return chain.some(isCsrfReference)}const EXPRESS_IDENTIFIERS=new Set(["app","router","api","apiRouter","routes","express"]);function isLikelyExpressObject(callee){const obj=callee.object;if(obj.type==="Identifier"){if(EXPRESS_IDENTIFIERS.has(obj.name)){return true}return false}if(obj.type==="CallExpression"){const objCallee=obj.callee;if(objCallee.type==="Identifier"&&objCallee.name==="express"){return true}if(objCallee.type==="MemberExpression"&&objCallee.object.type==="Identifier"&&objCallee.object.name==="express"&&objCallee.property.type==="Identifier"&&objCallee.property.name==="Router"){return true}}if(obj.type==="MemberExpression"){return false}return false}exports.requireCsrfProtection=(0,eslint_devkit_1.createRule)({name:"require-csrf-protection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-csrf-protection.md",description:"Require CSRF protection middleware for state-changing HTTP methods",cwe:"CWE-352",cvss:8.8},messages:{missingCsrf:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CSRF Protection",cwe:"CWE-352",description:"Route handler for {{method}} request lacks CSRF protection. Attackers can forge requests from malicious sites.",severity:"HIGH",fix:"Add CSRF middleware: app.use(csrf()) or use csurf package. Include csrfToken in forms.",documentationLink:"https://owasp.org/www-community/attacks/csrf"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing CSRF in test files"},protectedMethods:{type:"array",items:{type:"string"},default:["post","put","patch","delete"],description:"HTTP methods that require CSRF protection"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Route patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,protectedMethods:DEFAULT_PROTECTED_METHODS,ignorePatterns:[]}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};if(!(0,app_composition_1.fileHasAmbientCredentials)(context.sourceCode.ast))return{};const{allowInTests=false,protectedMethods=DEFAULT_PROTECTED_METHODS,ignorePatterns=[]}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}let hasGlobalCsrf=false;const candidates=[];let hasGlobalAuth=false;function shouldIgnoreRoute(routeArg){if(routeArg.type!=="Literal"||typeof routeArg.value!=="string"){return false}const route=routeArg.value;return ignorePatterns.some(pattern=>{try{return new RegExp(pattern).test(route)}catch{return route.includes(pattern)}})}return{CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="use"){for(const arg of node.arguments){if(arg.type==="CallExpression"&&isCsrfMiddleware(arg)){hasGlobalCsrf=true;return}if(arg.type==="Identifier"){const name=arg.name.toLowerCase();if(name.includes("csrf")||name.includes("csurf")){hasGlobalCsrf=true;return}}}const[first]=node.arguments;const pathScoped=first?.type==="Literal"&&typeof first.value==="string";if(!pathScoped&&(0,auth_evidence_1.routeIsAuthenticated)(node.arguments,void 0,EMPTY)){hasGlobalAuth=true}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const method=callee.property.name.toLowerCase();if(!protectedMethods.includes(method)){return}if(!isLikelyExpressObject(callee)){return}const[routeArg,...rest]=node.arguments;if(routeArg&&shouldIgnoreRoute(routeArg)){return}if(hasCsrfInMiddlewareChain(rest.slice(0,-1))){return}candidates.push({node,method:method.toUpperCase(),chain:rest.slice(0,-1),handler:rest[rest.length-1]})}},"Program:exit"(){if(hasGlobalCsrf)return;for(const candidate of candidates){if(!hasGlobalAuth&&!(0,auth_evidence_1.routeIsAuthenticated)(candidate.chain,candidate.handler,EMPTY)){continue}context.report({node:candidate.node,messageId:"missingCsrf",data:{method:candidate.method}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireCsrfProtection=void 0;const express_evidence_1=require("../../utils/express-evidence");const app_composition_1=require("../../utils/app-composition");const auth_evidence_1=require("../../utils/auth-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_PROTECTED_METHODS=["post","put","patch","delete"];const EMPTY=new Set;function isCsrfMiddleware(node){const callee=node.callee;if(callee.type==="Identifier"){const name=callee.name.toLowerCase();return name==="csrf"||name==="csurf"||name==="csrfprotection"}if(callee.type==="MemberExpression"&&callee.object.type==="Identifier"&&callee.object.name==="lusca"&&(0,eslint_devkit_1.propertyName)(callee)==="csrf"){return true}return false}function isCsrfReference(node){if(node.type==="Identifier")return/csrf|csurf/i.test(node.name);if(node.type==="MemberExpression"){return isCsrfReference(node.object)||node.property.type==="Identifier"&&isCsrfReference(node.property)}if(node.type==="CallExpression")return isCsrfReference(node.callee);return false}function hasCsrfInMiddlewareChain(chain){return chain.some(isCsrfReference)}const EXPRESS_IDENTIFIERS=new Set(["app","router","api","apiRouter","routes","express"]);function isLikelyExpressObject(callee){const obj=callee.object;if(obj.type==="Identifier"){if(EXPRESS_IDENTIFIERS.has(obj.name)){return true}return false}if(obj.type==="CallExpression"){const objCallee=obj.callee;if(objCallee.type==="Identifier"&&objCallee.name==="express"){return true}if(objCallee.type==="MemberExpression"&&objCallee.object.type==="Identifier"&&objCallee.object.name==="express"&&(0,eslint_devkit_1.propertyName)(objCallee)==="Router"){return true}}if(obj.type==="MemberExpression"){return false}return false}exports.requireCsrfProtection=(0,eslint_devkit_1.createRule)({name:"require-csrf-protection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-csrf-protection.md",description:"Require CSRF protection middleware for state-changing HTTP methods",cwe:"CWE-352",cvss:8.8},messages:{missingCsrf:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CSRF Protection",cwe:"CWE-352",description:"Route handler for {{method}} request lacks CSRF protection. Attackers can forge requests from malicious sites.",severity:"HIGH",fix:"Add CSRF middleware: app.use(csrf()) or use csurf package. Include csrfToken in forms.",documentationLink:"https://owasp.org/www-community/attacks/csrf"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing CSRF in test files"},protectedMethods:{type:"array",items:{type:"string"},default:["post","put","patch","delete"],description:"HTTP methods that require CSRF protection"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Route patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,protectedMethods:DEFAULT_PROTECTED_METHODS,ignorePatterns:[]}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};if(!(0,app_composition_1.fileHasAmbientCredentials)(context.sourceCode.ast))return{};const{allowInTests=false,protectedMethods=DEFAULT_PROTECTED_METHODS,ignorePatterns=[]}=options;const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}let hasGlobalCsrf=false;const candidates=[];let hasGlobalAuth=false;function shouldIgnoreRoute(routeArg){if(routeArg.type!=="Literal"||typeof routeArg.value!=="string"){return false}const route=routeArg.value;return ignorePatterns.some(pattern=>{try{return new RegExp(pattern).test(route)}catch{return route.includes(pattern)}})}return{CallExpression(node){const callee=node.callee;if(callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(callee)==="use"){for(const arg of node.arguments){if(arg.type==="CallExpression"&&isCsrfMiddleware(arg)){hasGlobalCsrf=true;return}if(arg.type==="Identifier"){const name=arg.name.toLowerCase();if(name.includes("csrf")||name.includes("csurf")){hasGlobalCsrf=true;return}}}const[first]=node.arguments;const pathScoped=first?.type==="Literal"&&typeof first.value==="string";if(!pathScoped&&(0,auth_evidence_1.routeIsAuthenticated)(node.arguments,void 0,EMPTY)){hasGlobalAuth=true}}const routeMethod=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&routeMethod!==null){const method=routeMethod.toLowerCase();if(!protectedMethods.includes(method)){return}if(!isLikelyExpressObject(callee)){return}const[routeArg,...rest]=node.arguments;if(routeArg&&shouldIgnoreRoute(routeArg)){return}if(hasCsrfInMiddlewareChain(rest.slice(0,-1))){return}candidates.push({node,method:method.toUpperCase(),chain:rest.slice(0,-1),handler:rest[rest.length-1]})}},"Program:exit"(){if(hasGlobalCsrf)return;for(const candidate of candidates){if(!hasGlobalAuth&&!(0,auth_evidence_1.routeIsAuthenticated)(candidate.chain,candidate.handler,EMPTY)){continue}context.report({node:candidate.node,messageId:"missingCsrf",data:{method:candidate.method}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireHelmet=void 0;const express_evidence_1=require("../../utils/express-evidence");const app_composition_1=require("../../utils/app-composition");const eslint_devkit_1=require("@interlace/eslint-devkit");function isHelmetMiddleware(node){const callee=node.callee;if(callee.type!=="MemberExpression"){return false}if(callee.property.type!=="Identifier"||callee.property.name!=="use"){return false}for(const arg of node.arguments){if(arg.type==="CallExpression"){const argCallee=arg.callee;if(argCallee.type==="Identifier"&&argCallee.name==="helmet"){return true}if(argCallee.type==="MemberExpression"&&argCallee.object.type==="Identifier"&&argCallee.object.name==="helmet"){return true}}if(arg.type==="Identifier"&&arg.name==="helmet"){return true}}return false}function isAlternativeMiddleware(node,alternatives){for(const arg of node.arguments){if(arg.type==="CallExpression"&&arg.callee.type==="Identifier"){if(alternatives.includes(arg.callee.name)){return true}}if(arg.type==="Identifier"&&alternatives.includes(arg.name)){return true}}return false}exports.requireHelmet=(0,eslint_devkit_1.createRule)({name:"require-helmet",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-helmet.md",description:"Require helmet middleware for security headers in Express.js applications",cwe:"CWE-693",cvss:7.5,confidence:"high"},messages:{missingHelmet:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Security Headers",cwe:"CWE-693",description:"This Express app renders documents to a browser but never mounts helmet. Without it the responses carry no Content-Security-Policy, X-Frame-Options or referrer policy, so any rendered page is framable and unconstrained.",severity:"HIGH",fix:"Add helmet middleware: app.use(helmet()). Install with 'npm install helmet'.",documentationLink:"https://helmetjs.github.io/"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing helmet in test files"},alternativeMiddleware:{type:"array",items:{type:"string"},default:[],description:"Alternative security headers middleware names to accept"},assumeHelmetMiddleware:{type:"boolean",default:false,description:"Skip rule if security headers are provided elsewhere (e.g., reverse proxy)"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,alternativeMiddleware:[],assumeHelmetMiddleware:false}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};if(!(0,app_composition_1.servesBrowserDocuments)(context.sourceCode.ast))return{};const{allowInTests=false,alternativeMiddleware=[],assumeHelmetMiddleware=false}=options;if(assumeHelmetMiddleware){return{}}const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}let hasExpressApp=false;let hasHelmet=false;let expressAppNode=null;let appBinding=null;let appEscapes=false;return{[app_composition_1.RELEASE_SELECTOR](node){if(appBinding!==null&&(0,app_composition_1.nodeReleasesBinding)(node,appBinding)){appEscapes=true}},CallExpression(node){const callee=node.callee;if(appBinding!==null&&(0,app_composition_1.nodeReleasesBinding)(node,appBinding)){appEscapes=true}if(callee.type==="Identifier"&&callee.name==="express"){hasExpressApp=true;expressAppNode=node;if(node.parent?.type==="VariableDeclarator"&&node.parent.id.type==="Identifier"){appBinding=node.parent.id.name}return}if(callee.type==="CallExpression"&&callee.callee.type==="Identifier"&&callee.callee.name==="require"){const firstArg=callee.arguments[0];if(firstArg&&firstArg.type==="Literal"&&firstArg.value==="express"){hasExpressApp=true;expressAppNode=node;return}}if(isHelmetMiddleware(node)){hasHelmet=true;return}if(isAlternativeMiddleware(node,alternativeMiddleware)){hasHelmet=true;return}},"Program:exit"(){if(hasExpressApp&&!hasHelmet&&!appEscapes&&expressAppNode){context.report({node:expressAppNode,messageId:"missingHelmet"})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireHelmet=void 0;const express_evidence_1=require("../../utils/express-evidence");const app_composition_1=require("../../utils/app-composition");const eslint_devkit_1=require("@interlace/eslint-devkit");function isHelmetMiddleware(node){const callee=node.callee;if(callee.type!=="MemberExpression"){return false}if((0,eslint_devkit_1.propertyName)(callee)!=="use"){return false}for(const arg of node.arguments){if(arg.type==="CallExpression"){const argCallee=arg.callee;if(argCallee.type==="Identifier"&&argCallee.name==="helmet"){return true}if(argCallee.type==="MemberExpression"&&argCallee.object.type==="Identifier"&&argCallee.object.name==="helmet"){return true}}if(arg.type==="Identifier"&&arg.name==="helmet"){return true}}return false}function isAlternativeMiddleware(node,alternatives){for(const arg of node.arguments){if(arg.type==="CallExpression"&&arg.callee.type==="Identifier"){if(alternatives.includes(arg.callee.name)){return true}}if(arg.type==="Identifier"&&alternatives.includes(arg.name)){return true}}return false}exports.requireHelmet=(0,eslint_devkit_1.createRule)({name:"require-helmet",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-helmet.md",description:"Require helmet middleware for security headers in Express.js applications",cwe:"CWE-693",cvss:7.5,confidence:"high"},messages:{missingHelmet:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Security Headers",cwe:"CWE-693",description:"This Express app renders documents to a browser but never mounts helmet. Without it the responses carry no Content-Security-Policy, X-Frame-Options or referrer policy, so any rendered page is framable and unconstrained.",severity:"HIGH",fix:"Add helmet middleware: app.use(helmet()). Install with 'npm install helmet'.",documentationLink:"https://helmetjs.github.io/"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing helmet in test files"},alternativeMiddleware:{type:"array",items:{type:"string"},default:[],description:"Alternative security headers middleware names to accept"},assumeHelmetMiddleware:{type:"boolean",default:false,description:"Skip rule if security headers are provided elsewhere (e.g., reverse proxy)"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,alternativeMiddleware:[],assumeHelmetMiddleware:false}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};if(!(0,app_composition_1.servesBrowserDocuments)(context.sourceCode.ast))return{};const{allowInTests=false,alternativeMiddleware=[],assumeHelmetMiddleware=false}=options;if(assumeHelmetMiddleware){return{}}const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}let hasExpressApp=false;let hasHelmet=false;let expressAppNode=null;let appBinding=null;let appEscapes=false;return{[app_composition_1.RELEASE_SELECTOR](node){if(appBinding!==null&&(0,app_composition_1.nodeReleasesBinding)(node,appBinding)){appEscapes=true}},CallExpression(node){const callee=node.callee;if(appBinding!==null&&(0,app_composition_1.nodeReleasesBinding)(node,appBinding)){appEscapes=true}if(callee.type==="Identifier"&&callee.name==="express"){hasExpressApp=true;expressAppNode=node;if(node.parent?.type==="VariableDeclarator"&&node.parent.id.type==="Identifier"){appBinding=node.parent.id.name}return}if(callee.type==="CallExpression"&&callee.callee.type==="Identifier"&&callee.callee.name==="require"){const firstArg=callee.arguments[0];if(firstArg&&firstArg.type==="Literal"&&firstArg.value==="express"){hasExpressApp=true;expressAppNode=node;return}}if(isHelmetMiddleware(node)){hasHelmet=true;return}if(isAlternativeMiddleware(node,alternativeMiddleware)){hasHelmet=true;return}},"Program:exit"(){if(hasExpressApp&&!hasHelmet&&!appEscapes&&expressAppNode){context.report({node:expressAppNode,messageId:"missingHelmet"})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireQueryTypeGuard=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const STRING_METHODS=new Set(["replace","toLowerCase","toUpperCase","trim","split","substring","slice","startsWith","endsWith","includes","match"]);const EQUALITY_OPS=new Set(["===","==","!==","!="]);exports.requireQueryTypeGuard=(0,eslint_devkit_1.createRule)({name:"require-query-type-guard",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-query-type-guard.md",description:"Require a type guard or String() coercion before calling string methods on req.query values",cwe:"CWE-843",cvss:7.5},messages:{unguardedQueryStringMethod:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"req.query Type Confusion (CWE-843)",cwe:"CWE-843",description:".{{method}}() is called on {{target}}, but req.query values are string | string[] | ParsedQs \u2014 ?x=a&x=b yields an array, so this throws (DoS) or bypasses sanitization.",severity:"HIGH",fix:"Coerce with String(...) or guard with typeof value === 'string' / Array.isArray(value) before treating the query value as a string.",documentationLink:"https://cwe.mitre.org/data/definitions/843.html"}),wrapString:"Coerce the query value with String(...) before calling .{{method}}()",coerceAtAssignment:"Coerce at the assignment: wrap the req.query access in String(...)"},schema:[{type:"object",properties:{coercers:{type:"array",items:{type:"string"},description:"Callee names whose result is a safe string coercion"},validators:{type:"array",items:{type:"string"},description:"Callee / method names treated as type-safe sources"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{coercers,validators}=options;const coercerNames=new Set(coercers??["String"]);const validatorNames=new Set(validators??["parse","safeParse"]);const sourceCode=context.sourceCode;function newFrame(){return{tracked:new Map,guardedVars:new Set,guardedProps:new Set}}const frames=[newFrame()];const current=()=>frames[frames.length-1];function isRequestIdent(name){const lower=name.toLowerCase();return lower==="req"||lower==="request"}function isReqQuery(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isRequestIdent(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.property.name==="query"}function isQueryMember(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&isReqQuery(node.object)}function propKey(node){return sourceCode.getText(node.property)}function guardVar(name){for(let i=frames.length-1;i>=0;i--){if(frames[i].tracked.has(name)){frames[i].guardedVars.add(name);return}}current().guardedVars.add(name)}function markGuard(target){if(target.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){guardVar(target.name)}else if(isQueryMember(target)){current().guardedProps.add(propKey(target))}}function isVarGuarded(name){return frames.some(f=>f.guardedVars.has(name))}function isPropGuarded(key){return frames.some(f=>f.guardedProps.has(key))}function lookupTracked(name){for(let i=frames.length-1;i>=0;i--){const init=frames[i].tracked.get(name);if(init)return init}return null}function extractTypeofTarget(a,b){if(a.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&a.operator==="typeof"&&b.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&b.value==="string"){return a.argument}return null}function isArrayIsArrayCall(node){const callee=node.callee;return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Array"&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.property.name==="isArray"}function isSafeCall(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return coercerNames.has(callee.name)||validatorNames.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return validatorNames.has(callee.property.name)}return false}function wrapWithString(fixer,target){return[fixer.insertTextBefore(target,"String("),fixer.insertTextAfter(target,")")]}function enterFunction(){frames.push(newFrame())}function exitFunction(){frames.pop()}return{"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression":enterFunction,"FunctionDeclaration:exit":exitFunction,"FunctionExpression:exit":exitFunction,"ArrowFunctionExpression:exit":exitFunction,VariableDeclarator(node){if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const init=node.init;if(!init)return;if(isQueryMember(init)){current().tracked.set(node.id.name,init)}},AssignmentExpression(node){if(node.operator!=="=")return;if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(isQueryMember(node.right)){current().tracked.set(node.left.name,node.right);return}if(isSafeCall(node.right)){guardVar(node.left.name)}},BinaryExpression(node){if(!EQUALITY_OPS.has(node.operator))return;const target=extractTypeofTarget(node.left,node.right)??extractTypeofTarget(node.right,node.left);if(target)markGuard(target)},CallExpression(node){if(isArrayIsArrayCall(node)){const arg=node.arguments[0];if(arg)markGuard(arg);return}const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const method=callee.property.name;if(!STRING_METHODS.has(method))return;const obj=callee.object;if(isQueryMember(obj)){if(isPropGuarded(propKey(obj)))return;context.report({node:callee,messageId:"unguardedQueryStringMethod",data:{target:sourceCode.getText(obj),method},suggest:[{messageId:"wrapString",data:{method},fix:fixer=>wrapWithString(fixer,obj)}]});return}if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const trackedInit=lookupTracked(obj.name);if(!trackedInit)return;if(isVarGuarded(obj.name))return;context.report({node:callee,messageId:"unguardedQueryStringMethod",data:{target:obj.name,method},suggest:[{messageId:"coerceAtAssignment",fix:fixer=>wrapWithString(fixer,trackedInit)}]})}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireQueryTypeGuard=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const STRING_METHODS=new Set(["replace","toLowerCase","toUpperCase","trim","split","substring","slice","startsWith","endsWith","includes","match"]);const EQUALITY_OPS=new Set(["===","==","!==","!="]);exports.requireQueryTypeGuard=(0,eslint_devkit_1.createRule)({name:"require-query-type-guard",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-query-type-guard.md",description:"Require a type guard or String() coercion before calling string methods on req.query values",cwe:"CWE-843",cvss:7.5},messages:{unguardedQueryStringMethod:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"req.query Type Confusion (CWE-843)",cwe:"CWE-843",description:".{{method}}() is called on {{target}}, but req.query values are string | string[] | ParsedQs \u2014 ?x=a&x=b yields an array, so this throws (DoS) or bypasses sanitization.",severity:"HIGH",fix:"Coerce with String(...) or guard with typeof value === 'string' / Array.isArray(value) before treating the query value as a string.",documentationLink:"https://cwe.mitre.org/data/definitions/843.html"}),wrapString:"Coerce the query value with String(...) before calling .{{method}}()",coerceAtAssignment:"Coerce at the assignment: wrap the req.query access in String(...)"},schema:[{type:"object",properties:{coercers:{type:"array",items:{type:"string"},description:"Callee names whose result is a safe string coercion"},validators:{type:"array",items:{type:"string"},description:"Callee / method names treated as type-safe sources"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{coercers,validators}=options;const coercerNames=new Set(coercers??["String"]);const validatorNames=new Set(validators??["parse","safeParse"]);const sourceCode=context.sourceCode;function newFrame(){return{tracked:new Map,guardedVars:new Set,guardedProps:new Set}}const frames=[newFrame()];const current=()=>frames[frames.length-1];function isRequestIdent(name){const lower=name.toLowerCase();return lower==="req"||lower==="request"}function isReqQuery(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isRequestIdent(node.object.name)&&(0,eslint_devkit_1.propertyName)(node)==="query"}function isQueryMember(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&isReqQuery(node.object)}function propKey(node){return sourceCode.getText(node.property)}function guardVar(name){for(let i=frames.length-1;i>=0;i--){if(frames[i].tracked.has(name)){frames[i].guardedVars.add(name);return}}current().guardedVars.add(name)}function markGuard(target){if(target.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){guardVar(target.name)}else if(isQueryMember(target)){current().guardedProps.add(propKey(target))}}function isVarGuarded(name){return frames.some(f=>f.guardedVars.has(name))}function isPropGuarded(key){return frames.some(f=>f.guardedProps.has(key))}function lookupTracked(name){for(let i=frames.length-1;i>=0;i--){const init=frames[i].tracked.get(name);if(init)return init}return null}function extractTypeofTarget(a,b){if(a.type===eslint_devkit_1.AST_NODE_TYPES.UnaryExpression&&a.operator==="typeof"&&b.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&b.value==="string"){return a.argument}return null}function isArrayIsArrayCall(node){const callee=node.callee;return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Array"&&(0,eslint_devkit_1.propertyName)(callee)==="isArray"}function isSafeCall(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return coercerNames.has(callee.name)||validatorNames.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return validatorNames.has(callee.property.name)}return false}function wrapWithString(fixer,target){return[fixer.insertTextBefore(target,"String("),fixer.insertTextAfter(target,")")]}function enterFunction(){frames.push(newFrame())}function exitFunction(){frames.pop()}return{"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression":enterFunction,"FunctionDeclaration:exit":exitFunction,"FunctionExpression:exit":exitFunction,"ArrowFunctionExpression:exit":exitFunction,VariableDeclarator(node){if(node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const init=node.init;if(!init)return;if(isQueryMember(init)){current().tracked.set(node.id.name,init)}},AssignmentExpression(node){if(node.operator!=="=")return;if(node.left.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(isQueryMember(node.right)){current().tracked.set(node.left.name,node.right);return}if(isSafeCall(node.right)){guardVar(node.left.name)}},BinaryExpression(node){if(!EQUALITY_OPS.has(node.operator))return;const target=extractTypeofTarget(node.left,node.right)??extractTypeofTarget(node.right,node.left);if(target)markGuard(target)},CallExpression(node){if(isArrayIsArrayCall(node)){const arg=node.arguments[0];if(arg)markGuard(arg);return}const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const method=callee.property.name;if(!STRING_METHODS.has(method))return;const obj=callee.object;if(isQueryMember(obj)){if(isPropGuarded(propKey(obj)))return;context.report({node:callee,messageId:"unguardedQueryStringMethod",data:{target:sourceCode.getText(obj),method},suggest:[{messageId:"wrapString",data:{method},fix:fixer=>wrapWithString(fixer,obj)}]});return}if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const trackedInit=lookupTracked(obj.name);if(!trackedInit)return;if(isVarGuarded(obj.name))return;context.report({node:callee,messageId:"unguardedQueryStringMethod",data:{target:obj.name,method},suggest:[{messageId:"coerceAtAssignment",fix:fixer=>wrapWithString(fixer,trackedInit)}]})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireRateLimiting=void 0;const express_evidence_1=require("../../utils/express-evidence");const app_receiver_1=require("../../utils/app-receiver");const app_composition_1=require("../../utils/app-composition");const eslint_devkit_1=require("@interlace/eslint-devkit");const STATE_CHANGING_METHODS=new Set(["post","put","patch","delete"]);const CREDENTIAL_PATH=/(^|[^a-z0-9])(login|log-in|signin|sign-in|signup|sign-up|register|authenticate|auth|authorize|token|password|passwd|credential|otp|mfa|2fa|totp|verify|verification|confirm|reset|forgot|recover|unlock|challenge|session|invite|redeem|coupon|promo)([^a-z0-9]|$)/i;const RATE_LIMIT_PACKAGES=["ratelimit","rateLimit","rateLimiter","limiter","expressRateLimit","slowDown","expressBrute"];function isRateLimitMiddleware(node,alternatives){const allPatterns=[...RATE_LIMIT_PACKAGES,...alternatives];for(const arg of node.arguments){if(arg.type==="CallExpression"&&arg.callee.type==="Identifier"){const calleeName=arg.callee.name.toLowerCase();if(allPatterns.some(p=>calleeName.includes(p.toLowerCase()))){return true}}if(arg.type==="Identifier"){if(allPatterns.some(p=>arg.name.toLowerCase().includes(p.toLowerCase()))){return true}}}return false}exports.requireRateLimiting=(0,eslint_devkit_1.createRule)({name:"require-rate-limiting",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-rate-limiting.md",description:"Require rate-limiting middleware in Express.js applications",cwe:"CWE-770",cvss:7.5},messages:{missingRateLimiting:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unthrottled Credential Endpoint",cwe:"CWE-770",description:"{{method}} {{path}} accepts a secret to be checked and this app mounts no rate limiter. An attacker can run the guess-and-retry loop at full speed.",severity:"HIGH",fix:"Add rate limiting: npm install express-rate-limit; app.use(rateLimit({ windowMs: 15*60*1000, max: 100 }))",documentationLink:"https://www.npmjs.com/package/express-rate-limit"})},schema:[{type:"object",properties:{...app_receiver_1.APP_RECEIVER_SCHEMA,allowInTests:{type:"boolean",default:false},alternativeMiddleware:{type:"array",items:{type:"string"},default:[],description:"Extra middleware names that count as rate limiting"},assumeRateLimiting:{type:"boolean",default:false,description:"Skip if rate limiting is provided by infrastructure (API Gateway, nginx, etc.)"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,alternativeMiddleware:[],assumeRateLimiting:false}],create(context,[options]){const{appReceiverNames}=options;if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false,alternativeMiddleware=[],assumeRateLimiting=false}=options;if(assumeRateLimiting){return{}}const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}let hasExpressApp=false;let hasRateLimiting=false;let credentialRoute=null;let appBinding=null;let appEscapes=false;return{[app_composition_1.RELEASE_SELECTOR](node){if(appBinding!==null&&(0,app_composition_1.nodeReleasesBinding)(node,appBinding)){appEscapes=true}},CallExpression(node){const callee=node.callee;if(appBinding!==null&&(0,app_composition_1.nodeReleasesBinding)(node,appBinding)){appEscapes=true}if(callee.type==="Identifier"&&callee.name==="express"){hasExpressApp=true;if(node.parent?.type==="VariableDeclarator"&&node.parent.id.type==="Identifier"){appBinding=node.parent.id.name}return}if(callee.type!=="MemberExpression"||callee.property.type!=="Identifier"){return}const method=callee.property.name.toLowerCase();if(isRateLimitMiddleware(node,alternativeMiddleware)){hasRateLimiting=true;return}if(!STATE_CHANGING_METHODS.has(method))return;if(callee.object.type!=="Identifier"||!(0,app_receiver_1.isAppReceiver)(callee.object.name,appReceiverNames)){return}const[pathArg,...rest]=node.arguments;if(rest.length===0||pathArg?.type!=="Literal"||typeof pathArg.value!=="string"){return}if(!CREDENTIAL_PATH.test(pathArg.value))return;credentialRoute??={node,method:method.toUpperCase(),path:pathArg.value}},"Program:exit"(){if(hasExpressApp&&!hasRateLimiting&&!appEscapes&&credentialRoute){context.report({node:credentialRoute.node,messageId:"missingRateLimiting",data:{method:credentialRoute.method,path:credentialRoute.path}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireRateLimiting=void 0;const express_evidence_1=require("../../utils/express-evidence");const app_receiver_1=require("../../utils/app-receiver");const app_composition_1=require("../../utils/app-composition");const eslint_devkit_1=require("@interlace/eslint-devkit");const STATE_CHANGING_METHODS=new Set(["post","put","patch","delete"]);const CREDENTIAL_PATH=/(^|[^a-z0-9])(login|log-in|signin|sign-in|signup|sign-up|register|authenticate|auth|authorize|token|password|passwd|credential|otp|mfa|2fa|totp|verify|verification|confirm|reset|forgot|recover|unlock|challenge|session|invite|redeem|coupon|promo)([^a-z0-9]|$)/i;const RATE_LIMIT_PACKAGES=["ratelimit","rateLimit","rateLimiter","limiter","expressRateLimit","slowDown","expressBrute"];function isRateLimitMiddleware(node,alternatives){const allPatterns=[...RATE_LIMIT_PACKAGES,...alternatives];for(const arg of node.arguments){if(arg.type==="CallExpression"&&arg.callee.type==="Identifier"){const calleeName=arg.callee.name.toLowerCase();if(allPatterns.some(p=>calleeName.includes(p.toLowerCase()))){return true}}if(arg.type==="Identifier"){if(allPatterns.some(p=>arg.name.toLowerCase().includes(p.toLowerCase()))){return true}}}return false}exports.requireRateLimiting=(0,eslint_devkit_1.createRule)({name:"require-rate-limiting",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-rate-limiting.md",description:"Require rate-limiting middleware in Express.js applications",cwe:"CWE-770",cvss:7.5},messages:{missingRateLimiting:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unthrottled Credential Endpoint",cwe:"CWE-770",description:"{{method}} {{path}} accepts a secret to be checked and this app mounts no rate limiter. An attacker can run the guess-and-retry loop at full speed.",severity:"HIGH",fix:"Add rate limiting: npm install express-rate-limit; app.use(rateLimit({ windowMs: 15*60*1000, max: 100 }))",documentationLink:"https://www.npmjs.com/package/express-rate-limit"})},schema:[{type:"object",properties:{...app_receiver_1.APP_RECEIVER_SCHEMA,allowInTests:{type:"boolean",default:false},alternativeMiddleware:{type:"array",items:{type:"string"},default:[],description:"Extra middleware names that count as rate limiting"},assumeRateLimiting:{type:"boolean",default:false,description:"Skip if rate limiting is provided by infrastructure (API Gateway, nginx, etc.)"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,alternativeMiddleware:[],assumeRateLimiting:false}],create(context,[options]){const{appReceiverNames}=options;if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false,alternativeMiddleware=[],assumeRateLimiting=false}=options;if(assumeRateLimiting){return{}}const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return{}}let hasExpressApp=false;let hasRateLimiting=false;let credentialRoute=null;let appBinding=null;let appEscapes=false;return{[app_composition_1.RELEASE_SELECTOR](node){if(appBinding!==null&&(0,app_composition_1.nodeReleasesBinding)(node,appBinding)){appEscapes=true}},CallExpression(node){const callee=node.callee;if(appBinding!==null&&(0,app_composition_1.nodeReleasesBinding)(node,appBinding)){appEscapes=true}if(callee.type==="Identifier"&&callee.name==="express"){hasExpressApp=true;if(node.parent?.type==="VariableDeclarator"&&node.parent.id.type==="Identifier"){appBinding=node.parent.id.name}return}const routeMethod=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type!=="MemberExpression"||routeMethod===null){return}const method=routeMethod.toLowerCase();if(isRateLimitMiddleware(node,alternativeMiddleware)){hasRateLimiting=true;return}if(!STATE_CHANGING_METHODS.has(method))return;if(callee.object.type!=="Identifier"||!(0,app_receiver_1.isAppReceiver)(callee.object.name,appReceiverNames)){return}const[pathArg,...rest]=node.arguments;if(rest.length===0||pathArg?.type!=="Literal"||typeof pathArg.value!=="string"){return}if(!CREDENTIAL_PATH.test(pathArg.value))return;credentialRoute??={node,method:method.toUpperCase(),path:pathArg.value}},"Program:exit"(){if(hasExpressApp&&!hasRateLimiting&&!appEscapes&&credentialRoute){context.report({node:credentialRoute.node,messageId:"missingRateLimiting",data:{method:credentialRoute.method,path:credentialRoute.path}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireRouteAuthentication=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const app_receiver_1=require("../../utils/app-receiver");const auth_evidence_1=require("../../utils/auth-evidence");const express_evidence_1=require("../../utils/express-evidence");const DEFAULT_CRITICAL_PATHS=["password","credential","secret","apikey","api-key","user","account","profile","role","permission","grant","payment","billing","invoice","charge","refund","transfer","withdraw","order","config","setting","export","import","mfa","2fa","otp","deploy","migrate","backup","restore","internal","private"];const DEFAULT_PUBLIC_PATHS=["login","signin","sign-in","logout","signup","sign-up","register","forgot","reset","confirm","verify","recover","recovery","unlock","challenge","enroll","enrol","enrollment","activate","activation","resend","consent","webhook","hook","health","healthz","readyz","livez","ping","status","public","static","assets","favicon","robots","callback","oauth","sso","docs","swagger","openapi"];const ROUTE_METHODS=new Set(["get","post","put","patch","delete","all"]);function matchesFragment(path,fragment){const escaped=fragment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-z0-9])${escaped}s?([^a-z0-9]|$)`).test(path)}function asFunction(node){return node?.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node?.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node?.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression?node:void 0}function isDelegatingHandler(fn){let callsNext=false;let touchesResponse=false;(0,utils_1.walk)(fn.body,node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="next"){callsNext=true;return}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&RESPONSE_RECEIVER.test(node.object.name)){touchesResponse=true}});return callsNext&&!touchesResponse}const RESPONSE_RECEIVER=/^(res|response)$/i;exports.requireRouteAuthentication=(0,eslint_devkit_1.createRule)({name:"require-route-authentication",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-route-authentication.md",description:"Require authentication on routes that expose a critical function (account, credential, payment, configuration)",cwe:"CWE-306",cvss:8.2,confidence:"medium"},messages:{missingAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Critical Route Without Authentication (CWE-306)",cwe:"CWE-306",cvss:8.2,description:"{{method}} {{path}} exposes a critical function but its chain has no authentication middleware and the handler never reads an authenticated principal. Anyone who can reach the port can call it.",severity:"HIGH",fix:"Mount an authentication middleware on the route \u2014 app.{{method}}('{{path}}', requireAuth, handler) \u2014 or app.use(requireAuth) for the whole router.",documentationLink:"https://cwe.mitre.org/data/definitions/306.html"})},schema:[{type:"object",properties:{...app_receiver_1.APP_RECEIVER_SCHEMA,criticalPaths:{type:"array",items:{type:"string"},description:"Path fragments that mark a route as critical"},publicPaths:{type:"array",items:{type:"string"},description:"Path fragments that are public by design"},authMiddleware:{type:"array",items:{type:"string"},description:"Extra middleware names accepted as authentication"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{criticalPaths,publicPaths,authMiddleware,appReceiverNames}=options;const critical=(criticalPaths??DEFAULT_CRITICAL_PATHS).map(p=>p.toLowerCase());const publics=(publicPaths??DEFAULT_PUBLIC_PATHS).map(p=>p.toLowerCase());const extraAuth=new Set(authMiddleware??[]);const topLevelFunctions=new Map;for(const stmt of context.sourceCode.ast.body){if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&stmt.id){topLevelFunctions.set(stmt.id.name,stmt);continue}if(stmt.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration)continue;for(const decl of stmt.declarations){if(decl.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&decl.init){topLevelFunctions.set(decl.id.name,decl.init)}}}const candidates=[];let hasGlobalAuth=false;function routeMethodOf(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(callee.computed)return null;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(!(0,app_receiver_1.isAppReceiver)(callee.object.name,appReceiverNames))return null;return callee.property.name}return{CallExpression(node){const method=routeMethodOf(node);if(!method)return;if(method==="use"){const[first]=node.arguments;const pathScoped=first?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof first.value==="string";if(!pathScoped){for(const arg of node.arguments){if(arg.type!==eslint_devkit_1.AST_NODE_TYPES.Literal&&(0,auth_evidence_1.isAuthMiddlewareArg)(arg,extraAuth)){hasGlobalAuth=true}}}return}if(!ROUTE_METHODS.has(method))return;const[pathArg,...rest]=node.arguments;if(!pathArg||pathArg.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||typeof pathArg.value!=="string"){return}if(rest.length===0)return;const path=pathArg.value.toLowerCase();if(publics.some(fragment=>matchesFragment(path,fragment)))return;if(!critical.some(fragment=>matchesFragment(path,fragment)))return;const handler=rest[rest.length-1];if((0,auth_evidence_1.routeIsAuthenticated)(rest.slice(0,-1),handler,extraAuth)){return}const fn=asFunction(handler)??(handler.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?asFunction(topLevelFunctions.get(handler.name)):void 0);if(fn&&isDelegatingHandler(fn))return;candidates.push({node:pathArg,method,path:pathArg.value})},"Program:exit"(){if(hasGlobalAuth)return;for(const candidate of candidates){context.report({node:candidate.node,messageId:"missingAuthentication",data:{method:candidate.method,path:candidate.path}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireRouteAuthentication=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const app_receiver_1=require("../../utils/app-receiver");const auth_evidence_1=require("../../utils/auth-evidence");const express_evidence_1=require("../../utils/express-evidence");const DEFAULT_CRITICAL_PATHS=["password","credential","secret","apikey","api-key","user","account","profile","role","permission","grant","payment","billing","invoice","charge","refund","transfer","withdraw","order","config","setting","export","import","mfa","2fa","otp","deploy","migrate","backup","restore","internal","private"];const DEFAULT_PUBLIC_PATHS=["login","signin","sign-in","logout","signup","sign-up","register","forgot","reset","confirm","verify","recover","recovery","unlock","challenge","enroll","enrol","enrollment","activate","activation","resend","consent","webhook","hook","health","healthz","readyz","livez","ping","status","public","static","assets","favicon","robots","callback","oauth","sso","docs","swagger","openapi"];const ROUTE_METHODS=new Set(["get","post","put","patch","delete","all"]);function matchesFragment(path,fragment){const escaped=fragment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-z0-9])${escaped}s?([^a-z0-9]|$)`).test(path)}function asFunction(node){return node?.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||node?.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||node?.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression?node:void 0}function isDelegatingHandler(fn){let callsNext=false;let touchesResponse=false;(0,utils_1.walk)(fn.body,node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="next"){callsNext=true;return}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&RESPONSE_RECEIVER.test(node.object.name)){touchesResponse=true}});return callsNext&&!touchesResponse}const RESPONSE_RECEIVER=/^(res|response)$/i;exports.requireRouteAuthentication=(0,eslint_devkit_1.createRule)({name:"require-route-authentication",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-route-authentication.md",description:"Require authentication on routes that expose a critical function (account, credential, payment, configuration)",cwe:"CWE-306",cvss:8.2,confidence:"medium"},messages:{missingAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Critical Route Without Authentication (CWE-306)",cwe:"CWE-306",cvss:8.2,description:"{{method}} {{path}} exposes a critical function but its chain has no authentication middleware and the handler never reads an authenticated principal. Anyone who can reach the port can call it.",severity:"HIGH",fix:"Mount an authentication middleware on the route \u2014 app.{{method}}('{{path}}', requireAuth, handler) \u2014 or app.use(requireAuth) for the whole router.",documentationLink:"https://cwe.mitre.org/data/definitions/306.html"})},schema:[{type:"object",properties:{...app_receiver_1.APP_RECEIVER_SCHEMA,criticalPaths:{type:"array",items:{type:"string"},description:"Path fragments that mark a route as critical"},publicPaths:{type:"array",items:{type:"string"},description:"Path fragments that are public by design"},authMiddleware:{type:"array",items:{type:"string"},description:"Extra middleware names accepted as authentication"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{criticalPaths,publicPaths,authMiddleware,appReceiverNames}=options;const critical=(criticalPaths??DEFAULT_CRITICAL_PATHS).map(p=>p.toLowerCase());const publics=(publicPaths??DEFAULT_PUBLIC_PATHS).map(p=>p.toLowerCase());const extraAuth=new Set(authMiddleware??[]);const topLevelFunctions=new Map;for(const stmt of context.sourceCode.ast.body){if(stmt.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&stmt.id){topLevelFunctions.set(stmt.id.name,stmt);continue}if(stmt.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration)continue;for(const decl of stmt.declarations){if(decl.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&decl.init){topLevelFunctions.set(decl.id.name,decl.init)}}}const candidates=[];let hasGlobalAuth=false;function routeMethodOf(node){const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return null;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(!(0,app_receiver_1.isAppReceiver)(callee.object.name,appReceiverNames))return null;return method}return{CallExpression(node){const method=routeMethodOf(node);if(!method)return;if(method==="use"){const[first]=node.arguments;const pathScoped=first?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof first.value==="string";if(!pathScoped){for(const arg of node.arguments){if(arg.type!==eslint_devkit_1.AST_NODE_TYPES.Literal&&(0,auth_evidence_1.isAuthMiddlewareArg)(arg,extraAuth)){hasGlobalAuth=true}}}return}if(!ROUTE_METHODS.has(method))return;const[pathArg,...rest]=node.arguments;if(!pathArg||pathArg.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||typeof pathArg.value!=="string"){return}if(rest.length===0)return;const path=pathArg.value.toLowerCase();if(publics.some(fragment=>matchesFragment(path,fragment)))return;if(!critical.some(fragment=>matchesFragment(path,fragment)))return;const handler=rest[rest.length-1];if((0,auth_evidence_1.routeIsAuthenticated)(rest.slice(0,-1),handler,extraAuth)){return}const fn=asFunction(handler)??(handler.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?asFunction(topLevelFunctions.get(handler.name)):void 0);if(fn&&isDelegatingHandler(fn))return;candidates.push({node:pathArg,method,path:pathArg.value})},"Program:exit"(){if(hasGlobalAuth)return;for(const candidate of candidates){context.report({node:candidate.node,messageId:"missingAuthentication",data:{method:candidate.method,path:candidate.path}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RELEASE_SELECTOR=void 0;exports.nodeReleasesBinding=nodeReleasesBinding;exports.fileHasAmbientCredentials=fileHasAmbientCredentials;exports.servesBrowserDocuments=servesBrowserDocuments;const eslint_devkit_1=require("@interlace/eslint-devkit");const index_1=require("./index");function nodeReleasesBinding(node,binding){const isBinding=n=>n?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&n.name===binding;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(isBinding);case eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression:return isBinding(node.right);case eslint_devkit_1.AST_NODE_TYPES.ExportDefaultDeclaration:return isBinding(node.declaration);default:return isBinding(node.argument)}}exports.RELEASE_SELECTOR="AssignmentExpression, ExportDefaultDeclaration, ReturnStatement";const CREDENTIAL_PACKAGES=new Set(["cookie-parser","express-session","cookie-session","client-sessions","csurf","csrf","lusca","passport"]);const CREDENTIAL_MEMBERS=new Set(["session","cookies","signedCookies","cookie","clearCookie"]);const CREDENTIAL_RECEIVER=/^(req|request|res|response)$/i;function specifierRoot(specifier){const parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function isCredentialModuleLoad(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&typeof node.source.value==="string"){return CREDENTIAL_PACKAGES.has(specifierRoot(node.source.value))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){const[arg]=node.arguments;return arg?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&CREDENTIAL_PACKAGES.has(specifierRoot(arg.value))}return false}function isCredentialMember(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(node.computed||node.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}if(!CREDENTIAL_MEMBERS.has(node.property.name))return false;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&CREDENTIAL_RECEIVER.test(node.object.name)}function fileHasAmbientCredentials(ast){let found=false;(0,index_1.walk)(ast,node=>{if(found)return;if(isCredentialModuleLoad(node)||isCredentialMember(node))found=true});return found}const DOCUMENT_RESPONDERS=new Set(["render","sendFile"]);function servesBrowserDocuments(ast){let found=false;(0,index_1.walk)(ast,node=>{if(found)return;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return;const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const name=callee.property.name;if(DOCUMENT_RESPONDERS.has(name)||name==="engine"){found=true;return}if(name!=="set")return;const[key]=node.arguments;found=key?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof key.value==="string"&&key.value.toLowerCase().startsWith("view ")});return found}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.RELEASE_SELECTOR=void 0;exports.nodeReleasesBinding=nodeReleasesBinding;exports.fileHasAmbientCredentials=fileHasAmbientCredentials;exports.servesBrowserDocuments=servesBrowserDocuments;const eslint_devkit_1=require("@interlace/eslint-devkit");const index_1=require("./index");function nodeReleasesBinding(node,binding){const isBinding=n=>n?.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&n.name===binding;switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return node.arguments.some(isBinding);case eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression:return isBinding(node.right);case eslint_devkit_1.AST_NODE_TYPES.ExportDefaultDeclaration:return isBinding(node.declaration);default:return isBinding(node.argument)}}exports.RELEASE_SELECTOR="AssignmentExpression, ExportDefaultDeclaration, ReturnStatement";const CREDENTIAL_PACKAGES=new Set(["cookie-parser","express-session","cookie-session","client-sessions","csurf","csrf","lusca","passport"]);const CREDENTIAL_MEMBERS=new Set(["session","cookies","signedCookies","cookie","clearCookie"]);const CREDENTIAL_RECEIVER=/^(req|request|res|response)$/i;function specifierRoot(specifier){const parts=specifier.split("/");return specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0]}function isCredentialModuleLoad(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&typeof node.source.value==="string"){return CREDENTIAL_PACKAGES.has(specifierRoot(node.source.value))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){const[arg]=node.arguments;return arg?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&CREDENTIAL_PACKAGES.has(specifierRoot(arg.value))}return false}function isCredentialMember(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const member=(0,eslint_devkit_1.propertyName)(node);if(member===null||!CREDENTIAL_MEMBERS.has(member))return false;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&CREDENTIAL_RECEIVER.test(node.object.name)}function fileHasAmbientCredentials(ast){let found=false;(0,index_1.walk)(ast,node=>{if(found)return;if(isCredentialModuleLoad(node)||isCredentialMember(node))found=true});return found}const DOCUMENT_RESPONDERS=new Set(["render","sendFile"]);function servesBrowserDocuments(ast){let found=false;(0,index_1.walk)(ast,node=>{if(found)return;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return;const callee=node.callee;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const name=(0,eslint_devkit_1.propertyName)(callee);if(name===null)return;if(DOCUMENT_RESPONDERS.has(name)||name==="engine"){found=true;return}if(name!=="set")return;const[key]=node.arguments;found=key?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof key.value==="string"&&key.value.toLowerCase().startsWith("view ")});return found}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AUTH_MIDDLEWARE=void 0;exports.isAuthMiddlewareArg=isAuthMiddlewareArg;exports.routeIsAuthenticated=routeIsAuthenticated;const eslint_devkit_1=require("@interlace/eslint-devkit");const index_1=require("./index");exports.AUTH_MIDDLEWARE=/auth|jwt|passport|token|session|guard|protect|ensure|require|permit|acl|rbac|verify|login|identity|principal/i;function referenceNames(node){switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:return[node.name];case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return[...referenceNames(node.object),...node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?[node.property.name]:[]];case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return referenceNames(node.callee);default:return[]}}const CREDENTIAL_STORES=new Set(["session","expresssession","cookiesession","clientsessions","cookieparser"]);function isAuthMiddlewareArg(arg,extra){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="require"){return false}const names=referenceNames(arg);if(names.length===1&&CREDENTIAL_STORES.has(names[0].toLowerCase())){return false}if(names.some(name=>exports.AUTH_MIDDLEWARE.test(name)))return true;return names.some(name=>[...extra].some(wanted=>name.includes(wanted)))}function routeIsAuthenticated(chain,handler,extra){if(chain.some(arg=>isAuthMiddlewareArg(arg,extra)))return true;return handler!==void 0&&(0,index_1.readsPrincipal)(handler)}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.AUTH_MIDDLEWARE=void 0;exports.isAuthMiddlewareArg=isAuthMiddlewareArg;exports.routeIsAuthenticated=routeIsAuthenticated;const eslint_devkit_1=require("@interlace/eslint-devkit");const index_1=require("./index");exports.AUTH_MIDDLEWARE=/auth|jwt|passport|token|session|guard|protect|ensure|require|permit|acl|rbac|verify|login|identity|principal/i;function referenceNames(node){switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:return[node.name];case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{const link=(0,eslint_devkit_1.propertyName)(node);return[...referenceNames(node.object),...link===null?[]:[link]]}case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return referenceNames(node.callee);default:return[]}}const CREDENTIAL_STORES=new Set(["session","expresssession","cookiesession","clientsessions","cookieparser"]);function isAuthMiddlewareArg(arg,extra){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="require"){return false}const names=referenceNames(arg);if(names.length===1&&CREDENTIAL_STORES.has(names[0].toLowerCase())){return false}if(names.some(name=>exports.AUTH_MIDDLEWARE.test(name)))return true;return names.some(name=>[...extra].some(wanted=>name.includes(wanted)))}function routeIsAuthenticated(chain,handler,extra){if(chain.some(arg=>isAuthMiddlewareArg(arg,extra)))return true;return handler!==void 0&&(0,index_1.readsPrincipal)(handler)}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.walk=walk;exports.readsPrincipal=readsPrincipal;exports.isClientRequestMember=isClientRequestMember;const eslint_devkit_1=require("@interlace/eslint-devkit");const PRINCIPAL_PROPERTIES=new Set(["user","auth","session","currentUser","principal","identity","userId","authInfo"]);const PRINCIPAL_RECEIVER=/^(req|request|res|response|ctx|locals)$/i;const CLIENT_CONTAINERS=new Set(["body","query","params"]);const REQUEST_RECEIVER=/^(req|request)$/i;function walk(node,visit){visit(node);for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const item of value){if(item&&typeof item==="object"&&"type"in item){walk(item,visit)}}continue}if(value&&typeof value==="object"&&"type"in value){walk(value,visit)}}}function readsPrincipal(node){let found=false;walk(node,child=>{if(found)return;if(child.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;if(child.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(!PRINCIPAL_PROPERTIES.has(child.property.name))return;const{object}=child;if(object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){found=PRINCIPAL_RECEIVER.test(object.name);return}if(object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&object.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){found=PRINCIPAL_RECEIVER.test(object.property.name)}});return found}function isClientRequestMember(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const{object}=node;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(object.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(!CLIENT_CONTAINERS.has(object.property.name))return false;const root=object.object;if(root.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return REQUEST_RECEIVER.test(root.name)}if(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return REQUEST_RECEIVER.test(root.property.name)}return false}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.walk=walk;exports.readsPrincipal=readsPrincipal;exports.isClientRequestMember=isClientRequestMember;const eslint_devkit_1=require("@interlace/eslint-devkit");const PRINCIPAL_PROPERTIES=new Set(["user","auth","session","currentUser","principal","identity","userId","authInfo"]);const PRINCIPAL_RECEIVER=/^(req|request|res|response|ctx|locals)$/i;const CLIENT_CONTAINERS=new Set(["body","query","params"]);const REQUEST_RECEIVER=/^(req|request)$/i;function walk(node,visit){visit(node);for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const item of value){if(item&&typeof item==="object"&&"type"in item){walk(item,visit)}}continue}if(value&&typeof value==="object"&&"type"in value){walk(value,visit)}}}function readsPrincipal(node){let found=false;walk(node,child=>{if(found)return;if(child.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const principal=(0,eslint_devkit_1.propertyName)(child);if(principal===null||!PRINCIPAL_PROPERTIES.has(principal))return;const{object}=child;if(object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){found=PRINCIPAL_RECEIVER.test(object.name);return}if(object.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){found=PRINCIPAL_RECEIVER.test((0,eslint_devkit_1.propertyName)(object))}});return found}function isClientRequestMember(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const{object}=node;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;const container=(0,eslint_devkit_1.propertyName)(object);if(container===null||!CLIENT_CONTAINERS.has(container))return false;const root=object.object;if(root.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return REQUEST_RECEIVER.test(root.name)}if(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return REQUEST_RECEIVER.test(root.property.name)}return false}