eslint-plugin-express-security 1.5.5 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -3
  3. package/src/index.js +1 -1
  4. package/src/rules/no-client-controlled-authorization/index.js +1 -1
  5. package/src/rules/no-cors-credentials-wildcard/index.js +1 -1
  6. package/src/rules/no-disabled-helmet-protections/index.js +1 -1
  7. package/src/rules/no-error-details-in-response/index.js +1 -1
  8. package/src/rules/no-exposed-debug-endpoints/index.js +1 -1
  9. package/src/rules/no-express-unsafe-regex-route/index.js +1 -1
  10. package/src/rules/no-graphql-introspection-production/index.js +1 -1
  11. package/src/rules/no-host-header-in-links/index.js +1 -1
  12. package/src/rules/no-idor-resource-access/index.js +1 -1
  13. package/src/rules/no-insecure-cookie-options/index.js +1 -1
  14. package/src/rules/no-missing-cors-check/index.js +1 -1
  15. package/src/rules/no-missing-csrf-protection/index.js +1 -1
  16. package/src/rules/no-missing-security-headers/index.js +1 -1
  17. package/src/rules/no-permissive-cors/index.js +1 -1
  18. package/src/rules/no-permissive-trust-proxy/index.js +1 -1
  19. package/src/rules/no-sensitive-data-in-query/index.js +1 -1
  20. package/src/rules/no-static-root-exposure/index.js +1 -1
  21. package/src/rules/no-unsafe-csp-directives/index.js +1 -1
  22. package/src/rules/no-user-controlled-redirect/index.js +1 -1
  23. package/src/rules/no-user-controlled-render-locals/index.js +1 -1
  24. package/src/rules/require-case-insensitive-path-guard/index.js +1 -1
  25. package/src/rules/require-csrf-protection/index.js +1 -1
  26. package/src/rules/require-express-body-parser-limits/index.js +1 -1
  27. package/src/rules/require-helmet/index.js +1 -1
  28. package/src/rules/require-query-type-guard/index.js +1 -1
  29. package/src/rules/require-rate-limiting/index.js +1 -1
  30. package/src/rules/require-route-authentication/index.js +1 -1
  31. package/src/rules/require-strict-transport-security/index.js +1 -1
  32. package/src/utils/express-evidence.js +1 -0
package/README.md CHANGED
@@ -67,7 +67,7 @@ npm install eslint-plugin-express-security --save-dev
67
67
 
68
68
  | Package | Version |
69
69
  | :------ | :-------------------------------- |
70
- | ESLint | `^8.0.0 \|\| ^9.0.0 \|\| ^10.0.0` |
70
+ | ESLint | `^8.40.0 \|\| ^9.0.0 \|\| ^10.0.0` |
71
71
  | Node.js | `>=18.0.0` |
72
72
 
73
73
  See the [ESLint Version Support Policy](../../docs/ESLINT_VERSION_SUPPORT.md) — current ecosystem share data, the 20% gate, and the forward-looking exception that covers v10.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eslint-plugin-express-security",
3
- "version": "1.5.5",
3
+ "version": "2.0.0",
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,10 +76,10 @@
76
76
  "node": ">=18.0.0"
77
77
  },
78
78
  "dependencies": {
79
- "@interlace/eslint-devkit": "^1.10.0"
79
+ "@interlace/eslint-devkit": "^1.12.0"
80
80
  },
81
81
  "peerDependencies": {
82
- "eslint": "^8.0.0 || ^9.0.0 || ^10.0.0",
82
+ "eslint": "^8.40.0 || ^9.0.0 || ^10.0.0",
83
83
  "express": "^4.0.0 || ^5.0.0",
84
84
  "helmet": "^6.0.0 || ^7.0.0 || ^8.0.0",
85
85
  "cors": "^2.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;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}};exports.plugin={meta:{name:"eslint-plugin-express-security",version:"1.5.5"},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":"warn","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-missing-cors-check":"warn","express-security/no-missing-csrf-protection":"warn","express-security/no-missing-security-headers":"warn","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;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}};exports.plugin={meta:{name:"eslint-plugin-express-security",version:"2.0.0"},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":"warn","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 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]){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&&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 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noCorsCredentialsWildcard=void 0;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},hasSuggestions:true,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"}),useExplicitOrigins:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Explicit Origins",description:"Replace wildcard with explicit origin whitelist",severity:"LOW",fix:'origin: ["https://your-frontend.com"]',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options]){const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(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",suggest:[{messageId:"useExplicitOrigins",fix:()=>null}]})}}}}}});
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},hasSuggestions:true,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"}),useExplicitOrigins:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Explicit Origins",description:"Replace wildcard with explicit origin whitelist",severity:"LOW",fix:'origin: ["https://your-frontend.com"]',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"})},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&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(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",suggest:[{messageId:"useExplicitOrigins",fix:()=>null}]})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDisabledHelmetProtections=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const PROTECTIONS={contentSecurityPolicy:"Content-Security-Policy",frameguard:"X-Frame-Options",xFrameOptions:"X-Frame-Options",noSniff:"X-Content-Type-Options",xContentTypeOptions:"X-Content-Type-Options",referrerPolicy:"Referrer-Policy",hidePoweredBy:"X-Powered-By (removal)",xPoweredBy:"X-Powered-By (removal)",crossOriginResourcePolicy:"Cross-Origin-Resource-Policy",crossOriginOpenerPolicy:"Cross-Origin-Opener-Policy"};function isHelmetCall(node){return node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="helmet"}function propertyKeyName(prop){if(prop.computed)return null;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return null}exports.noDisabledHelmetProtections=(0,eslint_devkit_1.createRule)({name:"no-disabled-helmet-protections",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-disabled-helmet-protections.md",description:"Disallow disabling helmet security-header defaults: contentSecurityPolicy, frameguard/xFrameOptions, noSniff/xContentTypeOptions, referrerPolicy, hidePoweredBy/xPoweredBy, crossOriginResourcePolicy, crossOriginOpenerPolicy",cwe:"CWE-693",cvss:6.5,confidence:"high"},messages:{disabledProtection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Helmet Protection Disabled (CWE-693)",cwe:"CWE-693",cvss:6.5,description:"helmet({ {{option}}: false }) stops the {{header}} header from being sent. The middleware is mounted but this protection is off, so the app ships the same exposure as an app with no helmet at all.",severity:"HIGH",fix:"Remove the `{{option}}: false` entry and keep the helmet default. If the header must be customised, pass its options object instead of `false`.",documentationLink:"https://helmetjs.github.io/"}),restoreDefault:"Remove `{{option}}: false` and keep the helmet default"},schema:[{type:"object",properties:{allowDisabled:{type:"array",items:{type:"string"},description:"Helmet option names that may be disabled without a report"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){const{allowDisabled}=options;const allowed=new Set(allowDisabled??[]);function removeProperty(fixer,prop){const sourceCode=context.sourceCode;const after=sourceCode.getTokenAfter(prop);if(after&&after.value===","){return fixer.removeRange([prop.range[0],after.range[1]])}const before=sourceCode.getTokenBefore(prop);if(before&&before.value===","){return fixer.removeRange([before.range[0],prop.range[1]])}return fixer.remove(prop)}return{CallExpression(node){if(!isHelmetCall(node))return;const config=node.arguments[0];if(!config||config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;for(const prop of config.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=propertyKeyName(prop);if(!name)continue;const header=PROTECTIONS[name];if(!header)continue;if(allowed.has(name))continue;if(prop.value.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||prop.value.value!==false){continue}context.report({node:prop,messageId:"disabledProtection",data:{option:name,header},suggest:[{messageId:"restoreDefault",data:{option:name},fix:fixer=>removeProperty(fixer,prop)}]})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noDisabledHelmetProtections=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const PROTECTIONS={contentSecurityPolicy:"Content-Security-Policy",frameguard:"X-Frame-Options",xFrameOptions:"X-Frame-Options",noSniff:"X-Content-Type-Options",xContentTypeOptions:"X-Content-Type-Options",referrerPolicy:"Referrer-Policy",hidePoweredBy:"X-Powered-By (removal)",xPoweredBy:"X-Powered-By (removal)",crossOriginResourcePolicy:"Cross-Origin-Resource-Policy",crossOriginOpenerPolicy:"Cross-Origin-Opener-Policy"};function isHelmetCall(node){return node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="helmet"}function propertyKeyName(prop){if(prop.computed)return null;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return null}exports.noDisabledHelmetProtections=(0,eslint_devkit_1.createRule)({name:"no-disabled-helmet-protections",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-disabled-helmet-protections.md",description:"Disallow disabling helmet security-header defaults: contentSecurityPolicy, frameguard/xFrameOptions, noSniff/xContentTypeOptions, referrerPolicy, hidePoweredBy/xPoweredBy, crossOriginResourcePolicy, crossOriginOpenerPolicy",cwe:"CWE-693",cvss:6.5,confidence:"high"},messages:{disabledProtection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Helmet Protection Disabled (CWE-693)",cwe:"CWE-693",cvss:6.5,description:"helmet({ {{option}}: false }) stops the {{header}} header from being sent. The middleware is mounted but this protection is off, so the app ships the same exposure as an app with no helmet at all.",severity:"HIGH",fix:"Remove the `{{option}}: false` entry and keep the helmet default. If the header must be customised, pass its options object instead of `false`.",documentationLink:"https://helmetjs.github.io/"}),restoreDefault:"Remove `{{option}}: false` and keep the helmet default"},schema:[{type:"object",properties:{allowDisabled:{type:"array",items:{type:"string"},description:"Helmet option names that may be disabled without a report"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowDisabled}=options;const allowed=new Set(allowDisabled??[]);function removeProperty(fixer,prop){const sourceCode=context.sourceCode;const after=sourceCode.getTokenAfter(prop);if(after&&after.value===","){return fixer.removeRange([prop.range[0],after.range[1]])}const before=sourceCode.getTokenBefore(prop);if(before&&before.value===","){return fixer.removeRange([before.range[0],prop.range[1]])}return fixer.remove(prop)}return{CallExpression(node){if(!isHelmetCall(node))return;const config=node.arguments[0];if(!config||config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;for(const prop of config.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=propertyKeyName(prop);if(!name)continue;const header=PROTECTIONS[name];if(!header)continue;if(allowed.has(name))continue;if(prop.value.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||prop.value.value!==false){continue}context.report({node:prop,messageId:"disabledProtection",data:{option:name,header},suggest:[{messageId:"restoreDefault",data:{option:name},fix:fixer=>removeProperty(fixer,prop)}]})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noErrorDetailsInResponse=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const SEND_METHODS=new Set(["send","json","end"]);const ERROR_PARAM_NAME=/^(err|error)$/i;exports.noErrorDetailsInResponse=(0,eslint_devkit_1.createRule)({name:"no-error-details-in-response",meta:{type:"problem",hasSuggestions:false,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-error-details-in-response.md",description:"Disallow sending caught error objects, stacks, or spreads of them in HTTP responses",cwe:"CWE-209",cvss:5.3},messages:{errorDetailsExposed:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Error Details Exposed (CWE-209)",cwe:"CWE-209",description:"The HTTP response includes {{detail}}. Stack traces and driver errors leak file paths, dependency versions, query text and hostnames to the caller.",severity:"MEDIUM",fix:"Log the error server-side and respond with a generic body: logger.error(err); res.status(500).json({ error: 'Internal Server Error' })",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Error_Handling_Cheat_Sheet.html"})},schema:[{type:"object",properties:{allowMessage:{type:"boolean",default:true,description:"Allow err.message in responses"},allowInDev:{type:"boolean",default:false,description:"Allow error details inside an if-guard checking NODE_ENV"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){const{allowMessage,allowInDev}=options;const messageAllowed=allowMessage??true;const devAllowed=allowInDev??false;const sourceCode=context.sourceCode;const frames=[];function isErrorName(name){return frames.some(frame=>frame.name===name)}function enterFunction(node){const first=node.params[0];if(first!==void 0&&first.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&ERROR_PARAM_NAME.test(first.name)){frames.push({node,name:first.name})}}function exitFrame(node){if(frames.length>0&&frames[frames.length-1].node===node){frames.pop()}}function isResponseSend(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(!SEND_METHODS.has(callee.property.name))return false;let obj=callee.object;while(obj.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&obj.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){obj=obj.callee.object}if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const lower=obj.name.toLowerCase();return lower==="res"||lower==="response"||lower==="reply"}function detailOf(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isErrorName(node.name)){return`the raw error \`${node.name}\``}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isErrorName(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(node.property.name==="stack"){return`\`${node.object.name}.stack\``}if(node.property.name==="message"&&!messageAllowed){return`\`${node.object.name}.message\``}}return null}function collectFindings(arg){const direct=detailOf(arg);if(direct!==null)return[{node:arg,detail:direct}];if(arg.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return[];const findings=[];for(const prop of arg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){if(prop.argument.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isErrorName(prop.argument.name)){findings.push({node:prop,detail:`\`{ ...${prop.argument.name} }\` (spread of the raw error)`})}continue}const detail=detailOf(prop.value);if(detail!==null)findings.push({node:prop.value,detail})}return findings}function isInDevGuard(node){let current=node.parent;while(current!=null){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&sourceCode.getText(current.test).includes("NODE_ENV")){return true}current=current.parent}return false}return{CatchClause(node){if(node.param!==null&&node.param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){frames.push({node,name:node.param.name})}},"CatchClause:exit":exitFrame,FunctionDeclaration:enterFunction,"FunctionDeclaration:exit":exitFrame,FunctionExpression:enterFunction,"FunctionExpression:exit":exitFrame,ArrowFunctionExpression:enterFunction,"ArrowFunctionExpression:exit":exitFrame,CallExpression(node){if(frames.length===0)return;if(!isResponseSend(node))return;const arg=node.arguments[0];if(arg===void 0)return;if(devAllowed&&isInDevGuard(node))return;for(const finding of collectFindings(arg)){context.report({node:finding.node,messageId:"errorDetailsExposed",data:{detail:finding.detail}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noErrorDetailsInResponse=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const SEND_METHODS=new Set(["send","json","end"]);const ERROR_PARAM_NAME=/^(err|error)$/i;exports.noErrorDetailsInResponse=(0,eslint_devkit_1.createRule)({name:"no-error-details-in-response",meta:{type:"problem",hasSuggestions:false,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-error-details-in-response.md",description:"Disallow sending caught error objects, stacks, or spreads of them in HTTP responses",cwe:"CWE-209",cvss:5.3},messages:{errorDetailsExposed:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Error Details Exposed (CWE-209)",cwe:"CWE-209",description:"The HTTP response includes {{detail}}. Stack traces and driver errors leak file paths, dependency versions, query text and hostnames to the caller.",severity:"MEDIUM",fix:"Log the error server-side and respond with a generic body: logger.error(err); res.status(500).json({ error: 'Internal Server Error' })",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Error_Handling_Cheat_Sheet.html"})},schema:[{type:"object",properties:{allowMessage:{type:"boolean",default:true,description:"Allow err.message in responses"},allowInDev:{type:"boolean",default:false,description:"Allow error details inside an if-guard checking NODE_ENV"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowMessage,allowInDev}=options;const messageAllowed=allowMessage??true;const devAllowed=allowInDev??false;const sourceCode=context.sourceCode;const frames=[];function isErrorName(name){return frames.some(frame=>frame.name===name)}function enterFunction(node){const first=node.params[0];if(first!==void 0&&first.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&ERROR_PARAM_NAME.test(first.name)){frames.push({node,name:first.name})}}function exitFrame(node){if(frames.length>0&&frames[frames.length-1].node===node){frames.pop()}}function isResponseSend(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(!SEND_METHODS.has(callee.property.name))return false;let obj=callee.object;while(obj.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&obj.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){obj=obj.callee.object}if(obj.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const lower=obj.name.toLowerCase();return lower==="res"||lower==="response"||lower==="reply"}function detailOf(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isErrorName(node.name)){return`the raw error \`${node.name}\``}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isErrorName(node.object.name)&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(node.property.name==="stack"){return`\`${node.object.name}.stack\``}if(node.property.name==="message"&&!messageAllowed){return`\`${node.object.name}.message\``}}return null}function collectFindings(arg){const direct=detailOf(arg);if(direct!==null)return[{node:arg,detail:direct}];if(arg.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return[];const findings=[];for(const prop of arg.properties){if(prop.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){if(prop.argument.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&isErrorName(prop.argument.name)){findings.push({node:prop,detail:`\`{ ...${prop.argument.name} }\` (spread of the raw error)`})}continue}const detail=detailOf(prop.value);if(detail!==null)findings.push({node:prop.value,detail})}return findings}function isInDevGuard(node){let current=node.parent;while(current!=null){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&sourceCode.getText(current.test).includes("NODE_ENV")){return true}current=current.parent}return false}return{CatchClause(node){if(node.param!==null&&node.param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){frames.push({node,name:node.param.name})}},"CatchClause:exit":exitFrame,FunctionDeclaration:enterFunction,"FunctionDeclaration:exit":exitFrame,FunctionExpression:enterFunction,"FunctionExpression:exit":exitFrame,ArrowFunctionExpression:enterFunction,"ArrowFunctionExpression:exit":exitFrame,CallExpression(node){if(frames.length===0)return;if(!isResponseSend(node))return;const arg=node.arguments[0];if(arg===void 0)return;if(devAllowed&&isInDevGuard(node))return;for(const finding of collectFindings(arg)){context.report({node:finding.node,messageId:"errorDetailsExposed",data:{detail:finding.detail}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noExposedDebugEndpoints=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");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",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){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",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 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noExpressUnsafeRegexRoute=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const HTTP_METHODS=new Set(["get","post","put","patch","delete","all","use"]);const VULNERABLE_PATTERNS=[/\([^)]*[+*][^)]*\)[+*]/,/\([^)]*\|[^)]*\)[+*]/,/[+*]{2,}/,/\([^)]+\)[+*].*\\[1-9]/];const VULNERABLE_PARAM_PATTERNS=[/:[a-zA-Z_][a-zA-Z0-9_]*\+/,/:[a-zA-Z_][a-zA-Z0-9_]*\*/];function isVulnerableRegex(pattern){return VULNERABLE_PATTERNS.some(regex=>regex.test(pattern))}function hasVulnerableParamPattern(route){return VULNERABLE_PARAM_PATTERNS.some(regex=>regex.test(route))}exports.noExpressUnsafeRegexRoute=(0,eslint_devkit_1.createRule)({name:"no-express-unsafe-regex-route",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-express-unsafe-regex-route.md",description:"Disallow ReDoS-vulnerable regular expressions in Express.js route patterns",cwe:"CWE-1333",cvss:7.5},hasSuggestions:true,messages:{unsafeRegexRoute:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"ReDoS Vulnerable Route Pattern",cwe:"CWE-1333",description:"Route uses a regular expression vulnerable to Regular Expression Denial of Service (ReDoS). Malicious input can cause catastrophic backtracking.",severity:"HIGH",fix:"Simplify the regex pattern. Avoid nested quantifiers like (a+)+ and overlapping alternatives. Consider using a string route with explicit parameters.",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),unsafeParamPattern:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe Route Parameter Pattern",cwe:"CWE-1333",description:"Route parameter uses + or * quantifier which can match multiple path segments, potentially causing ReDoS or unexpected behavior.",severity:"MEDIUM",fix:"Use explicit path segments instead of :param+ or :param*. For example: /api/:id/details instead of /api/:path+",documentationLink:"https://expressjs.com/en/guide/routing.html"}),refactorRoute:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Refactor Route",description:"Refactor to use a simpler, non-vulnerable pattern",severity:"LOW",fix:"Use string routes with explicit path segments",documentationLink:"https://expressjs.com/en/guide/routing.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],create(context,[options]){const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}return{CallExpression(node){const callee=node.callee;if(callee.type!=="MemberExpression"){return}const property=callee.property;if(property.type!=="Identifier"){return}if(!HTTP_METHODS.has(property.name)){return}const routeArg=node.arguments[0];if(!routeArg){return}if(routeArg.type==="Literal"&&"regex"in routeArg&&routeArg.regex){const regexNode=routeArg;const pattern=regexNode.regex.pattern;if(isVulnerableRegex(pattern)){context.report({node:routeArg,messageId:"unsafeRegexRoute",suggest:[{messageId:"refactorRoute",fix:()=>null}]})}return}if(routeArg.type==="NewExpression"&&routeArg.callee.type==="Identifier"&&routeArg.callee.name==="RegExp"){const patternArg=routeArg.arguments[0];if(patternArg&&patternArg.type==="Literal"&&typeof patternArg.value==="string"){if(isVulnerableRegex(patternArg.value)){context.report({node:routeArg,messageId:"unsafeRegexRoute",suggest:[{messageId:"refactorRoute",fix:()=>null}]})}}return}if(routeArg.type==="Literal"&&typeof routeArg.value==="string"){if(hasVulnerableParamPattern(routeArg.value)){context.report({node:routeArg,messageId:"unsafeParamPattern",suggest:[{messageId:"refactorRoute",fix:()=>null}]})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noExpressUnsafeRegexRoute=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const HTTP_METHODS=new Set(["get","post","put","patch","delete","all","use"]);const VULNERABLE_PATTERNS=[/\([^)]*[+*][^)]*\)[+*]/,/\([^)]*\|[^)]*\)[+*]/,/[+*]{2,}/,/\([^)]+\)[+*].*\\[1-9]/];const VULNERABLE_PARAM_PATTERNS=[/:[a-zA-Z_][a-zA-Z0-9_]*\+/,/:[a-zA-Z_][a-zA-Z0-9_]*\*/];function isVulnerableRegex(pattern){return VULNERABLE_PATTERNS.some(regex=>regex.test(pattern))}function hasVulnerableParamPattern(route){return VULNERABLE_PARAM_PATTERNS.some(regex=>regex.test(route))}exports.noExpressUnsafeRegexRoute=(0,eslint_devkit_1.createRule)({name:"no-express-unsafe-regex-route",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-express-unsafe-regex-route.md",description:"Disallow ReDoS-vulnerable regular expressions in Express.js route patterns",cwe:"CWE-1333",cvss:7.5},hasSuggestions:true,messages:{unsafeRegexRoute:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"ReDoS Vulnerable Route Pattern",cwe:"CWE-1333",description:"Route uses a regular expression vulnerable to Regular Expression Denial of Service (ReDoS). Malicious input can cause catastrophic backtracking.",severity:"HIGH",fix:"Simplify the regex pattern. Avoid nested quantifiers like (a+)+ and overlapping alternatives. Consider using a string route with explicit parameters.",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"}),unsafeParamPattern:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unsafe Route Parameter Pattern",cwe:"CWE-1333",description:"Route parameter uses + or * quantifier which can match multiple path segments, potentially causing ReDoS or unexpected behavior.",severity:"MEDIUM",fix:"Use explicit path segments instead of :param+ or :param*. For example: /api/:id/details instead of /api/:path+",documentationLink:"https://expressjs.com/en/guide/routing.html"}),refactorRoute:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Refactor Route",description:"Refactor to use a simpler, non-vulnerable pattern",severity:"LOW",fix:"Use string routes with explicit path segments",documentationLink:"https://expressjs.com/en/guide/routing.html"})},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&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}return{CallExpression(node){const callee=node.callee;if(callee.type!=="MemberExpression"){return}const property=callee.property;if(property.type!=="Identifier"){return}if(!HTTP_METHODS.has(property.name)){return}const routeArg=node.arguments[0];if(!routeArg){return}if(routeArg.type==="Literal"&&"regex"in routeArg&&routeArg.regex){const regexNode=routeArg;const pattern=regexNode.regex.pattern;if(isVulnerableRegex(pattern)){context.report({node:routeArg,messageId:"unsafeRegexRoute",suggest:[{messageId:"refactorRoute",fix:()=>null}]})}return}if(routeArg.type==="NewExpression"&&routeArg.callee.type==="Identifier"&&routeArg.callee.name==="RegExp"){const patternArg=routeArg.arguments[0];if(patternArg&&patternArg.type==="Literal"&&typeof patternArg.value==="string"){if(isVulnerableRegex(patternArg.value)){context.report({node:routeArg,messageId:"unsafeRegexRoute",suggest:[{messageId:"refactorRoute",fix:()=>null}]})}}return}if(routeArg.type==="Literal"&&typeof routeArg.value==="string"){if(hasVulnerableParamPattern(routeArg.value)){context.report({node:routeArg,messageId:"unsafeParamPattern",suggest:[{messageId:"refactorRoute",fix:()=>null}]})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlIntrospectionProduction=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");function hasIntrospectionEnabled(node,sourceCode){const text=sourceCode.getText(node);if(/\bintrospection\s*:\s*true\b/.test(text)){return true}return false}function hasProductionGuard(node,sourceCode){const text=sourceCode.getText(node);const productionGuards=[/introspection\s*:\s*process\.env\.NODE_ENV\s*[!=]==?\s*['"]production['"]/,/introspection\s*:\s*!?\s*isProd/,/introspection\s*:\s*!?\s*isProduction/,/introspection\s*:\s*process\.env\.NODE_ENV\s*[!=]==?\s*['"]development['"]/];return productionGuards.some(guard=>guard.test(text))}exports.noGraphqlIntrospectionProduction=(0,eslint_devkit_1.createRule)({name:"no-graphql-introspection-production",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-graphql-introspection-production.md",description:"Disallow GraphQL introspection in production environments",cwe:"CWE-200",cvss:5},hasSuggestions:true,messages:{graphqlIntrospection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"GraphQL Introspection Enabled",cwe:"CWE-200",description:"GraphQL introspection is enabled. In production, this exposes your entire API schema to attackers.",severity:"MEDIUM",fix:"Set introspection: process.env.NODE_ENV !== 'production' or introspection: false",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html#introspection-graphiql"}),disableIntrospection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Disable Introspection in Production",description:"Disable GraphQL introspection for production",severity:"LOW",fix:"introspection: process.env.NODE_ENV !== 'production'",documentationLink:"https://www.apollographql.com/docs/apollo-server/api/apollo-server/#introspection"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},allowInDevelopment:{type:"boolean",default:true,description:"Allow introspection when the code is guarded by a development check"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,allowInDevelopment:true}],create(context,[options]){const{allowInTests=true}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;return{CallExpression(node){const callee=node.callee;const isGraphQLServer=callee.type==="Identifier"&&["ApolloServer","GraphQLServer","createServer"].includes(callee.name)||callee.type==="NewExpression"&&callee.callee.type==="Identifier"&&["ApolloServer","GraphQLServer"].includes(callee.callee.name);const isExpressGraphQL=callee.type==="Identifier"&&callee.name==="graphqlHTTP";if(!isGraphQLServer&&!isExpressGraphQL){return}const configArg=node.arguments[0];if(!configArg||configArg.type!=="ObjectExpression"){return}if(hasProductionGuard(configArg,sourceCode)){return}if(hasIntrospectionEnabled(configArg,sourceCode)){context.report({node:configArg,messageId:"graphqlIntrospection",suggest:[{messageId:"disableIntrospection",fix:()=>null}]})}},NewExpression(node){const callee=node.callee;if(callee.type!=="Identifier"||!["ApolloServer","GraphQLServer"].includes(callee.name)){return}const configArg=node.arguments[0];if(!configArg||configArg.type!=="ObjectExpression"){return}if(hasProductionGuard(configArg,sourceCode)){return}if(hasIntrospectionEnabled(configArg,sourceCode)){context.report({node:configArg,messageId:"graphqlIntrospection",suggest:[{messageId:"disableIntrospection",fix:()=>null}]})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noGraphqlIntrospectionProduction=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");function hasIntrospectionEnabled(node,sourceCode){const text=sourceCode.getText(node);if(/\bintrospection\s*:\s*true\b/.test(text)){return true}return false}function hasProductionGuard(node,sourceCode){const text=sourceCode.getText(node);const productionGuards=[/introspection\s*:\s*process\.env\.NODE_ENV\s*[!=]==?\s*['"]production['"]/,/introspection\s*:\s*!?\s*isProd/,/introspection\s*:\s*!?\s*isProduction/,/introspection\s*:\s*process\.env\.NODE_ENV\s*[!=]==?\s*['"]development['"]/];return productionGuards.some(guard=>guard.test(text))}exports.noGraphqlIntrospectionProduction=(0,eslint_devkit_1.createRule)({name:"no-graphql-introspection-production",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-graphql-introspection-production.md",description:"Disallow GraphQL introspection in production environments",cwe:"CWE-200",cvss:5},hasSuggestions:true,messages:{graphqlIntrospection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"GraphQL Introspection Enabled",cwe:"CWE-200",description:"GraphQL introspection is enabled. In production, this exposes your entire API schema to attackers.",severity:"MEDIUM",fix:"Set introspection: process.env.NODE_ENV !== 'production' or introspection: false",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/GraphQL_Cheat_Sheet.html#introspection-graphiql"}),disableIntrospection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Disable Introspection in Production",description:"Disable GraphQL introspection for production",severity:"LOW",fix:"introspection: process.env.NODE_ENV !== 'production'",documentationLink:"https://www.apollographql.com/docs/apollo-server/api/apollo-server/#introspection"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},allowInDevelopment:{type:"boolean",default:true,description:"Allow introspection when the code is guarded by a development check"}},additionalProperties:false}]},defaultOptions:[{allowInTests:true,allowInDevelopment:true}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=true}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;return{CallExpression(node){const callee=node.callee;const isGraphQLServer=callee.type==="Identifier"&&["ApolloServer","GraphQLServer","createServer"].includes(callee.name)||callee.type==="NewExpression"&&callee.callee.type==="Identifier"&&["ApolloServer","GraphQLServer"].includes(callee.callee.name);const isExpressGraphQL=callee.type==="Identifier"&&callee.name==="graphqlHTTP";if(!isGraphQLServer&&!isExpressGraphQL){return}const configArg=node.arguments[0];if(!configArg||configArg.type!=="ObjectExpression"){return}if(hasProductionGuard(configArg,sourceCode)){return}if(hasIntrospectionEnabled(configArg,sourceCode)){context.report({node:configArg,messageId:"graphqlIntrospection",suggest:[{messageId:"disableIntrospection",fix:()=>null}]})}},NewExpression(node){const callee=node.callee;if(callee.type!=="Identifier"||!["ApolloServer","GraphQLServer"].includes(callee.name)){return}const configArg=node.arguments[0];if(!configArg||configArg.type!=="ObjectExpression"){return}if(hasProductionGuard(configArg,sourceCode)){return}if(hasIntrospectionEnabled(configArg,sourceCode)){context.report({node:configArg,messageId:"graphqlIntrospection",suggest:[{messageId:"disableIntrospection",fix:()=>null}]})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noHostHeaderInLinks=void 0;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",hasSuggestions:true,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"}),useConfiguredOrigin:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use a configured origin",description:"Replace the header-derived host with a deployment constant such as process.env.PUBLIC_ORIGIN",severity:"LOW",fix:"const origin = process.env.PUBLIC_ORIGIN; // 'https://app.example.com'",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]){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},suggest:[{messageId:"useConfiguredOrigin",fix:()=>null}]})}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",hasSuggestions:true,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"}),useConfiguredOrigin:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use a configured origin",description:"Replace the header-derived host with a deployment constant such as process.env.PUBLIC_ORIGIN",severity:"LOW",fix:"const origin = process.env.PUBLIC_ORIGIN; // 'https://app.example.com'",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},suggest:[{messageId:"useConfiguredOrigin",fix:()=>null}]})}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.noIdorResourceAccess=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const DEFAULT_LOOKUP_METHODS=["findById","findByPk","findOne","findUnique","findFirst","findByIdAndUpdate","findByIdAndDelete","findByIdAndRemove","getById","deleteOne","deleteById","updateOne","replaceOne"];const REQUEST_PARAM=/^(req|request)$/i;function isHandlerFunction(node){if(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){return false}return node.params.some(param=>param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_PARAM.test(param.name))}function isRequestKeyArgument(arg){if((0,utils_1.isClientRequestMember)(arg))return true;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){let found=false;(0,utils_1.walk)(arg,child=>{if(found)return;if((0,utils_1.isClientRequestMember)(child))found=true});return found}return false}exports.noIdorResourceAccess=(0,eslint_devkit_1.createRule)({name:"no-idor-resource-access",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-idor-resource-access.md",description:"Disallow fetching a resource by a request-supplied key in a handler with no principal in scope",cwe:"CWE-639",cvss:7.5,confidence:"medium"},messages:{unscopedResourceLookup:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Resource Fetched By Client-Supplied Key (CWE-639)",cwe:"CWE-639",cvss:7.5,description:"{{method}}() is keyed on {{key}} and nothing in this handler ties the lookup to the caller. Incrementing the id in the URL returns another tenant\u2019s record.",severity:"HIGH",fix:"Scope the query to the principal \u2014 {{method}}({ _id: {{key}}, owner: req.user.id }) \u2014 or verify ownership on the loaded document before responding.",documentationLink:"https://cwe.mitre.org/data/definitions/639.html"})},schema:[{type:"object",properties:{lookupMethods:{type:"array",items:{type:"string"},description:"Lookup methods treated as a fetch-by-key"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){const{lookupMethods}=options;const lookups=new Set(lookupMethods??DEFAULT_LOOKUP_METHODS);function enclosingHandler(node){let current=node.parent;while(current){if(isHandlerFunction(current))return current;current=current.parent}return null}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(callee.computed)return;const method=callee.property.name;if(!lookups.has(method))return;const keyArg=node.arguments.find(arg=>isRequestKeyArgument(arg));if(!keyArg)return;const handler=enclosingHandler(node);if(!handler)return;if((0,utils_1.readsPrincipal)(handler))return;context.report({node,messageId:"unscopedResourceLookup",data:{method,key:context.sourceCode.getText(keyArg)}})}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noIdorResourceAccess=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const utils_1=require("../../utils");const express_evidence_1=require("../../utils/express-evidence");const DEFAULT_LOOKUP_METHODS=["findById","findByPk","findOne","findUnique","findFirst","findByIdAndUpdate","findByIdAndDelete","findByIdAndRemove","getById","deleteOne","deleteById","updateOne","replaceOne"];const REQUEST_PARAM=/^(req|request)$/i;function isHandlerFunction(node){if(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){return false}return node.params.some(param=>param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_PARAM.test(param.name))}function isRequestKeyArgument(arg){if((0,utils_1.isClientRequestMember)(arg))return true;if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){let found=false;(0,utils_1.walk)(arg,child=>{if(found)return;if((0,utils_1.isClientRequestMember)(child))found=true});return found}return false}exports.noIdorResourceAccess=(0,eslint_devkit_1.createRule)({name:"no-idor-resource-access",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-idor-resource-access.md",description:"Disallow fetching a resource by a request-supplied key in a handler with no principal in scope",cwe:"CWE-639",cvss:7.5,confidence:"medium"},messages:{unscopedResourceLookup:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Resource Fetched By Client-Supplied Key (CWE-639)",cwe:"CWE-639",cvss:7.5,description:"{{method}}() is keyed on {{key}} and nothing in this handler ties the lookup to the caller. Incrementing the id in the URL returns another tenant\u2019s record.",severity:"HIGH",fix:"Scope the query to the principal \u2014 {{method}}({ _id: {{key}}, owner: req.user.id }) \u2014 or verify ownership on the loaded document before responding.",documentationLink:"https://cwe.mitre.org/data/definitions/639.html"})},schema:[{type:"object",properties:{lookupMethods:{type:"array",items:{type:"string"},description:"Lookup methods treated as a fetch-by-key"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{lookupMethods}=options;const lookups=new Set(lookupMethods??DEFAULT_LOOKUP_METHODS);function enclosingHandler(node){let current=node.parent;while(current){if(isHandlerFunction(current))return current;current=current.parent}return null}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(callee.computed)return;const method=callee.property.name;if(!lookups.has(method))return;const keyArg=node.arguments.find(arg=>isRequestKeyArgument(arg));if(!keyArg)return;const handler=enclosingHandler(node);if(!handler)return;if((0,utils_1.readsPrincipal)(handler))return;context.report({node,messageId:"unscopedResourceLookup",data:{method,key:context.sourceCode.getText(keyArg)}})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noInsecureCookieOptions=void 0;exports.checkCookieOptions=checkCookieOptions;const eslint_devkit_1=require("@interlace/eslint-devkit");function checkCookieOptions(node,sourceCode,options){const text=sourceCode.getText(node);const issues=[];if(options.requireHttpOnly!==false){const hasHttpOnly=/\bhttpOnly\s*:\s*true\b/i.test(text);if(!hasHttpOnly){issues.push("missing httpOnly flag (prevents XSS access to cookie)")}}if(options.requireSecure!==false){const hasSecure=/\bsecure\s*:\s*true\b/i.test(text);if(!hasSecure){issues.push("missing secure flag (cookie sent over HTTPS only)")}}if(options.requireSameSite!==false){const acceptableValues=options.acceptableSameSiteValues||["strict","lax"];const sameSiteMatch=text.match(/\bsameSite\s*:\s*['"](\w+)['"]/i);if(!sameSiteMatch){issues.push("missing sameSite flag (prevents CSRF)")}else if(!acceptableValues.includes(sameSiteMatch[1].toLowerCase())){issues.push(`sameSite should be 'strict' or 'lax', not '${sameSiteMatch[1]}'`)}}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]){const{allowInTests=false}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;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,sourceCode,options);if(issues.length>0){context.report({node:optionsArg,messageId:"insecureCookie",data:{issues:issues.join("; ")},suggest:[{messageId:"addSecureFlags",fix:()=>null}]})}}}}}}});
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 checkCookieOptions(node,sourceCode,options){const text=sourceCode.getText(node);const issues=[];if(options.requireHttpOnly!==false){const hasHttpOnly=/\bhttpOnly\s*:\s*true\b/i.test(text);if(!hasHttpOnly){issues.push("missing httpOnly flag (prevents XSS access to cookie)")}}if(options.requireSecure!==false){const hasSecure=/\bsecure\s*:\s*true\b/i.test(text);if(!hasSecure){issues.push("missing secure flag (cookie sent over HTTPS only)")}}if(options.requireSameSite!==false){const acceptableValues=options.acceptableSameSiteValues||["strict","lax"];const sameSiteMatch=text.match(/\bsameSite\s*:\s*['"](\w+)['"]/i);if(!sameSiteMatch){issues.push("missing sameSite flag (prevents CSRF)")}else if(!acceptableValues.includes(sameSiteMatch[1].toLowerCase())){issues.push(`sameSite should be 'strict' or 'lax', not '${sameSiteMatch[1]}'`)}}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&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;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,sourceCode,options);if(issues.length>0){context.report({node:optionsArg,messageId:"insecureCookie",data:{issues:issues.join("; ")},suggest:[{messageId:"addSecureFlags",fix:()=>null}]})}}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingCorsCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function matchesIgnorePattern(text,ignorePatterns){return ignorePatterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return false}})}exports.noMissingCorsCheck=(0,eslint_devkit_2.createRule)({name:"no-missing-cors-check",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/no-permissive-cors"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-cors-check.md",description:"Detects missing CORS validation (wildcard CORS, missing origin check)",cwe:"CWE-346",cvss:7.5},hasSuggestions:true,messages:{missingCorsCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CORS Validation",cwe:"CWE-346",description:"Missing CORS validation detected: {{issue}}",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/346.html"}),useOriginValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Validate Origin",description:"Validate CORS origin",severity:"LOW",fix:"cors({ origin: (origin, cb) => allowedOrigins.includes(origin) ? cb(null, true) : cb(new Error()) })",documentationLink:"https://github.com/expressjs/cors#configuration-options"}),useCorsMiddleware:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use CORS Middleware",description:"Use CORS middleware with origin validation",severity:"LOW",fix:"app.use(cors({ origin: allowedOrigins }))",documentationLink:"https://github.com/expressjs/cors"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing CORS checks in test files"},trustedLibraries:{type:"array",items:{type:"string"},default:[],description:"Custom CORS libraries to trust (wildcard origins in these libraries will not be reported)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional safe patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,trustedLibraries:[],ignorePatterns:[]}],create(context,[options]){const{allowInTests=false,trustedLibraries:corsTrustedLibraries=[],ignorePatterns=[]}=options;const trustedLibraries=corsTrustedLibraries;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);const sourceCode=context.sourceCode;function checkLiteral(node){if(isTestFile){return}if(node.value==="*"&&typeof node.value==="string"){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}let shouldSkip=false;let current=node;while(current&&current.parent){current=current.parent;if(current.type==="CallExpression"){const callText=sourceCode.getText(current);if(/\b(setHeader|header)\s*\(/i.test(callText)&&/\bAccess-Control-Allow-Origin\b/i.test(callText)){shouldSkip=true;break}if(/\buse\s*\(/i.test(callText)&&/\bcors\s*\(/i.test(callText)){if(node.parent&&node.parent.type==="Property"){const prop=node.parent;if(prop.key.type==="Identifier"&&prop.key.name==="origin"){shouldSkip=true;break}}}}}if(shouldSkip){return}let isActualCorsContext=false;current=node;while(current&&current.parent){current=current.parent;if(current.type==="CallExpression"){const callText=sourceCode.getText(current);if(/\b(use|cors)\s*\(/i.test(callText)&&/\bcors\s*\(/i.test(callText)){isActualCorsContext=true;break}}}if(node.parent&&node.parent.type==="Property"){const prop=node.parent;if(prop.key.type==="Identifier"){const keyName=prop.key.name.toLowerCase();if(keyName==="origin"||keyName==="allowedorigins"){let inCorsCall=false;let checkNode=prop;while(checkNode&&checkNode.parent){checkNode=checkNode.parent;if(checkNode.type==="CallExpression"){const callText=sourceCode.getText(checkNode);if(/\bcors\s*\(/i.test(callText)||/\buse\s*\(/i.test(callText)&&/\bcors/i.test(callText)){inCorsCall=true;break}}}if(inCorsCall){context.report({node,messageId:"missingCorsCheck",data:{issue:"Wildcard CORS origin (*) allows all origins",safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'},suggest:[{messageId:"useOriginValidation",fix:_fixer=>null}]});return}}}}if(isActualCorsContext){context.report({node,messageId:"missingCorsCheck",data:{issue:"Wildcard CORS origin (*) allows all origins",safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'},suggest:[{messageId:"useOriginValidation",fix:_fixer=>null}]})}}}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const property=node.callee.property;if(property.type==="Identifier"&&property.name==="use"){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}const firstArg=node.arguments.length>0?node.arguments[0]:null;let isCorsCall=/\bcors\s*\(/i.test(text);if(!isCorsCall&&firstArg&&firstArg.type==="CallExpression"&&firstArg.callee.type==="Identifier"){const callee=firstArg.callee;const calleeName=callee.name.toLowerCase();isCorsCall=calleeName==="cors"||trustedLibraries.some(lib=>{return calleeName.includes(lib.toLowerCase())})}let isTrustedLibrary=false;if(firstArg&&firstArg.type==="CallExpression"&&firstArg.callee.type==="Identifier"){const calleeName=firstArg.callee.name.toLowerCase();isTrustedLibrary=trustedLibraries.some(lib=>calleeName.includes(lib.toLowerCase()))}if(isTrustedLibrary){return}if(/\bcors\s*\(/i.test(text)||isCorsCall){const corsCallArg=firstArg&&firstArg.type==="CallExpression"?firstArg:null;const argsToCheck=corsCallArg?corsCallArg.arguments:node.arguments;for(const arg of argsToCheck){if(arg.type==="ObjectExpression"){for(const prop of arg.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"&&prop.key.name==="origin"&&prop.value.type==="Literal"&&prop.value.value==="*"){context.report({node:prop.value,messageId:"missingCorsCheck",data:{issue:"Wildcard CORS origin (*) allows all origins",safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'},suggest:[{messageId:"useOriginValidation",fix:_fixer=>null}]})}}}else if(arg.type==="Identifier"){const varName=arg.name;let current=node;while(current){if(current.type==="Program"||current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const scopeBody=current.type==="Program"?current.body:current.body.type==="BlockStatement"?current.body.body:[];for(const stmt of scopeBody){if(stmt.type==="VariableDeclaration"){for(const declarator of stmt.declarations){if(declarator.id.type==="Identifier"&&declarator.id.name===varName&&declarator.init){if(declarator.init.type==="ObjectExpression"){for(const prop of declarator.init.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"&&prop.key.name==="origin"&&prop.value.type==="Literal"&&prop.value.value==="*"){context.report({node:arg,messageId:"missingCorsCheck",data:{issue:"Wildcard CORS origin (*) allows all origins",safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'},suggest:[{messageId:"useOriginValidation",fix:_fixer=>null}]});return}}}}}}}break}if(current.parent){current=current.parent}else{break}}}}}}}}function checkMemberExpression(node){if(isTestFile){return}if(node.property.type==="Identifier"){const propertyName=node.property.name;if(propertyName==="setHeader"||propertyName==="header"){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}const parent=node.parent;if(parent&&parent.type==="CallExpression"){const callText=sourceCode.getText(parent);if(/\bAccess-Control-Allow-Origin\b/i.test(callText)){const args=parent.arguments;if(args.length>=2&&args[1].type==="Literal"&&args[1].value==="*"){context.report({node:args[1],messageId:"missingCorsCheck",data:{issue:"Wildcard CORS header allows all origins",safeAlternative:'Validate origin before setting header: res.setHeader("Access-Control-Allow-Origin", allowedOrigins.includes(origin) ? origin : "null");'},suggest:[{messageId:"useOriginValidation",fix:_fixer=>null}]})}}}}}}return{Literal:checkLiteral,CallExpression:checkCallExpression,MemberExpression:checkMemberExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingCorsCheck=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const express_evidence_1=require("../../utils/express-evidence");function matchesIgnorePattern(text,ignorePatterns){return ignorePatterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return false}})}exports.noMissingCorsCheck=(0,eslint_devkit_2.createRule)({name:"no-missing-cors-check",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/no-permissive-cors"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-cors-check.md",description:"Detects missing CORS validation (wildcard CORS, missing origin check)",cwe:"CWE-346",cvss:7.5},hasSuggestions:true,messages:{missingCorsCheck:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CORS Validation",cwe:"CWE-346",description:"Missing CORS validation detected: {{issue}}",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/346.html"}),useOriginValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Validate Origin",description:"Validate CORS origin",severity:"LOW",fix:"cors({ origin: (origin, cb) => allowedOrigins.includes(origin) ? cb(null, true) : cb(new Error()) })",documentationLink:"https://github.com/expressjs/cors#configuration-options"}),useCorsMiddleware:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use CORS Middleware",description:"Use CORS middleware with origin validation",severity:"LOW",fix:"app.use(cors({ origin: allowedOrigins }))",documentationLink:"https://github.com/expressjs/cors"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing CORS checks in test files"},trustedLibraries:{type:"array",items:{type:"string"},default:[],description:"Custom CORS libraries to trust (wildcard origins in these libraries will not be reported)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional safe patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,trustedLibraries:[],ignorePatterns:[]}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false,trustedLibraries:corsTrustedLibraries=[],ignorePatterns=[]}=options;const trustedLibraries=corsTrustedLibraries;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);const sourceCode=context.sourceCode;function checkLiteral(node){if(isTestFile){return}if(node.value==="*"&&typeof node.value==="string"){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}let shouldSkip=false;let current=node;while(current&&current.parent){current=current.parent;if(current.type==="CallExpression"){const callText=sourceCode.getText(current);if(/\b(setHeader|header)\s*\(/i.test(callText)&&/\bAccess-Control-Allow-Origin\b/i.test(callText)){shouldSkip=true;break}if(/\buse\s*\(/i.test(callText)&&/\bcors\s*\(/i.test(callText)){if(node.parent&&node.parent.type==="Property"){const prop=node.parent;if(prop.key.type==="Identifier"&&prop.key.name==="origin"){shouldSkip=true;break}}}}}if(shouldSkip){return}let isActualCorsContext=false;current=node;while(current&&current.parent){current=current.parent;if(current.type==="CallExpression"){const callText=sourceCode.getText(current);if(/\b(use|cors)\s*\(/i.test(callText)&&/\bcors\s*\(/i.test(callText)){isActualCorsContext=true;break}}}if(node.parent&&node.parent.type==="Property"){const prop=node.parent;if(prop.key.type==="Identifier"){const keyName=prop.key.name.toLowerCase();if(keyName==="origin"||keyName==="allowedorigins"){let inCorsCall=false;let checkNode=prop;while(checkNode&&checkNode.parent){checkNode=checkNode.parent;if(checkNode.type==="CallExpression"){const callText=sourceCode.getText(checkNode);if(/\bcors\s*\(/i.test(callText)||/\buse\s*\(/i.test(callText)&&/\bcors/i.test(callText)){inCorsCall=true;break}}}if(inCorsCall){context.report({node,messageId:"missingCorsCheck",data:{issue:"Wildcard CORS origin (*) allows all origins",safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'},suggest:[{messageId:"useOriginValidation",fix:_fixer=>null}]});return}}}}if(isActualCorsContext){context.report({node,messageId:"missingCorsCheck",data:{issue:"Wildcard CORS origin (*) allows all origins",safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'},suggest:[{messageId:"useOriginValidation",fix:_fixer=>null}]})}}}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const property=node.callee.property;if(property.type==="Identifier"&&property.name==="use"){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}const firstArg=node.arguments.length>0?node.arguments[0]:null;let isCorsCall=/\bcors\s*\(/i.test(text);if(!isCorsCall&&firstArg&&firstArg.type==="CallExpression"&&firstArg.callee.type==="Identifier"){const callee=firstArg.callee;const calleeName=callee.name.toLowerCase();isCorsCall=calleeName==="cors"||trustedLibraries.some(lib=>{return calleeName.includes(lib.toLowerCase())})}let isTrustedLibrary=false;if(firstArg&&firstArg.type==="CallExpression"&&firstArg.callee.type==="Identifier"){const calleeName=firstArg.callee.name.toLowerCase();isTrustedLibrary=trustedLibraries.some(lib=>calleeName.includes(lib.toLowerCase()))}if(isTrustedLibrary){return}if(/\bcors\s*\(/i.test(text)||isCorsCall){const corsCallArg=firstArg&&firstArg.type==="CallExpression"?firstArg:null;const argsToCheck=corsCallArg?corsCallArg.arguments:node.arguments;for(const arg of argsToCheck){if(arg.type==="ObjectExpression"){for(const prop of arg.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"&&prop.key.name==="origin"&&prop.value.type==="Literal"&&prop.value.value==="*"){context.report({node:prop.value,messageId:"missingCorsCheck",data:{issue:"Wildcard CORS origin (*) allows all origins",safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'},suggest:[{messageId:"useOriginValidation",fix:_fixer=>null}]})}}}else if(arg.type==="Identifier"){const varName=arg.name;let current=node;while(current){if(current.type==="Program"||current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){const scopeBody=current.type==="Program"?current.body:current.body.type==="BlockStatement"?current.body.body:[];for(const stmt of scopeBody){if(stmt.type==="VariableDeclaration"){for(const declarator of stmt.declarations){if(declarator.id.type==="Identifier"&&declarator.id.name===varName&&declarator.init){if(declarator.init.type==="ObjectExpression"){for(const prop of declarator.init.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"&&prop.key.name==="origin"&&prop.value.type==="Literal"&&prop.value.value==="*"){context.report({node:arg,messageId:"missingCorsCheck",data:{issue:"Wildcard CORS origin (*) allows all origins",safeAlternative:'Use origin validation: app.use(cors({ origin: (origin, callback) => { if (allowedOrigins.includes(origin)) callback(null, true); else callback(new Error("Not allowed")); } } }));'},suggest:[{messageId:"useOriginValidation",fix:_fixer=>null}]});return}}}}}}}break}if(current.parent){current=current.parent}else{break}}}}}}}}function checkMemberExpression(node){if(isTestFile){return}if(node.property.type==="Identifier"){const propertyName=node.property.name;if(propertyName==="setHeader"||propertyName==="header"){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}const parent=node.parent;if(parent&&parent.type==="CallExpression"){const callText=sourceCode.getText(parent);if(/\bAccess-Control-Allow-Origin\b/i.test(callText)){const args=parent.arguments;if(args.length>=2&&args[1].type==="Literal"&&args[1].value==="*"){context.report({node:args[1],messageId:"missingCorsCheck",data:{issue:"Wildcard CORS header allows all origins",safeAlternative:'Validate origin before setting header: res.setHeader("Access-Control-Allow-Origin", allowedOrigins.includes(origin) ? origin : "null");'},suggest:[{messageId:"useOriginValidation",fix:_fixer=>null}]})}}}}}}return{Literal:checkLiteral,CallExpression:checkCallExpression,MemberExpression:checkMemberExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingCsrfProtection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_CSRF_MIDDLEWARE_PATTERNS=["csrf","csurf","csrfProtection","verifyCsrfToken","csrfToken","validateCsrf","checkCsrf","csrfMiddleware"];const DEFAULT_PROTECTED_METHODS=["post","put","delete","patch"];function matchesIgnorePattern(text,patterns){return patterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return text.toLowerCase().includes(pattern.toLowerCase())}})}exports.noMissingCsrfProtection=(0,eslint_devkit_2.createRule)({name:"no-missing-csrf-protection",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/require-csrf-protection"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-csrf-protection.md",description:"Detects missing CSRF token validation in POST/PUT/DELETE requests",cwe:"CWE-352",cvss:8.8},hasSuggestions:true,messages:{missingCsrfProtection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CSRF Protection",cwe:"CWE-352",description:"Missing CSRF protection detected: {{issue}}",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/352.html"}),addCsrfValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add CSRF Validation",description:"Add CSRF middleware",severity:"LOW",fix:"app.use(csrf({ cookie: true }))",documentationLink:"https://github.com/expressjs/csurf"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing CSRF protection in test files"},csrfMiddlewarePatterns:{type:"array",items:{type:"string"},default:[],description:"CSRF middleware patterns to recognize"},protectedMethods:{type:"array",items:{type:"string"},default:[],description:"HTTP methods that require CSRF protection"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional safe patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,csrfMiddlewarePatterns:[],protectedMethods:[],ignorePatterns:[]}],create(context,[options]){const{allowInTests=false,csrfMiddlewarePatterns,protectedMethods:customProtectedMethods,ignorePatterns=[]}=options;const csrfPatterns=csrfMiddlewarePatterns&&csrfMiddlewarePatterns.length>0?csrfMiddlewarePatterns:DEFAULT_CSRF_MIDDLEWARE_PATTERNS;const protectedMethods=customProtectedMethods&&customProtectedMethods.length>0?customProtectedMethods:DEFAULT_PROTECTED_METHODS;const protectedMethodsSet=new Set(protectedMethods.map(m=>m.toLowerCase()));const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);const sourceCode=context.sourceCode;function checkCallExpression(node){if(isTestFile){return}const callee=node.callee;const callText=sourceCode.getText(node);if(matchesIgnorePattern(callText,ignorePatterns)){return}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const methodName=callee.property.name;if(protectedMethodsSet.has(methodName.toLowerCase())){if(node.arguments.length<2){return}let hasCsrfInChain=false;for(let i=1;i<node.arguments.length;i++){const arg=node.arguments[i];const argText=sourceCode.getText(arg);if(csrfPatterns.some(pattern=>argText.toLowerCase().includes(pattern.toLowerCase()))){hasCsrfInChain=true;break}}if(!hasCsrfInChain){context.report({node,messageId:"missingCsrfProtection",data:{issue:`${methodName.toUpperCase()} route handler missing CSRF protection`,safeAlternative:`Add CSRF middleware: app.${methodName}("/path", csrf(), handler) or use app.use(csrf()) globally`},suggest:[{messageId:"addCsrfValidation",fix(fixer){return fixer.insertTextAfter(node.arguments[0],", csrf()")}}]})}}}}return{CallExpression:checkCallExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingCsrfProtection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const express_evidence_1=require("../../utils/express-evidence");const DEFAULT_CSRF_MIDDLEWARE_PATTERNS=["csrf","csurf","csrfProtection","verifyCsrfToken","csrfToken","validateCsrf","checkCsrf","csrfMiddleware"];const DEFAULT_PROTECTED_METHODS=["post","put","delete","patch"];function matchesIgnorePattern(text,patterns){return patterns.some(pattern=>{try{const regex=new RegExp(pattern,"i");return regex.test(text)}catch{return text.toLowerCase().includes(pattern.toLowerCase())}})}exports.noMissingCsrfProtection=(0,eslint_devkit_2.createRule)({name:"no-missing-csrf-protection",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/require-csrf-protection"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-csrf-protection.md",description:"Detects missing CSRF token validation in POST/PUT/DELETE requests",cwe:"CWE-352",cvss:8.8},hasSuggestions:true,messages:{missingCsrfProtection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing CSRF Protection",cwe:"CWE-352",description:"Missing CSRF protection detected: {{issue}}",severity:"HIGH",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/352.html"}),addCsrfValidation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add CSRF Validation",description:"Add CSRF middleware",severity:"LOW",fix:"app.use(csrf({ cookie: true }))",documentationLink:"https://github.com/expressjs/csurf"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing CSRF protection in test files"},csrfMiddlewarePatterns:{type:"array",items:{type:"string"},default:[],description:"CSRF middleware patterns to recognize"},protectedMethods:{type:"array",items:{type:"string"},default:[],description:"HTTP methods that require CSRF protection"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional safe patterns to ignore"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,csrfMiddlewarePatterns:[],protectedMethods:[],ignorePatterns:[]}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false,csrfMiddlewarePatterns,protectedMethods:customProtectedMethods,ignorePatterns=[]}=options;const csrfPatterns=csrfMiddlewarePatterns&&csrfMiddlewarePatterns.length>0?csrfMiddlewarePatterns:DEFAULT_CSRF_MIDDLEWARE_PATTERNS;const protectedMethods=customProtectedMethods&&customProtectedMethods.length>0?customProtectedMethods:DEFAULT_PROTECTED_METHODS;const protectedMethodsSet=new Set(protectedMethods.map(m=>m.toLowerCase()));const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);const sourceCode=context.sourceCode;function checkCallExpression(node){if(isTestFile){return}const callee=node.callee;const callText=sourceCode.getText(node);if(matchesIgnorePattern(callText,ignorePatterns)){return}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const methodName=callee.property.name;if(protectedMethodsSet.has(methodName.toLowerCase())){if(node.arguments.length<2){return}let hasCsrfInChain=false;for(let i=1;i<node.arguments.length;i++){const arg=node.arguments[i];const argText=sourceCode.getText(arg);if(csrfPatterns.some(pattern=>argText.toLowerCase().includes(pattern.toLowerCase()))){hasCsrfInChain=true;break}}if(!hasCsrfInChain){context.report({node,messageId:"missingCsrfProtection",data:{issue:`${methodName.toUpperCase()} route handler missing CSRF protection`,safeAlternative:`Add CSRF middleware: app.${methodName}("/path", csrf(), handler) or use app.use(csrf()) globally`},suggest:[{messageId:"addCsrfValidation",fix(fixer){return fixer.insertTextAfter(node.arguments[0],", csrf()")}}]})}}}}return{CallExpression:checkCallExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingSecurityHeaders=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_REQUIRED_HEADERS=["Content-Security-Policy","X-Frame-Options","X-Content-Type-Options"];const HEADER_METHODS=new Set(["setHeader","header","set"]);const RESPONSE_RECEIVER=/^(res|resp|response|reply)$/i;function isResponseHeaderCall(node){const{callee}=node;if(callee.type!=="MemberExpression"||callee.property.type!=="Identifier"||!HEADER_METHODS.has(callee.property.name)){return false}const{object}=callee;if(object.type==="Identifier"){return RESPONSE_RECEIVER.test(object.name)}if(object.type==="MemberExpression"&&object.property.type==="Identifier"){return RESPONSE_RECEIVER.test(object.property.name)}return false}function extractHeaderName(node){if(node.arguments.length>0&&node.arguments[0].type==="Literal"){return String(node.arguments[0].value)}return null}function checkFunctionForSecurityHeaders(node,requiredHeaders,context){const setHeaders=new Set;let current=node;let scopeNode=null;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){scopeNode=current;break}current=current.parent??null}if(!scopeNode){scopeNode=context.sourceCode.ast}function collectHeaders(astNode){if(astNode.type==="CallExpression"&&isResponseHeaderCall(astNode)){const headerName=extractHeaderName(astNode);if(headerName){setHeaders.add(headerName)}}if(astNode.type==="Program"&&astNode.body){astNode.body.forEach(collectHeaders)}else if((astNode.type==="FunctionDeclaration"||astNode.type==="FunctionExpression"||astNode.type==="ArrowFunctionExpression")&&astNode.body){collectHeaders(astNode.body)}else if(astNode.type==="BlockStatement"&&astNode.body){astNode.body.forEach(collectHeaders)}else if(astNode.type==="ExpressionStatement"&&astNode.expression){collectHeaders(astNode.expression)}}collectHeaders(scopeNode);return requiredHeaders.filter(header=>!setHeaders.has(header))}exports.noMissingSecurityHeaders=(0,eslint_devkit_2.createRule)({name:"no-missing-security-headers",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/require-helmet"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-security-headers.md",description:"Detects missing security headers in HTTP responses",cwe:"CWE-693",cvss:7.5},hasSuggestions:true,messages:{missingSecurityHeader:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing security headers",cwe:"CWE-693",description:"Missing security headers: {{headers}}",severity:"HIGH",fix:"Set security headers: Content-Security-Policy, X-Frame-Options, X-Content-Type-Options",documentationLink:"https://owasp.org/www-project-secure-headers/"}),addSecurityHeaders:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Security Headers",description:"Add security headers middleware",severity:"LOW",fix:"Add Content-Security-Policy, X-Frame-Options headers",documentationLink:"https://owasp.org/www-project-secure-headers/"}),useMiddleware:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Helmet",description:"Use helmet.js for security headers",severity:"LOW",fix:"app.use(helmet())",documentationLink:"https://helmetjs.github.io/"}),setHeader:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Set Headers",description:"Set security headers manually",severity:"LOW",fix:'res.setHeader("X-Frame-Options", "DENY")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers"})},schema:[{type:"object",properties:{requiredHeaders:{type:"array",items:{type:"string"},default:DEFAULT_REQUIRED_HEADERS},ignoreInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{requiredHeaders:DEFAULT_REQUIRED_HEADERS,ignoreInTests:true}],create(context,[options]){const{requiredHeaders=DEFAULT_REQUIRED_HEADERS,ignoreInTests=true}=options;const filename=context.filename;const isTestFile=ignoreInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}const reportedScopes=new Set;function getScopeKey(node){let current=node;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return`${current.range?.[0]}-${current.range?.[1]}`}current=current.parent??null}return"program"}function checkCallExpression(node){if(!isResponseHeaderCall(node)){return}const scopeKey=getScopeKey(node);if(reportedScopes.has(scopeKey)){return}const missing=checkFunctionForSecurityHeaders(node,requiredHeaders,context);reportedScopes.add(scopeKey);if(missing.length>0){context.report({node,messageId:"missingSecurityHeader",data:{headers:missing.join(", ")},suggest:[{messageId:"addSecurityHeaders",fix:()=>null},{messageId:"useMiddleware",fix:()=>null},{messageId:"setHeader",fix:()=>null}]})}}return{CallExpression:checkCallExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingSecurityHeaders=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const express_evidence_1=require("../../utils/express-evidence");const DEFAULT_REQUIRED_HEADERS=["Content-Security-Policy","X-Frame-Options","X-Content-Type-Options"];const HEADER_METHODS=new Set(["setHeader","header","set"]);const RESPONSE_RECEIVER=/^(res|resp|response|reply)$/i;function isResponseHeaderCall(node){const{callee}=node;if(callee.type!=="MemberExpression"||callee.property.type!=="Identifier"||!HEADER_METHODS.has(callee.property.name)){return false}const{object}=callee;if(object.type==="Identifier"){return RESPONSE_RECEIVER.test(object.name)}if(object.type==="MemberExpression"&&object.property.type==="Identifier"){return RESPONSE_RECEIVER.test(object.property.name)}return false}function extractHeaderName(node){if(node.arguments.length>0&&node.arguments[0].type==="Literal"){return String(node.arguments[0].value)}return null}function checkFunctionForSecurityHeaders(node,requiredHeaders,context){const setHeaders=new Set;let current=node;let scopeNode=null;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){scopeNode=current;break}current=current.parent??null}if(!scopeNode){scopeNode=context.sourceCode.ast}function collectHeaders(astNode){if(astNode.type==="CallExpression"&&isResponseHeaderCall(astNode)){const headerName=extractHeaderName(astNode);if(headerName){setHeaders.add(headerName)}}if(astNode.type==="Program"&&astNode.body){astNode.body.forEach(collectHeaders)}else if((astNode.type==="FunctionDeclaration"||astNode.type==="FunctionExpression"||astNode.type==="ArrowFunctionExpression")&&astNode.body){collectHeaders(astNode.body)}else if(astNode.type==="BlockStatement"&&astNode.body){astNode.body.forEach(collectHeaders)}else if(astNode.type==="ExpressionStatement"&&astNode.expression){collectHeaders(astNode.expression)}}collectHeaders(scopeNode);return requiredHeaders.filter(header=>!setHeaders.has(header))}exports.noMissingSecurityHeaders=(0,eslint_devkit_2.createRule)({name:"no-missing-security-headers",meta:{type:"problem",deprecated:true,replacedBy:["@see eslint-plugin-express-security/require-helmet"],docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-browser-security/docs/rules/no-missing-security-headers.md",description:"Detects missing security headers in HTTP responses",cwe:"CWE-693",cvss:7.5},hasSuggestions:true,messages:{missingSecurityHeader:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing security headers",cwe:"CWE-693",description:"Missing security headers: {{headers}}",severity:"HIGH",fix:"Set security headers: Content-Security-Policy, X-Frame-Options, X-Content-Type-Options",documentationLink:"https://owasp.org/www-project-secure-headers/"}),addSecurityHeaders:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Security Headers",description:"Add security headers middleware",severity:"LOW",fix:"Add Content-Security-Policy, X-Frame-Options headers",documentationLink:"https://owasp.org/www-project-secure-headers/"}),useMiddleware:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Helmet",description:"Use helmet.js for security headers",severity:"LOW",fix:"app.use(helmet())",documentationLink:"https://helmetjs.github.io/"}),setHeader:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Set Headers",description:"Set security headers manually",severity:"LOW",fix:'res.setHeader("X-Frame-Options", "DENY")',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers"})},schema:[{type:"object",properties:{requiredHeaders:{type:"array",items:{type:"string"},default:DEFAULT_REQUIRED_HEADERS},ignoreInTests:{type:"boolean",default:true}},additionalProperties:false}]},defaultOptions:[{requiredHeaders:DEFAULT_REQUIRED_HEADERS,ignoreInTests:true}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{requiredHeaders=DEFAULT_REQUIRED_HEADERS,ignoreInTests=true}=options;const filename=context.filename;const isTestFile=ignoreInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}const reportedScopes=new Set;function getScopeKey(node){let current=node;while(current){if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return`${current.range?.[0]}-${current.range?.[1]}`}current=current.parent??null}return"program"}function checkCallExpression(node){if(!isResponseHeaderCall(node)){return}const scopeKey=getScopeKey(node);if(reportedScopes.has(scopeKey)){return}const missing=checkFunctionForSecurityHeaders(node,requiredHeaders,context);reportedScopes.add(scopeKey);if(missing.length>0){context.report({node,messageId:"missingSecurityHeader",data:{headers:missing.join(", ")},suggest:[{messageId:"addSecurityHeaders",fix:()=>null},{messageId:"useMiddleware",fix:()=>null},{messageId:"setHeader",fix:()=>null}]})}}return{CallExpression:checkCallExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveCors=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");function isPermissiveCorsConfig(node,sourceCode,options){const text=sourceCode.getText(node);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"}}if(/\bcredentials\s*:\s*true\b/.test(text)){if(/\borigin\s*:\s*true\b/.test(text)){return{isPermissive:true,reason:"origin: true with credentials: true allows credential leakage to 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},hasSuggestions:true,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"}),useWhitelist:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Origin Whitelist",description:"Replace with explicit origin whitelist",severity:"LOW",fix:'origin: ["https://your-frontend.com", "https://app.your-domain.com"]',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"})},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]){const{allowInTests=false,allowOriginTrue=false}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(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"},suggest:[{messageId:"useWhitelist",fix:()=>null}]});return}if(corsConfigNode){const{isPermissive,reason}=isPermissiveCorsConfig(corsConfigNode,sourceCode,{allowOriginTrue});if(isPermissive){context.report({node:corsConfigNode,messageId:"permissiveCors",data:{reason},suggest:[{messageId:"useWhitelist",fix:()=>null}]})}}}}}}});
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 isPermissiveCorsConfig(node,sourceCode,options){const text=sourceCode.getText(node);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"}}if(/\bcredentials\s*:\s*true\b/.test(text)){if(/\borigin\s*:\s*true\b/.test(text)){return{isPermissive:true,reason:"origin: true with credentials: true allows credential leakage to 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},hasSuggestions:true,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"}),useWhitelist:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use Origin Whitelist",description:"Replace with explicit origin whitelist",severity:"LOW",fix:'origin: ["https://your-frontend.com", "https://app.your-domain.com"]',documentationLink:"https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS"})},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&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(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"},suggest:[{messageId:"useWhitelist",fix:()=>null}]});return}if(corsConfigNode){const{isPermissive,reason}=isPermissiveCorsConfig(corsConfigNode,sourceCode,{allowOriginTrue});if(isPermissive){context.report({node:corsConfigNode,messageId:"permissiveCors",data:{reason},suggest:[{messageId:"useWhitelist",fix:()=>null}]})}}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPermissiveTrustProxy=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const TRUST_PROXY="trust proxy";const APP_RECEIVER=/^(app|server|router|express)$/i;function isAppMethodCall(node,method){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 APP_RECEIVER.test(callee.object.name)}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:{hopCount:{type:"number",minimum:1,description:"Number of reverse proxies used in the suggested fix"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){const{hopCount}=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")){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"))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 eslint_devkit_1=require("@interlace/eslint-devkit");const TRUST_PROXY="trust proxy";const APP_RECEIVER=/^(app|server|router|express)$/i;function isAppMethodCall(node,method){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 APP_RECEIVER.test(callee.object.name)}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:{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}=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")){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"))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 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",hasSuggestions:true,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"}),moveToBody:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Move the secret out of the query string",description:"Accept the value from the POST body or an Authorization header instead",severity:"LOW",fix:"app.post('/login', (req, res) => { const { password } = req.body; })",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]){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},suggest:[{messageId:"moveToBody",fix:()=>null}]})}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",hasSuggestions:true,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"}),moveToBody:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Move the secret out of the query string",description:"Accept the value from the POST body or an Authorization header instead",severity:"LOW",fix:"app.post('/login', (req, res) => { const { password } = req.body; })",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},suggest:[{messageId:"moveToBody",fix:()=>null}]})}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 eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_ALLOWED_ROOTS=["public","static","dist","build","assets"];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]){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){context.report({node:call,messageId:"nonLiteralPath"});return}if(literalSegments.length===0){reportRoot(call,context.sourceCode.getText(call));return}if(!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.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=["public","static","dist","build","assets"];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){context.report({node:call,messageId:"nonLiteralPath"});return}if(literalSegments.length===0){reportRoot(call,context.sourceCode.getText(call));return}if(!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.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.noUnsafeCspDirectives=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");function canonicalDirective(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}const SCRIPT_DIRECTIVES=new Set(["default-src","script-src","script-src-elem","script-src-attr","object-src","worker-src"]);const STYLE_DIRECTIVES=new Set(["style-src","style-src-elem","style-src-attr"]);const UNSAFE_KEYWORDS=new Set(["'unsafe-inline'","'unsafe-eval'"]);const WILDCARD_SOURCES=new Set(["*","data:","http:","https:","http://*","https://*"]);function propertyKeyName(prop){if(prop.computed)return null;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return null}function isCspFactory(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.computed)return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return callee.object.name==="helmet"&&callee.property.name==="contentSecurityPolicy"}function isHelmetCall(node){return node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="helmet"}exports.noUnsafeCspDirectives=(0,eslint_devkit_1.createRule)({name:"no-unsafe-csp-directives",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-unsafe-csp-directives.md",description:"Disallow Content-Security-Policy directives that permit 'unsafe-inline', 'unsafe-eval', wildcard sources, or unrestricted framing",cwe:"CWE-79",cvss:6.5,confidence:"high"},messages:{unsafeInlineSource:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP Allows Unsafe Script Execution (CWE-79)",cwe:"CWE-79",cvss:6.5,description:"{{directive}} includes {{source}}, which re-enables exactly the script execution CSP is there to block \u2014 an injected <script> or eval() runs normally.",severity:"HIGH",fix:"Remove {{source}} and use a per-response nonce or hash source instead: scriptSrc: [\"'self'\", (req, res) => `'nonce-${res.locals.nonce}'`].",documentationLink:"https://cwe.mitre.org/data/definitions/79.html"}),wildcardSource:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP Wildcard Source (CWE-79)",cwe:"CWE-79",cvss:6.5,description:"{{directive}} includes the wildcard source {{source}}, so script can be loaded from any host \u2014 the directive stops constraining anything.",severity:"HIGH",fix:"List the exact origins the app loads code from instead of a wildcard scheme or host.",documentationLink:"https://cwe.mitre.org/data/definitions/79.html"}),permissiveFrameAncestors:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP Permits Framing By Any Origin (CWE-1021)",cwe:"CWE-1021",cvss:5.4,description:"frame-ancestors is set to {{source}}, so any site can embed this app in an iframe and drive clicks through it (clickjacking).",severity:"MEDIUM",fix:`Set frameAncestors: ["'self'"] \u2014 or name the exact origins allowed to frame the app.`,documentationLink:"https://cwe.mitre.org/data/definitions/1021.html"}),missingFrameAncestors:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP Without frame-ancestors (CWE-1021)",cwe:"CWE-1021",cvss:5.4,description:"useDefaults is false and no frame-ancestors directive is set. frame-ancestors does NOT fall back to default-src, so this policy places no limit on who may frame the app.",severity:"MEDIUM",fix:"Add frameAncestors: [\"'self'\"] to the directives object, or drop `useDefaults: false` and keep helmet's defaults.",documentationLink:"https://cwe.mitre.org/data/definitions/1021.html"}),mixedContentAllowed:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP Mixed-Content Upgrade Removed (CWE-311)",cwe:"CWE-311",cvss:5.9,description:"upgradeInsecureRequests is set to null, which removes the directive from the policy. Sub-resources referenced over http:// are then fetched in cleartext from an https:// page.",severity:"MEDIUM",fix:"Delete the `upgradeInsecureRequests: null` entry so the directive stays in the policy.",documentationLink:"https://cwe.mitre.org/data/definitions/311.html"}),removeUnsafeSource:"Remove {{source}} from {{directive}}"},schema:[{type:"object",properties:{checkStyleSrc:{type:"boolean",description:"Also report unsafe sources in style-executing directives"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){const{checkStyleSrc}=options;const withStyle=checkStyleSrc??true;function removeElement(fixer,element){const sourceCode=context.sourceCode;const after=sourceCode.getTokenAfter(element);if(after&&after.value===","){return fixer.removeRange([element.range[0],after.range[1]])}const before=sourceCode.getTokenBefore(element);if(before&&before.value===","){return fixer.removeRange([before.range[0],element.range[1]])}return fixer.remove(element)}function reportSource(element,messageId,directive,source){context.report({node:element,messageId,data:{directive,source},suggest:[{messageId:"removeUnsafeSource",data:{directive,source},fix:fixer=>removeElement(fixer,element)}]})}function checkSources(directive,value){if(value.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return;const isScript=SCRIPT_DIRECTIVES.has(directive);const isStyle=withStyle&&STYLE_DIRECTIVES.has(directive);const isFrameAncestors=directive==="frame-ancestors";if(!isScript&&!isStyle&&!isFrameAncestors)return;for(const element of value.elements){if(!element)continue;if(element.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)continue;if(typeof element.value!=="string")continue;const source=element.value;if(isFrameAncestors){if(source==="*"){context.report({node:element,messageId:"permissiveFrameAncestors",data:{source:"'*'"}})}continue}if(UNSAFE_KEYWORDS.has(source)){reportSource(element,"unsafeInlineSource",directive,source);continue}if(WILDCARD_SOURCES.has(source)){reportSource(element,"wildcardSource",directive,`'${source}'`)}}}function checkDirectives(directives,useDefaultsDisabled){let sawFrameAncestors=false;for(const prop of directives.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=propertyKeyName(prop);if(!name)continue;const directive=canonicalDirective(name);if(directive==="frame-ancestors"){sawFrameAncestors=true}if(directive==="upgrade-insecure-requests"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value===null){context.report({node:prop,messageId:"mixedContentAllowed"});continue}checkSources(directive,prop.value)}if(useDefaultsDisabled&&!sawFrameAncestors){context.report({node:directives,messageId:"missingFrameAncestors"})}}function checkCspConfig(config){if(config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;let directives=null;let useDefaultsDisabled=false;for(const prop of config.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=propertyKeyName(prop);if(name==="directives"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){directives=prop.value}continue}if(name==="useDefaults"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value===false){useDefaultsDisabled=true}}if(directives){checkDirectives(directives,useDefaultsDisabled)}}return{CallExpression(node){if(isCspFactory(node)){const config2=node.arguments[0];if(config2)checkCspConfig(config2);return}if(!isHelmetCall(node))return;const config=node.arguments[0];if(!config||config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;for(const prop of config.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(propertyKeyName(prop)!=="contentSecurityPolicy")continue;checkCspConfig(prop.value)}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeCspDirectives=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");function canonicalDirective(name){return name.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}const SCRIPT_DIRECTIVES=new Set(["default-src","script-src","script-src-elem","script-src-attr","object-src","worker-src"]);const STYLE_DIRECTIVES=new Set(["style-src","style-src-elem","style-src-attr"]);const UNSAFE_KEYWORDS=new Set(["'unsafe-inline'","'unsafe-eval'"]);const WILDCARD_SOURCES=new Set(["*","data:","http:","https:","http://*","https://*"]);function propertyKeyName(prop){if(prop.computed)return null;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return null}function isCspFactory(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.computed)return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return callee.object.name==="helmet"&&callee.property.name==="contentSecurityPolicy"}function isHelmetCall(node){return node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="helmet"}exports.noUnsafeCspDirectives=(0,eslint_devkit_1.createRule)({name:"no-unsafe-csp-directives",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/no-unsafe-csp-directives.md",description:"Disallow Content-Security-Policy directives that permit 'unsafe-inline', 'unsafe-eval', wildcard sources, or unrestricted framing",cwe:"CWE-79",cvss:6.5,confidence:"high"},messages:{unsafeInlineSource:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP Allows Unsafe Script Execution (CWE-79)",cwe:"CWE-79",cvss:6.5,description:"{{directive}} includes {{source}}, which re-enables exactly the script execution CSP is there to block \u2014 an injected <script> or eval() runs normally.",severity:"HIGH",fix:"Remove {{source}} and use a per-response nonce or hash source instead: scriptSrc: [\"'self'\", (req, res) => `'nonce-${res.locals.nonce}'`].",documentationLink:"https://cwe.mitre.org/data/definitions/79.html"}),wildcardSource:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP Wildcard Source (CWE-79)",cwe:"CWE-79",cvss:6.5,description:"{{directive}} includes the wildcard source {{source}}, so script can be loaded from any host \u2014 the directive stops constraining anything.",severity:"HIGH",fix:"List the exact origins the app loads code from instead of a wildcard scheme or host.",documentationLink:"https://cwe.mitre.org/data/definitions/79.html"}),permissiveFrameAncestors:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP Permits Framing By Any Origin (CWE-1021)",cwe:"CWE-1021",cvss:5.4,description:"frame-ancestors is set to {{source}}, so any site can embed this app in an iframe and drive clicks through it (clickjacking).",severity:"MEDIUM",fix:`Set frameAncestors: ["'self'"] \u2014 or name the exact origins allowed to frame the app.`,documentationLink:"https://cwe.mitre.org/data/definitions/1021.html"}),missingFrameAncestors:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP Without frame-ancestors (CWE-1021)",cwe:"CWE-1021",cvss:5.4,description:"useDefaults is false and no frame-ancestors directive is set. frame-ancestors does NOT fall back to default-src, so this policy places no limit on who may frame the app.",severity:"MEDIUM",fix:"Add frameAncestors: [\"'self'\"] to the directives object, or drop `useDefaults: false` and keep helmet's defaults.",documentationLink:"https://cwe.mitre.org/data/definitions/1021.html"}),mixedContentAllowed:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"CSP Mixed-Content Upgrade Removed (CWE-311)",cwe:"CWE-311",cvss:5.9,description:"upgradeInsecureRequests is set to null, which removes the directive from the policy. Sub-resources referenced over http:// are then fetched in cleartext from an https:// page.",severity:"MEDIUM",fix:"Delete the `upgradeInsecureRequests: null` entry so the directive stays in the policy.",documentationLink:"https://cwe.mitre.org/data/definitions/311.html"}),removeUnsafeSource:"Remove {{source}} from {{directive}}"},schema:[{type:"object",properties:{checkStyleSrc:{type:"boolean",description:"Also report unsafe sources in style-executing directives"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{checkStyleSrc}=options;const withStyle=checkStyleSrc??true;function removeElement(fixer,element){const sourceCode=context.sourceCode;const after=sourceCode.getTokenAfter(element);if(after&&after.value===","){return fixer.removeRange([element.range[0],after.range[1]])}const before=sourceCode.getTokenBefore(element);if(before&&before.value===","){return fixer.removeRange([before.range[0],element.range[1]])}return fixer.remove(element)}function reportSource(element,messageId,directive,source){context.report({node:element,messageId,data:{directive,source},suggest:[{messageId:"removeUnsafeSource",data:{directive,source},fix:fixer=>removeElement(fixer,element)}]})}function checkSources(directive,value){if(value.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return;const isScript=SCRIPT_DIRECTIVES.has(directive);const isStyle=withStyle&&STYLE_DIRECTIVES.has(directive);const isFrameAncestors=directive==="frame-ancestors";if(!isScript&&!isStyle&&!isFrameAncestors)return;for(const element of value.elements){if(!element)continue;if(element.type!==eslint_devkit_1.AST_NODE_TYPES.Literal)continue;if(typeof element.value!=="string")continue;const source=element.value;if(isFrameAncestors){if(source==="*"){context.report({node:element,messageId:"permissiveFrameAncestors",data:{source:"'*'"}})}continue}if(UNSAFE_KEYWORDS.has(source)){reportSource(element,"unsafeInlineSource",directive,source);continue}if(WILDCARD_SOURCES.has(source)){reportSource(element,"wildcardSource",directive,`'${source}'`)}}}function checkDirectives(directives,useDefaultsDisabled){let sawFrameAncestors=false;for(const prop of directives.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=propertyKeyName(prop);if(!name)continue;const directive=canonicalDirective(name);if(directive==="frame-ancestors"){sawFrameAncestors=true}if(directive==="upgrade-insecure-requests"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value===null){context.report({node:prop,messageId:"mixedContentAllowed"});continue}checkSources(directive,prop.value)}if(useDefaultsDisabled&&!sawFrameAncestors){context.report({node:directives,messageId:"missingFrameAncestors"})}}function checkCspConfig(config){if(config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;let directives=null;let useDefaultsDisabled=false;for(const prop of config.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=propertyKeyName(prop);if(name==="directives"){if(prop.value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){directives=prop.value}continue}if(name==="useDefaults"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value===false){useDefaultsDisabled=true}}if(directives){checkDirectives(directives,useDefaultsDisabled)}}return{CallExpression(node){if(isCspFactory(node)){const config2=node.arguments[0];if(config2)checkCspConfig(config2);return}if(!isHelmetCall(node))return;const config=node.arguments[0];if(!config||config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;for(const prop of config.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;if(propertyKeyName(prop)!=="contentSecurityPolicy")continue;checkCspConfig(prop.value)}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUserControlledRedirect=void 0;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"]);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]){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 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;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"]);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 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;context.report({node:firstArg,messageId:"openRedirect",data:{source}})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUserControlledRenderLocals=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const USER_SOURCE_PROPS=new Set(["body","query","params"]);const RESPONSE_NAMES=new Set(["res","response","reply"]);const REQUEST_NAMES=new Set(["req","request","ctx"]);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]){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 isRequestName(name){return REQUEST_NAMES.has(name.toLowerCase())}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(!isRequestName(object.name))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 RESPONSE_NAMES.has(obj.name.toLowerCase())}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"]);const RESPONSE_NAMES=new Set(["res","response","reply"]);const REQUEST_NAMES=new Set(["req","request","ctx"]);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 isRequestName(name){return REQUEST_NAMES.has(name.toLowerCase())}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(!isRequestName(object.name))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 RESPONSE_NAMES.has(obj.name.toLowerCase())}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 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]){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 node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"}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.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 node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"}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 eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_PROTECTED_METHODS=["post","put","patch","delete"];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 hasCsrfInMiddlewareChain(node,sourceCode){const text=sourceCode.getText(node);return/\b(csrf|csurf|csrfProtection|csrfMiddleware)\s*\(?\)?/.test(text)}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},hasSuggestions:true,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"}),addCsrf:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add CSRF Protection",description:"Add CSRF middleware to protect state-changing requests",severity:"LOW",fix:"npm install csurf; app.use(csurf({ cookie: true }))",documentationLink:"https://www.npmjs.com/package/csurf"})},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]){const{allowInTests=false,protectedMethods=DEFAULT_PROTECTED_METHODS,ignorePatterns=[]}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;let hasGlobalCsrf=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}}}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const method=callee.property.name.toLowerCase();if(!protectedMethods.includes(method)){return}if(!isLikelyExpressObject(callee)){return}if(hasGlobalCsrf){return}const routeArg=node.arguments[0];if(routeArg&&shouldIgnoreRoute(routeArg)){return}if(hasCsrfInMiddlewareChain(node,sourceCode)){return}context.report({node,messageId:"missingCsrf",data:{method:method.toUpperCase()},suggest:[{messageId:"addCsrf",fix:()=>null}]})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireCsrfProtection=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_PROTECTED_METHODS=["post","put","patch","delete"];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 hasCsrfInMiddlewareChain(node,sourceCode){const text=sourceCode.getText(node);return/\b(csrf|csurf|csrfProtection|csrfMiddleware)\s*\(?\)?/.test(text)}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},hasSuggestions:true,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"}),addCsrf:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add CSRF Protection",description:"Add CSRF middleware to protect state-changing requests",severity:"LOW",fix:"npm install csurf; app.use(csurf({ cookie: true }))",documentationLink:"https://www.npmjs.com/package/csurf"})},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{};const{allowInTests=false,protectedMethods=DEFAULT_PROTECTED_METHODS,ignorePatterns=[]}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}const sourceCode=context.sourceCode;let hasGlobalCsrf=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}}}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const method=callee.property.name.toLowerCase();if(!protectedMethods.includes(method)){return}if(!isLikelyExpressObject(callee)){return}if(hasGlobalCsrf){return}const routeArg=node.arguments[0];if(routeArg&&shouldIgnoreRoute(routeArg)){return}if(hasCsrfInMiddlewareChain(node,sourceCode)){return}context.report({node,messageId:"missingCsrf",data:{method:method.toUpperCase()},suggest:[{messageId:"addCsrf",fix:()=>null}]})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireExpressBodyParserLimits=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_EXCESSIVE_LIMITS=["10mb","50mb","100mb","500mb","1gb","1GB","10MB","50MB","100MB","500MB"];const BODY_PARSER_METHODS=new Set(["json","urlencoded","raw","text"]);function getLimitOption(properties){for(const prop of properties){if(prop.type==="Property"&&prop.key.type==="Identifier"&&prop.key.name==="limit"){return prop}}return null}function isExcessiveLimit(value,excessiveLimits){if(value.type==="Literal"&&typeof value.value==="string"){return excessiveLimits.some(limit=>value.value===limit||String(value.value).toLowerCase()===limit.toLowerCase())}return false}exports.requireExpressBodyParserLimits=(0,eslint_devkit_1.createRule)({name:"require-express-body-parser-limits",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-express-body-parser-limits.md",description:"Require size limits on Express.js body parsers to prevent DoS attacks",cwe:"CWE-400",cvss:7.5},hasSuggestions:true,messages:{missingLimit:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Body Parser Limit",cwe:"CWE-400",description:"Body parser used without explicit size limit. Attackers can exhaust server memory with large payloads. CVE-2024-45590.",severity:"HIGH",fix:"Add a size limit: express.json({ limit: '10kb' }) or express.json({ limit: '100kb' })",documentationLink:"https://expressjs.com/en/4x/api.html#express.json"}),excessiveLimit:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Excessive Body Parser Limit",cwe:"CWE-400",description:"Body parser limit is excessively high, making the application vulnerable to DoS attacks via large payloads.",severity:"MEDIUM",fix:"Reduce the limit to a reasonable size: '100kb' for JSON APIs, '1mb' for file uploads with proper handling",documentationLink:"https://expressjs.com/en/4x/api.html#express.json"}),addLimit:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Size Limit",description:"Add a size limit to the body parser",severity:"LOW",fix:"Add limit: '100kb' or appropriate size for your use case",documentationLink:"https://expressjs.com/en/4x/api.html#express.json"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"},maxLimit:{type:"number",default:102400,description:"Maximum allowed limit in bytes"},excessiveLimits:{type:"array",items:{type:"string"},default:DEFAULT_EXCESSIVE_LIMITS,description:"Limits considered excessive"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,maxLimit:102400,excessiveLimits:DEFAULT_EXCESSIVE_LIMITS}],create(context,[options]){const{allowInTests=false,excessiveLimits=DEFAULT_EXCESSIVE_LIMITS}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}return{CallExpression(node){const callee=node.callee;if(callee.type!=="MemberExpression"){return}const object=callee.object;const property=callee.property;if(object.type!=="Identifier"){return}if(object.name!=="express"&&object.name!=="bodyParser"){return}if(property.type!=="Identifier"){return}if(!BODY_PARSER_METHODS.has(property.name)){return}const firstArg=node.arguments[0];if(!firstArg){const sourceCode=context.sourceCode;const calleeText=sourceCode.getText(callee);context.report({node,messageId:"missingLimit",suggest:[{messageId:"addLimit",fix:fixer=>{return fixer.replaceText(node,`${calleeText}({ limit: '100kb' })`)}}]});return}if(firstArg.type==="ObjectExpression"){const limitProp=getLimitOption(firstArg.properties);if(!limitProp){context.report({node,messageId:"missingLimit",suggest:[{messageId:"addLimit",fix:fixer=>{const lastProp=firstArg.properties[firstArg.properties.length-1];if(lastProp){return fixer.insertTextAfter(lastProp,", limit: '100kb'")}return null}}]});return}if(isExcessiveLimit(limitProp.value,excessiveLimits)){context.report({node:limitProp,messageId:"excessiveLimit"})}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireExpressBodyParserLimits=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_EXCESSIVE_LIMITS=["10mb","50mb","100mb","500mb","1gb","1GB","10MB","50MB","100MB","500MB"];const BODY_PARSER_METHODS=new Set(["json","urlencoded","raw","text"]);function getLimitOption(properties){for(const prop of properties){if(prop.type==="Property"&&prop.key.type==="Identifier"&&prop.key.name==="limit"){return prop}}return null}function isExcessiveLimit(value,excessiveLimits){if(value.type==="Literal"&&typeof value.value==="string"){return excessiveLimits.some(limit=>value.value===limit||String(value.value).toLowerCase()===limit.toLowerCase())}return false}exports.requireExpressBodyParserLimits=(0,eslint_devkit_1.createRule)({name:"require-express-body-parser-limits",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-express-body-parser-limits.md",description:"Require size limits on Express.js body parsers to prevent DoS attacks",cwe:"CWE-400",cvss:7.5},hasSuggestions:true,messages:{missingLimit:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Body Parser Limit",cwe:"CWE-400",description:"Body parser used without explicit size limit. Attackers can exhaust server memory with large payloads. CVE-2024-45590.",severity:"HIGH",fix:"Add a size limit: express.json({ limit: '10kb' }) or express.json({ limit: '100kb' })",documentationLink:"https://expressjs.com/en/4x/api.html#express.json"}),excessiveLimit:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Excessive Body Parser Limit",cwe:"CWE-400",description:"Body parser limit is excessively high, making the application vulnerable to DoS attacks via large payloads.",severity:"MEDIUM",fix:"Reduce the limit to a reasonable size: '100kb' for JSON APIs, '1mb' for file uploads with proper handling",documentationLink:"https://expressjs.com/en/4x/api.html#express.json"}),addLimit:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Size Limit",description:"Add a size limit to the body parser",severity:"LOW",fix:"Add limit: '100kb' or appropriate size for your use case",documentationLink:"https://expressjs.com/en/4x/api.html#express.json"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow in test files"},maxLimit:{type:"number",default:102400,description:"Maximum allowed limit in bytes"},excessiveLimits:{type:"array",items:{type:"string"},default:DEFAULT_EXCESSIVE_LIMITS,description:"Limits considered excessive"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,maxLimit:102400,excessiveLimits:DEFAULT_EXCESSIVE_LIMITS}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{allowInTests=false,excessiveLimits=DEFAULT_EXCESSIVE_LIMITS}=options;const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}return{CallExpression(node){const callee=node.callee;if(callee.type!=="MemberExpression"){return}const object=callee.object;const property=callee.property;if(object.type!=="Identifier"){return}if(object.name!=="express"&&object.name!=="bodyParser"){return}if(property.type!=="Identifier"){return}if(!BODY_PARSER_METHODS.has(property.name)){return}const firstArg=node.arguments[0];if(!firstArg){const sourceCode=context.sourceCode;const calleeText=sourceCode.getText(callee);context.report({node,messageId:"missingLimit",suggest:[{messageId:"addLimit",fix:fixer=>{return fixer.replaceText(node,`${calleeText}({ limit: '100kb' })`)}}]});return}if(firstArg.type==="ObjectExpression"){const limitProp=getLimitOption(firstArg.properties);if(!limitProp){context.report({node,messageId:"missingLimit",suggest:[{messageId:"addLimit",fix:fixer=>{const lastProp=firstArg.properties[firstArg.properties.length-1];if(lastProp){return fixer.insertTextAfter(lastProp,", limit: '100kb'")}return null}}]});return}if(isExcessiveLimit(limitProp.value,excessiveLimits)){context.report({node:limitProp,messageId:"excessiveLimit"})}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireHelmet=void 0;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"},hasSuggestions:true,messages:{missingHelmet:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Security Headers",cwe:"CWE-693",description:"Express app created without helmet middleware. Missing security headers: X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security, etc.",severity:"HIGH",fix:"Add helmet middleware: app.use(helmet()). Install with 'npm install helmet'.",documentationLink:"https://helmetjs.github.io/"}),addHelmet:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Helmet",description:"Add helmet middleware for security headers",severity:"LOW",fix:"import helmet from 'helmet'; app.use(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]){const{allowInTests=false,alternativeMiddleware=[],assumeHelmetMiddleware=false}=options;if(assumeHelmetMiddleware){return{}}const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}let hasExpressApp=false;let hasHelmet=false;let expressAppNode=null;return{CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="express"){hasExpressApp=true;expressAppNode=node;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&&expressAppNode){context.report({node:expressAppNode,messageId:"missingHelmet",suggest:[{messageId:"addHelmet",fix:()=>null}]})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireHelmet=void 0;const express_evidence_1=require("../../utils/express-evidence");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"},hasSuggestions:true,messages:{missingHelmet:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Security Headers",cwe:"CWE-693",description:"Express app created without helmet middleware. Missing security headers: X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security, etc.",severity:"HIGH",fix:"Add helmet middleware: app.use(helmet()). Install with 'npm install helmet'.",documentationLink:"https://helmetjs.github.io/"}),addHelmet:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Helmet",description:"Add helmet middleware for security headers",severity:"LOW",fix:"import helmet from 'helmet'; app.use(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{};const{allowInTests=false,alternativeMiddleware=[],assumeHelmetMiddleware=false}=options;if(assumeHelmetMiddleware){return{}}const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}let hasExpressApp=false;let hasHelmet=false;let expressAppNode=null;let appBinding=null;let appEscapes=false;return{CallExpression(node){const callee=node.callee;if(appBinding!==null){for(const arg of node.arguments){if(arg.type==="Identifier"&&arg.name===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",suggest:[{messageId:"addHelmet",fix:()=>null}]})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireQueryTypeGuard=void 0;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]){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.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 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireRateLimiting=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");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},hasSuggestions:true,messages:{missingRateLimiting:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Rate Limiting",cwe:"CWE-770",description:"Express app created without rate limiting. Vulnerable to DDoS and brute-force attacks.",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"}),addRateLimiting:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Rate Limiting",description:"Add rate limiting middleware to protect against abuse",severity:"LOW",fix:"import rateLimit from '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:{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{allowInTests=false,alternativeMiddleware=[],assumeRateLimiting=false}=options;if(assumeRateLimiting){return{}}const filename=context.filename;const isTestFile=allowInTests&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}let hasExpressApp=false;let hasRateLimiting=false;let expressAppNode=null;return{CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"&&callee.name==="express"){hasExpressApp=true;expressAppNode=node;return}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="use"){if(isRateLimitMiddleware(node,alternativeMiddleware)){hasRateLimiting=true}}},"Program:exit"(){if(hasExpressApp&&!hasRateLimiting&&expressAppNode){context.report({node:expressAppNode,messageId:"missingRateLimiting",suggest:[{messageId:"addRateLimiting",fix:()=>null}]})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireRateLimiting=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");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},hasSuggestions:true,messages:{missingRateLimiting:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Rate Limiting",cwe:"CWE-770",description:"Express app created without rate limiting. Vulnerable to DDoS and brute-force attacks.",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"}),addRateLimiting:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Add Rate Limiting",description:"Add rate limiting middleware to protect against abuse",severity:"LOW",fix:"import rateLimit from '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:{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]){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&&/\.(test|spec)\.(ts|tsx|js|jsx)$/.test(filename);if(isTestFile){return{}}let hasExpressApp=false;let hasRateLimiting=false;let expressAppNode=null;let appBinding=null;let appEscapes=false;return{CallExpression(node){const callee=node.callee;if(appBinding!==null){for(const arg of node.arguments){if(arg.type==="Identifier"&&arg.name===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==="MemberExpression"&&callee.property.type==="Identifier"&&callee.property.name==="use"){if(isRateLimitMiddleware(node,alternativeMiddleware)){hasRateLimiting=true}}},"Program:exit"(){if(hasExpressApp&&!hasRateLimiting&&!appEscapes&&expressAppNode){context.report({node:expressAppNode,messageId:"missingRateLimiting",suggest:[{messageId:"addRateLimiting",fix:()=>null}]})}}}}});
@@ -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 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","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"]);const APP_RECEIVER=/^(app|router|express|api)$/i;function matchesFragment(path,fragment){const escaped=fragment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-z0-9])${escaped}s?([^a-z0-9]|$)`).test(path)}const AUTH_MIDDLEWARE=/auth|jwt|passport|token|session|guard|protect|ensure|require|permit|acl|rbac|verify|login|identity|principal/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:{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]){const{criticalPaths,publicPaths,authMiddleware}=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 candidates=[];let hasGlobalAuth=false;function isAuthMiddlewareArg(arg){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 text=context.sourceCode.getText(arg);if(AUTH_MIDDLEWARE.test(text))return true;for(const name of extraAuth){if(text.includes(name))return true}return 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(!APP_RECEIVER.test(callee.object.name))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&&isAuthMiddlewareArg(arg)){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 chain=rest.slice(0,-1);if(chain.some(arg=>isAuthMiddlewareArg(arg)))return;const handler=rest[rest.length-1];if((0,utils_1.readsPrincipal)(handler))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 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","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"]);const APP_RECEIVER=/^(app|router|express|api)$/i;function matchesFragment(path,fragment){const escaped=fragment.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-z0-9])${escaped}s?([^a-z0-9]|$)`).test(path)}const AUTH_MIDDLEWARE=/auth|jwt|passport|token|session|guard|protect|ensure|require|permit|acl|rbac|verify|login|identity|principal/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:{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}=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 candidates=[];let hasGlobalAuth=false;function isAuthMiddlewareArg(arg){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 text=context.sourceCode.getText(arg);if(AUTH_MIDDLEWARE.test(text))return true;for(const name of extraAuth){if(text.includes(name))return true}return 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(!APP_RECEIVER.test(callee.object.name))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&&isAuthMiddlewareArg(arg)){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 chain=rest.slice(0,-1);if(chain.some(arg=>isAuthMiddlewareArg(arg)))return;const handler=rest[rest.length-1];if((0,utils_1.readsPrincipal)(handler))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.requireStrictTransportSecurity=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_MIN_MAX_AGE=15552e3;const HSTS_NAMES=new Set(["hsts","strictTransportSecurity"]);function propertyKeyName(prop){if(prop.computed)return null;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return null}function isHelmetHstsFactory(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.computed)return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return callee.object.name==="helmet"&&HSTS_NAMES.has(callee.property.name)}function isHelmetCall(node){return node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="helmet"}exports.requireStrictTransportSecurity=(0,eslint_devkit_1.createRule)({name:"require-strict-transport-security",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-strict-transport-security.md",description:"Require a Strict-Transport-Security header with a long max-age and includeSubDomains",cwe:"CWE-319",cvss:7.4,confidence:"high"},messages:{hstsDisabled:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"HSTS Disabled (CWE-319)",cwe:"CWE-319",cvss:7.4,description:"helmet({ {{option}}: false }) removes the Strict-Transport-Security header. Every first request of a session can then be downgraded to plaintext HTTP and stripped in transit.",severity:"HIGH",fix:"Remove the `{{option}}: false` entry, or configure it: { maxAge: 31536000, includeSubDomains: true, preload: true }.",documentationLink:"https://cwe.mitre.org/data/definitions/319.html"}),maxAgeTooShort:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"HSTS max-age Too Short (CWE-319)",cwe:"CWE-319",cvss:5.9,description:"Strict-Transport-Security max-age is {{maxAge}}s, below the {{minimum}}s floor. Once it lapses, the next visit is downgradeable again.",severity:"MEDIUM",fix:"Set maxAge to at least {{minimum}} seconds. Preload submission (hstspreload.org) requires 31536000 \u2014 one year \u2014 plus includeSubDomains and preload.",documentationLink:"https://hstspreload.org/"}),subdomainsExcluded:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"HSTS Excludes Subdomains (CWE-319)",cwe:"CWE-319",cvss:5.9,description:"includeSubDomains is off, so any subdomain still answers over plaintext HTTP \u2014 enough to plant a cookie the parent domain trusts.",severity:"MEDIUM",fix:"Set includeSubDomains: true once every subdomain serves HTTPS.",documentationLink:"https://cwe.mitre.org/data/definitions/319.html"}),raiseMaxAge:"Raise maxAge to {{minimum}} seconds"},schema:[{type:"object",properties:{minMaxAge:{type:"number",minimum:0,description:"Minimum accepted max-age in seconds"},requireSubDomains:{type:"boolean",description:"Require includeSubDomains"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){const{minMaxAge,requireSubDomains}=options;const minimum=minMaxAge??DEFAULT_MIN_MAX_AGE;const wantSubDomains=requireSubDomains??true;function checkHstsOptions(config){for(const prop of config.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=propertyKeyName(prop);if(!name)continue;if(name==="maxAge"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value.value==="number"&&prop.value.value<minimum){const maxAgeNode=prop.value;context.report({node:prop,messageId:"maxAgeTooShort",data:{maxAge:String(maxAgeNode.value),minimum:String(minimum)},suggest:[{messageId:"raiseMaxAge",data:{minimum:String(minimum)},fix:fixer=>fixer.replaceText(maxAgeNode,String(minimum))}]});continue}if(wantSubDomains&&name==="includeSubDomains"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value===false){context.report({node:prop,messageId:"subdomainsExcluded"})}}}function checkHstsValue(node,value,option){if(value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&value.value===false){context.report({node,messageId:"hstsDisabled",data:{option}});return}if(value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkHstsOptions(value)}}return{CallExpression(node){if(isHelmetHstsFactory(node)){const config2=node.arguments[0];if(config2&&config2.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkHstsOptions(config2)}return}if(!isHelmetCall(node))return;const config=node.arguments[0];if(!config||config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;for(const prop of config.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=propertyKeyName(prop);if(!name||!HSTS_NAMES.has(name))continue;checkHstsValue(prop,prop.value,name)}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.requireStrictTransportSecurity=void 0;const express_evidence_1=require("../../utils/express-evidence");const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_MIN_MAX_AGE=15552e3;const HSTS_NAMES=new Set(["hsts","strictTransportSecurity"]);function propertyKeyName(prop){if(prop.computed)return null;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return null}function isHelmetHstsFactory(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.computed)return false;if(callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return callee.object.name==="helmet"&&HSTS_NAMES.has(callee.property.name)}function isHelmetCall(node){return node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="helmet"}exports.requireStrictTransportSecurity=(0,eslint_devkit_1.createRule)({name:"require-strict-transport-security",meta:{type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-express-security/docs/rules/require-strict-transport-security.md",description:"Require a Strict-Transport-Security header with a long max-age and includeSubDomains",cwe:"CWE-319",cvss:7.4,confidence:"high"},messages:{hstsDisabled:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"HSTS Disabled (CWE-319)",cwe:"CWE-319",cvss:7.4,description:"helmet({ {{option}}: false }) removes the Strict-Transport-Security header. Every first request of a session can then be downgraded to plaintext HTTP and stripped in transit.",severity:"HIGH",fix:"Remove the `{{option}}: false` entry, or configure it: { maxAge: 31536000, includeSubDomains: true, preload: true }.",documentationLink:"https://cwe.mitre.org/data/definitions/319.html"}),maxAgeTooShort:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"HSTS max-age Too Short (CWE-319)",cwe:"CWE-319",cvss:5.9,description:"Strict-Transport-Security max-age is {{maxAge}}s, below the {{minimum}}s floor. Once it lapses, the next visit is downgradeable again.",severity:"MEDIUM",fix:"Set maxAge to at least {{minimum}} seconds. Preload submission (hstspreload.org) requires 31536000 \u2014 one year \u2014 plus includeSubDomains and preload.",documentationLink:"https://hstspreload.org/"}),subdomainsExcluded:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"HSTS Excludes Subdomains (CWE-319)",cwe:"CWE-319",cvss:5.9,description:"includeSubDomains is off, so any subdomain still answers over plaintext HTTP \u2014 enough to plant a cookie the parent domain trusts.",severity:"MEDIUM",fix:"Set includeSubDomains: true once every subdomain serves HTTPS.",documentationLink:"https://cwe.mitre.org/data/definitions/319.html"}),raiseMaxAge:"Raise maxAge to {{minimum}} seconds"},schema:[{type:"object",properties:{minMaxAge:{type:"number",minimum:0,description:"Minimum accepted max-age in seconds"},requireSubDomains:{type:"boolean",description:"Require includeSubDomains"}},additionalProperties:false}]},defaultOptions:[{}],create(context,[options]){if(!(0,express_evidence_1.fileUsesExpress)(context.sourceCode.ast))return{};const{minMaxAge,requireSubDomains}=options;const minimum=minMaxAge??DEFAULT_MIN_MAX_AGE;const wantSubDomains=requireSubDomains??true;function checkHstsOptions(config){for(const prop of config.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=propertyKeyName(prop);if(!name)continue;if(name==="maxAge"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof prop.value.value==="number"&&prop.value.value<minimum){const maxAgeNode=prop.value;context.report({node:prop,messageId:"maxAgeTooShort",data:{maxAge:String(maxAgeNode.value),minimum:String(minimum)},suggest:[{messageId:"raiseMaxAge",data:{minimum:String(minimum)},fix:fixer=>fixer.replaceText(maxAgeNode,String(minimum))}]});continue}if(wantSubDomains&&name==="includeSubDomains"&&prop.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&prop.value.value===false){context.report({node:prop,messageId:"subdomainsExcluded"})}}}function checkHstsValue(node,value,option){if(value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&value.value===false){context.report({node,messageId:"hstsDisabled",data:{option}});return}if(value.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkHstsOptions(value)}}return{CallExpression(node){if(isHelmetHstsFactory(node)){const config2=node.arguments[0];if(config2&&config2.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){checkHstsOptions(config2)}return}if(!isHelmetCall(node))return;const config=node.arguments[0];if(!config||config.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;for(const prop of config.properties){if(prop.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const name=propertyKeyName(prop);if(!name||!HSTS_NAMES.has(name))continue;checkHstsValue(prop,prop.value,name)}}}}});
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.fileUsesExpress=fileUsesExpress;const eslint_devkit_1=require("@interlace/eslint-devkit");const EXPRESS_PACKAGES=new Set(["express","express-serve-static-core"]);const REQ_NAMES=new Set(["req","request"]);const RES_NAMES=new Set(["res","response"]);function normalizeSpecifier(specifier){if(specifier.startsWith("npm:"))return specifier.slice(4);const deno=/^https?:\/\/deno\.land\/x\/([^@/]+)/.exec(specifier);if(deno)return deno[1];return specifier}function isExpressSpecifier(specifier){specifier=normalizeSpecifier(specifier);if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return EXPRESS_PACKAGES.has(root)}function isImportEqualsLoad(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.TSImportEqualsDeclaration&&node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference&&node.moduleReference.expression.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.moduleReference.expression.value==="string"&&isExpressSpecifier(node.moduleReference.expression.value)}function bindsRequire(node){if(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){return node.params.some(p=>p.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&p.name==="require")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Program||node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(stmt=>stmt.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclaration&&stmt.declarations.some(d=>d.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&d.id.name==="require"))}return false}function isExpressDynamicLoad(node,requireIsShadowed){const argument=node.type===eslint_devkit_1.AST_NODE_TYPES.ImportExpression?node.source:!requireIsShadowed&&node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"?node.arguments[0]:void 0;return argument?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof argument.value==="string"&&isExpressSpecifier(argument.value)}function hasMiddlewareSignature(node){if(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){return false}const params=node.params;if(params.length!==3&&params.length!==4)return false;const tail=params.slice(-3);if(tail.some(p=>p.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier))return false;const[first,second,third]=tail;return REQ_NAMES.has(first.name)&&RES_NAMES.has(second.name)&&third.name==="next"}const cache=new WeakMap;function fileUsesExpress(ast){const cached=cache.get(ast);if(cached!==void 0)return cached;const result=computeUsesExpress(ast);cache.set(ast,result);return result}function computeUsesExpress(ast){let found=false;const visit=(node,requireIsShadowed)=>{if((node.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.ExportNamedDeclaration||node.type===eslint_devkit_1.AST_NODE_TYPES.ExportAllDeclaration)&&node.source?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.source.value==="string"&&isExpressSpecifier(node.source.value)){found=true;return}if(isImportEqualsLoad(node)||isExpressDynamicLoad(node,requireIsShadowed)||hasMiddlewareSignature(node)){found=true;return}const shadowedHere=requireIsShadowed||bindsRequire(node);for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const child of value){if(child&&typeof child.type==="string"){visit(child,shadowedHere);if(found)return}}}else if(value&&typeof value==="object"&&typeof value.type==="string"){visit(value,shadowedHere);if(found)return}}};visit(ast,false);return found}