eslint-plugin-secure-coding 5.2.2 → 5.3.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 (31) hide show
  1. package/package.json +2 -2
  2. package/src/index.js +1 -1
  3. package/src/rules/detect-non-literal-regexp/index.js +1 -1
  4. package/src/rules/detect-object-injection/index.js +1 -1
  5. package/src/rules/detect-weak-password-validation/index.js +1 -1
  6. package/src/rules/no-directive-injection/index.js +1 -1
  7. package/src/rules/no-electron-security-issues/index.js +1 -1
  8. package/src/rules/no-fail-open-auth/index.js +1 -1
  9. package/src/rules/no-format-string-injection/index.js +1 -1
  10. package/src/rules/no-graphql-injection/index.js +1 -1
  11. package/src/rules/no-hardcoded-credentials/index.js +1 -1
  12. package/src/rules/no-improper-sanitization/index.js +1 -1
  13. package/src/rules/no-improper-type-validation/index.js +1 -1
  14. package/src/rules/no-insecure-comparison/index.js +1 -1
  15. package/src/rules/no-ldap-injection/index.js +1 -1
  16. package/src/rules/no-log-injection/index.js +1 -1
  17. package/src/rules/no-missing-authentication/index.js +1 -1
  18. package/src/rules/no-pii-in-logs/index.js +1 -1
  19. package/src/rules/no-privilege-escalation/index.js +1 -1
  20. package/src/rules/no-redos-vulnerable-regex/index.js +1 -1
  21. package/src/rules/no-sensitive-data-exposure/index.js +1 -1
  22. package/src/rules/no-sql-injection/index.js +1 -1
  23. package/src/rules/no-template-injection/index.js +1 -1
  24. package/src/rules/no-unchecked-loop-condition/index.js +1 -1
  25. package/src/rules/no-unlimited-resource-allocation/index.js +1 -1
  26. package/src/rules/no-unsafe-deserialization/index.js +1 -1
  27. package/src/rules/no-unsafe-regex-construction/index.js +1 -1
  28. package/src/rules/no-weak-password-recovery/index.js +1 -1
  29. package/src/rules/no-xpath-injection/index.js +1 -1
  30. package/src/rules/no-xxe-injection/index.js +1 -1
  31. package/src/utils/regexp-intrinsic.js +1 -1
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLogInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_LOGGER_RECEIVERS=["console","log","logger","winston","pino","bunyan"];const LOG_LEVEL_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];function requestFieldOf(node,roots,requestProperties){if(node.type!=="MemberExpression")return null;const properties=[];let root=node;while(root.type==="MemberExpression"){const property=root.property;if(!root.computed&&property.type==="Identifier"){properties.unshift(property.name)}else{const name=(0,eslint_devkit_1.staticString)(property);if(name!==null)properties.unshift(name)}root=root.object}if(root.type!=="Identifier")return null;if(!roots.has(root.name))return null;if(!properties.some(p=>requestProperties.has(p)))return null;return`${root.name}.${properties.join(".")}`}function findLocalVariable(scope,name){let current=scope;for(;;){const variable=current.set.get(name);if(variable)return variable;if(current.type==="function"||!current.upper)return null;current=current.upper}}function attributableSource(node,scope,roots,requestProperties){if(node.type==="Identifier"){const variable=findLocalVariable(scope,node.name);if(!variable)return null;const definition=variable.defs[0];if(!definition||definition.type!=="Variable"||!definition.node.init){return null}return requestFieldOf(definition.node.init,roots,requestProperties)}return requestFieldOf(node,roots,requestProperties)}function isMessageShaped(node){return node.type==="TemplateLiteral"||node.type==="BinaryExpression"&&node.operator==="+"}function directOperands(node,out){if(node.type==="TemplateLiteral"){for(const expression of node.expressions)out.push(expression);return}if(node.type==="BinaryExpression"&&node.operator==="+"){directOperands(node.left,out);directOperands(node.right,out);return}out.push(node)}function receiverName(object,receivers){if(object.type==="Identifier"){return receivers.has(object.name)?object.name:null}if(object.type==="MemberExpression"&&object.property.type==="Identifier"){return receivers.has(object.property.name)?object.property.name:null}return null}exports.noLogInjection=(0,eslint_devkit_1.createRule)({name:"no-log-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-log-injection.md",description:"Detects request data concatenated into a log message, which lets an attacker forge log records",cwe:"CWE-117",cvss:5.3},messages:{logInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Log Injection",cwe:"CWE-117",description:"Log message embeds {{source}} directly - a CR/LF in that value forges a log record",severity:"MEDIUM",fix:'Log it as a structured field (logger.info({ value }, "message")) or strip CR/LF/control characters first',documentationLink:"https://cwe.mitre.org/data/definitions/117.html"})},schema:[{type:"object",properties:{loggerReceivers:{type:"array",items:{type:"string"},default:DEFAULT_LOGGER_RECEIVERS,description:"Receiver names whose level methods write a log line, compared as an exact name and never as a substring. Replaces the built-in list."},loggerNames:{type:"array",items:{type:"string"},default:[],description:"Additional receiver names whose level methods write a log line, on top of `loggerReceivers`"},requestRootNames:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifier roots that denote an inbound request, matched as the exact ROOT of a member chain. Replaces the built-in list."},requestRoots:{type:"array",items:{type:"string"},default:[],description:"Additional identifier roots that denote an inbound request, on top of `requestRootNames`"},requestProperties:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_PROPERTIES,description:"Request properties that carry caller-supplied data, matched as a whole segment of the member chain. Replaces the built-in list."},additionalRequestProperties:{type:"array",items:{type:"string"},default:[],description:"Extra request properties, on top of `requestProperties` \u2014 hapi's `request.payload` belongs here"}},additionalProperties:false}]},defaultOptions:[{loggerReceivers:DEFAULT_LOGGER_RECEIVERS,loggerNames:[],requestRootNames:DEFAULT_REQUEST_ROOTS,requestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[]}],create(context){const options=context.options[0]??{};const receivers=new Set([...options.loggerReceivers??DEFAULT_LOGGER_RECEIVERS,...options.loggerNames??[]]);const roots=new Set([...options.requestRootNames??DEFAULT_REQUEST_ROOTS,...options.requestRoots??[]]);const requestProperties=new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]);const sourceCode=context.sourceCode;function isLoggingCall(node){const callee=node.callee;if(callee.type!=="MemberExpression")return false;if(callee.property.type!=="Identifier")return false;if(!LOG_LEVEL_METHODS.has(callee.property.name))return false;return receiverName(callee.object,receivers)!==null}return{CallExpression(node){if(!isLoggingCall(node))return;for(const argument of node.arguments){if(!isMessageShaped(argument))continue;const operands=[];directOperands(argument,operands);for(const operand of operands){const source=attributableSource(operand,sourceCode.getScope(operand),roots,requestProperties);if(source===null)continue;context.report({node:argument,messageId:"logInjection",data:{source}});return}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noLogInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_LOGGER_RECEIVERS=["console","log","logger","winston","pino","bunyan"];const LOG_LEVEL_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];function requestFieldOf(node,roots,requestProperties){if(node.type!=="MemberExpression")return null;const properties=[];let root=node;while(root.type==="MemberExpression"){const name=(0,eslint_devkit_1.propertyName)(root);if(name!==null)properties.unshift(name);root=root.object}if(root.type!=="Identifier")return null;if(!roots.has(root.name))return null;if(!properties.some(p=>requestProperties.has(p)))return null;return`${root.name}.${properties.join(".")}`}function findLocalVariable(scope,name){let current=scope;for(;;){const variable=current.set.get(name);if(variable)return variable;if(current.type==="function"||!current.upper)return null;current=current.upper}}function attributableSource(node,scope,roots,requestProperties){if(node.type==="Identifier"){const variable=findLocalVariable(scope,node.name);if(!variable)return null;const definition=variable.defs[0];if(!definition||definition.type!=="Variable"||!definition.node.init){return null}return requestFieldOf(definition.node.init,roots,requestProperties)}return requestFieldOf(node,roots,requestProperties)}function isMessageShaped(node){return node.type==="TemplateLiteral"||node.type==="BinaryExpression"&&node.operator==="+"}function directOperands(node,out){if(node.type==="TemplateLiteral"){for(const expression of node.expressions)out.push(expression);return}if(node.type==="BinaryExpression"&&node.operator==="+"){directOperands(node.left,out);directOperands(node.right,out);return}out.push(node)}function receiverName(object,receivers){if(object.type==="Identifier"){return receivers.has(object.name)?object.name:null}if(object.type==="MemberExpression"){const held=(0,eslint_devkit_1.propertyName)(object);return held!==null&&receivers.has(held)?held:null}return null}exports.noLogInjection=(0,eslint_devkit_1.createRule)({name:"no-log-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-log-injection.md",description:"Detects request data concatenated into a log message, which lets an attacker forge log records",cwe:"CWE-117",cvss:5.3},messages:{logInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Log Injection",cwe:"CWE-117",description:"Log message embeds {{source}} directly - a CR/LF in that value forges a log record",severity:"MEDIUM",fix:'Log it as a structured field (logger.info({ value }, "message")) or strip CR/LF/control characters first',documentationLink:"https://cwe.mitre.org/data/definitions/117.html"})},schema:[{type:"object",properties:{loggerReceivers:{type:"array",items:{type:"string"},default:DEFAULT_LOGGER_RECEIVERS,description:"Receiver names whose level methods write a log line, compared as an exact name and never as a substring. Replaces the built-in list."},loggerNames:{type:"array",items:{type:"string"},default:[],description:"Additional receiver names whose level methods write a log line, on top of `loggerReceivers`"},requestRootNames:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifier roots that denote an inbound request, matched as the exact ROOT of a member chain. Replaces the built-in list."},requestRoots:{type:"array",items:{type:"string"},default:[],description:"Additional identifier roots that denote an inbound request, on top of `requestRootNames`"},requestProperties:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_PROPERTIES,description:"Request properties that carry caller-supplied data, matched as a whole segment of the member chain. Replaces the built-in list."},additionalRequestProperties:{type:"array",items:{type:"string"},default:[],description:"Extra request properties, on top of `requestProperties` \u2014 hapi's `request.payload` belongs here"}},additionalProperties:false}]},defaultOptions:[{loggerReceivers:DEFAULT_LOGGER_RECEIVERS,loggerNames:[],requestRootNames:DEFAULT_REQUEST_ROOTS,requestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[]}],create(context){const options=context.options[0]??{};const receivers=new Set([...options.loggerReceivers??DEFAULT_LOGGER_RECEIVERS,...options.loggerNames??[]]);const roots=new Set([...options.requestRootNames??DEFAULT_REQUEST_ROOTS,...options.requestRoots??[]]);const requestProperties=new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]);const sourceCode=context.sourceCode;function isLoggingCall(node){const callee=node.callee;if(callee.type!=="MemberExpression")return false;if(!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),LOG_LEVEL_METHODS))return false;return receiverName(callee.object,receivers)!==null}return{CallExpression(node){if(!isLoggingCall(node))return;for(const argument of node.arguments){if(!isMessageShaped(argument))continue;const operands=[];directOperands(argument,operands);for(const operand of operands){const source=attributableSource(operand,sourceCode.getScope(operand),roots,requestProperties);if(source===null)continue;context.report({node:argument,messageId:"logInjection",data:{source}});return}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingAuthentication=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_AUTH_MIDDLEWARE_PATTERNS=["authenticate","auth","requireAuth","isAuthenticated","verifyToken","checkAuth","ensureAuthenticated","passport.authenticate","jwt","session"];const DEFAULT_PUBLIC_ROUTE_PATTERNS=["login","logout","signin","sign-in","signup","sign-up","register","forgot-password","reset-password","password-reset","verify-email","health","healthz","readyz","livez","alive","liveness","readiness","heartbeat","status","metrics","ping","favicon","webhook","/public/","oauth","callback"];const DEFAULT_ROUTE_HANDLER_PATTERNS=["get","post","put","delete","patch","all","use"];const ROUTER_NAME_WORDS=["app","router","route","server","express","fastify","koa","hapi"];const ROUTER_FACTORY_NAMES=new Set(["express","Router","fastify","polka","restify","connect","Koa"]);const ROUTER_FACTORY_MEMBERS=new Set(["Router","router","Server","server","createServer"]);function routeChainBase(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&current.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=current.callee.property;if(property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.name==="route"){return current}current=current.callee.object}return null}function isDefinitelyNotRouter(init){return init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression}function isRouterFactory(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return false}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_NAMES.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_MEMBERS.has(callee.property.name)}return false}function referencedName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.name}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const objectPart=node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${node.object.name}.`:"";return`${objectPart}${node.property.name}`}return null}function isAuthMiddlewareArg(arg,authPatterns){const target=arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression?arg.callee:arg;const name=referencedName(target);return name!==null&&(0,eslint_devkit_1.nameHasAnyWord)(name,authPatterns)}function isInsideAuthMiddleware(node,authPatterns){let current=node;while(current){if(current.parent&&current.parent.type==="CallExpression"){const callExpr=current.parent;const isArgument=callExpr.arguments.some(arg=>arg===current);if(!isArgument){current=current.parent;continue}const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,authPatterns)){return true}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){const propertyName=callee.property.name.toLowerCase();if(propertyName==="use"||propertyName==="all"){for(const arg of callExpr.arguments){if(isAuthMiddlewareArg(arg,authPatterns)){return true}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}exports.noMissingAuthentication=(0,eslint_devkit_2.createRule)({name:"no-missing-authentication",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-missing-authentication.md",description:"Detects missing authentication checks in route handlers",cwe:"CWE-287",cvss:9.8},messages:{missingAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Authentication",cwe:"CWE-287",description:"Route handler missing authentication check: {{route}}",severity:"CRITICAL",fix:"Add authentication middleware: app.{{method}}('{{path}}', authenticate(), handler)",documentationLink:"https://cwe.mitre.org/data/definitions/287.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing authentication in test files"},authMiddlewarePatterns:{type:"array",items:{type:"string"},default:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,description:"Authentication middleware patterns to recognize"},routeHandlerPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROUTE_HANDLER_PATTERNS,description:"Route handler patterns to check"},ignorePatterns:{type:"array",items:{type:"string"},default:DEFAULT_PUBLIC_ROUTE_PATTERNS,description:"Route paths that are public by definition and need no authentication. Replaces the built-in list; supplying it also widens matching from the route path to the whole registration text."},routerNameWords:{type:"array",items:{type:"string"},default:ROUTER_NAME_WORDS,description:"Object names that denote an HTTP application or router, compared as WHOLE WORDS and never as a substring. Read only when the binding cannot be resolved to a framework factory call. Replaces the built-in list."},additionalRouterNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra router-object name words, on top of `routerNameWords`."},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,authMiddlewarePatterns:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns:DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns:DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords:ROUTER_NAME_WORDS,additionalRouterNameWords:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,authMiddlewarePatterns=DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns=DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns=DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords=ROUTER_NAME_WORDS,additionalRouterNameWords=[]}=options;const routerWords=[...routerNameWords,...additionalRouterNameWords];const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const scansWholeCallText=context.options[0]?.ignorePatterns!==void 0;function looksLikeRouter(object){const scope=sourceCode.getScope(object);const reference=scope.references.find(ref=>ref.identifier===object);const resolved=reference?.resolved;for(const def of resolved?.defs??[]){const parent=def.name.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){if(isRouterFactory(parent.init)){return true}if(isDefinitelyNotRouter(parent.init)){return false}}}return(0,eslint_devkit_1.nameHasAnyWord)(object.name,routerWords)}function findVariableDeclaration(identifier){const varName=identifier.name;let current=identifier;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){return declarator}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return null}function isIdentifierFromAuthMiddleware(identifier){const declarator=findVariableDeclaration(identifier);if(!declarator||!declarator.init){return false}if(declarator.init.type==="CallExpression"&&declarator.init.callee.type==="Identifier"){return(0,eslint_devkit_1.nameHasAnyWord)(declarator.init.callee.name,authMiddlewarePatterns)}return false}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const property=node.callee.property;const object=node.callee.object;let chainedPath;if(object.type==="Identifier"){if(!looksLikeRouter(object)){return}}else{const base=routeChainBase(object);const baseObject=base?.callee.type==="MemberExpression"?base.callee.object:void 0;if(!base||baseObject?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!looksLikeRouter(baseObject)){return}chainedPath=base.arguments[0]}if(property.type==="Identifier"){const methodName=property.name.toLowerCase();if(routeHandlerPatterns.includes(methodName)){if(methodName!=="use"&&chainedPath===void 0&&node.arguments.length<2){return}if(methodName==="use"){const first=node.arguments[0];const mountsAPath=first!==void 0&&first.type==="Literal"&&typeof first.value==="string";if(!mountsAPath){return}}const pathArgument=chainedPath??node.arguments[0];const routePath=pathArgument.type==="Literal"?String(pathArgument.value):sourceCode.getText(pathArgument);const text=sourceCode.getText(node);if(matchesIgnorePattern(routePath,ignorePatterns)){return}if(scansWholeCallText&&matchesIgnorePattern(text,ignorePatterns)){return}const firstMiddlewareIndex=chainedPath===void 0?1:0;const middlewareArgs=methodName==="use"?node.arguments.slice(firstMiddlewareIndex):node.arguments.slice(firstMiddlewareIndex,-1);let hasAuth=false;for(const arg of middlewareArgs){if(isAuthMiddlewareArg(arg,authMiddlewarePatterns)){hasAuth=true;break}if(arg.type==="Identifier"&&isIdentifierFromAuthMiddleware(arg)){hasAuth=true;break}}if(!hasAuth&&node.arguments.length>0){const lastArg=node.arguments[node.arguments.length-1];if(lastArg.type==="ArrowFunctionExpression"||lastArg.type==="FunctionExpression"){if(isInsideAuthMiddleware(lastArg,authMiddlewarePatterns)){hasAuth=true}}}if(!hasAuth){context.report({node:node.callee,messageId:"missingAuthentication",data:{route:`${methodName}(${routePath})`,method:methodName,path:routePath}})}}}}}return{CallExpression:checkCallExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noMissingAuthentication=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_AUTH_MIDDLEWARE_PATTERNS=["authenticate","auth","requireAuth","isAuthenticated","verifyToken","checkAuth","ensureAuthenticated","passport.authenticate","jwt","session"];const DEFAULT_PUBLIC_ROUTE_PATTERNS=["login","logout","signin","sign-in","signup","sign-up","register","forgot-password","reset-password","password-reset","verify-email","health","healthz","readyz","livez","alive","liveness","readiness","heartbeat","status","metrics","ping","favicon","webhook","/public/","oauth","callback"];const DEFAULT_ROUTE_HANDLER_PATTERNS=["get","post","put","delete","patch","all","use"];const ROUTER_NAME_WORDS=["app","router","route","server","express","fastify","koa","hapi"];const ROUTER_FACTORY_NAMES=new Set(["express","Router","fastify","polka","restify","connect","Koa"]);const ROUTER_FACTORY_MEMBERS=new Set(["Router","router","Server","server","createServer"]);function routeChainBase(node){let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&current.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if((0,eslint_devkit_2.propertyName)(current.callee)==="route"){return current}current=current.callee.object}return null}function isDefinitelyNotRouter(init){return init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression}function isRouterFactory(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.type!==eslint_devkit_1.AST_NODE_TYPES.NewExpression){return false}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return ROUTER_FACTORY_NAMES.has(callee.name)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_2.propertyName)(callee)!==null){return ROUTER_FACTORY_MEMBERS.has((0,eslint_devkit_2.propertyName)(callee))}return false}function referencedName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.name}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=(0,eslint_devkit_1.propertyName)(node);if(property===null)return null;const objectPart=node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?`${node.object.name}.`:"";return`${objectPart}${property}`}return null}function isAuthMiddlewareArg(arg,authPatterns){const target=arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression?arg.callee:arg;const name=referencedName(target);return name!==null&&(0,eslint_devkit_1.nameHasAnyWord)(name,authPatterns)}function isInsideAuthMiddleware(node,authPatterns){let current=node;while(current){if(current.parent&&current.parent.type==="CallExpression"){const callExpr=current.parent;const isArgument=callExpr.arguments.some(arg=>arg===current);if(!isArgument){current=current.parent;continue}const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,authPatterns)){return true}}if(callee.type==="MemberExpression"&&(0,eslint_devkit_2.propertyName)(callee)!==null){const propertyName=(0,eslint_devkit_2.propertyName)(callee).toLowerCase();if(propertyName==="use"||propertyName==="all"){for(const arg of callExpr.arguments){if(isAuthMiddlewareArg(arg,authPatterns)){return true}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}exports.noMissingAuthentication=(0,eslint_devkit_2.createRule)({name:"no-missing-authentication",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-missing-authentication.md",description:"Detects missing authentication checks in route handlers",cwe:"CWE-287",cvss:9.8},messages:{missingAuthentication:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Missing Authentication",cwe:"CWE-287",description:"Route handler missing authentication check: {{route}}",severity:"CRITICAL",fix:"Add authentication middleware: app.{{method}}('{{path}}', authenticate(), handler)",documentationLink:"https://cwe.mitre.org/data/definitions/287.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow missing authentication in test files"},authMiddlewarePatterns:{type:"array",items:{type:"string"},default:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,description:"Authentication middleware patterns to recognize"},routeHandlerPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROUTE_HANDLER_PATTERNS,description:"Route handler patterns to check"},ignorePatterns:{type:"array",items:{type:"string"},default:DEFAULT_PUBLIC_ROUTE_PATTERNS,description:"Route paths that are public by definition and need no authentication. Replaces the built-in list; supplying it also widens matching from the route path to the whole registration text."},routerNameWords:{type:"array",items:{type:"string"},default:ROUTER_NAME_WORDS,description:"Object names that denote an HTTP application or router, compared as WHOLE WORDS and never as a substring. Read only when the binding cannot be resolved to a framework factory call. Replaces the built-in list."},additionalRouterNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra router-object name words, on top of `routerNameWords`."},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,authMiddlewarePatterns:DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns:DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns:DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords:ROUTER_NAME_WORDS,additionalRouterNameWords:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,authMiddlewarePatterns=DEFAULT_AUTH_MIDDLEWARE_PATTERNS,routeHandlerPatterns=DEFAULT_ROUTE_HANDLER_PATTERNS,ignorePatterns=DEFAULT_PUBLIC_ROUTE_PATTERNS,routerNameWords=ROUTER_NAME_WORDS,additionalRouterNameWords=[]}=options;const routerWords=[...routerNameWords,...additionalRouterNameWords];const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const scansWholeCallText=context.options[0]?.ignorePatterns!==void 0;function looksLikeRouter(object){const scope=sourceCode.getScope(object);const reference=scope.references.find(ref=>ref.identifier===object);const resolved=reference?.resolved;for(const def of resolved?.defs??[]){const parent=def.name.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){if(isRouterFactory(parent.init)){return true}if(isDefinitelyNotRouter(parent.init)){return false}}}return(0,eslint_devkit_1.nameHasAnyWord)(object.name,routerWords)}function findVariableDeclaration(identifier){const varName=identifier.name;let current=identifier;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){return declarator}}}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return null}function isIdentifierFromAuthMiddleware(identifier){const declarator=findVariableDeclaration(identifier);if(!declarator||!declarator.init){return false}if(declarator.init.type==="CallExpression"&&declarator.init.callee.type==="Identifier"){return(0,eslint_devkit_1.nameHasAnyWord)(declarator.init.callee.name,authMiddlewarePatterns)}return false}function checkCallExpression(node){if(isTestFile){return}if(node.callee.type==="MemberExpression"){const object=node.callee.object;let chainedPath;if(object.type==="Identifier"){if(!looksLikeRouter(object)){return}}else{const base=routeChainBase(object);const baseObject=base?.callee.type==="MemberExpression"?base.callee.object:void 0;if(!base||baseObject?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!looksLikeRouter(baseObject)){return}chainedPath=base.arguments[0]}const resolvedMethod=(0,eslint_devkit_2.propertyName)(node.callee);if(resolvedMethod!==null){const methodName=resolvedMethod.toLowerCase();if(routeHandlerPatterns.includes(methodName)){if(methodName!=="use"&&chainedPath===void 0&&node.arguments.length<2){return}if(methodName==="use"){const first=node.arguments[0];const mountsAPath=first!==void 0&&first.type==="Literal"&&typeof first.value==="string";if(!mountsAPath){return}}const pathArgument=chainedPath??node.arguments[0];const routePath=pathArgument.type==="Literal"?String(pathArgument.value):sourceCode.getText(pathArgument);const text=sourceCode.getText(node);if(matchesIgnorePattern(routePath,ignorePatterns)){return}if(scansWholeCallText&&matchesIgnorePattern(text,ignorePatterns)){return}const firstMiddlewareIndex=chainedPath===void 0?1:0;const middlewareArgs=methodName==="use"?node.arguments.slice(firstMiddlewareIndex):node.arguments.slice(firstMiddlewareIndex,-1);let hasAuth=false;for(const arg of middlewareArgs){if(isAuthMiddlewareArg(arg,authMiddlewarePatterns)){hasAuth=true;break}if(arg.type==="Identifier"&&isIdentifierFromAuthMiddleware(arg)){hasAuth=true;break}}if(!hasAuth&&node.arguments.length>0){const lastArg=node.arguments[node.arguments.length-1];if(lastArg.type==="ArrowFunctionExpression"||lastArg.type==="FunctionExpression"){if(isInsideAuthMiddleware(lastArg,authMiddlewarePatterns)){hasAuth=true}}}if(!hasAuth){context.report({node:node.callee,messageId:"missingAuthentication",data:{route:`${methodName}(${routePath})`,method:methodName,path:routePath}})}}}}}return{CallExpression:checkCallExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPiiInLogs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_CONSOLE_METHODS=["log","error","warn","info"];const DEFAULT_PII_TERMS=["email","ssn","password","credit card","phone"];const DEFAULT_PII_LABELS=["email:","ssn:","password:","credit card:","creditcard:"];function collectLoggedValues(root){const found=[];const pending=[root];while(pending.length>0){const node=pending.pop();found.push(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression){pending.push(node.expression)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){pending.push(...node.expressions)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){pending.push(node.left,node.right)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of node.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property){pending.push(property.value)}}}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){pending.push(node.consequent,node.alternate)}}return found}function isPiiFieldAccess(node,piiTerms){return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(node.property.name,piiTerms)}exports.noPiiInLogs=(0,eslint_devkit_1.createRule)({name:"no-pii-in-logs",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-pii-in-logs.md",description:"Prevent PII (email, SSN, credit cards) in console logs",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-359",description:"Prevent PII (email, SSN, credit cards) in console logs detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[{type:"object",properties:{consoleMethods:{type:"array",items:{type:"string"},default:DEFAULT_CONSOLE_METHODS,description:"`console` methods treated as a log sink, matched as an exact method name. Replaces the built-in list."},additionalConsoleMethods:{type:"array",items:{type:"string"},default:[],description:"Extra `console` methods, on top of `consoleMethods`."},piiTerms:{type:"array",items:{type:"string"},default:DEFAULT_PII_TERMS,description:'Field vocabulary, matched as WHOLE WORDS of an identifier \u2014 never as a substring. Multi-word terms such as "credit card" match consecutive segments. Replaces the built-in list.'},additionalPiiTerms:{type:"array",items:{type:"string"},default:[],description:"Extra PII field terms, on top of `piiTerms`."},piiLabels:{type:"array",items:{type:"string"},default:DEFAULT_PII_LABELS,description:"String literals that are EXACTLY a field label announcing the next argument. Compared case-insensitively after trimming. Replaces the built-in list."},additionalPiiLabels:{type:"array",items:{type:"string"},default:[],description:"Extra field labels, on top of `piiLabels`."}},additionalProperties:false}]},defaultOptions:[{consoleMethods:DEFAULT_CONSOLE_METHODS,additionalConsoleMethods:[],piiTerms:DEFAULT_PII_TERMS,additionalPiiTerms:[],piiLabels:DEFAULT_PII_LABELS,additionalPiiLabels:[]}],create(context,[options={}]){const{consoleMethods=DEFAULT_CONSOLE_METHODS,additionalConsoleMethods=[],piiTerms=DEFAULT_PII_TERMS,additionalPiiTerms=[],piiLabels=DEFAULT_PII_LABELS,additionalPiiLabels=[]}=options;const logMethods=new Set([...consoleMethods,...additionalConsoleMethods]);const terms=[...piiTerms,...additionalPiiTerms];const labels=new Set([...piiLabels,...additionalPiiLabels].map(label=>label.trim().toLowerCase()));const sourceCode=context.sourceCode;function report(node){context.report({node,messageId:"violationDetected"})}function isPiiBinding(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);const resolved=reference?.resolved;if(!resolved){return false}return resolved.defs.some(def=>{const declared=def.name;const parent=declared.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return(0,eslint_devkit_1.nameHasAnyWord)(parent.key.name,terms)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){return isPiiFieldAccess(parent.init,terms)}return false})}return{CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||node.callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.object.name!=="console"||node.callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!logMethods.has(node.callee.property.name)){return}for(const[index,arg]of node.arguments.entries()){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&index<node.arguments.length-1&&labels.has(arg.value.trim().toLowerCase())){report(node);return}for(const value of collectLoggedValues(arg)){if(isPiiFieldAccess(value,terms)||isPiiBinding(value)){report(node);return}}}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPiiInLogs=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const DEFAULT_CONSOLE_METHODS=["log","error","warn","info"];const DEFAULT_PII_TERMS=["email","ssn","password","credit card","phone"];const DEFAULT_PII_LABELS=["email:","ssn:","password:","credit card:","creditcard:"];function collectLoggedValues(root){const found=[];const pending=[root];while(pending.length>0){const node=pending.pop();found.push(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TSAsExpression){pending.push(node.expression)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){pending.push(...node.expressions)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){pending.push(node.left,node.right)}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of node.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.Property){pending.push(property.value)}}}else if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){pending.push(node.consequent,node.alternate)}}return found}function isPiiFieldAccess(node,piiTerms){const field=(0,eslint_devkit_1.memberPropertyName)(node);return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&field!==null&&(0,eslint_devkit_1.nameHasAnyWord)(field,piiTerms)}exports.noPiiInLogs=(0,eslint_devkit_1.createRule)({name:"no-pii-in-logs",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-pii-in-logs.md",description:"Prevent PII (email, SSN, credit cards) in console logs",cwe:"CWE-359",cvss:5.3},messages:{violationDetected:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"violation Detected",cwe:"CWE-359",description:"Prevent PII (email, SSN, credit cards) in console logs detected - this is a security risk",severity:"HIGH",fix:"Review and apply secure practices",documentationLink:"https://cwe.mitre.org/data/definitions/359.html"})},schema:[{type:"object",properties:{consoleMethods:{type:"array",items:{type:"string"},default:DEFAULT_CONSOLE_METHODS,description:"`console` methods treated as a log sink, matched as an exact method name. Replaces the built-in list."},additionalConsoleMethods:{type:"array",items:{type:"string"},default:[],description:"Extra `console` methods, on top of `consoleMethods`."},piiTerms:{type:"array",items:{type:"string"},default:DEFAULT_PII_TERMS,description:'Field vocabulary, matched as WHOLE WORDS of an identifier \u2014 never as a substring. Multi-word terms such as "credit card" match consecutive segments. Replaces the built-in list.'},additionalPiiTerms:{type:"array",items:{type:"string"},default:[],description:"Extra PII field terms, on top of `piiTerms`."},piiLabels:{type:"array",items:{type:"string"},default:DEFAULT_PII_LABELS,description:"String literals that are EXACTLY a field label announcing the next argument. Compared case-insensitively after trimming. Replaces the built-in list."},additionalPiiLabels:{type:"array",items:{type:"string"},default:[],description:"Extra field labels, on top of `piiLabels`."}},additionalProperties:false}]},defaultOptions:[{consoleMethods:DEFAULT_CONSOLE_METHODS,additionalConsoleMethods:[],piiTerms:DEFAULT_PII_TERMS,additionalPiiTerms:[],piiLabels:DEFAULT_PII_LABELS,additionalPiiLabels:[]}],create(context,[options={}]){const{consoleMethods=DEFAULT_CONSOLE_METHODS,additionalConsoleMethods=[],piiTerms=DEFAULT_PII_TERMS,additionalPiiTerms=[],piiLabels=DEFAULT_PII_LABELS,additionalPiiLabels=[]}=options;const logMethods=new Set([...consoleMethods,...additionalConsoleMethods]);const terms=[...piiTerms,...additionalPiiTerms];const labels=new Set([...piiLabels,...additionalPiiLabels].map(label=>label.trim().toLowerCase()));const sourceCode=context.sourceCode;function report(node){context.report({node,messageId:"violationDetected"})}function isPiiBinding(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);const resolved=reference?.resolved;if(!resolved){return false}return resolved.defs.some(def=>{const declared=def.name;const parent=declared.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return(0,eslint_devkit_1.nameHasAnyWord)(parent.key.name,terms)}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init){return isPiiFieldAccess(parent.init,terms)}return false})}return{CallExpression(node){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||node.callee.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||node.callee.object.name!=="console"||!(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),logMethods)){return}for(const[index,arg]of node.arguments.entries()){if(arg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&index<node.arguments.length-1&&labels.has(arg.value.trim().toLowerCase())){report(node);return}for(const value of collectLoggedValues(arg)){if(isPiiFieldAccess(value,terms)||isPiiBinding(value)){report(node);return}}}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPrivilegeEscalation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_ROLE_CHECK_PATTERNS=["hasRole","checkRole","isAdmin","isAuthorized","hasPermission","checkPermission","verifyRole","requireRole"];const DEFAULT_USER_INPUT_PATTERNS=[/\breq\.(body|query|params)\b/,/\brequest\.(body|query|params)\b/,/\buserInput\b/];const DEFAULT_PRIVILEGE_PROPERTIES=["role","permission","privilege","access"];const DEFAULT_PRIVILEGE_TERMS=["setRole","updateRole","elevate","grant role","grant permission","grant access","grant privilege","promote user","promote admin","revoke role","revoke permission","revoke access","revoke privilege"];const DEFAULT_BARE_PRIVILEGE_VERBS=["grant","promote","revoke"];function isPrivilegeOperationName(name,privilegeTerms,bareVerbs){if((0,eslint_devkit_1.nameHasAnyWord)(name,privilegeTerms)){return true}const words=(0,eslint_devkit_1.identifierWords)(name);return words.length===1&&bareVerbs.has(words[0])}function assignedPropertyName(member){if(!member.computed&&member.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return member.property.name}const staticText=(0,eslint_devkit_1.staticString)(member.property);if(staticText!==null){return staticText}return null}function forEachNode(root,visit){const pending=[root];while(pending.length>0){const node=pending.pop();visit(node);for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){pending.push(child)}}}}}function containsRoleCheck(root,roleCheckPatterns){let found=false;forEachNode(root,node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(node.name,roleCheckPatterns)){found=true}});return found}function exitsUnconditionally(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||statement.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)}return false}function isAfterRoleGuard(node,roleCheckPatterns){let current=node;while(current.parent){const parent=current.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=parent.body;const index=body.indexOf(current);for(let i=0;i<index;i++){const statement=body[i];if(statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&exitsUnconditionally(statement.consequent)&&containsRoleCheck(statement.test,roleCheckPatterns)){return true}}}current=parent}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}function containsUserInput(node,sourceCode,userInputPatterns){const text=sourceCode.getText(node);return userInputPatterns.some(pattern=>pattern.test(text))}function isInsideRoleCheck(node,roleCheckPatterns){let current=node;while(current){if(current.parent&&current.parent.type==="IfStatement"){const ifStmt=current.parent;if(containsRoleCheck(ifStmt.test,roleCheckPatterns)){return true}}if(current.parent&&current.parent.type==="ConditionalExpression"){const condExpr=current.parent;if(containsRoleCheck(condExpr.test,roleCheckPatterns)){return true}}if(current.parent&&current.parent.type==="CallExpression"){const callExpr=current.parent;const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,roleCheckPatterns)){return true}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.property.name,roleCheckPatterns)){return true}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}exports.noPrivilegeEscalation=(0,eslint_devkit_2.createRule)({name:"no-privilege-escalation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-privilege-escalation.md",description:"Detects potential privilege escalation vulnerabilities",cwe:"CWE-269",cvss:8.8},messages:{privilegeEscalation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Privilege Escalation",cwe:"CWE-269",description:"Potential privilege escalation: {{issue}} - user input used without role validation",severity:"HIGH",fix:'Add role check before using user input: if (!hasRole(user, requiredRole)) throw new Error("Unauthorized");',documentationLink:"https://cwe.mitre.org/data/definitions/269.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow privilege escalation patterns in test files"},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."},roleCheckPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROLE_CHECK_PATTERNS,description:"Role check patterns to recognize"},userInputPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional user input patterns to check (regex strings)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},privilegeProperties:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_PROPERTIES,description:"Property names whose assignment is an authorisation decision, compared case-insensitively as an exact name. Replaces the built-in list."},additionalPrivilegeProperties:{type:"array",items:{type:"string"},default:[],description:"Extra privilege property names, on top of `privilegeProperties`."},privilegeTerms:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_TERMS,description:"Privilege operations, matched as whole words or whole consecutive phrases of a callee name \u2014 never as a substring. Replaces the built-in list."},additionalPrivilegeTerms:{type:"array",items:{type:"string"},default:[],description:"Extra privilege operation terms, on top of `privilegeTerms`."},barePrivilegeVerbs:{type:"array",items:{type:"string"},default:DEFAULT_BARE_PRIVILEGE_VERBS,description:"Verbs that count only when they are the WHOLE callee name, because their ordinary English sense dominates otherwise. Replaces the built-in list."},additionalBarePrivilegeVerbs:{type:"array",items:{type:"string"},default:[],description:"Extra bare privilege verbs, on top of `barePrivilegeVerbs`."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,roleCheckPatterns:DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:[],ignorePatterns:[],privilegeProperties:DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties:[],privilegeTerms:DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms:[],barePrivilegeVerbs:DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,roleCheckPatterns=DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:additionalUserInputPatterns=[],ignorePatterns=[],privilegeProperties=DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties=[],privilegeTerms=DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms=[],barePrivilegeVerbs=DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs=[]}=options;const privilegeProps=new Set([...privilegeProperties,...additionalPrivilegeProperties].map(name=>name.toLowerCase()));const privilegeOperationTerms=[...privilegeTerms,...additionalPrivilegeTerms];const bareVerbs=new Set([...barePrivilegeVerbs,...additionalBarePrivilegeVerbs]);const isPrivilegeOperationCallee=name=>isPrivilegeOperationName(name,privilegeOperationTerms,bareVerbs);const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const userInputPatterns=[...DEFAULT_USER_INPUT_PATTERNS,...(0,eslint_devkit_1.compileUserPatterns)(additionalUserInputPatterns,"i")];function isRoleChecked(node){return isInsideRoleCheck(node,roleCheckPatterns)||isAfterRoleGuard(node,roleCheckPatterns)}function resolvesToUserInput(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);for(const def of reference?.resolved?.defs??[]){let declarator=def.name;while(declarator&&declarator.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){declarator=declarator.parent}if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&containsUserInput(declarator.init,sourceCode,userInputPatterns)){return true}}return false}function isUserControlled(node){return containsUserInput(node,sourceCode,userInputPatterns)||resolvesToUserInput(node)}function checkAssignmentExpression(node){if(isTestFile){return}if(node.left.type==="MemberExpression"){const propertyName=assignedPropertyName(node.left)?.toLowerCase();if(propertyName!==void 0&&privilegeProps.has(propertyName)){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isUserControlled(node.right)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Role assignment from user input: ${sourceCode.getText(node.left)} = ${sourceCode.getText(node.right)}`}})}}}}}function checkCallExpression(node){if(isTestFile){return}const callee=node.callee;let isPrivilegeOperation=false;let operationName="";if(callee.type==="Identifier"){if(isPrivilegeOperationCallee(callee.name)){isPrivilegeOperation=true;operationName=callee.name}}if(callee.type==="MemberExpression"&&callee.property.type==="Identifier"){if(isPrivilegeOperationCallee(callee.property.name)){isPrivilegeOperation=true;operationName=callee.property.name.toLowerCase()}}if(isPrivilegeOperation){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}for(const arg of node.arguments){if(isUserControlled(arg)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Privilege operation (${operationName}) with user input without role validation`}});return}}}}}function checkObjectExpression(node){if(isTestFile)return;for(const prop of node.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){const keyName=prop.key.name.toLowerCase();if(privilegeProps.has(keyName)){const text=sourceCode.getText(prop);if(matchesIgnorePattern(text,ignorePatterns))continue;if(isUserControlled(prop.value)){if(!isRoleChecked(node)){context.report({node:prop,messageId:"privilegeEscalation",data:{issue:`Role assignment in object from user input: ${sourceCode.getText(prop)}`}})}}}}}}return{AssignmentExpression:checkAssignmentExpression,CallExpression:checkCallExpression,ObjectExpression:checkObjectExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noPrivilegeEscalation=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const DEFAULT_ROLE_CHECK_PATTERNS=["hasRole","checkRole","isAdmin","isAuthorized","hasPermission","checkPermission","verifyRole","requireRole"];const DEFAULT_USER_INPUT_PATTERNS=[/\breq\.(body|query|params)\b/,/\brequest\.(body|query|params)\b/,/\buserInput\b/];const DEFAULT_PRIVILEGE_PROPERTIES=["role","permission","privilege","access"];const DEFAULT_PRIVILEGE_TERMS=["setRole","updateRole","elevate","grant role","grant permission","grant access","grant privilege","promote user","promote admin","revoke role","revoke permission","revoke access","revoke privilege"];const DEFAULT_BARE_PRIVILEGE_VERBS=["grant","promote","revoke"];function isPrivilegeOperationName(name,privilegeTerms,bareVerbs){if((0,eslint_devkit_1.nameHasAnyWord)(name,privilegeTerms)){return true}const words=(0,eslint_devkit_1.identifierWords)(name);return words.length===1&&bareVerbs.has(words[0])}function assignedPropertyName(member){if(!member.computed&&member.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return member.property.name}const staticText=(0,eslint_devkit_1.staticString)(member.property);if(staticText!==null){return staticText}return null}function forEachNode(root,visit){const pending=[root];while(pending.length>0){const node=pending.pop();visit(node);for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){pending.push(child)}}}}}function containsRoleCheck(root,roleCheckPatterns){let found=false;forEachNode(root,node=>{if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.nameHasAnyWord)(node.name,roleCheckPatterns)){found=true}});return found}function exitsUnconditionally(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return node.body.some(statement=>statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement||statement.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)}return false}function isAfterRoleGuard(node,roleCheckPatterns){let current=node;while(current.parent){const parent=current.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=parent.body;const index=body.indexOf(current);for(let i=0;i<index;i++){const statement=body[i];if(statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&exitsUnconditionally(statement.consequent)&&containsRoleCheck(statement.test,roleCheckPatterns)){return true}}}current=parent}return false}function matchesIgnorePattern(text,patterns){return(0,eslint_devkit_1.matchesAnyUserPattern)((0,eslint_devkit_1.compileUserPatterns)(patterns,"i"),text)}function containsUserInput(node,sourceCode,userInputPatterns){const text=sourceCode.getText(node);return userInputPatterns.some(pattern=>pattern.test(text))}function isInsideRoleCheck(node,roleCheckPatterns){let current=node;while(current){if(current.parent&&current.parent.type==="IfStatement"){const ifStmt=current.parent;if(containsRoleCheck(ifStmt.test,roleCheckPatterns)){return true}}if(current.parent&&current.parent.type==="ConditionalExpression"){const condExpr=current.parent;if(containsRoleCheck(condExpr.test,roleCheckPatterns)){return true}}if(current.parent&&current.parent.type==="CallExpression"){const callExpr=current.parent;const callee=callExpr.callee;if(callee.type==="Identifier"){if((0,eslint_devkit_1.nameHasAnyWord)(callee.name,roleCheckPatterns)){return true}}const memberName=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&memberName!==null){if((0,eslint_devkit_1.nameHasAnyWord)(memberName,roleCheckPatterns)){return true}}}if("parent"in current&&current.parent){current=current.parent}else{break}}return false}exports.noPrivilegeEscalation=(0,eslint_devkit_2.createRule)({name:"no-privilege-escalation",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-privilege-escalation.md",description:"Detects potential privilege escalation vulnerabilities",cwe:"CWE-269",cvss:8.8},messages:{privilegeEscalation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Privilege Escalation",cwe:"CWE-269",description:"Potential privilege escalation: {{issue}} - user input used without role validation",severity:"HIGH",fix:'Add role check before using user input: if (!hasRole(user, requiredRole)) throw new Error("Unauthorized");',documentationLink:"https://cwe.mitre.org/data/definitions/269.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow privilege escalation patterns in test files"},testFilePattern:{type:["string","null"],default:null,description:"Override which filenames `allowInTests` applies to. Null \u2014 the default \u2014 leaves it to the shared structural predicate."},roleCheckPatterns:{type:"array",items:{type:"string"},default:DEFAULT_ROLE_CHECK_PATTERNS,description:"Role check patterns to recognize"},userInputPatterns:{type:"array",items:{type:"string"},default:[],description:"Additional user input patterns to check (regex strings)"},ignorePatterns:{type:"array",items:{type:"string"},default:[],description:"Additional patterns to ignore"},privilegeProperties:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_PROPERTIES,description:"Property names whose assignment is an authorisation decision, compared case-insensitively as an exact name. Replaces the built-in list."},additionalPrivilegeProperties:{type:"array",items:{type:"string"},default:[],description:"Extra privilege property names, on top of `privilegeProperties`."},privilegeTerms:{type:"array",items:{type:"string"},default:DEFAULT_PRIVILEGE_TERMS,description:"Privilege operations, matched as whole words or whole consecutive phrases of a callee name \u2014 never as a substring. Replaces the built-in list."},additionalPrivilegeTerms:{type:"array",items:{type:"string"},default:[],description:"Extra privilege operation terms, on top of `privilegeTerms`."},barePrivilegeVerbs:{type:"array",items:{type:"string"},default:DEFAULT_BARE_PRIVILEGE_VERBS,description:"Verbs that count only when they are the WHOLE callee name, because their ordinary English sense dominates otherwise. Replaces the built-in list."},additionalBarePrivilegeVerbs:{type:"array",items:{type:"string"},default:[],description:"Extra bare privilege verbs, on top of `barePrivilegeVerbs`."}},additionalProperties:false}]},defaultOptions:[{allowInTests:false,roleCheckPatterns:DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:[],ignorePatterns:[],privilegeProperties:DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties:[],privilegeTerms:DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms:[],barePrivilegeVerbs:DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs:[]}],create(context,[options={}]){const{allowInTests=false,testFilePattern,roleCheckPatterns=DEFAULT_ROLE_CHECK_PATTERNS,userInputPatterns:additionalUserInputPatterns=[],ignorePatterns=[],privilegeProperties=DEFAULT_PRIVILEGE_PROPERTIES,additionalPrivilegeProperties=[],privilegeTerms=DEFAULT_PRIVILEGE_TERMS,additionalPrivilegeTerms=[],barePrivilegeVerbs=DEFAULT_BARE_PRIVILEGE_VERBS,additionalBarePrivilegeVerbs=[]}=options;const privilegeProps=new Set([...privilegeProperties,...additionalPrivilegeProperties].map(name=>name.toLowerCase()));const privilegeOperationTerms=[...privilegeTerms,...additionalPrivilegeTerms];const bareVerbs=new Set([...barePrivilegeVerbs,...additionalBarePrivilegeVerbs]);const isPrivilegeOperationCallee=name=>isPrivilegeOperationName(name,privilegeOperationTerms,bareVerbs);const filename=context.filename;const isTestFile=allowInTests&&(testFilePattern==null?(0,eslint_devkit_2.isTestFilePath)(filename):(0,eslint_devkit_1.compileUserPattern)(testFilePattern).test(filename));const sourceCode=context.sourceCode;const userInputPatterns=[...DEFAULT_USER_INPUT_PATTERNS,...(0,eslint_devkit_1.compileUserPatterns)(additionalUserInputPatterns,"i")];function isRoleChecked(node){return isInsideRoleCheck(node,roleCheckPatterns)||isAfterRoleGuard(node,roleCheckPatterns)}function resolvesToUserInput(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return false}const scope=sourceCode.getScope(node);const reference=scope.references.find(ref=>ref.identifier===node);for(const def of reference?.resolved?.defs??[]){let declarator=def.name;while(declarator&&declarator.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){declarator=declarator.parent}if(declarator?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&declarator.init&&containsUserInput(declarator.init,sourceCode,userInputPatterns)){return true}}return false}function isUserControlled(node){return containsUserInput(node,sourceCode,userInputPatterns)||resolvesToUserInput(node)}function checkAssignmentExpression(node){if(isTestFile){return}if(node.left.type==="MemberExpression"){const propertyName=assignedPropertyName(node.left)?.toLowerCase();if(propertyName!==void 0&&privilegeProps.has(propertyName)){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}if(isUserControlled(node.right)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Role assignment from user input: ${sourceCode.getText(node.left)} = ${sourceCode.getText(node.right)}`}})}}}}}function checkCallExpression(node){if(isTestFile){return}const callee=node.callee;let isPrivilegeOperation=false;let operationName="";if(callee.type==="Identifier"){if(isPrivilegeOperationCallee(callee.name)){isPrivilegeOperation=true;operationName=callee.name}}const method=(0,eslint_devkit_1.memberPropertyName)(callee);if(callee.type==="MemberExpression"&&method!==null){if(isPrivilegeOperationCallee(method)){isPrivilegeOperation=true;operationName=method.toLowerCase()}}if(isPrivilegeOperation){const text=sourceCode.getText(node);if(matchesIgnorePattern(text,ignorePatterns)){return}for(const arg of node.arguments){if(isUserControlled(arg)){if(!isRoleChecked(node)){context.report({node,messageId:"privilegeEscalation",data:{issue:`Privilege operation (${operationName}) with user input without role validation`}});return}}}}}function checkObjectExpression(node){if(isTestFile)return;for(const prop of node.properties){if(prop.type==="Property"&&prop.key.type==="Identifier"){const keyName=prop.key.name.toLowerCase();if(privilegeProps.has(keyName)){const text=sourceCode.getText(prop);if(matchesIgnorePattern(text,ignorePatterns))continue;if(isUserControlled(prop.value)){if(!isRoleChecked(node)){context.report({node:prop,messageId:"privilegeEscalation",data:{issue:`Role assignment in object from user input: ${sourceCode.getText(prop)}`}})}}}}}}return{AssignmentExpression:checkAssignmentExpression,CallExpression:checkCallExpression,ObjectExpression:checkObjectExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noRedosVulnerableRegex=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const regexpp_1=require("@eslint-community/regexpp");const scslre_1=require("scslre");const regexp_intrinsic_1=require("../../utils/regexp-intrinsic");const redos_oracle_1=require("../../utils/redos-oracle");const COMPLEMENTARY_CLASS_PROBES=[["\\\\S","\\\\s"],["\\\\W","\\\\w"],["\\\\D","\\\\d"]].map(([x,y])=>({group:new RegExp(`\\(\\s*(?:${x}|${y})[+*][^)]*(?:${x}|${y})[+*?][^)]*\\)[+*]`),a:new RegExp(`${x}[+*]`),b:new RegExp(`${y}[+*?]`)}));const REGEXPP_PARSER=new regexpp_1.RegExpParser;const INTERPOLATION_PLACEHOLDER="\uE000";function relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern){const edits=[];const walk=(node,underUnbounded)=>{const n=node;if(n.type==="Quantifier"){const{min=0,max=0}=n;if(underUnbounded&&Number.isFinite(max)&&max>1&&min!==max){edits.push([n.element.end,n.end,`{${min},}${n.greedy===false?"?":""}`])}walk(n.element,underUnbounded||max===Infinity);return}for(const child of[...n.alternatives??[],...n.elements??[]]){walk(child,underUnbounded)}};walk(ast,false);if(edits.length===0)return pattern;let out=pattern;for(const[start,end,text]of edits.sort((a,b)=>b[0]-a[0])){out=out.slice(0,start)+text+out.slice(end)}return out}const isRegExpLiteral=node=>{return node.type==="Literal"&&Object.prototype.hasOwnProperty.call(node,"regex")};exports.noRedosVulnerableRegex=(0,eslint_devkit_2.createRule)({name:"no-redos-vulnerable-regex",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-redos-vulnerable-regex.md",description:"Detects ReDoS-vulnerable regex patterns in literal regex patterns",cwe:"CWE-400"},messages:{redosVulnerable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"ReDoS vulnerable regex",cwe:"CWE-400",description:"{{vulnerabilityName}}: {{description}}",severity:"{{severity}}",fix:"{{fix}} \u2014 Not a finding if the quantifiers cannot overlap",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"})},schema:[{type:"object",properties:{allowCommonPatterns:{type:"boolean",default:false,description:"Deprecated and ignored. Gated the removed heuristic layer; kept so existing configs still load."},maxPatternLength:{type:"number",default:500,minimum:1,description:"Maximum pattern length to analyze"},reportSecondDegreePolynomial:{type:"boolean",default:true,description:"Report quadratic backtracking. On by default \u2014 the CWE-1333 corpus pins a degree-2 fixture as must-detect. Turn it off only for patterns that provably run over short, sized input; doing so costs recall. Requires the recheck oracle."}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowCommonPatterns:false,maxPatternLength:500,reportSecondDegreePolynomial:true}],create(context,[options={}]){const{maxPatternLength=500,reportSecondDegreePolynomial=true}=options||{};const MAX_SAFE_REPETITION=5;function isProvablyLinear(pattern){const groupUnderUnboundedQuantifier=/\)[*+]/.test(pattern);const bounded=groupUnderUnboundedQuantifier?null:/\)\{(\d+)(?:,(\d+))?\}/.exec(pattern);if(bounded!==null){const max=bounded[2]!==void 0?Number(bounded[2]):Number(bounded[1]);if(max<=MAX_SAFE_REPETITION)return true}for(const{group,a,b}of COMPLEMENTARY_CLASS_PROBES){if(!group.test(pattern))continue;if(a.test(pattern)&&b.test(pattern))return true}return false}function isProvablyCatastrophic(pattern){const m=/\(([^()|]+)\|([^()|]+)\)[+*]/.exec(pattern);return m!==null&&m[1]===m[2]}function checkWithScslre(node,pattern,flags,runtimeBuilt=false){try{const parse=source=>REGEXPP_PARSER.parsePattern(source,0,source.length,{unicode:flags.includes("u"),unicodeSets:flags.includes("v")});const run=ast2=>(0,scslre_1.analyse)({pattern:ast2,flags:{ignoreCase:flags.includes("i"),unicode:flags.includes("u"),dotAll:flags.includes("s"),multiline:flags.includes("m")}},{reportTypes:{Move:false}});const ast=parse(pattern);let result=run(ast);if(result.reports.length===0){const relaxed=relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern);if(relaxed!==pattern){result=run(parse(relaxed))}}if(isProvablyLinear(pattern)){return}if(result.reports.length===0&&isProvablyCatastrophic(pattern)){if(!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:"Ambiguous alternation (exponential backtracking)",description:"Alternatives inside a quantified group match the same input, so every character can be taken by either branch and the engine explores 2^n paths before failing.",severity:"CRITICAL",fix:"Remove the duplicate alternative, or make the branches mutually exclusive"}});return}const worst=result.reports.find(r=>r.exponential)??result.reports[0];if(worst&&!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;if(worst&&!reportSecondDegreePolynomial){const degree=(0,redos_oracle_1.worstBacktrackingDegree)(pattern,flags);if(degree!==null&&degree<=2)return}for(const report of worst?[worst]:[]){const isExp=report.exponential;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:`${runtimeBuilt?"Runtime-built ":""}${report.type==="Self"?`Self-loop quantifier (${isExp?"exponential":"polynomial"} backtracking)`:`Cross-quantifier trade (${isExp?"exponential":"polynomial"} backtracking)`}`,description:report.type==="Self"?`A quantifier reaches itself via the parent loop. An attacker can craft input that triggers ${isExp?"exponential":"polynomial"} backtracking.`:`Two quantifiers can exchange characters, enabling ${isExp?"exponential":"polynomial"} backtracking on crafted input.`,severity:isExp?"CRITICAL":"HIGH",fix:"Atomic group, possessive quantifier, or rewrite to remove the ambiguity"}})}}catch{}}function checkLiteralRegExp(node){if(!isRegExpLiteral(node)){return}const pattern=node.regex.pattern;const flags=node.regex.flags||"";if(pattern.length>maxPatternLength){return}checkWithScslre(node,pattern,flags)}function resolvePatternSource(node,seen){if(seen.has(node))return null;seen.add(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?{pattern:node.value,exact:true}:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return joinQuasis(node.quasis.map(q=>q.value.cooked??q.value.raw),node.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression&&node.tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.tag.computed&&node.tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.tag.object.name==="String"&&node.tag.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.tag.property.name==="raw"&&!isShadowed("String",node)){return joinQuasis(node.quasi.quasis.map(q=>q.value.raw),node.quasi.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=resolveOrPlaceholder(node.left,seen);const right=resolveOrPlaceholder(node.right,seen);return{pattern:left.pattern+right.pattern,exact:left.exact&&right.exact}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=resolveBindingInit(node);return init?resolvePatternSource(init,seen):null}return null}function joinQuasis(staticParts,expressions,seen){let pattern="";let exact=true;for(const[index,part]of staticParts.entries()){pattern+=part;const expression=expressions[index];if(!expression)continue;const resolved=resolveOrPlaceholder(expression,seen);pattern+=resolved.pattern;exact&&=resolved.exact}return{pattern,exact}}function resolveOrPlaceholder(node,seen){return resolvePatternSource(node,seen)??{pattern:INTERPOLATION_PLACEHOLDER,exact:false}}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;const writes=variable.references.filter(r=>r.isWrite());return writes.length===1?def.node.init:null}return null}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function checkNewRegExp(node){const callee=node.callee;if(!(0,regexp_intrinsic_1.isRegExpConstructor)(callee,context.sourceCode)){return}const firstArg=node.arguments[0];if(!firstArg||firstArg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const resolved=resolvePatternSource(firstArg,new Set);if(!resolved||resolved.pattern.length>maxPatternLength){return}const flagsArg=node.arguments[1];const flags=flagsArg?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof flagsArg.value==="string"?flagsArg.value:"";checkWithScslre(node,resolved.pattern,flags,!resolved.exact)}return{Literal:checkLiteralRegExp,CallExpression:node=>checkNewRegExp((0,regexp_intrinsic_1.asDirectConstruction)(node,context.sourceCode)),NewExpression:checkNewRegExp}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noRedosVulnerableRegex=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const regexpp_1=require("@eslint-community/regexpp");const scslre_1=require("scslre");const regexp_intrinsic_1=require("../../utils/regexp-intrinsic");const redos_oracle_1=require("../../utils/redos-oracle");const COMPLEMENTARY_CLASS_PROBES=[["\\\\S","\\\\s"],["\\\\W","\\\\w"],["\\\\D","\\\\d"]].map(([x,y])=>({group:new RegExp(`\\(\\s*(?:${x}|${y})[+*][^)]*(?:${x}|${y})[+*?][^)]*\\)[+*]`),a:new RegExp(`${x}[+*]`),b:new RegExp(`${y}[+*?]`)}));const REGEXPP_PARSER=new regexpp_1.RegExpParser;const INTERPOLATION_PLACEHOLDER="\uE000";function relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern){const edits=[];const walk=(node,underUnbounded)=>{const n=node;if(n.type==="Quantifier"){const{min=0,max=0}=n;if(underUnbounded&&Number.isFinite(max)&&max>1&&min!==max){edits.push([n.element.end,n.end,`{${min},}${n.greedy===false?"?":""}`])}walk(n.element,underUnbounded||max===Infinity);return}for(const child of[...n.alternatives??[],...n.elements??[]]){walk(child,underUnbounded)}};walk(ast,false);if(edits.length===0)return pattern;let out=pattern;for(const[start,end,text]of edits.sort((a,b)=>b[0]-a[0])){out=out.slice(0,start)+text+out.slice(end)}return out}const isRegExpLiteral=node=>{return node.type==="Literal"&&Object.prototype.hasOwnProperty.call(node,"regex")};exports.noRedosVulnerableRegex=(0,eslint_devkit_2.createRule)({name:"no-redos-vulnerable-regex",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-redos-vulnerable-regex.md",description:"Detects ReDoS-vulnerable regex patterns in literal regex patterns",cwe:"CWE-400"},messages:{redosVulnerable:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"ReDoS vulnerable regex",cwe:"CWE-400",description:"{{vulnerabilityName}}: {{description}}",severity:"{{severity}}",fix:"{{fix}} \u2014 Not a finding if the quantifiers cannot overlap",documentationLink:"https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS"})},schema:[{type:"object",properties:{allowCommonPatterns:{type:"boolean",default:false,description:"Deprecated and ignored. Gated the removed heuristic layer; kept so existing configs still load."},maxPatternLength:{type:"number",default:500,minimum:1,description:"Maximum pattern length to analyze"},reportSecondDegreePolynomial:{type:"boolean",default:true,description:"Report quadratic backtracking. On by default \u2014 the CWE-1333 corpus pins a degree-2 fixture as must-detect. Turn it off only for patterns that provably run over short, sized input; doing so costs recall. Requires the recheck oracle."}},additionalProperties:false}]},skipTestFiles:true,defaultOptions:[{allowCommonPatterns:false,maxPatternLength:500,reportSecondDegreePolynomial:true}],create(context,[options={}]){const{maxPatternLength=500,reportSecondDegreePolynomial=true}=options||{};const MAX_SAFE_REPETITION=5;function isProvablyLinear(pattern){const groupUnderUnboundedQuantifier=/\)[*+]/.test(pattern);const bounded=groupUnderUnboundedQuantifier?null:/\)\{(\d+)(?:,(\d+))?\}/.exec(pattern);if(bounded!==null){const max=bounded[2]!==void 0?Number(bounded[2]):Number(bounded[1]);if(max<=MAX_SAFE_REPETITION)return true}for(const{group,a,b}of COMPLEMENTARY_CLASS_PROBES){if(!group.test(pattern))continue;if(a.test(pattern)&&b.test(pattern))return true}return false}function isProvablyCatastrophic(pattern){const m=/\(([^()|]+)\|([^()|]+)\)[+*]/.exec(pattern);return m!==null&&m[1]===m[2]}function checkWithScslre(node,pattern,flags,runtimeBuilt=false){try{const parse=source=>REGEXPP_PARSER.parsePattern(source,0,source.length,{unicode:flags.includes("u"),unicodeSets:flags.includes("v")});const run=ast2=>(0,scslre_1.analyse)({pattern:ast2,flags:{ignoreCase:flags.includes("i"),unicode:flags.includes("u"),dotAll:flags.includes("s"),multiline:flags.includes("m")}},{reportTypes:{Move:false}});const ast=parse(pattern);let result=run(ast);if(result.reports.length===0){const relaxed=relaxBoundedRangesUnderUnboundedQuantifier(ast,pattern);if(relaxed!==pattern){result=run(parse(relaxed))}}if(isProvablyLinear(pattern)){return}if(result.reports.length===0&&isProvablyCatastrophic(pattern)){if(!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:"Ambiguous alternation (exponential backtracking)",description:"Alternatives inside a quantified group match the same input, so every character can be taken by either branch and the engine explores 2^n paths before failing.",severity:"CRITICAL",fix:"Remove the duplicate alternative, or make the branches mutually exclusive"}});return}const worst=result.reports.find(r=>r.exponential)??result.reports[0];if(worst&&!(0,redos_oracle_1.confirmsRedos)(pattern,flags))return;if(worst&&!reportSecondDegreePolynomial){const degree=(0,redos_oracle_1.worstBacktrackingDegree)(pattern,flags);if(degree!==null&&degree<=2)return}for(const report of worst?[worst]:[]){const isExp=report.exponential;context.report({node,messageId:"redosVulnerable",data:{vulnerabilityName:`${runtimeBuilt?"Runtime-built ":""}${report.type==="Self"?`Self-loop quantifier (${isExp?"exponential":"polynomial"} backtracking)`:`Cross-quantifier trade (${isExp?"exponential":"polynomial"} backtracking)`}`,description:report.type==="Self"?`A quantifier reaches itself via the parent loop. An attacker can craft input that triggers ${isExp?"exponential":"polynomial"} backtracking.`:`Two quantifiers can exchange characters, enabling ${isExp?"exponential":"polynomial"} backtracking on crafted input.`,severity:isExp?"CRITICAL":"HIGH",fix:"Atomic group, possessive quantifier, or rewrite to remove the ambiguity"}})}}catch{}}function checkLiteralRegExp(node){if(!isRegExpLiteral(node)){return}const pattern=node.regex.pattern;const flags=node.regex.flags||"";if(pattern.length>maxPatternLength){return}checkWithScslre(node,pattern,flags)}function resolvePatternSource(node,seen){if(seen.has(node))return null;seen.add(node);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?{pattern:node.value,exact:true}:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return joinQuasis(node.quasis.map(q=>q.value.cooked??q.value.raw),node.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TaggedTemplateExpression&&node.tag.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.tag.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.tag.object.name==="String"&&(0,eslint_devkit_1.propertyName)(node.tag)==="raw"&&!isShadowed("String",node)){return joinQuasis(node.quasi.quasis.map(q=>q.value.raw),node.quasi.expressions,seen)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){const left=resolveOrPlaceholder(node.left,seen);const right=resolveOrPlaceholder(node.right,seen);return{pattern:left.pattern+right.pattern,exact:left.exact&&right.exact}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=resolveBindingInit(node);return init?resolvePatternSource(init,seen):null}return null}function joinQuasis(staticParts,expressions,seen){let pattern="";let exact=true;for(const[index,part]of staticParts.entries()){pattern+=part;const expression=expressions[index];if(!expression)continue;const resolved=resolveOrPlaceholder(expression,seen);pattern+=resolved.pattern;exact&&=resolved.exact}return{pattern,exact}}function resolveOrPlaceholder(node,seen){return resolvePatternSource(node,seen)??{pattern:INTERPOLATION_PLACEHOLDER,exact:false}}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;const writes=variable.references.filter(r=>r.isWrite());return writes.length===1?def.node.init:null}return null}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function checkNewRegExp(node){const callee=node.callee;if(!(0,regexp_intrinsic_1.isRegExpConstructor)(callee,context.sourceCode)){return}const firstArg=node.arguments[0];if(!firstArg||firstArg.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const resolved=resolvePatternSource(firstArg,new Set);if(!resolved||resolved.pattern.length>maxPatternLength){return}const flagsArg=node.arguments[1];const flags=flagsArg?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof flagsArg.value==="string"?flagsArg.value:"";checkWithScslre(node,resolved.pattern,flags,!resolved.exact)}return{Literal:checkLiteralRegExp,CallExpression:node=>checkNewRegExp((0,regexp_intrinsic_1.asDirectConstruction)(node,context.sourceCode)),NewExpression:checkNewRegExp}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[ _-]{0,2}(?:[a-z0-9]{1,12}[ _-]{0,2})?[:=]\\s*\\S`,"i").test(normalized)&&/[:=]\s*\S+\s*$/.test(text)})}function literalLabelsValue(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b\\s*[:=]\\s*$`,"i").test(normalized)){return pattern}}return null}const DESCRIPTOR_SEGMENTS=["msg","message","error","err","label","prompt","hint","description","desc","regex","pattern","placeholder","warning","notice"];function identifierNamesSecret(name,patterns,descriptors){const matched=containsSensitiveData(name,patterns);if(!matched)return null;const last=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(-1).join("");return descriptors.has(last)?null:matched}function memberCarriesSecret(node,patterns,descriptors){const prop=node.property;const propName=node.computed?(0,eslint_devkit_1.staticString)(prop)!==null?(0,eslint_devkit_1.staticString)(prop):null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?identifierNamesSecret(propName,patterns,descriptors):null;if(fromProp)return fromProp;if(propName&&(VALUE_FREE_PROPERTIES.has(propName)||DIAGNOSTIC_ACCESSORS.has(propName)))return null;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(node.object.name,patterns,descriptors):null}const VALUE_FREE_PROPERTIES=new Set(["length","size","byteLength","byteOffset"]);const DIAGNOSTIC_ACCESSORS=new Set(["message","stack","name","status","statusText"]);function isDiagnosticAccessor(node){const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);const value=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;return value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!value.computed&&value.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&DIAGNOSTIC_ACCESSORS.has(value.property.name)}function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},descriptorSegments:{type:"array",items:{type:"string"},default:DESCRIPTOR_SEGMENTS,description:"Trailing name segments that describe a secret rather than hold one, so `apiKeyMsg` and `passwordError` are not reported. Compared as the whole FINAL segment of the name, never as a substring. Replaces the built-in list."},additionalDescriptorSegments:{type:"array",items:{type:"string"},default:[],description:"Extra descriptor segments, on top of `descriptorSegments`."}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,descriptorSegments:DESCRIPTOR_SEGMENTS,additionalDescriptorSegments:[]}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true,descriptorSegments=DESCRIPTOR_SEGMENTS,additionalDescriptorSegments=[]}=options||{};const descriptors=new Set([...descriptorSegments,...additionalDescriptorSegments]);const LOGGER_RECEIVERS=new Set(["console","logger","log"]);const LOG_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);function isLoggerReceiver(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return LOGGER_RECEIVERS.has(node.name.toLowerCase())}return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!node.computed&&node.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOGGER_RECEIVERS.has(node.property.name.toLowerCase())}function describeExposure(argument){const arg=(0,eslint_devkit_1.unwrapTypeSyntax)(argument);const staticText1=(0,eslint_devkit_1.staticString)(arg);if(staticText1!==null){const pattern=literalCarriesSecret(staticText1,sensitivePatterns)?containsSensitiveData(staticText1,sensitivePatterns):null;return pattern?{node:arg,pattern}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){const staticText2=(0,eslint_devkit_1.staticString)(arg.left);if(staticText2!==null){const labelled=literalLabelsValue(staticText2,sensitivePatterns);if(labelled)return{node:arg.left,pattern:labelled}}else{const fromLeft=describeExposure(arg.left);if(fromLeft)return fromLeft}return namedValueExposure(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>namedValueExposure(e)).find(m=>Boolean(m));if(fromExpression)return{node:arg,pattern:fromExpression.pattern};const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const allHolesAreDiagnostic=arg.expressions.every(isNonSecretHole);const fromText=arg.expressions.length>0&&!allHolesAreDiagnostic&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;return fromText?{node:arg,pattern:fromText}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of arg.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const keyName=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"?property.key.value:null;const pattern=keyName?identifierNamesSecret(keyName,sensitivePatterns,descriptors):null;if(!pattern)continue;if((0,eslint_devkit_1.isStaticExpression)({node:property.value,scope:context.sourceCode.getScope(arg)})){continue}return{node:property,pattern}}return null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return describeExposure(arg.consequent)??describeExposure(arg.alternate)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="String"&&arg.arguments.length===1&&arg.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!isShadowed("String",arg)){return describeExposure(arg.arguments[0])}return namedValueExposure(arg)}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function namedValueExposure(node,seen=new Set){const value=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(seen.has(value))return null;seen.add(value);if(value.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return namedValueExposure(value.expression,seen)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const pattern=identifierNamesSecret(value.name,sensitivePatterns,descriptors);if(pattern)return{node:value,pattern};const init=resolveBindingInit(value);const viaBinding=init?namedValueExposure(init,seen):null;return viaBinding?{node:value,pattern:viaBinding.pattern}:null}if(value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const pattern=memberCarriesSecret(value,sensitivePatterns,descriptors);return pattern?{node:value,pattern}:null}return null}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;return variable.references.filter(r=>r.isWrite()).length===1?def.node.init:null}return null}function isNonSecretHole(expression){if(!isDiagnosticAccessor(expression))return false;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(expression);const member=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;if(member.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return true;const init=resolveBindingInit(member.object);if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return true;const key=member.property.name;const assigned=init.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.key.name===key||property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.key.value===key));if(!assigned)return true;return namedValueExposure(assigned.value)===null}function reportFirstExposure(argumentList,exposureContext){for(const argument of argumentList){const exposure=describeExposure(argument);if(exposure){context.report({node:exposure.node,messageId:"sensitiveDataExposure",data:{context:exposureContext,dataType:exposure.pattern}});return}}}function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const property=node.callee.property;return!node.callee.computed&&property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&LOG_METHODS.has(property.name.toLowerCase())&&isLoggerReceiver(node.callee.object)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const words=node.callee.name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.includes("log")||words.includes("logger")}return false})();if(isLoggingCall&&checkConsoleLog){reportFirstExposure(node.arguments,"logs")}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Error"){reportFirstExposure(node.arguments,"error messages")}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSensitiveDataExposure=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");function literalCarriesSecret(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();return patterns.some(pattern=>{const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");return new RegExp(`\\b${flexPattern}\\b[ _-]{0,2}(?:[a-z0-9]{1,12}[ _-]{0,2})?[:=]\\s*\\S`,"i").test(normalized)&&/[:=]\s*\S+\s*$/.test(text)})}function literalLabelsValue(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b\\s*[:=]\\s*$`,"i").test(normalized)){return pattern}}return null}const DESCRIPTOR_SEGMENTS=["msg","message","error","err","label","prompt","hint","description","desc","regex","pattern","placeholder","warning","notice"];function identifierNamesSecret(name,patterns,descriptors){const matched=containsSensitiveData(name,patterns);if(!matched)return null;const last=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(-1).join("");return descriptors.has(last)?null:matched}function memberCarriesSecret(node,patterns,descriptors){const prop=node.property;const propName=node.computed?(0,eslint_devkit_1.staticString)(prop)!==null?(0,eslint_devkit_1.staticString)(prop):null:prop.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?prop.name:null;const fromProp=propName?identifierNamesSecret(propName,patterns,descriptors):null;if(fromProp)return fromProp;if(propName&&(VALUE_FREE_PROPERTIES.has(propName)||DIAGNOSTIC_ACCESSORS.has(propName)))return null;return node.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?identifierNamesSecret(node.object.name,patterns,descriptors):null}const VALUE_FREE_PROPERTIES=new Set(["length","size","byteLength","byteOffset"]);const DIAGNOSTIC_ACCESSORS=new Set(["message","stack","name","status","statusText"]);function isDiagnosticAccessor(node){const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(node);const value=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;return value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(value),DIAGNOSTIC_ACCESSORS)}function containsSensitiveData(text,patterns){const normalized=text.replace(/([a-z])([A-Z])/g,"$1 $2").toLowerCase();for(const pattern of patterns){const escaped=pattern.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");const flexPattern=escaped.replace(/[_ ]/g,"[_ ]");if(new RegExp(`\\b${flexPattern}\\b`,"i").test(normalized)){return pattern}}return null}exports.noSensitiveDataExposure=(0,eslint_devkit_2.createRule)({name:"no-sensitive-data-exposure",meta:{type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sensitive-data-exposure.md",description:"Detects PII/credentials in logs, responses, or error messages",cwe:"CWE-532",cvss:5.3},messages:{sensitiveDataExposure:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Sensitive data exposure",cwe:"CWE-532",description:"Sensitive data detected in {{context}}: {{dataType}}",severity:"HIGH",fix:"Redact or mask sensitive data before logging/exposing",documentationLink:"https://cwe.mitre.org/data/definitions/532.html"})},schema:[{type:"object",properties:{sensitivePatterns:{type:"array",items:{type:"string"},default:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],description:"Sensitive data patterns"},checkConsoleLog:{type:"boolean",default:true,description:"Check console.log statements"},checkErrorMessages:{type:"boolean",default:true,description:"Check error messages"},descriptorSegments:{type:"array",items:{type:"string"},default:DESCRIPTOR_SEGMENTS,description:"Trailing name segments that describe a secret rather than hold one, so `apiKeyMsg` and `passwordError` are not reported. Compared as the whole FINAL segment of the name, never as a substring. Replaces the built-in list."},additionalDescriptorSegments:{type:"array",items:{type:"string"},default:[],description:"Extra descriptor segments, on top of `descriptorSegments`."}},additionalProperties:false}]},defaultOptions:[{sensitivePatterns:["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog:true,checkErrorMessages:true,descriptorSegments:DESCRIPTOR_SEGMENTS,additionalDescriptorSegments:[]}],create(context,[options={}]){const{sensitivePatterns=["password","passwd","secret","token","access_token","auth_token","ssn","credit_card","creditcard","api_key","apikey","secret_key","private_key","encryption_key"],checkConsoleLog=true,checkErrorMessages=true,descriptorSegments=DESCRIPTOR_SEGMENTS,additionalDescriptorSegments=[]}=options||{};const descriptors=new Set([...descriptorSegments,...additionalDescriptorSegments]);const LOGGER_RECEIVERS=new Set(["console","logger","log"]);const LOG_METHODS=new Set(["log","info","warn","error","debug","trace","fatal","verbose","silly"]);function isLoggerReceiver(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return LOGGER_RECEIVERS.has(node.name.toLowerCase())}const name=node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(node):null;return name!==null&&LOGGER_RECEIVERS.has(name.toLowerCase())}function describeExposure(argument){const arg=(0,eslint_devkit_1.unwrapTypeSyntax)(argument);const staticText1=(0,eslint_devkit_1.staticString)(arg);if(staticText1!==null){const pattern=literalCarriesSecret(staticText1,sensitivePatterns)?containsSensitiveData(staticText1,sensitivePatterns):null;return pattern?{node:arg,pattern}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){const staticText2=(0,eslint_devkit_1.staticString)(arg.left);if(staticText2!==null){const labelled=literalLabelsValue(staticText2,sensitivePatterns);if(labelled)return{node:arg.left,pattern:labelled}}else{const fromLeft=describeExposure(arg.left);if(fromLeft)return fromLeft}return namedValueExposure(arg.right)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){const fromExpression=arg.expressions.map(e=>namedValueExposure(e)).find(m=>Boolean(m));if(fromExpression)return{node:arg,pattern:fromExpression.pattern};const INTERPOLATION="";const joined=arg.quasis.map(q=>q.value.cooked).join(INTERPOLATION);const allHolesAreDiagnostic=arg.expressions.every(isNonSecretHole);const fromText=arg.expressions.length>0&&!allHolesAreDiagnostic&&literalCarriesSecret(joined,sensitivePatterns)?containsSensitiveData(joined,sensitivePatterns):null;return fromText?{node:arg,pattern:fromText}:null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){for(const property of arg.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const keyName=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof property.key.value==="string"?property.key.value:null;const pattern=keyName?identifierNamesSecret(keyName,sensitivePatterns,descriptors):null;if(!pattern)continue;if((0,eslint_devkit_1.isStaticExpression)({node:property.value,scope:context.sourceCode.getScope(arg)})){continue}return{node:property,pattern}}return null}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return describeExposure(arg.consequent)??describeExposure(arg.alternate)}if(arg.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&arg.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&arg.callee.name==="String"&&arg.arguments.length===1&&arg.arguments[0].type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!isShadowed("String",arg)){return describeExposure(arg.arguments[0])}return namedValueExposure(arg)}function isShadowed(name,node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length>0}return false}function namedValueExposure(node,seen=new Set){const value=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(seen.has(value))return null;seen.add(value);if(value.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression){return namedValueExposure(value.expression,seen)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const pattern=identifierNamesSecret(value.name,sensitivePatterns,descriptors);if(pattern)return{node:value,pattern};const init=resolveBindingInit(value);const viaBinding=init?namedValueExposure(init,seen):null;return viaBinding?{node:value,pattern:viaBinding.pattern}:null}if(value.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const pattern=memberCarriesSecret(value,sensitivePatterns,descriptors);return pattern?{node:value,pattern}:null}return null}function resolveBindingInit(node){const scope=context.sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(!variable)continue;if(variable.defs.length!==1)return null;const[def]=variable.defs;if(def.type!=="Variable"||!def.node.init)return null;return variable.references.filter(r=>r.isWrite()).length===1?def.node.init:null}return null}function isNonSecretHole(expression){if(!isDiagnosticAccessor(expression))return false;const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(expression);const member=unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?unwrapped.expression:unwrapped;if(member.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return true;const init=resolveBindingInit(member.object);if(init===null||init.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return true;const key=member.property.name;const assigned=init.properties.find(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&!property.computed&&(property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.key.name===key||property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.key.value===key));if(!assigned)return true;return namedValueExposure(assigned.value)===null}function reportFirstExposure(argumentList,exposureContext){for(const argument of argumentList){const exposure=describeExposure(argument);if(exposure){context.report({node:exposure.node,messageId:"sensitiveDataExposure",data:{context:exposureContext,dataType:exposure.pattern}});return}}}function checkCallExpression(node){const isLoggingCall=(()=>{if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const method=(0,eslint_devkit_1.propertyName)(node.callee);return method!==null&&LOG_METHODS.has(method.toLowerCase())&&isLoggerReceiver(node.callee.object)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const words=node.callee.name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.includes("log")||words.includes("logger")}return false})();if(isLoggingCall&&checkConsoleLog){reportFirstExposure(node.arguments,"logs")}}function checkNewExpression(node){if(!checkErrorMessages){return}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="Error"){reportFirstExposure(node.arguments,"error messages")}}return{CallExpression:checkCallExpression,NewExpression:checkNewExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NO_SUBSTITUTIONS=new Map;function substitutionFor(node,scope,substitutions){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=resolveVariable(node.name,scope);return variable===null?void 0:substitutions.get(variable)}function hasRawUnattributedPart(node,scope,substitutions){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>{if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawUnattributedPart(part,scope,substitutions)}const bound=substitutionFor(part,scope,substitutions);if(bound!==void 0){return bound.node!==null&&!(0,eslint_devkit_1.isStaticExpression)({node:bound.node,scope:bound.scope})}return!(0,eslint_devkit_1.isStaticExpression)({node:part,scope})})}const SQL_DRIVER_MODULES=new Set(["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite","mysql","mysql2","@planetscale/database","sqlite3","better-sqlite3","node:sqlite","bun:sqlite","@libsql/client","typeorm","@nestjs/typeorm","sequelize","sequelize-typescript","@nestjs/sequelize","knex","objection","drizzle-orm","@prisma/client","prisma","kysely","mssql","oracledb"]);function isSqlDriverSpecifier(specifier){if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return SQL_DRIVER_MODULES.has(root)}function stringLiteralValue(node){if(node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return null}const SQL_SINK_METHODS=["query","execute"];const TRANSPARENT_CALLS=["String"];const QUERY_TEXT_PROPERTIES=["text","sql"];function invokedMethodName(callee,scope){if(!callee.computed){return callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property.name:null}const direct=stringLiteralValue(callee.property);if(direct!==null)return direct;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=resolveVariable(callee.property.name,scope);if(variable===null)return null;const init=singleAssignedInit(variable);return init===null?null:stringLiteralValue(init)}const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i];function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}const literal=stringLiteralValue(node);return literal===null?"":literal}function looksLikeSqlStatement(nodes){const text=nodes.map(staticText).join("");return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function isBuiltString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.length>0}return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}const REQUEST_ROOTS=["req","request","ctx","event"];const REQUEST_PROPERTIES=["query","params","body","headers","cookies","url","path"];function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function singleAssignedInit(variable){const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function isParameterBinding(variable){return variable.defs.some(def=>def.type==="Parameter"&&!bindsADeclaredContract(def))}function bindsADeclaredContract(def){for(let node=def.name;node!==void 0;node=node.parent??void 0){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){continue}const annotation=node.typeAnnotation?.typeAnnotation;if(annotation?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference)return true}return false}function allWritesStatic(variable,scope){const writes=writeExpressions(variable);if(writes.length===0)return false;return writes.every(node=>(0,eslint_devkit_1.isStaticExpression)({node,scope}))}function writeExpressions(variable){const written=[];for(const reference of variable.references){const{writeExpr}=reference;if(reference.isWrite()&&writeExpr!==void 0&&writeExpr!==null){written.push(writeExpr)}}return written}function isLocallyConstructed(variable,scope){if(variable===null)return false;const init=singleAssignedInit(variable);if(init===null)return false;return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_1.isStaticExpression)({node:init,scope})}function isAmbientGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function attributedThroughCall(node,scope,attribution,depth){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.transparentCalls.has(node.callee.name)&&isAmbientGlobal(node.callee.name,scope)){for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=attributedSource(argument,scope,attribution,depth+1);if(found!==null)return found}return null}const inlined=effectiveExpression(node,scope,attribution);if(inlined.nodes.length===1&&inlined.nodes[0]===node)return null;const inner={...attribution,substitutions:inlined.substitutions};for(const candidate of inlined.nodes){const found=attributedSource(candidate,inlined.scope,inner,depth+1);if(found!==null)return found}return null}function attributedSource(node,scope,attribution,depth=0){if(depth>5)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return attributedSource(bare,scope,attribution,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,attribution,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){properties.unshift(root.property.name)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(isLocallyConstructed(resolveVariable(root.name,scope),scope))return null;if(!properties.some(property=>attribution.requestProperties.has(property))){return null}if(attribution.requestRoots.has(root.name)||attribution.trustRequestShape&&(0,eslint_devkit_1.readsRequestShape)(node,attribution.sourceCode)){return`${root.name}.${properties.join(".")}`}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return attributedSource(node.consequent,scope,attribution,depth+1)??attributedSource(node.alternate,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return attributedThroughCall(node,scope,attribution,depth)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return null;const bound=attribution.substitutions.get(variable);if(bound!==void 0){return bound.node===null?null:attributedSource(bound.node,bound.scope,{...attribution,substitutions:NO_SUBSTITUTIONS},depth+1)}const writes=writeExpressions(variable);for(const write of writes){const found=attributedSource(write,scope,attribution,depth+1);if(found!==null)return found}if(attribution.untrustedParameters&&isParameterBinding(variable)&&!allWritesStatic(variable,scope)&&!isNarrowedByGuardClause(node.name,node,attribution.sourceCode)){return`${node.name} (a caller-supplied parameter)`}return null}return null}function isNarrowedByGuardClause(name,node,sourceCode){let fn=node;while(fn.parent!==void 0&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){fn=fn.parent}const body=fn.body;if(body===void 0||body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return false;for(const statement of body.body){if(statement.range[0]>=node.range[0])break;if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement)continue;const leaves=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(inner=>inner.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||inner.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return false};if(!leaves(statement.consequent))continue;const test=statement.test;if(test.type!==eslint_devkit_1.AST_NODE_TYPES.UnaryExpression||test.operator!=="!")continue;const call=test.argument;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)continue;if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)continue;const method=call.callee.property;if(method.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||method.name!=="has"&&method.name!=="includes"){continue}const[checked]=call.arguments;if(checked?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||checked.name!==name)continue;const receiver=call.callee.object;if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;let search=sourceCode.getScope(node);let declared;while(search!==null&&declared===void 0){declared=search.variables.find(v=>v.name===receiver.name);search=search.upper}const source=declared?.defs[0]?.node.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator?declared.defs[0].node.init:void 0;if(source===void 0||source===null)continue;const listOf=init=>{if(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return[...init.elements].filter(Boolean);if(init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="Set"&&init.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return[...init.arguments[0].elements].filter(Boolean)}return void 0};const members=listOf(source);if(members===void 0||members.length===0)continue;if(members.every(el=>el.type===eslint_devkit_1.AST_NODE_TYPES.Literal))return true}return false}function effectiveExpression(node,scope,attribution,depth=0){const unresolved={nodes:[node],scope,substitutions:NO_SUBSTITUTIONS};if(depth>5)return unresolved;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node){return effectiveExpression(bare,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return effectiveExpression(node.argument,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const joined=joinedArrayElements(node,scope);if(joined!==null){return{nodes:joined,scope,substitutions:NO_SUBSTITUTIONS}}return resolveBuilderCall(node,scope,attribution)??unresolved}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=queryTextProperty(node,attribution.queryTextProperties);return text===null?unresolved:effectiveExpression(text,scope,attribution,depth+1)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return unresolved;const variable=resolveVariable(node.name,scope);if(variable===null)return unresolved;const writes=writeExpressions(variable);if(writes.length===0)return unresolved;if(writes.length===1){return effectiveExpression(writes[0],scope,attribution,depth+1)}return{nodes:writes,scope,substitutions:NO_SUBSTITUTIONS}}function resolveBuilderCall(node,scope,attribution){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const impl=resolveLocalFunction(node.callee.name,scope);if(impl===null)return null;const returned=returnedExpression(impl);if(returned===null||returned.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&returned.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return null}const bindings=bindParameters(impl,node.arguments,scope,attribution.sourceCode);if(bindings===null)return null;return{nodes:[returned],scope:attribution.sourceCode.getScope(returned),substitutions:bindings}}function resolveLocalFunction(name,scope){const variable=resolveVariable(name,scope);if(variable===null)return null;const declared=variable.defs.find(def=>def.type==="FunctionName");if(declared!==void 0){return declared.node}const init=singleAssignedInit(variable);if(init!==null&&(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression)){return init}return null}function returnedExpression(impl){if(impl.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return impl.body;const[only]=impl.body.body;if(impl.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument??null}function joinedArrayElements(node,scope){const{callee}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed){return null}if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||callee.property.name!=="join"){return null}let receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(receiver.name,scope);const init=variable===null?null:singleAssignedInit(variable);if(init===null)return null;receiver=init}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;const elements=[];for(const element of receiver.elements){if(element===null||element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){continue}elements.push(element)}return elements}function queryTextProperty(node,names){for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const key=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:stringLiteralValue(property.key);if(key!==null&&names.has(key))return property.value}return null}function bindParameters(impl,args,callerScope,sourceCode){if(args.some(a=>a.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement))return null;if(impl.params.some(p=>p.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier))return null;const bindings=new Map;sourceCode.getDeclaredVariables(impl).filter(variable=>isParameterBinding(variable)).forEach((variable,index)=>{bindings.set(variable,{node:args[index]??null,scope:callerScope})});return bindings}exports.noSqlInjection=(0,eslint_devkit_1.createRule)({name:"no-sql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sql-injection.md",description:"Prevent SQL injection when a query is built from attacker-controlled input and executed through a driver-agnostic handle",cwe:"CWE-89",cvss:9.8,confidence:"high"},messages:{sqlInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",cwe:"CWE-89",owasp:"A03:2021",cvss:9.8,description:'SQL statement built from "{{source}}" and executed. An attacker controls part of the statement text.',severity:"CRITICAL",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:"Pass the value as a bound parameter (`$1` / `?`) instead of concatenating it into the statement.",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"})},schema:[{type:"object",properties:{reportUnattributedInterpolation:{type:"boolean",default:false,description:"Report SQL built by interpolation even when the interpolated value cannot be traced to a request in this file (a property of `this`, a property of a non-request object, a helper return). Parameterise either way. Set false to report only attributable taint."},treatParametersAsUntrusted:{type:"boolean",default:true,description:"Treat a function parameter spliced into statement text as an untrusted inlet \u2014 nothing in this file constrains what a caller passes. Set false to report only values traceable to a request within the linted file."},requestRoots:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Identifier roots that denote an inbound request. Matched exactly."},requestProperties:{type:"array",items:{type:"string"},default:[...REQUEST_PROPERTIES],description:"Request properties that carry caller-supplied data. Matched exactly."},sinkMethods:{type:"array",items:{type:"string"},default:[...SQL_SINK_METHODS],description:"Method names that execute a raw SQL string. Matched exactly against the called member name."},queryTextProperties:{type:"array",items:{type:"string"},default:[...QUERY_TEXT_PROPERTIES],description:"Properties of a driver query-config object that hold the statement text. Matched exactly."},transparentCalls:{type:"array",items:{type:"string"},default:[...TRANSPARENT_CALLS],description:"Ambient global calls that pass their argument through unchanged, so taint survives them. Matched exactly, and only when the file declares no binding of that name."}},additionalProperties:false}]},defaultOptions:[{reportUnattributedInterpolation:false,treatParametersAsUntrusted:true,requestRoots:REQUEST_ROOTS,requestProperties:REQUEST_PROPERTIES,sinkMethods:SQL_SINK_METHODS,transparentCalls:TRANSPARENT_CALLS,queryTextProperties:QUERY_TEXT_PROPERTIES}],create(context,[options={}]){const{reportUnattributedInterpolation=false,treatParametersAsUntrusted=true,requestRoots=REQUEST_ROOTS,requestProperties=REQUEST_PROPERTIES,sinkMethods=SQL_SINK_METHODS,transparentCalls=TRANSPARENT_CALLS,queryTextProperties=QUERY_TEXT_PROPERTIES}=options;const attribution={substitutions:NO_SUBSTITUTIONS,untrustedParameters:treatParametersAsUntrusted,requestRoots:new Set(requestRoots),trustRequestShape:requestRoots.length===REQUEST_ROOTS.length&&REQUEST_ROOTS.every((name,index)=>requestRoots[index]===name),requestProperties:new Set(requestProperties),transparentCalls:new Set(transparentCalls),queryTextProperties:new Set(queryTextProperties),sourceCode:context.sourceCode};const sinks=new Set(sinkMethods);const pending=[];let importsSqlDriver=false;const noteSpecifier=specifier=>{if(specifier!==null&&isSqlDriverSpecifier(specifier)){importsSqlDriver=true}};return{ImportDeclaration(node){noteSpecifier(node.source.value)},ImportExpression(node){noteSpecifier(stringLiteralValue(node.source))},TSImportEqualsDeclaration(node){if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){noteSpecifier(stringLiteralValue(node.moduleReference.expression))}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){noteSpecifier(stringLiteralValue(node.arguments[0]));return}if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callScope=context.sourceCode.getScope(node);const method=invokedMethodName(node.callee,callScope);if(method===null||!sinks.has(method))return;const[firstArgument]=node.arguments;if(firstArgument===void 0||firstArgument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const{nodes,scope,substitutions}=effectiveExpression(firstArgument,callScope,attribution);const built=nodes.some(isBuiltString)||nodes.length>1&&nodes.some(n=>!(0,eslint_devkit_1.isStaticExpression)({node:n,scope}));if(!built)return;if(!looksLikeSqlStatement(nodes))return;const sinkAttribution={...attribution,substitutions};for(const candidate of nodes){const source=attributedSource(candidate,scope,sinkAttribution);if(source!==null){pending.push({node,source});return}}if(reportUnattributedInterpolation&&nodes.some(n=>(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&hasRawUnattributedPart(n,scope,substitutions))){pending.push({node,source:"a value this file cannot attribute"})}},"Program:exit"(){if(importsSqlDriver)return;for(const finding of pending){context.report({node:finding.node,messageId:"sqlInjection",data:{source:finding.source}})}}}}});exports.default=exports.noSqlInjection;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSqlInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const NO_SUBSTITUTIONS=new Map;function substitutionFor(node,scope,substitutions){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return void 0;const variable=resolveVariable(node.name,scope);return variable===null?void 0:substitutions.get(variable)}function hasRawUnattributedPart(node,scope,substitutions){const parts=node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral?[...node.expressions]:[node.left,node.right];return parts.some(part=>{if(part.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(part.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||part.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return hasRawUnattributedPart(part,scope,substitutions)}const bound=substitutionFor(part,scope,substitutions);if(bound!==void 0){return bound.node!==null&&!(0,eslint_devkit_1.isStaticExpression)({node:bound.node,scope:bound.scope})}return!(0,eslint_devkit_1.isStaticExpression)({node:part,scope})})}const SQL_DRIVER_MODULES=new Set(["pg","pg-pool","pg-native","pg-cursor","pg-promise","pg-copy-streams","postgres","slonik","@vercel/postgres","@neondatabase/serverless","@electric-sql/pglite","mysql","mysql2","@planetscale/database","sqlite3","better-sqlite3","node:sqlite","bun:sqlite","@libsql/client","typeorm","@nestjs/typeorm","sequelize","sequelize-typescript","@nestjs/sequelize","knex","objection","drizzle-orm","@prisma/client","prisma","kysely","mssql","oracledb"]);function isSqlDriverSpecifier(specifier){if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return SQL_DRIVER_MODULES.has(root)}function stringLiteralValue(node){if(node!==void 0&&node.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return null}const SQL_SINK_METHODS=["query","execute"];const TRANSPARENT_CALLS=["String"];const QUERY_TEXT_PROPERTIES=["text","sql"];function invokedMethodName(callee,scope){const named=(0,eslint_devkit_1.propertyName)(callee);if(named!==null)return named;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=resolveVariable(callee.property.name,scope);if(variable===null)return null;const init=singleAssignedInit(variable);return init===null?null:stringLiteralValue(init)}const SQL_STATEMENTS=[/^\s*select\b[\s\S]*\bfrom\b/i,/^\s*insert\s+into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*replace\s+into\b/i,/^\s*merge\s+into\b/i];function staticText(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join("")}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return`${staticText(node.left)}${staticText(node.right)}`}const literal=stringLiteralValue(node);return literal===null?"":literal}function looksLikeSqlStatement(nodes){const text=nodes.map(staticText).join("");return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function isBuiltString(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.length>0}return node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"}const REQUEST_ROOTS=["req","request","ctx","event"];const REQUEST_PROPERTIES=["query","params","body","headers","cookies","url","path"];function resolveVariable(name,scope){for(let current=scope;current!==null;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function singleAssignedInit(variable){const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return null;const def=variable.defs.find(d=>d.type==="Variable");if(def===void 0)return null;return def.node.init??null}function isParameterBinding(variable){return variable.defs.some(def=>def.type==="Parameter"&&!bindsADeclaredContract(def))}function bindsADeclaredContract(def){for(let node=def.name;node!==void 0;node=node.parent??void 0){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayPattern&&node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){continue}const annotation=node.typeAnnotation?.typeAnnotation;if(annotation?.type===eslint_devkit_1.AST_NODE_TYPES.TSTypeReference)return true}return false}function allWritesStatic(variable,scope){const writes=writeExpressions(variable);if(writes.length===0)return false;return writes.every(node=>(0,eslint_devkit_1.isStaticExpression)({node,scope}))}function writeExpressions(variable){const written=[];for(const reference of variable.references){const{writeExpr}=reference;if(reference.isWrite()&&writeExpr!==void 0&&writeExpr!==null){written.push(writeExpr)}}return written}function isLocallyConstructed(variable,scope){if(variable===null)return false;const init=singleAssignedInit(variable);if(init===null)return false;return init.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression||(0,eslint_devkit_1.isStaticExpression)({node:init,scope})}function isAmbientGlobal(name,scope){const variable=resolveVariable(name,scope);return variable===null||variable.defs.length===0}function attributedThroughCall(node,scope,attribution,depth){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&attribution.transparentCalls.has(node.callee.name)&&isAmbientGlobal(node.callee.name,scope)){for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=attributedSource(argument,scope,attribution,depth+1);if(found!==null)return found}return null}const inlined=effectiveExpression(node,scope,attribution);if(inlined.nodes.length===1&&inlined.nodes[0]===node)return null;const inner={...attribution,substitutions:inlined.substitutions};for(const candidate of inlined.nodes){const found=attributedSource(candidate,inlined.scope,inner,depth+1);if(found!==null)return found}return null}function attributedSource(node,scope,attribution,depth=0){if(depth>5)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return attributedSource(bare,scope,attribution,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=attributedSource(expression,scope,attribution,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){properties.unshift(root.property.name)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;if(isLocallyConstructed(resolveVariable(root.name,scope),scope))return null;if(!properties.some(property=>attribution.requestProperties.has(property))){return null}if(attribution.requestRoots.has(root.name)||attribution.trustRequestShape&&(0,eslint_devkit_1.readsRequestShape)(node,attribution.sourceCode)){return`${root.name}.${properties.join(".")}`}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){return attributedSource(node.consequent,scope,attribution,depth+1)??attributedSource(node.alternate,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return attributedSource(node.left,scope,attribution,depth+1)??attributedSource(node.right,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){return attributedThroughCall(node,scope,attribution,depth)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(node.name,scope);if(variable===null)return null;const bound=attribution.substitutions.get(variable);if(bound!==void 0){return bound.node===null?null:attributedSource(bound.node,bound.scope,{...attribution,substitutions:NO_SUBSTITUTIONS},depth+1)}const writes=writeExpressions(variable);for(const write of writes){const found=attributedSource(write,scope,attribution,depth+1);if(found!==null)return found}if(attribution.untrustedParameters&&isParameterBinding(variable)&&!allWritesStatic(variable,scope)&&!isNarrowedByGuardClause(node.name,node,attribution.sourceCode)){return`${node.name} (a caller-supplied parameter)`}return null}return null}function isNarrowedByGuardClause(name,node,sourceCode){let fn=node;while(fn.parent!==void 0&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.FunctionExpression&&fn.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){fn=fn.parent}const body=fn.body;if(body===void 0||body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return false;for(const statement of body.body){if(statement.range[0]>=node.range[0])break;if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.IfStatement)continue;const leaves=consequent=>{if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)return true;if(consequent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){return consequent.body.some(inner=>inner.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement||inner.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement)}return false};if(!leaves(statement.consequent))continue;const test=statement.test;if(test.type!==eslint_devkit_1.AST_NODE_TYPES.UnaryExpression||test.operator!=="!")continue;const call=test.argument;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)continue;if(call.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)continue;const method=call.callee.property;if(method.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||method.name!=="has"&&method.name!=="includes"){continue}const[checked]=call.arguments;if(checked?.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||checked.name!==name)continue;const receiver=call.callee.object;if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)continue;let search=sourceCode.getScope(node);let declared;while(search!==null&&declared===void 0){declared=search.variables.find(v=>v.name===receiver.name);search=search.upper}const source=declared?.defs[0]?.node.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator?declared.defs[0].node.init:void 0;if(source===void 0||source===null)continue;const listOf=init=>{if(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return[...init.elements].filter(Boolean);if(init.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&init.callee.name==="Set"&&init.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression){return[...init.arguments[0].elements].filter(Boolean)}return void 0};const members=listOf(source);if(members===void 0||members.length===0)continue;if(members.every(el=>el.type===eslint_devkit_1.AST_NODE_TYPES.Literal))return true}return false}function effectiveExpression(node,scope,attribution,depth=0){const unresolved={nodes:[node],scope,substitutions:NO_SUBSTITUTIONS};if(depth>5)return unresolved;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node){return effectiveExpression(bare,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return effectiveExpression(node.argument,scope,attribution,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const joined=joinedArrayElements(node,scope);if(joined!==null){return{nodes:joined,scope,substitutions:NO_SUBSTITUTIONS}}return resolveBuilderCall(node,scope,attribution)??unresolved}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression){const text=queryTextProperty(node,attribution.queryTextProperties);return text===null?unresolved:effectiveExpression(text,scope,attribution,depth+1)}if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return unresolved;const variable=resolveVariable(node.name,scope);if(variable===null)return unresolved;const writes=writeExpressions(variable);if(writes.length===0)return unresolved;if(writes.length===1){return effectiveExpression(writes[0],scope,attribution,depth+1)}return{nodes:writes,scope,substitutions:NO_SUBSTITUTIONS}}function resolveBuilderCall(node,scope,attribution){if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const impl=resolveLocalFunction(node.callee.name,scope);if(impl===null)return null;const returned=returnedExpression(impl);if(returned===null||returned.type!==eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&returned.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return null}const bindings=bindParameters(impl,node.arguments,scope,attribution.sourceCode);if(bindings===null)return null;return{nodes:[returned],scope:attribution.sourceCode.getScope(returned),substitutions:bindings}}function resolveLocalFunction(name,scope){const variable=resolveVariable(name,scope);if(variable===null)return null;const declared=variable.defs.find(def=>def.type==="FunctionName");if(declared!==void 0){return declared.node}const init=singleAssignedInit(variable);if(init!==null&&(init.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||init.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression)){return init}return null}function returnedExpression(impl){if(impl.body.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return impl.body;const[only]=impl.body.body;if(impl.body.body.length!==1||only?.type!==eslint_devkit_1.AST_NODE_TYPES.ReturnStatement){return null}return only.argument??null}function joinedArrayElements(node,scope){const{callee}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return null}if((0,eslint_devkit_1.propertyName)(callee)!=="join"){return null}let receiver=callee.object;if(receiver.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const variable=resolveVariable(receiver.name,scope);const init=variable===null?null:singleAssignedInit(variable);if(init===null)return null;receiver=init}if(receiver.type!==eslint_devkit_1.AST_NODE_TYPES.ArrayExpression)return null;const elements=[];for(const element of receiver.elements){if(element===null||element.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){continue}elements.push(element)}return elements}function queryTextProperty(node,names){for(const property of node.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed)continue;const key=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:stringLiteralValue(property.key);if(key!==null&&names.has(key))return property.value}return null}function bindParameters(impl,args,callerScope,sourceCode){if(args.some(a=>a.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement))return null;if(impl.params.some(p=>p.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier))return null;const bindings=new Map;sourceCode.getDeclaredVariables(impl).filter(variable=>isParameterBinding(variable)).forEach((variable,index)=>{bindings.set(variable,{node:args[index]??null,scope:callerScope})});return bindings}exports.noSqlInjection=(0,eslint_devkit_1.createRule)({name:"no-sql-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-sql-injection.md",description:"Prevent SQL injection when a query is built from attacker-controlled input and executed through a driver-agnostic handle",cwe:"CWE-89",cvss:9.8,confidence:"high"},messages:{sqlInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",cwe:"CWE-89",owasp:"A03:2021",cvss:9.8,description:'SQL statement built from "{{source}}" and executed. An attacker controls part of the statement text.',severity:"CRITICAL",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:"Pass the value as a bound parameter (`$1` / `?`) instead of concatenating it into the statement.",documentationLink:"https://owasp.org/www-community/attacks/SQL_Injection"})},schema:[{type:"object",properties:{reportUnattributedInterpolation:{type:"boolean",default:false,description:"Report SQL built by interpolation even when the interpolated value cannot be traced to a request in this file (a property of `this`, a property of a non-request object, a helper return). Parameterise either way. Set false to report only attributable taint."},treatParametersAsUntrusted:{type:"boolean",default:true,description:"Treat a function parameter spliced into statement text as an untrusted inlet \u2014 nothing in this file constrains what a caller passes. Set false to report only values traceable to a request within the linted file."},requestRoots:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Identifier roots that denote an inbound request. Matched exactly."},requestProperties:{type:"array",items:{type:"string"},default:[...REQUEST_PROPERTIES],description:"Request properties that carry caller-supplied data. Matched exactly."},sinkMethods:{type:"array",items:{type:"string"},default:[...SQL_SINK_METHODS],description:"Method names that execute a raw SQL string. Matched exactly against the called member name."},queryTextProperties:{type:"array",items:{type:"string"},default:[...QUERY_TEXT_PROPERTIES],description:"Properties of a driver query-config object that hold the statement text. Matched exactly."},transparentCalls:{type:"array",items:{type:"string"},default:[...TRANSPARENT_CALLS],description:"Ambient global calls that pass their argument through unchanged, so taint survives them. Matched exactly, and only when the file declares no binding of that name."}},additionalProperties:false}]},defaultOptions:[{reportUnattributedInterpolation:false,treatParametersAsUntrusted:true,requestRoots:REQUEST_ROOTS,requestProperties:REQUEST_PROPERTIES,sinkMethods:SQL_SINK_METHODS,transparentCalls:TRANSPARENT_CALLS,queryTextProperties:QUERY_TEXT_PROPERTIES}],create(context,[options={}]){const{reportUnattributedInterpolation=false,treatParametersAsUntrusted=true,requestRoots=REQUEST_ROOTS,requestProperties=REQUEST_PROPERTIES,sinkMethods=SQL_SINK_METHODS,transparentCalls=TRANSPARENT_CALLS,queryTextProperties=QUERY_TEXT_PROPERTIES}=options;const attribution={substitutions:NO_SUBSTITUTIONS,untrustedParameters:treatParametersAsUntrusted,requestRoots:new Set(requestRoots),trustRequestShape:requestRoots.length===REQUEST_ROOTS.length&&REQUEST_ROOTS.every((name,index)=>requestRoots[index]===name),requestProperties:new Set(requestProperties),transparentCalls:new Set(transparentCalls),queryTextProperties:new Set(queryTextProperties),sourceCode:context.sourceCode};const sinks=new Set(sinkMethods);const pending=[];let importsSqlDriver=false;const noteSpecifier=specifier=>{if(specifier!==null&&isSqlDriverSpecifier(specifier)){importsSqlDriver=true}};return{ImportDeclaration(node){noteSpecifier(node.source.value)},ImportExpression(node){noteSpecifier(stringLiteralValue(node.source))},TSImportEqualsDeclaration(node){if(node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){noteSpecifier(stringLiteralValue(node.moduleReference.expression))}},CallExpression(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"){noteSpecifier(stringLiteralValue(node.arguments[0]));return}if(node.callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const callScope=context.sourceCode.getScope(node);const method=invokedMethodName(node.callee,callScope);if(method===null||!sinks.has(method))return;const[firstArgument]=node.arguments;if(firstArgument===void 0||firstArgument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return}const{nodes,scope,substitutions}=effectiveExpression(firstArgument,callScope,attribution);const built=nodes.some(isBuiltString)||nodes.length>1&&nodes.some(n=>!(0,eslint_devkit_1.isStaticExpression)({node:n,scope}));if(!built)return;if(!looksLikeSqlStatement(nodes))return;const sinkAttribution={...attribution,substitutions};for(const candidate of nodes){const source=attributedSource(candidate,scope,sinkAttribution);if(source!==null){pending.push({node,source});return}}if(reportUnattributedInterpolation&&nodes.some(n=>(n.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral||n.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)&&hasRawUnattributedPart(n,scope,substitutions))){pending.push({node,source:"a value this file cannot attribute"})}},"Program:exit"(){if(importsSqlDriver)return;for(const finding of pending){context.report({node:finding.node,messageId:"sqlInjection",data:{source:finding.source}})}}}}});exports.default=exports.noSqlInjection;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTemplateInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const TEMPLATE_COMPILE_METHODS=new Set(["compile","precompile","create","parse","template"]);const TEMPLATE_RENDER_METHODS=new Set(["render","renderFile","renderString","renderToString","renderTemplate"]);const ALL_TEMPLATE_METHODS=new Set([...TEMPLATE_COMPILE_METHODS,...TEMPLATE_RENDER_METHODS]);const DEFAULT_TEMPLATE_ENGINES=["Handlebars","handlebars","ejs","pug","jade","mustache","Mustache","nunjucks","swig","dust","Dust","doT","consolidate"];const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const DEFAULT_UNTRUSTED_NAME_WORDS=["user","untrusted","attacker","external","remote","client","payload","input"];function nameStatesUntrusted(name,vocabulary){const words=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.some(word=>vocabulary.untrustedNameWords.has(word))}function untrustedSource(node,vocabulary,depth=0){if(depth>6)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return untrustedSource(bare,vocabulary,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameStatesUntrusted(node.name,vocabulary)?node.name:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=untrustedSource(expression,vocabulary,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return untrustedSource(node.argument,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){properties.unshift(root.property.name)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const chain=[root.name,...properties].join(".");if(vocabulary.requestRoots.has(root.name)&&properties.some(property=>vocabulary.requestProperties.has(property))){return chain}if(root.name==="process"&&properties[0]==="argv")return"process.argv";return[root.name,...properties].some(part=>nameStatesUntrusted(part,vocabulary))?chain:null}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&&READER_METHODS.has(callee.property.name)){return callee.property.name}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&READER_METHODS.has(callee.name)){return callee.name}for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=untrustedSource(argument,vocabulary,depth+1);if(found!==null)return found}return null}return null}exports.noTemplateInjection=(0,eslint_devkit_1.createRule)({name:"no-template-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-template-injection.md",description:"Disallow dynamic strings as template arguments to server-side template engines (CWE-94)",cwe:"CWE-94",cvss:9.8},messages:{templateInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Template Injection (CWE-94)",cwe:"CWE-94",description:"{{engine}}.{{method}}() receives a dynamic string. An attacker who controls the template can execute arbitrary server-side code.",severity:"CRITICAL",fix:"Pass only string literals as templates. If the template must vary, load it from a trusted file system path, never from user input.",documentationLink:"https://portswigger.net/web-security/server-side-template-injection"})},schema:[{type:"object",properties:{templateEngines:{type:"array",items:{type:"string"},default:DEFAULT_TEMPLATE_ENGINES,description:"Receiver names that denote a server-side template engine, compared as an exact identifier name and never as a substring. Replaces the built-in list."},additionalTemplateEngines:{type:"array",items:{type:"string"},default:[],description:"Extra template-engine receiver names, on top of `templateEngines` \u2014 an alias import such as `hbs` belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifier roots that denote an inbound request, matched as the exact ROOT of a member chain. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."},requestProperties:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_PROPERTIES,description:"Request properties that carry caller-supplied data, matched as a whole segment of the member chain. Replaces the built-in list."},additionalRequestProperties:{type:"array",items:{type:"string"},default:[],description:"Extra request properties, on top of `requestProperties` \u2014 hapi's `request.payload` belongs here."},untrustedNameWords:{type:"array",items:{type:"string"},default:DEFAULT_UNTRUSTED_NAME_WORDS,description:"Words with which an author states a value came from outside, compared as a WHOLE word of the split identifier and never as a substring. Replaces the built-in list."},additionalUntrustedNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra untrusted-provenance words, on top of `untrustedNameWords`."}},additionalProperties:false}]},defaultOptions:[{templateEngines:DEFAULT_TEMPLATE_ENGINES,additionalTemplateEngines:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[],untrustedNameWords:DEFAULT_UNTRUSTED_NAME_WORDS,additionalUntrustedNameWords:[]}],create(context){const options=context.options[0]??{};const engines=new Set([...options.templateEngines??DEFAULT_TEMPLATE_ENGINES,...options.additionalTemplateEngines??[]]);const vocabulary={requestRoots:new Set([...options.requestRoots??DEFAULT_REQUEST_ROOTS,...options.additionalRequestRoots??[]]),requestProperties:new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]),untrustedNameWords:new Set([...options.untrustedNameWords??DEFAULT_UNTRUSTED_NAME_WORDS,...options.additionalUntrustedNameWords??[]])};return{CallExpression(node){const{callee,arguments:args}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const{object,property}=callee;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const engineName=object.name;const methodName=property.name;if(!engines.has(engineName))return;if(!ALL_TEMPLATE_METHODS.has(methodName))return;const firstArg=args[0];if(!firstArg)return;if(firstArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof firstArg.value==="string")return;if(firstArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&firstArg.expressions.length===0)return;if(untrustedSource(firstArg,vocabulary)===null)return;context.report({node:firstArg,messageId:"templateInjection",data:{engine:engineName,method:methodName}})}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTemplateInjection=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const TEMPLATE_COMPILE_METHODS=new Set(["compile","precompile","create","parse","template"]);const TEMPLATE_RENDER_METHODS=new Set(["render","renderFile","renderString","renderToString","renderTemplate"]);const ALL_TEMPLATE_METHODS=new Set([...TEMPLATE_COMPILE_METHODS,...TEMPLATE_RENDER_METHODS]);const DEFAULT_TEMPLATE_ENGINES=["Handlebars","handlebars","ejs","pug","jade","mustache","Mustache","nunjucks","swig","dust","Dust","doT","consolidate"];const DEFAULT_REQUEST_ROOTS=["req","request","ctx","event","message"];const DEFAULT_REQUEST_PROPERTIES=["query","params","body","headers","url","path","cookies","data"];const READER_METHODS=new Set(["readFile","readFileSync","text","json","arrayBuffer","formData","blob"]);const DEFAULT_UNTRUSTED_NAME_WORDS=["user","untrusted","attacker","external","remote","client","payload","input"];function nameStatesUntrusted(name,vocabulary){const words=name.replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/);return words.some(word=>vocabulary.untrustedNameWords.has(word))}function untrustedSource(node,vocabulary,depth=0){if(depth>6)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return untrustedSource(bare,vocabulary,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameStatesUntrusted(node.name,vocabulary)?node.name:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){for(const expression of node.expressions){const found=untrustedSource(expression,vocabulary,depth+1);if(found!==null)return found}return null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return untrustedSource(node.left,vocabulary,depth+1)??untrustedSource(node.right,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression){return untrustedSource(node.argument,vocabulary,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){let root=node;const properties=[];while(root.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(root.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){properties.unshift(root.property.name)}root=root.object}if(root.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const chain=[root.name,...properties].join(".");if(vocabulary.requestRoots.has(root.name)&&properties.some(property=>vocabulary.requestProperties.has(property))){return chain}if(root.name==="process"&&properties[0]==="argv")return"process.argv";return[root.name,...properties].some(part=>nameStatesUntrusted(part,vocabulary))?chain:null}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),READER_METHODS)){return(0,eslint_devkit_1.propertyName)(callee)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&READER_METHODS.has(callee.name)){return callee.name}for(const argument of node.arguments){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)continue;const found=untrustedSource(argument,vocabulary,depth+1);if(found!==null)return found}return null}return null}exports.noTemplateInjection=(0,eslint_devkit_1.createRule)({name:"no-template-injection",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-template-injection.md",description:"Disallow dynamic strings as template arguments to server-side template engines (CWE-94)",cwe:"CWE-94",cvss:9.8},messages:{templateInjection:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Template Injection (CWE-94)",cwe:"CWE-94",description:"{{engine}}.{{method}}() receives a dynamic string. An attacker who controls the template can execute arbitrary server-side code.",severity:"CRITICAL",fix:"Pass only string literals as templates. If the template must vary, load it from a trusted file system path, never from user input.",documentationLink:"https://portswigger.net/web-security/server-side-template-injection"})},schema:[{type:"object",properties:{templateEngines:{type:"array",items:{type:"string"},default:DEFAULT_TEMPLATE_ENGINES,description:"Receiver names that denote a server-side template engine, compared as an exact identifier name and never as a substring. Replaces the built-in list."},additionalTemplateEngines:{type:"array",items:{type:"string"},default:[],description:"Extra template-engine receiver names, on top of `templateEngines` \u2014 an alias import such as `hbs` belongs here."},requestRoots:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_ROOTS,description:"Identifier roots that denote an inbound request, matched as the exact ROOT of a member chain. Replaces the built-in list."},additionalRequestRoots:{type:"array",items:{type:"string"},default:[],description:"Extra request-object root names, on top of `requestRoots`."},requestProperties:{type:"array",items:{type:"string"},default:DEFAULT_REQUEST_PROPERTIES,description:"Request properties that carry caller-supplied data, matched as a whole segment of the member chain. Replaces the built-in list."},additionalRequestProperties:{type:"array",items:{type:"string"},default:[],description:"Extra request properties, on top of `requestProperties` \u2014 hapi's `request.payload` belongs here."},untrustedNameWords:{type:"array",items:{type:"string"},default:DEFAULT_UNTRUSTED_NAME_WORDS,description:"Words with which an author states a value came from outside, compared as a WHOLE word of the split identifier and never as a substring. Replaces the built-in list."},additionalUntrustedNameWords:{type:"array",items:{type:"string"},default:[],description:"Extra untrusted-provenance words, on top of `untrustedNameWords`."}},additionalProperties:false}]},defaultOptions:[{templateEngines:DEFAULT_TEMPLATE_ENGINES,additionalTemplateEngines:[],requestRoots:DEFAULT_REQUEST_ROOTS,additionalRequestRoots:[],requestProperties:DEFAULT_REQUEST_PROPERTIES,additionalRequestProperties:[],untrustedNameWords:DEFAULT_UNTRUSTED_NAME_WORDS,additionalUntrustedNameWords:[]}],create(context){const options=context.options[0]??{};const engines=new Set([...options.templateEngines??DEFAULT_TEMPLATE_ENGINES,...options.additionalTemplateEngines??[]]);const vocabulary={requestRoots:new Set([...options.requestRoots??DEFAULT_REQUEST_ROOTS,...options.additionalRequestRoots??[]]),requestProperties:new Set([...options.requestProperties??DEFAULT_REQUEST_PROPERTIES,...options.additionalRequestProperties??[]]),untrustedNameWords:new Set([...options.untrustedNameWords??DEFAULT_UNTRUSTED_NAME_WORDS,...options.additionalUntrustedNameWords??[]])};return{CallExpression(node){const{callee,arguments:args}=node;if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return;const{object}=callee;if(object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return;const methodName=(0,eslint_devkit_1.propertyName)(callee);if(methodName===null)return;const engineName=object.name;if(!engines.has(engineName))return;if(!ALL_TEMPLATE_METHODS.has(methodName))return;const firstArg=args[0];if(!firstArg)return;if(firstArg.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof firstArg.value==="string")return;if(firstArg.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral&&firstArg.expressions.length===0)return;if(untrustedSource(firstArg,vocabulary)===null)return;context.report({node:firstArg,messageId:"templateInjection",data:{engine:engineName,method:methodName}})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUncheckedLoopCondition=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noUncheckedLoopCondition=(0,eslint_devkit_1.createRule)({name:"no-unchecked-loop-condition",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unchecked-loop-condition.md",description:"Detects unchecked loop conditions that could cause DoS",cwe:"CWE-400"},messages:{uncheckedLoopCondition:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unchecked Loop Condition",cwe:"CWE-400",description:"Loop condition may cause DoS through excessive iterations",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),infiniteLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Infinite Loop",cwe:"CWE-400",description:"Loop may run indefinitely",severity:"CRITICAL",fix:"Add termination condition or iteration limit",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),userControlledLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Loop Bound",cwe:"CWE-606",description:"Loop bound controlled by user input",severity:"HIGH",fix:"Limit maximum iterations or validate input",documentationLink:"https://cwe.mitre.org/data/definitions/606.html"}),missingLoopTermination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Loop Termination",cwe:"CWE-400",description:"Loop lacks clear termination condition",severity:"MEDIUM",fix:"Add explicit termination condition",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),largeLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Large Loop Bound",cwe:"CWE-400",description:"Loop may iterate excessively",severity:"MEDIUM",fix:"Limit maximum iterations",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),unsafeRecursion:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Recursion",cwe:"CWE-674",description:"Recursive function may cause stack overflow",severity:"HIGH",fix:"Add recursion depth limit or use iterative approach",documentationLink:"https://cwe.mitre.org/data/definitions/674.html"})},schema:[{type:"object",properties:{maxStaticIterations:{type:"number",minimum:100,default:1e4,description:"Literal iteration count above which a loop is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},allowWhileTrueWithBreak:{type:"boolean",default:true,description:"Allow `while (true)` when the body contains a `break`"},maxRecursionDepth:{type:"number",minimum:1,default:10,description:"Recursion depth above which a call is reported"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as loop protectors"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{maxStaticIterations:1e4,userInputVariables:["req","request","body","query","params","input","data"],allowWhileTrueWithBreak:true,maxRecursionDepth:10,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const functionCalls=new Map;const reportedRecursion=new Set;const currentFunctionStack=[];const taintedVariables=new Set;const REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"]);const isUserInput=varName=>{if(taintedVariables.has(varName)){return true}const lowerVarName=varName.toLowerCase();const isUsingDefaults=userInputVariables.length===7&&userInputVariables.includes("req")&&userInputVariables.includes("input");if(!isUsingDefaults){return userInputVariables.some(input=>lowerVarName===input.toLowerCase())}return REQUEST_OBJECTS.has(lowerVarName)};const checkIfCollectionIsValidated=(forOfNode,collection)=>{const guarded=collection;const validates=test=>{let sawArrayCheck=false;let sawLengthComparison=false;const walk=node=>{if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&!node.callee.computed&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Array"&&node.callee.property.type==="Identifier"&&node.callee.property.name==="isArray"&&node.arguments.some(a=>a.type!=="SpreadElement"&&samePath(a,guarded))){sawArrayCheck=true}if(node.type==="BinaryExpression"&&["<","<=",">",">=","===","==","!==","!="].includes(node.operator)){for(const side of[node.left,node.right]){if(side.type==="MemberExpression"&&!side.computed&&side.property.type==="Identifier"&&side.property.name==="length"&&samePath(side.object,guarded)){sawLengthComparison=true}}}const walkIfNode=value=>{if(value&&typeof value==="object"&&"type"in value)walk(value)};for(const key of["left","right","argument","expression","test","object","callee"]){walkIfNode(node[key])}const args=node.arguments;if(Array.isArray(args)){for(const a of args)walkIfNode(a)}};walk(test);return sawArrayCheck&&sawLengthComparison};for(let current=forOfNode.parent;current;current=current.parent){if(current.type==="IfStatement"&&validates(current.test))return true;if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}for(let current=forOfNode;current;current=current.parent){const parent=current.parent;if(parent?.type==="BlockStatement"||parent?.type==="Program"){const body=parent.body;const index=body.indexOf(current);for(const statement of body.slice(0,index)){if(statement.type==="IfStatement"&&validates(statement.test))return true}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}return false};const resolveVariable=node=>{const scope=sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(variable)return variable}return null};const samePath=(left,right)=>{const a=(0,eslint_devkit_3.unwrapTypeSyntax)(left);const b=(0,eslint_devkit_3.unwrapTypeSyntax)(right);if(a.type==="Identifier"&&b.type==="Identifier"){const va=resolveVariable(a);const vb=resolveVariable(b);return va||vb?va===vb:a.name===b.name}if(a.type==="MemberExpression"&&b.type==="MemberExpression"){return!a.computed&&!b.computed&&a.property.type==="Identifier"&&b.property.type==="Identifier"&&a.property.name===b.property.name&&samePath(a.object,b.object)}return false};const isClamped=node=>{const expression=(0,eslint_devkit_3.unwrapTypeSyntax)(node);if(expression.type==="CallExpression"&&expression.callee.type==="MemberExpression"&&!expression.callee.computed&&expression.callee.object.type==="Identifier"&&expression.callee.object.name==="Math"&&expression.callee.property.type==="Identifier"&&["min","max"].includes(expression.callee.property.name)){return true}if(expression.type==="BinaryExpression"||expression.type==="LogicalExpression"){return isClamped(expression.left)||isClamped(expression.right)}if(expression.type==="ConditionalExpression"){return isClamped(expression.consequent)&&isClamped(expression.alternate)}return false};const involvesUserInput=expression=>{const checkExpression=raw=>{const node=(0,eslint_devkit_3.unwrapTypeSyntax)(raw);if(node.type==="MemberExpression"){if(!node.computed&&node.property.type==="Identifier"&&node.property.name==="length"){return false}const objectText=sourceCode.getText(node.object);if(isUserInput(objectText)){return true}return checkExpression(node.object)}if(node.type==="Identifier"){return isUserInput(node.name)}if(node.type==="CallExpression"){return checkExpression(node.callee)||node.arguments.filter(arg=>arg.type!=="SpreadElement").some(arg=>checkExpression(arg))}if(node.type==="LogicalExpression"){return node.operator==="&&"?checkExpression(node.right):checkExpression(node.left)||checkExpression(node.right)}if(node.type==="BinaryExpression"){return checkExpression(node.left)||checkExpression(node.right)}if(node.type==="UpdateExpression"){return checkExpression(node.argument)}if(node.type==="UnaryExpression"){return checkExpression(node.argument)}return false};return checkExpression(expression)};const hasBreakStatement=loopBody=>{let hasBreak=false;const visited=new Set;const checkNode=(node,depth=0)=>{if(depth>10||visited.has(node)){return}visited.add(node);if(node.type==="BreakStatement"){hasBreak=true;return}for(const key in node){const child=node[key];if(child&&typeof child==="object"){if("type"in child){checkNode(child,depth+1)}else if(Array.isArray(child)){child.forEach(item=>{if(item&&typeof item==="object"&&"type"in item){checkNode(item,depth+1)}})}}}};checkNode(loopBody);return hasBreak};const isUnconditionalSelfCall=call=>{const BRANCHING=new Set(["IfStatement","ConditionalExpression","LogicalExpression","SwitchStatement","SwitchCase","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement","TryStatement","CatchClause"]);let child=call;for(let current=call.parent;current;child=current,current=current.parent){if(BRANCHING.has(current.type))return false;if(current.type==="BlockStatement"){const index=current.body.indexOf(child);const preceding=current.body.slice(0,index);if(preceding.some(statement=>statement.type==="IfStatement"&&exits(statement))){return false}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return true}}return false};const exits=node=>{if(node.type==="ReturnStatement"||node.type==="ThrowStatement")return true;for(const key in node){const child=node[key];if(key==="parent"||!child||typeof child!=="object")continue;if("type"in child){if(exits(child))return true}else if(Array.isArray(child)){for(const item of child){if(item&&typeof item==="object"&&"type"in item&&exits(item))return true}}}return false};const estimateIterations=loop=>{const test=loop.test;if(test&&test.type==="BinaryExpression"){if(test.operator==="<"||test.operator==="<="||test.operator===">"||test.operator===">="){const right=test.right;if(right.type==="Literal"&&typeof right.value==="number"){return Math.abs(right.value)}}}return null};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){const varName=declarator.id.name;const hasUserInput=involvesUserInput(declarator.init);const isSanitized=isClamped(declarator.init);if(hasUserInput&&!isSanitized){taintedVariables.add(varName)}}}},FunctionDeclaration(node){if(node.id){currentFunctionStack.push(node.id.name)}},"FunctionDeclaration:exit"(node){if(node.id&&currentFunctionStack[currentFunctionStack.length-1]===node.id.name){currentFunctionStack.pop()}},CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"){const functionName=callee.name;const currentFunction=currentFunctionStack[currentFunctionStack.length-1];if(currentFunction&&functionName===currentFunction){const callCount=(functionCalls.get(functionName)||0)+1;functionCalls.set(functionName,callCount);if(!reportedRecursion.has(functionName)){if(callCount>maxRecursionDepth||isUnconditionalSelfCall(node)){if(safetyChecker.isSafe(node,context)){return}reportedRecursion.add(functionName);context.report({node,messageId:"unsafeRecursion",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},WhileStatement(node){const test=node.test;if(test.type==="Literal"&&test.value===true){const hasBreak=hasBreakStatement(node.body);if(allowWhileTrueWithBreak&&hasBreak){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}},ForStatement(node){if(!node.test&&!node.update){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(!node.test){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingLoopTermination",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}const estimatedIterations=estimateIterations(node);if(estimatedIterations&&estimatedIterations>maxStaticIterations){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"largeLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},DoWhileStatement(node){const test=node.test;if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},ForInStatement(node){const right=node.right;if(involvesUserInput(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size or add iteration timeout"}})}},ForOfStatement(node){const right=node.right;if(involvesUserInput(right)){const isValidated=checkIfCollectionIsValidated(node,right);if(isValidated){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size before iteration"}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUncheckedLoopCondition=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const eslint_devkit_3=require("@interlace/eslint-devkit");exports.noUncheckedLoopCondition=(0,eslint_devkit_1.createRule)({name:"no-unchecked-loop-condition",meta:{type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-secure-coding/docs/rules/no-unchecked-loop-condition.md",description:"Detects unchecked loop conditions that could cause DoS",cwe:"CWE-400"},messages:{uncheckedLoopCondition:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unchecked Loop Condition",cwe:"CWE-400",description:"Loop condition may cause DoS through excessive iterations",severity:"{{severity}}",fix:"{{safeAlternative}}",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),infiniteLoop:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Infinite Loop",cwe:"CWE-400",description:"Loop may run indefinitely",severity:"CRITICAL",fix:"Add termination condition or iteration limit",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),userControlledLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"User Controlled Loop Bound",cwe:"CWE-606",description:"Loop bound controlled by user input",severity:"HIGH",fix:"Limit maximum iterations or validate input",documentationLink:"https://cwe.mitre.org/data/definitions/606.html"}),missingLoopTermination:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Missing Loop Termination",cwe:"CWE-400",description:"Loop lacks clear termination condition",severity:"MEDIUM",fix:"Add explicit termination condition",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),largeLoopBound:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Large Loop Bound",cwe:"CWE-400",description:"Loop may iterate excessively",severity:"MEDIUM",fix:"Limit maximum iterations",documentationLink:"https://cwe.mitre.org/data/definitions/400.html"}),unsafeRecursion:(0,eslint_devkit_2.formatLLMMessage)({icon:eslint_devkit_2.MessageIcons.SECURITY,issueName:"Unsafe Recursion",cwe:"CWE-674",description:"Recursive function may cause stack overflow",severity:"HIGH",fix:"Add recursion depth limit or use iterative approach",documentationLink:"https://cwe.mitre.org/data/definitions/674.html"})},schema:[{type:"object",properties:{maxStaticIterations:{type:"number",minimum:100,default:1e4,description:"Literal iteration count above which a loop is reported"},userInputVariables:{type:"array",items:{type:"string"},default:["req","request","body","query","params","input","data"],description:"Variable names treated as user-controlled input"},allowWhileTrueWithBreak:{type:"boolean",default:true,description:"Allow `while (true)` when the body contains a `break`"},maxRecursionDepth:{type:"number",minimum:1,default:10,description:"Recursion depth above which a call is reported"},trustedSanitizers:{type:"array",items:{type:"string"},default:[],description:"Additional function names to consider as loop protectors"},trustedAnnotations:{type:"array",items:{type:"string"},default:[],description:"Additional JSDoc annotations to consider as safe markers"},strictMode:{type:"boolean",default:false,description:"Disable all false positive detection (strict mode)"}},additionalProperties:false}]},defaultOptions:[{maxStaticIterations:1e4,userInputVariables:["req","request","body","query","params","input","data"],allowWhileTrueWithBreak:true,maxRecursionDepth:10,trustedSanitizers:[],trustedAnnotations:[],strictMode:false}],create(context){const options=context.options[0]||{};const{maxStaticIterations=1e4,userInputVariables=["req","request","body","query","params","input","data"],allowWhileTrueWithBreak=true,maxRecursionDepth=10,trustedSanitizers=[],trustedAnnotations=[],strictMode=false}=options;const sourceCode=context.sourceCode;const filename=context.filename;const safetyChecker=(0,eslint_devkit_3.createSafetyChecker)({trustedSanitizers,trustedAnnotations,trustedOrmPatterns:[],strictMode});const functionCalls=new Map;const reportedRecursion=new Set;const currentFunctionStack=[];const taintedVariables=new Set;const REQUEST_OBJECTS=new Set(["req","request","ctx","context","event"]);const isUserInput=varName=>{if(taintedVariables.has(varName)){return true}const lowerVarName=varName.toLowerCase();const isUsingDefaults=userInputVariables.length===7&&userInputVariables.includes("req")&&userInputVariables.includes("input");if(!isUsingDefaults){return userInputVariables.some(input=>lowerVarName===input.toLowerCase())}return REQUEST_OBJECTS.has(lowerVarName)};const checkIfCollectionIsValidated=(forOfNode,collection)=>{const guarded=collection;const validates=test=>{let sawArrayCheck=false;let sawLengthComparison=false;const walk=node=>{if(node.type==="CallExpression"&&node.callee.type==="MemberExpression"&&node.callee.object.type==="Identifier"&&node.callee.object.name==="Array"&&(0,eslint_devkit_1.propertyName)(node.callee)==="isArray"&&node.arguments.some(a=>a.type!=="SpreadElement"&&samePath(a,guarded))){sawArrayCheck=true}if(node.type==="BinaryExpression"&&["<","<=",">",">=","===","==","!==","!="].includes(node.operator)){for(const side of[node.left,node.right]){if(side.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(side)==="length"&&samePath(side.object,guarded)){sawLengthComparison=true}}}const walkIfNode=value=>{if(value&&typeof value==="object"&&"type"in value)walk(value)};for(const key of["left","right","argument","expression","test","object","callee"]){walkIfNode(node[key])}const args=node.arguments;if(Array.isArray(args)){for(const a of args)walkIfNode(a)}};walk(test);return sawArrayCheck&&sawLengthComparison};for(let current=forOfNode.parent;current;current=current.parent){if(current.type==="IfStatement"&&validates(current.test))return true;if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}for(let current=forOfNode;current;current=current.parent){const parent=current.parent;if(parent?.type==="BlockStatement"||parent?.type==="Program"){const body=parent.body;const index=body.indexOf(current);for(const statement of body.slice(0,index)){if(statement.type==="IfStatement"&&validates(statement.test))return true}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){break}}return false};const resolveVariable=node=>{const scope=sourceCode.getScope(node);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===node.name);if(variable)return variable}return null};const samePath=(left,right)=>{const a=(0,eslint_devkit_3.unwrapTypeSyntax)(left);const b=(0,eslint_devkit_3.unwrapTypeSyntax)(right);if(a.type==="Identifier"&&b.type==="Identifier"){const va=resolveVariable(a);const vb=resolveVariable(b);return va||vb?va===vb:a.name===b.name}if(a.type==="MemberExpression"&&b.type==="MemberExpression"){return(0,eslint_devkit_1.propertyName)(a)===(0,eslint_devkit_1.propertyName)(b)&&samePath(a.object,b.object)}return false};const isClamped=node=>{const expression=(0,eslint_devkit_3.unwrapTypeSyntax)(node);if(expression.type==="CallExpression"&&expression.callee.type==="MemberExpression"&&!expression.callee.computed&&expression.callee.object.type==="Identifier"&&expression.callee.object.name==="Math"&&expression.callee.property.type==="Identifier"&&["min","max"].includes(expression.callee.property.name)){return true}if(expression.type==="BinaryExpression"||expression.type==="LogicalExpression"){return isClamped(expression.left)||isClamped(expression.right)}if(expression.type==="ConditionalExpression"){return isClamped(expression.consequent)&&isClamped(expression.alternate)}return false};const involvesUserInput=expression=>{const checkExpression=raw=>{const node=(0,eslint_devkit_3.unwrapTypeSyntax)(raw);if(node.type==="MemberExpression"){if((0,eslint_devkit_1.propertyName)(node)==="length"){return false}const objectText=sourceCode.getText(node.object);if(isUserInput(objectText)){return true}return checkExpression(node.object)}if(node.type==="Identifier"){return isUserInput(node.name)}if(node.type==="CallExpression"){return checkExpression(node.callee)||node.arguments.filter(arg=>arg.type!=="SpreadElement").some(arg=>checkExpression(arg))}if(node.type==="LogicalExpression"){return node.operator==="&&"?checkExpression(node.right):checkExpression(node.left)||checkExpression(node.right)}if(node.type==="BinaryExpression"){return checkExpression(node.left)||checkExpression(node.right)}if(node.type==="UpdateExpression"){return checkExpression(node.argument)}if(node.type==="UnaryExpression"){return checkExpression(node.argument)}return false};return checkExpression(expression)};const hasBreakStatement=loopBody=>{let hasBreak=false;const visited=new Set;const checkNode=(node,depth=0)=>{if(depth>10||visited.has(node)){return}visited.add(node);if(node.type==="BreakStatement"){hasBreak=true;return}for(const key in node){const child=node[key];if(child&&typeof child==="object"){if("type"in child){checkNode(child,depth+1)}else if(Array.isArray(child)){child.forEach(item=>{if(item&&typeof item==="object"&&"type"in item){checkNode(item,depth+1)}})}}}};checkNode(loopBody);return hasBreak};const isUnconditionalSelfCall=call=>{const BRANCHING=new Set(["IfStatement","ConditionalExpression","LogicalExpression","SwitchStatement","SwitchCase","ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement","TryStatement","CatchClause"]);let child=call;for(let current=call.parent;current;child=current,current=current.parent){if(BRANCHING.has(current.type))return false;if(current.type==="BlockStatement"){const index=current.body.indexOf(child);const preceding=current.body.slice(0,index);if(preceding.some(statement=>statement.type==="IfStatement"&&exits(statement))){return false}}if(current.type==="FunctionDeclaration"||current.type==="FunctionExpression"||current.type==="ArrowFunctionExpression"){return true}}return false};const exits=node=>{if(node.type==="ReturnStatement"||node.type==="ThrowStatement")return true;for(const key in node){const child=node[key];if(key==="parent"||!child||typeof child!=="object")continue;if("type"in child){if(exits(child))return true}else if(Array.isArray(child)){for(const item of child){if(item&&typeof item==="object"&&"type"in item&&exits(item))return true}}}return false};const estimateIterations=loop=>{const test=loop.test;if(test&&test.type==="BinaryExpression"){if(test.operator==="<"||test.operator==="<="||test.operator===">"||test.operator===">="){const right=test.right;if(right.type==="Literal"&&typeof right.value==="number"){return Math.abs(right.value)}}}return null};return{VariableDeclaration(node){for(const declarator of node.declarations){if(declarator.id.type==="Identifier"&&declarator.init){const varName=declarator.id.name;const hasUserInput=involvesUserInput(declarator.init);const isSanitized=isClamped(declarator.init);if(hasUserInput&&!isSanitized){taintedVariables.add(varName)}}}},FunctionDeclaration(node){if(node.id){currentFunctionStack.push(node.id.name)}},"FunctionDeclaration:exit"(node){if(node.id&&currentFunctionStack[currentFunctionStack.length-1]===node.id.name){currentFunctionStack.pop()}},CallExpression(node){const callee=node.callee;if(callee.type==="Identifier"){const functionName=callee.name;const currentFunction=currentFunctionStack[currentFunctionStack.length-1];if(currentFunction&&functionName===currentFunction){const callCount=(functionCalls.get(functionName)||0)+1;functionCalls.set(functionName,callCount);if(!reportedRecursion.has(functionName)){if(callCount>maxRecursionDepth||isUnconditionalSelfCall(node)){if(safetyChecker.isSafe(node,context)){return}reportedRecursion.add(functionName);context.report({node,messageId:"unsafeRecursion",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}}}}},WhileStatement(node){const test=node.test;if(test.type==="Literal"&&test.value===true){const hasBreak=hasBreakStatement(node.body);if(allowWhileTrueWithBreak&&hasBreak){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}},ForStatement(node){if(!node.test&&!node.update){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"infiniteLoop",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(!node.test){if(safetyChecker.isSafe(node,context)){return}context.report({node,messageId:"missingLoopTermination",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}if(involvesUserInput(node.test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}});return}const estimatedIterations=estimateIterations(node);if(estimatedIterations&&estimatedIterations>maxStaticIterations){if(safetyChecker.isSafe(node,context)){return}context.report({node:node.test,messageId:"largeLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},DoWhileStatement(node){const test=node.test;if(involvesUserInput(test)){if(safetyChecker.isSafe(node,context)){return}context.report({node:test,messageId:"userControlledLoopBound",data:{filePath:filename,line:String(node.loc?.start.line??0)}})}},ForInStatement(node){const right=node.right;if(involvesUserInput(right)){if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size or add iteration timeout"}})}},ForOfStatement(node){const right=node.right;if(involvesUserInput(right)){const isValidated=checkIfCollectionIsValidated(node,right);if(isValidated){return}if(safetyChecker.isSafe(node,context)){return}context.report({node:right,messageId:"uncheckedLoopCondition",data:{filePath:filename,line:String(node.loc?.start.line??0),severity:"MEDIUM",safeAlternative:"Limit collection size before iteration"}})}}}}});