eslint-plugin-node-security 5.8.0 → 5.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +3 -2
  2. package/package.json +2 -2
  3. package/src/index.js +1 -1
  4. package/src/rules/detect-child-process/index.js +1 -1
  5. package/src/rules/detect-eval-with-expression/index.js +1 -1
  6. package/src/rules/detect-non-literal-fs-filename/index.js +1 -1
  7. package/src/rules/detect-suspicious-dependencies/index.js +1 -1
  8. package/src/rules/lock-file/index.js +1 -1
  9. package/src/rules/no-arbitrary-file-access/index.js +1 -1
  10. package/src/rules/no-buffer-overread/index.js +1 -1
  11. package/src/rules/no-cryptojs/index.js +1 -1
  12. package/src/rules/no-cryptojs-weak-random/index.js +1 -1
  13. package/src/rules/no-data-in-temp-storage/index.js +1 -1
  14. package/src/rules/no-deprecated-buffer/index.js +1 -1
  15. package/src/rules/no-deprecated-cipher-method/index.js +1 -1
  16. package/src/rules/no-dynamic-algorithm-selection/index.js +1 -1
  17. package/src/rules/no-dynamic-command-string/index.js +1 -1
  18. package/src/rules/no-dynamic-require/index.js +1 -1
  19. package/src/rules/no-ecb-mode/index.js +1 -1
  20. package/src/rules/no-insecure-key-derivation/index.js +1 -1
  21. package/src/rules/no-insecure-rsa-padding/index.js +1 -1
  22. package/src/rules/no-math-random-crypto/index.js +1 -1
  23. package/src/rules/no-self-signed-certs/index.js +1 -1
  24. package/src/rules/no-sha1-hash/index.js +1 -1
  25. package/src/rules/no-shell-injection/index.js +1 -1
  26. package/src/rules/no-ssrf/index.js +1 -1
  27. package/src/rules/no-static-iv/index.js +1 -1
  28. package/src/rules/no-timing-unsafe-compare/index.js +1 -1
  29. package/src/rules/no-toctou-vulnerability/index.js +1 -1
  30. package/src/rules/no-unbounded-decompression/index.js +1 -1
  31. package/src/rules/no-unsafe-buffer-alloc/index.js +1 -1
  32. package/src/rules/no-unsafe-dynamic-require/index.js +1 -1
  33. package/src/rules/no-weak-cipher-algorithm/index.js +1 -1
  34. package/src/rules/no-weak-dh-parameters/index.js +1 -1
  35. package/src/rules/no-weak-hash-algorithm/index.js +1 -1
  36. package/src/rules/no-zip-slip/index.js +1 -1
  37. package/src/rules/prefer-native-crypto/index.js +1 -1
  38. package/src/rules/require-aead-tag-verification/index.js +1 -1
  39. package/src/rules/require-dependency-integrity/index.js +1 -1
  40. package/src/rules/require-secure-deletion/index.js +1 -1
  41. package/src/rules/require-storage-encryption/index.js +1 -1
  42. package/src/rules/require-stream-error-handler/index.js +1 -1
  43. package/src/utils/const-value.js +1 -1
  44. package/src/utils/credential-evidence.js +1 -1
  45. package/src/utils/module-binding.js +1 -0
  46. package/src/utils/provenance.js +1 -1
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSsrf=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const HTTP_CLIENT_FUNCTIONS=new Set(["fetch","got","nodeFetch","undici"]);const HTTP_CLIENT_METHODS=new Set(["get","post","put","patch","delete","head","options","request"]);const HTTP_CLIENT_MODULES=["axios","got","superagent","request","http","https","node:http","node:https","undici","needle"];const VALIDATION_FUNCTION_NAMES=new Set(["validateUrl","validateURL","isValidUrl","isSafeUrl","isAllowed","isValidURL","checkUrl","checkURL","sanitizeUrl","sanitizeURL"]);const USER_INPUT_SUBSTRINGS=["url","endpoint","uri","href","link","target","dest","source","host","user","input","param"];function isUserInputParamName(name){const lower=name.toLowerCase();return USER_INPUT_SUBSTRINGS.some(sub=>lower.includes(sub))}const REQUEST_ROOT_NAMES=new Set(["req","request","ctx","event"]);const URL_OPTION_KEYS=new Set(["url","href","uri"]);function isRequestSourced(node,sourceCode){if((0,eslint_devkit_1.readsRequestShape)(node,sourceCode))return true;let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){current=current.object}return current!==node&&current.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_ROOT_NAMES.has(current.name.toLowerCase())}function makeCarriesUntrustedUrl(sourceCode,reportUnresolvedUrls){const carries=(node,depth)=>{if(depth>6)return false;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return carries(bare,depth+1);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=(0,provenance_1.bindingInit)(sourceCode,node);if(init!==void 0)return carries(init,depth+1);return reportUnresolvedUrls&&isUserInputParamName(node.name)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isRequestSourced(node,sourceCode)||carries(node.object,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(expression=>carries(expression,depth+1));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return node.arguments.some(argument=>carries(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return carries(node.left,depth+1)||carries(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.ObjectExpression:return node.properties.some(property=>{if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)return false;const value=property.value;if(isRequestSourced(value,sourceCode))return true;const key=property.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?property.key.name:property.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal?String(property.key.value):"";return URL_OPTION_KEYS.has(key.toLowerCase())&&carries(value,depth+1)});default:return false}};return node=>carries(node,0)}function nodeContainsValidation(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="URL"){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&VALIDATION_FUNCTION_NAMES.has(node.callee.name)){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const method=node.callee.property.name;if(method==="includes"||method==="has"||method==="startsWith"||method==="test"||method==="some"){return true}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&(node.operator==="==="||node.operator==="==")&&(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(node.left)==="hostname"||(0,eslint_devkit_1.propertyName)(node.left)==="host")||node.right.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(node.right)==="hostname"||(0,eslint_devkit_1.propertyName)(node.right)==="host"))){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}const SKIP_KEYS=new Set(["parent","range","loc","tokens","comments","start","end"]);for(const key of Object.keys(node)){if(SKIP_KEYS.has(key))continue;const value=node[key];if(value&&typeof value==="object"&&"type"in value){if(nodeContainsValidation(value))return true}if(Array.isArray(value)){for(const item of value){if(item&&typeof item==="object"&&"type"in item){if(nodeContainsValidation(item))return true}}}}return false}function hasValidationBefore(node){let current=node.parent;while(current){const parent=current.parent;if(!parent)break;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=parent.body;const idx=body.indexOf(current);for(let i=idx-1;i>=0&&i>=idx-10;i--){if(nodeContainsValidation(body[i])){return true}}}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&parent.test){if(nodeContainsValidation(parent.test)){return true}}current=parent}return false}exports.noSsrf=(0,eslint_devkit_1.createRule)({name:"no-ssrf",meta:{interop:{runtimes:["eslint","oxlint"]},type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-ssrf.md",description:"Flags HTTP calls whose URL argument is a user-input-named identifier or reads off a request object \u2014 a heuristic prompt for code review, not a proof of SSRF",cwe:"CWE-918",cvss:9.1},messages:{ssrfVulnerability:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Possible SSRF \u2014 heuristic (CWE-918)",cwe:"CWE-918",description:"HTTP call whose URL argument name suggests user input. This is a naming heuristic, not data-flow analysis \u2014 review whether the URL could originate from an untrusted source at runtime.",severity:"LOW",fix:"If the URL comes from user input, validate it against an allowlist of permitted hosts before making the request.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},reportUnresolvedUrls:{type:"boolean",default:false,description:"Report a URL argument that is a user-input-named identifier with no traceable request source. Restores the pre-inversion naming heuristic."}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],createOnce(context,currentOptions){let carriesUntrustedUrl;return{before(){const[options={}]=currentOptions();const{allowInTests=true,reportUnresolvedUrls=false}=options||{};carriesUntrustedUrl=makeCarriesUntrustedUrl(context.sourceCode,reportUnresolvedUrls);const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile)return false;return true},CallExpression(node){let isHttpCall=false;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&HTTP_CLIENT_FUNCTIONS.has(node.callee.name)){isHttpCall=true}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),HTTP_CLIENT_METHODS)&&HTTP_CLIENT_MODULES.some(mod=>(0,eslint_devkit_1.isModuleBinding)(node.callee.object,context.sourceCode.getScope(node),mod))){isHttpCall=true}if(!isHttpCall)return;const urlArg=node.arguments[0];if(!urlArg)return;if(hasValidationBefore(node)){return}if(!carriesUntrustedUrl(urlArg)){return}context.report({node,messageId:"ssrfVulnerability"})}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noSsrf=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const HTTP_CLIENT_FUNCTIONS=new Set(["fetch","got","nodeFetch","undici"]);const HTTP_CLIENT_METHODS=new Set(["get","post","put","patch","delete","head","options","request"]);const HTTP_CLIENT_MODULES=["axios","got","superagent","request","http","https","node:http","node:https","undici","needle"];const VALIDATION_FUNCTION_NAMES=new Set(["validateUrl","validateURL","isValidUrl","isSafeUrl","isAllowed","isValidURL","checkUrl","checkURL","sanitizeUrl","sanitizeURL"]);const USER_INPUT_SUBSTRINGS=["url","endpoint","uri","href","link","target","dest","source","host","user","input","param"];function isUserInputParamName(name){const lower=name.toLowerCase();return USER_INPUT_SUBSTRINGS.some(sub=>lower.includes(sub))}const REQUEST_ROOT_NAMES=new Set(["req","request","ctx","event"]);function isRequestSourced(node,sourceCode){if((0,eslint_devkit_1.readsRequestShape)(node,sourceCode))return true;let current=node;while(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){current=current.object}return current.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&REQUEST_ROOT_NAMES.has(current.name.toLowerCase())}function makeCarriesUntrustedUrl(sourceCode,reportUnresolvedUrls){const carries=(node,depth)=>{if(depth>6)return false;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return carries(bare,depth);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=(0,provenance_1.bindingInit)(sourceCode,node);if(init!==void 0)return carries(init,depth+1);return reportUnresolvedUrls&&isUserInputParamName(node.name)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:return isRequestSourced(node,sourceCode)||carries(node.object,depth+1);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(expression=>carries(expression,depth+1));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return node.arguments.some(argument=>carries(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return carries(node.left,depth+1)||carries(node.right,depth+1);case eslint_devkit_1.AST_NODE_TYPES.ObjectExpression:return node.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&carries(property.value,depth+1));default:return false}};return node=>carries(node,0)}function nodeContainsValidation(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="URL"){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&VALIDATION_FUNCTION_NAMES.has(node.callee.name)){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const method=(0,eslint_devkit_1.propertyName)(node.callee);if(method==="includes"||method==="has"||method==="startsWith"||method==="test"||method==="some"){return true}}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression&&(node.operator==="==="||node.operator==="==")&&(node.left.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(node.left)==="hostname"||(0,eslint_devkit_1.propertyName)(node.left)==="host")||node.right.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&((0,eslint_devkit_1.propertyName)(node.right)==="hostname"||(0,eslint_devkit_1.propertyName)(node.right)==="host"))){return true}if(node.type===eslint_devkit_1.AST_NODE_TYPES.ThrowStatement){return true}const SKIP_KEYS=new Set(["parent","range","loc","tokens","comments","start","end"]);for(const key of Object.keys(node)){if(SKIP_KEYS.has(key))continue;const value=node[key];if(value&&typeof value==="object"&&"type"in value){if(nodeContainsValidation(value))return true}if(Array.isArray(value)){for(const item of value){if(item&&typeof item==="object"&&"type"in item){if(nodeContainsValidation(item))return true}}}}return false}function hasValidationBefore(node){let current=node;while(current){const parent=current.parent;if(!parent)break;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.Program){const body=parent.body;const idx=body.indexOf(current);for(let i=idx-1;i>=0&&i>=idx-10;i--){if(nodeContainsValidation(body[i])){return true}}}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement||parent.type===eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression){if(nodeContainsValidation(parent.test)){return true}}current=parent}return false}exports.noSsrf=(0,eslint_devkit_1.createRule)({name:"no-ssrf",meta:{interop:{runtimes:["eslint","oxlint"]},type:"suggestion",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-ssrf.md",description:"Flags HTTP calls whose URL argument is a user-input-named identifier or reads off a request object \u2014 a heuristic prompt for code review, not a proof of SSRF",cwe:"CWE-918",cvss:9.1},messages:{ssrfVulnerability:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Possible SSRF \u2014 heuristic (CWE-918)",cwe:"CWE-918",description:"HTTP call whose URL argument name suggests user input. This is a naming heuristic, not data-flow analysis \u2014 review whether the URL could originate from an untrusted source at runtime.",severity:"LOW",fix:"If the URL comes from user input, validate it against an allowlist of permitted hosts before making the request.",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:true},reportUnresolvedUrls:{type:"boolean",default:false,description:"Report a URL argument that is a user-input-named identifier with no traceable request source. Restores the pre-inversion naming heuristic."}},additionalProperties:false}]},defaultOptions:[{allowInTests:true}],createOnce(context,currentOptions){let carriesUntrustedUrl;return{before(){const[options={}]=currentOptions();const{allowInTests=true,reportUnresolvedUrls=false}=options||{};carriesUntrustedUrl=makeCarriesUntrustedUrl(context.sourceCode,reportUnresolvedUrls);const filename=context.filename;const isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile)return false;return true},CallExpression(node){let isHttpCall=false;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&HTTP_CLIENT_FUNCTIONS.has(node.callee.name)){isHttpCall=true}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),HTTP_CLIENT_METHODS)&&HTTP_CLIENT_MODULES.some(mod=>(0,eslint_devkit_1.isModuleBinding)(node.callee.object,context.sourceCode.getScope(node),mod))){isHttpCall=true}if(!isHttpCall)return;const urlArg=node.arguments[0];if(!urlArg)return;if(hasValidationBefore(node)){return}if(!carriesUntrustedUrl(urlArg)){return}context.report({node,messageId:"ssrfVulnerability"})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noStaticIv=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");const STATIC_IV_PATTERNS=[/^[0-9a-f]+$/i,/^[A-Za-z0-9+/]+=*$/];const CIPHERIV_FACTORIES=["createCipheriv","createDecipheriv"];const TYPED_ARRAY_CONSTRUCTORS=new Set(["Uint8Array","Uint8ClampedArray","Int8Array"]);const RANDOM_FILL_FUNCTIONS=new Set(["randomFill","randomFillSync","getRandomValues"]);function calleeMemberName(callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;if(callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!callee.computed){return callee.property.name}return(0,eslint_devkit_1.staticString)(callee.property)!==null?(0,eslint_devkit_1.staticString)(callee.property):null}exports.noStaticIv=(0,eslint_devkit_1.createRule)({name:"no-static-iv",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-static-iv.md",description:"Disallow static or hardcoded initialization vectors (IVs)",cwe:"CWE-329",cvss:7.5},hasSuggestions:false,messages:{staticIv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Static IV detected",cwe:"CWE-329",description:"Hardcoded IV detected. Using static IVs makes encryption deterministic, allowing attackers to detect repeated plaintexts.",severity:"HIGH",fix:"Generate IV dynamically using crypto.randomBytes(16)",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#initialization-vectors"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow static IVs in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function isCipherivCall(node){const callee=node.callee;const spelled=calleeMemberName(callee)??(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:null);if(spelled!==null&&CIPHERIV_FACTORIES.includes(spelled))return true;const scope=context.sourceCode.getScope(node);return CIPHERIV_FACTORIES.some(fn=>(0,eslint_devkit_1.isModuleBinding)(callee,scope,"crypto",[fn]))}function checkCallExpression(node){if(isTestFile)return;if(isCipherivCall(node)&&node.arguments.length>=3){const ivArg=node.arguments[2];checkIvArgument(ivArg)}}function isStaticByteArray(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&node.elements.every(el=>el?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof el.value==="number")}function isRandomlyFilled(variable){return variable.references.some(ref=>{const parent=ref.identifier.parent;if(parent?.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(!parent.arguments.includes(ref.identifier))return false;const callee=parent.callee;const name=calleeMemberName(callee)??(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:null);return name!==null&&RANDOM_FILL_FUNCTIONS.has(name)})}function isStaticIvValue(value,binding){const constant=(0,const_value_1.resolveConstantString)(context.sourceCode,value);if(constant!==null){const text=constant.value;return STATIC_IV_PATTERNS.some(p=>p.test(text))||text.length>=8}if(value.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){return value.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TYPED_ARRAY_CONSTRUCTORS.has(value.callee.name)&&isStaticBufferSource(value.arguments[0],binding)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&value.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&value.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&value.callee.object.name==="Buffer"&&(calleeMemberName(value.callee)==="from"||calleeMemberName(value.callee)==="alloc")){return isStaticBufferSource(value.arguments[0],binding)}return false}function isStaticBufferSource(source,binding){if(source===void 0)return false;if((0,const_value_1.resolveConstantString)(context.sourceCode,source)!==null)return true;if(isStaticByteArray(source))return true;const size=(0,const_value_1.resolveConstant)(context.sourceCode,source);if(size===null||typeof size.value!=="number")return false;return binding===null||!isRandomlyFilled(binding)}function ivCandidates(identifier,variable){const constInit=(0,const_value_1.constInitializerOf)(context.sourceCode,identifier);if(constInit!==null)return[constInit];if(variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="Variable"||def.parent.kind==="const")return null;if(def.node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const candidates=def.node.init?[def.node.init]:[];for(const ref of variable.references){if(!ref.isWrite())continue;if(!ref.writeExpr)return null;if(ref.writeExpr!==def.node.init)candidates.push(ref.writeExpr)}return candidates.length>0?candidates:null}function checkIvArgument(ivArg){const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(ivArg);if(unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const binding=(0,provenance_1.findVariable)(context.sourceCode,unwrapped);if(binding===null)return;const candidates=ivCandidates(unwrapped,binding);if(candidates===null)return;if(candidates.every(c=>isStaticIvValue((0,eslint_devkit_1.unwrapTypeSyntax)(c),binding))){reportStaticIv(unwrapped)}return}if(isStaticIvValue(unwrapped,null))reportStaticIv(unwrapped)}function reportStaticIv(node){context.report({node,messageId:"staticIv"})}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noStaticIv=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");const CIPHERIV_FACTORIES=["createCipheriv","createDecipheriv"];const TYPED_ARRAY_CONSTRUCTORS=new Set(["Uint8Array","Uint8ClampedArray","Int8Array"]);const RANDOM_FILL_FUNCTIONS=new Set(["randomFill","randomFillSync","getRandomValues"]);function calleeMemberName(callee){return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(callee):null}exports.noStaticIv=(0,eslint_devkit_1.createRule)({name:"no-static-iv",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-static-iv.md",description:"Disallow static or hardcoded initialization vectors (IVs)",cwe:"CWE-329",cvss:7.5},hasSuggestions:false,messages:{staticIv:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Static IV detected",cwe:"CWE-329",description:"Hardcoded IV detected. Using static IVs makes encryption deterministic, allowing attackers to detect repeated plaintexts.",severity:"HIGH",fix:"Generate IV dynamically using crypto.randomBytes(16)",documentationLink:"https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#initialization-vectors"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow static IVs in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function isCipherivCall(node){const callee=node.callee;const spelled=calleeMemberName(callee)??(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:null);if(spelled!==null&&CIPHERIV_FACTORIES.includes(spelled))return true;const scope=context.sourceCode.getScope(node);return CIPHERIV_FACTORIES.some(fn=>(0,eslint_devkit_1.isModuleBinding)(callee,scope,"crypto",[fn]))}function checkCallExpression(node){if(isTestFile)return;if(isCipherivCall(node)&&node.arguments.length>=3){const ivArg=node.arguments[2];checkIvArgument(ivArg)}}function isStaticByteArray(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ArrayExpression&&node.elements.every(el=>el?.type===eslint_devkit_1.AST_NODE_TYPES.Literal)}function isRandomlyFilled(variable){return variable.references.some(ref=>{const parent=ref.identifier.parent;if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;if(!parent.arguments.includes(ref.identifier))return false;const callee=parent.callee;const name=calleeMemberName(callee)??(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:null);return name!==null&&RANDOM_FILL_FUNCTIONS.has(name)})}function isStaticIvValue(value,binding){const constant=(0,const_value_1.resolveConstantString)(context.sourceCode,value);if(constant!==null)return constant.value.length>0;if(value.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression){return value.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&TYPED_ARRAY_CONSTRUCTORS.has(value.callee.name)&&isStaticBufferSource(value.arguments[0],binding)}if(value.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&value.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&value.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&value.callee.object.name==="Buffer"&&(calleeMemberName(value.callee)==="from"||calleeMemberName(value.callee)==="alloc")){return isStaticBufferSource(value.arguments[0],binding)}return false}function isStaticBufferSource(source,binding){if(source===void 0)return false;if((0,const_value_1.resolveConstantString)(context.sourceCode,source)!==null)return true;if(isStaticByteArray(source))return true;if((0,const_value_1.resolveConstant)(context.sourceCode,source)===null)return false;return binding===null||!isRandomlyFilled(binding)}function ivCandidates(identifier,variable){const constInit=(0,const_value_1.constInitializerOf)(context.sourceCode,identifier);if(constInit!==null)return[constInit];if(variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="Variable")return null;if(def.node.id.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const candidates=[];for(const ref of variable.references){if(!ref.isWrite())continue;if(!ref.writeExpr)return null;candidates.push(ref.writeExpr)}return candidates.length>0?candidates:null}function checkIvArgument(ivArg){const unwrapped=(0,eslint_devkit_1.unwrapTypeSyntax)(ivArg);if(unwrapped.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const binding=(0,provenance_1.findVariable)(context.sourceCode,unwrapped);if(binding===null)return;const candidates=ivCandidates(unwrapped,binding);if(candidates===null)return;if(candidates.every(c=>isStaticIvValue((0,eslint_devkit_1.unwrapTypeSyntax)(c),binding))){reportStaticIv(unwrapped)}return}if(isStaticIvValue(unwrapped,null))reportStaticIv(unwrapped)}function reportStaticIv(node){context.report({node,messageId:"staticIv"})}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTimingUnsafeCompare=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const names_1=require("../../utils/names");const DEFAULT_SECRET_PATTERNS=["token","secret","password","hash","signature","mac","hmac","digest","apiKey","api_key","api-key","auth","credential","bearer","jwt","csrf","nonce","ssn","social_security","social-security","pii","private_key","private-key","privateKey","access_token","access-token","accessToken","refresh_token","refresh-token","refreshToken","session_id","session-id","sessionId","auth_token","auth-token","authToken","encryption_key","encryption-key","encryptionKey"];function isSourceConstant(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.name==="undefined")return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral)return node.expressions.length===0;return false}function isStringLiteral(node){return(0,eslint_devkit_1.staticString)(node)!==null}const BOOLEAN_PREDICATE_NAME=/^(?:is|has|should|can|did|was|will|does)[A-Z]/;const NAMED_CONSTANT=/^[A-Z][A-Z0-9_]*$/;const DEFAULT_UNTRUSTED_SOURCES=["req","request","ctx","event"];const NAMESPACE_NAME=/^(?:[A-Z][A-Z0-9_]*|[A-Z][a-zA-Z0-9]*)$/;function isNamedConstant(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(node.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const constant=(0,eslint_devkit_1.propertyName)(node);if(constant===null)return false;return NAMESPACE_NAME.test(node.object.name)&&NAMED_CONSTANT.test(constant)}function memberRoot(node){let current=node;for(;;){if(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){current=current.object;continue}if(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){current=current.callee;continue}break}return current.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?current:null}function isSelfComparison(left,right){const pair=(bare,derived)=>{if(bare.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(derived.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return memberRoot(derived)?.name===bare.name};return pair(left,right)||pair(right,left)}const NON_SECRET_MEMBERS=new Map([["hash",new Set(["location"])]]);const DEFAULT_NON_SECRET_WORDS=["author","authors","authored","authoring","authorship","hashtag","hashtags"];const DEFAULT_NON_SECRET_TAILS=["count","counts","limit","limits","usage","total","size","length","price","cost","quota","address","addresses","index","rank","percent","path","paths","pathname","pathnames","endpoint","endpoints","route","routes","hostname","host","port","origin","kind","kinds","type","types","flag","flags","category"];const CRYPTO_DERIVATIONS=new Set(["createHmac","createHash","createSign","pbkdf2Sync","scryptSync","hkdfSync","digest","sign","hmac"]);const RECEIVER_COMPARE_METHODS=new Set(["equals","startsWith","endsWith","localeCompare"]);const BINARY_EQUALITY_FUNCTIONS=new Set(["isEqual","isEqualWith","deepEqual","fastDeepEqual","shallowEqual"]);const SERVER_STATE_REQUEST_PROPERTIES=new Set(["session","user","locals","app","state"]);function unwrapChain(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?node.expression:node}function memberPropertyName(node){const{property}=node;return property.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier?property.name:(0,eslint_devkit_1.propertyName)(node)}function isNonSecretMember(node){const member=memberPropertyName(node);if(member===null)return false;const receivers=NON_SECRET_MEMBERS.get(member.toLowerCase());if(!receivers)return false;const owner=node.object;const ownerName=owner.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?owner.name:owner.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(owner)??"":"";return receivers.has(ownerName.toLowerCase())}exports.noTimingUnsafeCompare=(0,eslint_devkit_1.createRule)({name:"no-timing-unsafe-compare",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-timing-unsafe-compare.md",description:"Disallow timing-unsafe comparison of secrets",cwe:"CWE-208",cvss:5.9},messages:{timingUnsafeCompare:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Timing-unsafe comparison",cwe:"CWE-208",description:"Using === to compare secrets enables timing attacks. The comparison short-circuits on first mismatch, leaking information about the secret.",severity:"HIGH",fix:"Use crypto.timingSafeEqual() for constant-time comparison",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"})},schema:[{type:"object",properties:{secretPatterns:{type:"array",items:{type:"string"},default:DEFAULT_SECRET_PATTERNS,description:"Variable name patterns that indicate secrets"},untrustedSources:{type:"array",items:{type:"string"},default:DEFAULT_UNTRUSTED_SOURCES,description:"Identifier roots treated as attacker-controlled (default: req, request, ctx, event)"},reportUnverifiedComparisons:{type:"boolean",default:false,description:"Report on a secret-looking name alone, without an attacker-controlled operand. Restores the pre-inversion behaviour."},reportLiteralComparands:{type:"boolean",default:false,description:"Report a secret-named value compared against a string literal (password === 'mypass'), in either order, on the name alone. Off by default because string comparands are usually tags (revokedToken === 'access')."},nonSecretWords:{type:"array",items:{type:"string"},default:[...DEFAULT_NON_SECRET_WORDS],description:`Whole words that mean a secretPatterns match was a collision (default: ${DEFAULT_NON_SECRET_WORDS.join(", ")}). Replaces the list.`},nonSecretTails:{type:"array",items:{type:"string"},default:[...DEFAULT_NON_SECRET_TAILS],description:`Trailing words that make the value a measurement or location rather than a credential (default: ${DEFAULT_NON_SECRET_TAILS.join(", ")}). Replaces the list.`}},additionalProperties:false}]},defaultOptions:[{secretPatterns:DEFAULT_SECRET_PATTERNS,nonSecretWords:[...DEFAULT_NON_SECRET_WORDS],nonSecretTails:[...DEFAULT_NON_SECRET_TAILS]}],createOnce(context,currentOptions){let secretPatterns;let untrustedSources;let reportUnverifiedComparisons;let reportLiteralComparands;let nonSecretWords;let nonSecretTails;let nonSecretWordSet;let nonSecretTailSet;let sourceCode;let readsUntrusted;let patterns;function nameLooksSecret(name){if(BOOLEAN_PREDICATE_NAME.test(name))return false;const words=(0,names_1.identifierWords)(name);if(words.some(word=>nonSecretWordSet.has(word)))return false;if(words.length>0&&nonSecretTailSet.has(words[words.length-1])){return false}return patterns.some(p=>p.test(name))}function isCryptoDerivation(node){const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return isCryptoDerivation(bare);if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return CRYPTO_DERIVATIONS.has(callee.name)}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed)return false;if(callee.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;if(CRYPTO_DERIVATIONS.has(callee.property.name))return true;return isCryptoDerivation(callee.object)}function isCryptoSecret(node){if(isCryptoDerivation(node))return true;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const init=(0,provenance_1.bindingInit)(sourceCode,bare);return init!==void 0&&containsCryptoDerivation(init)}function containsCryptoDerivation(node){if(isCryptoDerivation(node))return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.some(expression=>containsCryptoDerivation(expression))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return containsCryptoDerivation(node.left)||containsCryptoDerivation(node.right)}return false}function isServerDerived(node,depth=0){if(depth>4)return false;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return isServerDerived(bare,depth+1);if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression)return true;if(containsCryptoDerivation(node))return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const propertyName=memberPropertyName(node);if(propertyName!==null&&SERVER_STATE_REQUEST_PROPERTIES.has(propertyName)){return true}return isServerDerived(node.object,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,provenance_1.bindingInit)(sourceCode,node);return init!==void 0&&isServerDerived(init,depth+1)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=unwrapChain(node.callee);if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;return!readsUntrusted(callee.object)||isServerDerived(callee.object,depth+1)}return false}function isSecretIdentifier(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameLooksSecret(node.name)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(isNonSecretMember(node))return false;const propertyName=memberPropertyName(node);if(propertyName!==null){return nameLooksSecret(propertyName)}}return false}function isResolvedConstant(node){if(isSourceConstant(node))return true;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return(0,provenance_1.constLiteralOf)(sourceCode,node)!==void 0}function resolveLocalFunction(callee){const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(!variable||variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type==="FunctionName")return def.node;if(def.type!=="Variable")return null;const init=def.node.init;if(!init)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(init);if(bare.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||bare.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return bare}return null}function comparesLengths(node){const isLength=operand=>operand.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&memberPropertyName(operand)==="length";return isLength(node.left)||isLength(node.right)}function equalityWrapperParams(callee){const fn=resolveLocalFunction(callee);if(!fn||fn.params.length<2)return null;const paramIndex=new Map;fn.params.forEach((param,index)=>{if(param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)paramIndex.set(param.name,index)});let found=null;const visit=node=>{if(found||!node||typeof node.type!=="string")return;if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const isEquality=node.operator==="==="||node.operator==="!=="||node.operator==="=="||node.operator==="!=";if(isEquality&&!comparesLengths(node)){const leftIndex=paramIndex.get(memberRoot(node.left)?.name??"");const rightIndex=paramIndex.get(memberRoot(node.right)?.name??"");if(leftIndex!==void 0&&rightIndex!==void 0&&leftIndex!==rightIndex){found=[leftIndex,rightIndex];return}}}for(const[key,value]of Object.entries(node)){if(key==="parent")continue;if(Array.isArray(value)){for(const entry of value)visit(entry)}else if(value&&typeof value==="object"&&"type"in value){visit(value)}}};visit(fn.body);return found}function comparisonOperands(node){const args=node.arguments;if(args.some(argument=>argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)){return null}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(BINARY_EQUALITY_FUNCTIONS.has(callee.name)&&args.length===2){return[args[0],args[1]]}const wrapped=equalityWrapperParams(callee);if(!wrapped)return null;const[leftIndex,rightIndex]=wrapped;const leftArg=args[leftIndex];const rightArg=args[rightIndex];if(!leftArg||!rightArg)return null;return[leftArg,rightArg]}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return null;if(method==="compare"&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Buffer"&&args.length===2){return[args[0],args[1]]}if(BINARY_EQUALITY_FUNCTIONS.has(method)&&args.length===2){return[args[0],args[1]]}if(RECEIVER_COMPARE_METHODS.has(method)&&args.length===1){return[callee.object,args[0]]}return null}function checkComparison(node,rawLeft,rawRight){const left=unwrapChain(rawLeft);const right=unwrapChain(rawRight);if(reportLiteralComparands){const literalLeft=isStringLiteral(left);if(literalLeft!==isStringLiteral(right)){if(isSecretIdentifier(literalLeft?right:left)){context.report({node,messageId:"timingUnsafeCompare"});return}}}if(isResolvedConstant(left)||isResolvedConstant(right)){return}if(isNamedConstant(left)||isNamedConstant(right)){return}if(isSelfComparison(left,right)){return}const leftIsSecret=isSecretIdentifier(left)||isCryptoSecret(left);const rightIsSecret=isSecretIdentifier(right)||isCryptoSecret(right);if(leftIsSecret||rightIsSecret){if(!reportUnverifiedComparisons){const leftUntrusted=readsUntrusted(left);const rightUntrusted=readsUntrusted(right);if(leftUntrusted===rightUntrusted){if(!leftUntrusted)return;if(!isServerDerived(left)&&!isServerDerived(right))return}}context.report({node,messageId:"timingUnsafeCompare"})}}function checkBinaryExpression(node){if(node.operator!=="==="&&node.operator!=="=="&&node.operator!=="!=="&&node.operator!=="!="){return}checkComparison(node,node.left,node.right)}function checkCallExpression(node){const operands=comparisonOperands(node);if(!operands)return;checkComparison(node,operands[0],operands[1])}return{before(){const[options={}]=currentOptions();({secretPatterns=DEFAULT_SECRET_PATTERNS,untrustedSources=DEFAULT_UNTRUSTED_SOURCES,reportUnverifiedComparisons=false,reportLiteralComparands=false,nonSecretWords=[...DEFAULT_NON_SECRET_WORDS],nonSecretTails=[...DEFAULT_NON_SECRET_TAILS]}=options);nonSecretWordSet=new Set(nonSecretWords.map(word=>word.toLowerCase()));nonSecretTailSet=new Set(nonSecretTails.map(word=>word.toLowerCase()));sourceCode=context.sourceCode;readsUntrusted=(0,provenance_1.makeReadsTaintSource)(sourceCode,new Set(untrustedSources.map(source=>source.toLowerCase())));patterns=(0,eslint_devkit_1.compileUserPatterns)(secretPatterns,"i")},BinaryExpression:checkBinaryExpression,CallExpression:checkCallExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noTimingUnsafeCompare=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const names_1=require("../../utils/names");const DEFAULT_SECRET_PATTERNS=["token","secret","password","hash","signature","mac","hmac","digest","apiKey","api_key","api-key","auth","credential","bearer","jwt","csrf","nonce","ssn","social_security","social-security","pii","private_key","private-key","privateKey","access_token","access-token","accessToken","refresh_token","refresh-token","refreshToken","session_id","session-id","sessionId","auth_token","auth-token","authToken","encryption_key","encryption-key","encryptionKey"];function isSourceConstant(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.name==="undefined")return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral)return node.expressions.length===0;return false}function isStringLiteral(node){return(0,eslint_devkit_1.staticString)(node)!==null}const BOOLEAN_PREDICATE_NAME=/^(?:is|has|should|can|did|was|will|does)[A-Z]/;const NAMED_CONSTANT=/^[A-Z][A-Z0-9_]*$/;const DEFAULT_UNTRUSTED_SOURCES=["req","request","ctx","event"];const NAMESPACE_NAME=/^(?:[A-Z][A-Z0-9_]*|[A-Z][a-zA-Z0-9]*)$/;function isNamedConstant(node){if(node.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;if(node.object.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const constant=(0,eslint_devkit_1.propertyName)(node);if(constant===null)return false;return NAMESPACE_NAME.test(node.object.name)&&NAMED_CONSTANT.test(constant)}function memberRoot(node){let current=node;for(;;){if(current.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){current=current.object;continue}if(current.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){current=current.callee;continue}break}return current.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?current:null}function isSelfComparison(left,right){const pair=(bare,derived)=>{if(bare.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return memberRoot(derived)?.name===bare.name};return pair(left,right)||pair(right,left)}const NON_SECRET_MEMBERS=new Map([["hash",new Set(["location"])]]);const DEFAULT_NON_SECRET_WORDS=["author","authors","authored","authoring","authorship","hashtag","hashtags"];const DEFAULT_NON_SECRET_TAILS=["count","counts","limit","limits","usage","total","size","length","price","cost","quota","address","addresses","index","rank","percent","path","paths","pathname","pathnames","endpoint","endpoints","route","routes","hostname","host","port","origin","kind","kinds","type","types","flag","flags","category"];const CRYPTO_DERIVATIONS=new Set(["createHmac","createHash","createSign","pbkdf2Sync","scryptSync","hkdfSync","digest","sign","hmac"]);const RECEIVER_COMPARE_METHODS=new Set(["equals","startsWith","endsWith","localeCompare"]);const BINARY_EQUALITY_FUNCTIONS=new Set(["isEqual","isEqualWith","deepEqual","fastDeepEqual","shallowEqual"]);const SERVER_STATE_REQUEST_PROPERTIES=new Set(["session","user","locals","app","state"]);function unwrapChain(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.ChainExpression?node.expression:node}function memberPropertyName(node){const{property}=node;return property.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier?property.name:(0,eslint_devkit_1.propertyName)(node)}function isNonSecretMember(node){const member=memberPropertyName(node);if(member===null)return false;const receivers=NON_SECRET_MEMBERS.get(member.toLowerCase());if(!receivers)return false;const owner=node.object;const ownerName=owner.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?owner.name:owner.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(owner)??"":"";return receivers.has(ownerName.toLowerCase())}exports.noTimingUnsafeCompare=(0,eslint_devkit_1.createRule)({name:"no-timing-unsafe-compare",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-timing-unsafe-compare.md",description:"Disallow timing-unsafe comparison of secrets",cwe:"CWE-208",cvss:5.9},messages:{timingUnsafeCompare:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Timing-unsafe comparison",cwe:"CWE-208",description:"Using === to compare secrets enables timing attacks. The comparison short-circuits on first mismatch, leaking information about the secret.",severity:"HIGH",fix:"Use crypto.timingSafeEqual() for constant-time comparison",documentationLink:"https://nodejs.org/api/crypto.html#cryptotimingsafeequala-b"})},schema:[{type:"object",properties:{secretPatterns:{type:"array",items:{type:"string"},default:DEFAULT_SECRET_PATTERNS,description:"Variable name patterns that indicate secrets"},untrustedSources:{type:"array",items:{type:"string"},default:DEFAULT_UNTRUSTED_SOURCES,description:"Identifier roots treated as attacker-controlled (default: req, request, ctx, event)"},reportUnverifiedComparisons:{type:"boolean",default:false,description:"Report on a secret-looking name alone, without an attacker-controlled operand. Restores the pre-inversion behaviour."},reportLiteralComparands:{type:"boolean",default:false,description:"Report a secret-named value compared against a string literal (password === 'mypass'), in either order, on the name alone. Off by default because string comparands are usually tags (revokedToken === 'access')."},nonSecretWords:{type:"array",items:{type:"string"},default:[...DEFAULT_NON_SECRET_WORDS],description:`Whole words that mean a secretPatterns match was a collision (default: ${DEFAULT_NON_SECRET_WORDS.join(", ")}). Replaces the list.`},nonSecretTails:{type:"array",items:{type:"string"},default:[...DEFAULT_NON_SECRET_TAILS],description:`Trailing words that make the value a measurement or location rather than a credential (default: ${DEFAULT_NON_SECRET_TAILS.join(", ")}). Replaces the list.`}},additionalProperties:false}]},defaultOptions:[{secretPatterns:DEFAULT_SECRET_PATTERNS,nonSecretWords:[...DEFAULT_NON_SECRET_WORDS],nonSecretTails:[...DEFAULT_NON_SECRET_TAILS]}],createOnce(context,currentOptions){let secretPatterns;let untrustedSources;let reportUnverifiedComparisons;let reportLiteralComparands;let nonSecretWords;let nonSecretTails;let nonSecretWordSet;let nonSecretTailSet;let sourceCode;let readsUntrusted;let patterns;function nameLooksSecret(name){if(BOOLEAN_PREDICATE_NAME.test(name))return false;const words=(0,names_1.identifierWords)(name);if(words.some(word=>nonSecretWordSet.has(word)))return false;if(words.length>0&&nonSecretTailSet.has(words[words.length-1])){return false}return patterns.some(p=>p.test(name))}function isCryptoDerivation(node){const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return isCryptoDerivation(bare);if(node.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return false;const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return CRYPTO_DERIVATIONS.has(callee.name)}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||callee.computed)return false;if(CRYPTO_DERIVATIONS.has(callee.property.name))return true;return isCryptoDerivation(callee.object)}function isCryptoSecret(node){if(isCryptoDerivation(node))return true;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const init=(0,provenance_1.bindingInit)(sourceCode,bare);return init!==void 0&&containsCryptoDerivation(init)}function containsCryptoDerivation(node){if(isCryptoDerivation(node))return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral){return node.expressions.some(expression=>containsCryptoDerivation(expression))}if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){return containsCryptoDerivation(node.left)||containsCryptoDerivation(node.right)}return false}function isServerDerived(node,visited=new Set){if(visited.has(node))return false;visited.add(node);const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return isServerDerived(bare,visited);if(node.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression)return true;if(containsCryptoDerivation(node))return true;if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const propertyName=memberPropertyName(node);if(propertyName!==null&&SERVER_STATE_REQUEST_PROPERTIES.has(propertyName)){return true}return isServerDerived(node.object,visited)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const init=(0,provenance_1.bindingInit)(sourceCode,node);return init!==void 0&&isServerDerived(init,visited)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const callee=unwrapChain(node.callee);if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return false;return!readsUntrusted(callee.object)||isServerDerived(callee.object,visited)}return false}function isSecretIdentifier(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return nameLooksSecret(node.name)}if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(isNonSecretMember(node))return false;const propertyName=memberPropertyName(node);if(propertyName!==null){return nameLooksSecret(propertyName)}}return false}function isResolvedConstant(node){if(isSourceConstant(node))return true;if(node.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;return(0,provenance_1.constLiteralOf)(sourceCode,node)!==void 0}function resolveLocalFunction(callee){const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(!variable||variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type==="FunctionName")return def.node;if(def.type!=="Variable")return null;const init=def.node.init;if(!init)return null;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(init);if(bare.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression||bare.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression){return bare}return null}function comparesLengths(node){const isLength=operand=>operand.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&memberPropertyName(operand)==="length";return isLength(node.left)||isLength(node.right)}function equalityWrapperParams(callee){const fn=resolveLocalFunction(callee);if(!fn||fn.params.length<2)return null;const paramIndex=new Map;fn.params.forEach((param,index)=>{if(param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)paramIndex.set(param.name,index)});let found=null;const visit=node=>{if(found||!node||typeof node.type!=="string")return;if(node.type===eslint_devkit_1.AST_NODE_TYPES.BinaryExpression){const isEquality=node.operator==="==="||node.operator==="!=="||node.operator==="=="||node.operator==="!=";if(isEquality&&!comparesLengths(node)){const leftIndex=paramIndex.get(memberRoot(node.left)?.name??"");const rightIndex=paramIndex.get(memberRoot(node.right)?.name??"");if(leftIndex!==void 0&&rightIndex!==void 0&&leftIndex!==rightIndex){found=[leftIndex,rightIndex];return}}}for(const[key,value]of Object.entries(node)){if(key==="parent")continue;if(Array.isArray(value)){for(const entry of value)visit(entry)}else if(value&&typeof value==="object"&&"type"in value){visit(value)}}};visit(fn.body);return found}function comparisonOperands(node){const args=node.arguments;if(args.some(argument=>argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)){return null}const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){if(BINARY_EQUALITY_FUNCTIONS.has(callee.name)&&args.length>=2){return[args[0],args[1]]}const wrapped=equalityWrapperParams(callee);if(!wrapped)return null;const[leftIndex,rightIndex]=wrapped;const leftArg=args[leftIndex];const rightArg=args[rightIndex];if(!leftArg||!rightArg)return null;return[leftArg,rightArg]}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;const method=(0,eslint_devkit_1.propertyName)(callee);if(method===null)return null;if(method==="compare"&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Buffer"&&args.length===2){return[args[0],args[1]]}if(BINARY_EQUALITY_FUNCTIONS.has(method)&&args.length>=2){return[args[0],args[1]]}if(RECEIVER_COMPARE_METHODS.has(method)&&args.length===1){return[callee.object,args[0]]}return null}function checkComparison(node,rawLeft,rawRight){const left=unwrapChain(rawLeft);const right=unwrapChain(rawRight);if(reportLiteralComparands){const literalLeft=isStringLiteral(left);if(literalLeft!==isStringLiteral(right)){if(isSecretIdentifier(literalLeft?right:left)){context.report({node,messageId:"timingUnsafeCompare"});return}}}if(isResolvedConstant(left)||isResolvedConstant(right)){return}if(isNamedConstant(left)||isNamedConstant(right)){return}if(isSelfComparison(left,right)){return}const leftIsSecret=isSecretIdentifier(left)||isCryptoSecret(left);const rightIsSecret=isSecretIdentifier(right)||isCryptoSecret(right);if(leftIsSecret||rightIsSecret){if(!reportUnverifiedComparisons){const leftUntrusted=readsUntrusted(left);const rightUntrusted=readsUntrusted(right);if(leftUntrusted===rightUntrusted){if(!leftUntrusted)return;if(!isServerDerived(left)&&!isServerDerived(right))return}}context.report({node,messageId:"timingUnsafeCompare"})}}function checkBinaryExpression(node){if(node.operator!=="==="&&node.operator!=="=="&&node.operator!=="!=="&&node.operator!=="!="){return}checkComparison(node,node.left,node.right)}function checkCallExpression(node){const operands=comparisonOperands(node);if(!operands)return;checkComparison(node,operands[0],operands[1])}return{before(){const[options={}]=currentOptions();({secretPatterns=DEFAULT_SECRET_PATTERNS,untrustedSources=DEFAULT_UNTRUSTED_SOURCES,reportUnverifiedComparisons=false,reportLiteralComparands=false,nonSecretWords=[...DEFAULT_NON_SECRET_WORDS],nonSecretTails=[...DEFAULT_NON_SECRET_TAILS]}=options);nonSecretWordSet=new Set(nonSecretWords.map(word=>word.toLowerCase()));nonSecretTailSet=new Set(nonSecretTails.map(word=>word.toLowerCase()));sourceCode=context.sourceCode;readsUntrusted=(0,provenance_1.makeReadsTaintSource)(sourceCode,new Set(untrustedSources.map(source=>source.toLowerCase())));patterns=(0,eslint_devkit_1.compileUserPatterns)(secretPatterns,"i")},BinaryExpression:checkBinaryExpression,CallExpression:checkCallExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noToctouVulnerability=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");const PER_USER_ROOT_FUNCTIONS=new Set(["homedir","userInfo"]);const PER_USER_ENV_VARS=new Set(["HOME","USERPROFILE","LOCALAPPDATA","APPDATA","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_STATE_HOME"]);const DEFAULT_FS_METHODS=["fs.existsSync","fs.statSync","fs.accessSync","fs.exists","fs.stat","fs.access"];const MKDIR_METHODS=new Set(["mkdir","mkdirSync"]);const RISKY_USE_METHODS=new Set(["readFileSync","readFile","openSync","open","createReadStream","writeFileSync","writeFile","appendFileSync","appendFile","createWriteStream","unlinkSync","unlink","rmSync","rm","rmdirSync","rmdir","mkdirSync","mkdir","renameSync","rename","copyFileSync","copyFile","truncateSync","truncate","chmodSync","chmod","chownSync","chown","symlinkSync","symlink","linkSync","link"]);function memberName(callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return null;if(callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&!callee.computed){return callee.property.name}return callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof callee.property.value==="string"?callee.property.value:null}exports.noToctouVulnerability=(0,eslint_devkit_2.createRule)({name:"no-toctou-vulnerability",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-toctou-vulnerability.md",description:"Detects Time-of-Check-Time-of-Use vulnerabilities",cwe:"CWE-367",cvss:7},messages:{toctouVulnerability:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"TOCTOU vulnerability",cwe:"CWE-367",description:"Time-of-check Time-of-use race condition detected",severity:"HIGH",fix:"Act on the result and handle the failure \u2014 open/unlink and catch ENOENT \u2014 instead of checking first. Not a finding if the path is inside a directory only this user can write",documentationLink:"https://cwe.mitre.org/data/definitions/367.html"})},schema:[{type:"object",properties:{ignoreInTests:{type:"boolean",default:true},fsMethods:{type:"array",items:{type:"string"},default:DEFAULT_FS_METHODS,description:"Filesystem check calls that create a time-of-check window. Replaces the built-in list. Only the final dotted segment is compared, so `fs.existsSync` and `existsSync` are the same entry."}},additionalProperties:false}]},defaultOptions:[{ignoreInTests:true,fsMethods:DEFAULT_FS_METHODS}],createOnce(context,currentOptions){let checkMethods;let sourceCode;let EXISTENCE_CHECKS;let READ_ONLY_USES;function returnedExpression(callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(!variable||variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="FunctionName")return null;const body=def.node.body;if(body?.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return null;for(const statement of body.body){if(statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement&&statement.argument){return statement.argument}}return null}function reachesPerUserRoot(node,depth=0){if(depth>8)return false;const next=child=>reachesPerUserRoot(child,depth+1);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const variable=(0,provenance_1.findVariable)(sourceCode,node);const def=variable?.defs.length===1?variable.defs[0]:void 0;if(def?.type!=="Variable"||!def.node.init)return false;return next(def.node.init)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),PER_USER_ENV_VARS)){return true}return next(node.object)}case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;const name=callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(callee):null;if(name!==null&&PER_USER_ROOT_FUNCTIONS.has(name))return true;if(node.arguments.some(argument=>next(argument)))return true;const returned=returnedExpression(callee);return returned!==null&&next(returned)}case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return next(node.consequent)||next(node.alternate);case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return next(node.left)||next(node.right);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(expression=>next(expression));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return next(node.left)||next(node.right);default:return false}}function isSecurityRelevantWindow(checkMethod,useMethod){if(!EXISTENCE_CHECKS.has(checkMethod))return true;return!READ_ONLY_USES.has(useMethod)}function resolvesToNonFsLocal(callee,at){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const scope=sourceCode.getScope(at);if((0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs")||(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs/promises")){return false}const variable=(0,provenance_1.findVariable)(sourceCode,callee);return!!variable&&variable.defs.length>0}function usedMethodName(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return resolvesToNonFsLocal(callee,node)?"":callee.name}const name=memberName(callee);if(name===null)return"";const objectName=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.object.name:"";if(objectName==="fs"||objectName==="fsPromises")return name;const scope=sourceCode.getScope(node);return(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs")||(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs/promises")?name:""}function collectConditionCalls(node,out,depth=0){if(depth>8)return;const inner=(0,eslint_devkit_1.unwrapTypeSyntax)(node);switch(inner.type){case eslint_devkit_1.AST_NODE_TYPES.CallExpression:out.push(inner);return;case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:case eslint_devkit_1.AST_NODE_TYPES.AwaitExpression:collectConditionCalls(inner.argument,out,depth+1);return;case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:collectConditionCalls(inner.left,out,depth+1);collectConditionCalls(inner.right,out,depth+1);return;case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:collectConditionCalls(inner.test,out,depth+1);return;case eslint_devkit_1.AST_NODE_TYPES.ChainExpression:collectConditionCalls(inner.expression,out,depth+1);return;case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:collectConditionCalls(inner.object,out,depth+1);return;case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=(0,const_value_1.constInitializerOf)(sourceCode,inner);if(init!==null)collectConditionCalls(init,out,depth+1);return}default:return}}function sameTarget(checkArg,useArg){const check=(0,eslint_devkit_1.unwrapTypeSyntax)(checkArg);const use=(0,eslint_devkit_1.unwrapTypeSyntax)(useArg);if(check.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&use.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return check.name===use.name}return sourceCode.getText(check).replace(/\s/g,"")===sourceCode.getText(use).replace(/\s/g,"")}function hasRecursiveOption(node){return node.arguments.some(argument=>argument.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&argument.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(property)==="recursive"&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.value.value===true))}function checkCallExpression(node){const useMethodName=usedMethodName(node);if(!RISKY_USE_METHODS.has(useMethodName)){return}if(MKDIR_METHODS.has(useMethodName)&&hasRecursiveOption(node)){return}const rawUseArg=node.arguments[0];if(!rawUseArg)return;const useArg=(0,eslint_devkit_1.unwrapTypeSyntax)(rawUseArg);if(reachesPerUserRoot(useArg))return;let current=node.parent;while(current){if(current.type==="IfStatement"){const conditionCalls=[];collectConditionCalls(current.test,conditionCalls);for(const condition of conditionCalls){const checkMethodName=resolvesToNonFsLocal(condition.callee,condition)?"":memberName(condition.callee)??(condition.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?condition.callee.name:"");if(checkMethods.has(checkMethodName)&&isSecurityRelevantWindow(checkMethodName,useMethodName)){const checkArg=condition.arguments[0];if(checkArg&&sameTarget(checkArg,useArg)){reportToctou(node);return}}if(condition.callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(condition.callee),["isFile","isDirectory"])&&condition.callee.object.type==="Identifier"){const statsVarName=condition.callee.object.name;let currentScope=sourceCode.getScope(condition);let variable=null;while(currentScope){variable=currentScope.variables.find(v=>v.name===statsVarName)||null;if(variable)break;currentScope=currentScope.upper}if(variable&&variable.defs.length>0){const def=variable.defs[0];const declared=def.type==="Variable"&&def.node.init?(0,eslint_devkit_1.unwrapTypeSyntax)(def.node.init):null;const init=declared?.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression?(0,eslint_devkit_1.unwrapTypeSyntax)(declared.argument):declared;if(init?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const statMethod=memberName(init.callee)??(init.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?init.callee.name:"");if(["statSync","lstatSync","stat","lstat"].includes(statMethod)){const statArg=init.arguments[0];if(statArg&&sameTarget(statArg,useArg)){reportToctou(node);return}}}}}}}current=current.parent}}function reportToctou(node){context.report({node,messageId:"toctouVulnerability"})}return{before(){const[options={}]=currentOptions();const{ignoreInTests=true,fsMethods=DEFAULT_FS_METHODS}=options||{};checkMethods=new Set(fsMethods.map(entry=>entry.split(".").at(-1)));const filename=context.filename;const isTestFile=ignoreInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return false}sourceCode=context.sourceCode;EXISTENCE_CHECKS=new Set(["existsSync","exists"]);READ_ONLY_USES=new Set(["readFileSync","readFile"]);return true},CallExpression:checkCallExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noToctouVulnerability=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");const PER_USER_ROOT_FUNCTIONS=new Set(["homedir","userInfo"]);const PER_USER_ENV_VARS=new Set(["HOME","USERPROFILE","LOCALAPPDATA","APPDATA","XDG_CACHE_HOME","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_STATE_HOME"]);const ACCESS_CHECKS=new Set(["access","accessSync"]);const DEFAULT_FS_METHODS=["fs.existsSync","fs.statSync","fs.accessSync","fs.exists","fs.stat","fs.access"];const MKDIR_METHODS=new Set(["mkdir","mkdirSync"]);const RISKY_USE_METHODS=new Set(["readFileSync","readFile","openSync","open","createReadStream","writeFileSync","writeFile","appendFileSync","appendFile","createWriteStream","unlinkSync","unlink","rmSync","rm","rmdirSync","rmdir","mkdirSync","mkdir","renameSync","rename","copyFileSync","copyFile","truncateSync","truncate","chmodSync","chmod","chownSync","chown","symlinkSync","symlink","linkSync","link"]);function calleeName(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return callee.name;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(callee)??""}return""}exports.noToctouVulnerability=(0,eslint_devkit_2.createRule)({name:"no-toctou-vulnerability",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-toctou-vulnerability.md",description:"Detects Time-of-Check-Time-of-Use vulnerabilities",cwe:"CWE-367",cvss:7},messages:{toctouVulnerability:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"TOCTOU vulnerability",cwe:"CWE-367",description:"Time-of-check Time-of-use race condition detected",severity:"HIGH",fix:"Act on the result and handle the failure \u2014 open/unlink and catch ENOENT \u2014 instead of checking first. Not a finding if the path is inside a directory only this user can write",documentationLink:"https://cwe.mitre.org/data/definitions/367.html"})},schema:[{type:"object",properties:{ignoreInTests:{type:"boolean",default:true},fsMethods:{type:"array",items:{type:"string"},default:DEFAULT_FS_METHODS,description:"Filesystem check calls that create a time-of-check window. Replaces the built-in list. Only the final dotted segment is compared, so `fs.existsSync` and `existsSync` are the same entry."}},additionalProperties:false}]},defaultOptions:[{ignoreInTests:true,fsMethods:DEFAULT_FS_METHODS}],createOnce(context,currentOptions){let checkMethods;let sourceCode;let EXISTENCE_CHECKS;let READ_ONLY_USES;function returnedExpression(callee){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(!variable||variable.defs.length!==1)return null;const def=variable.defs[0];if(def.type!=="FunctionName")return null;const body=def.node.body;if(body?.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement)return null;for(const statement of body.body){if(statement.type===eslint_devkit_1.AST_NODE_TYPES.ReturnStatement&&statement.argument){return statement.argument}}return null}function reachesPerUserRoot(node,visited=new Set){if(visited.has(node))return false;visited.add(node);const next=child=>reachesPerUserRoot(child,visited);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const variable=(0,provenance_1.findVariable)(sourceCode,node);const def=variable?.defs.length===1?variable.defs[0]:void 0;if(def?.type!=="Variable"||!def.node.init)return false;return next(def.node.init)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{if((0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node),PER_USER_ENV_VARS)){return true}return next(node.object)}case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{const callee=node.callee;const name=callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.name:callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression?(0,eslint_devkit_1.propertyName)(callee):null;if(name!==null&&PER_USER_ROOT_FUNCTIONS.has(name))return true;if(node.arguments.some(argument=>next(argument)))return true;const returned=returnedExpression(callee);return returned!==null&&next(returned)}case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:return next(node.consequent)||next(node.alternate);case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:return next(node.left)||next(node.right);case eslint_devkit_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.some(expression=>next(expression));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return next(node.left)||next(node.right);default:return false}}function isSecurityRelevantWindow(checkMethod,useMethod){if(!EXISTENCE_CHECKS.has(checkMethod))return true;return!READ_ONLY_USES.has(useMethod)}function resolvesToNonFsLocal(callee,at){if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const scope=sourceCode.getScope(at);if((0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs")||(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs/promises")){return false}const variable=(0,provenance_1.findVariable)(sourceCode,callee);return!!variable&&variable.defs.length>0}function usedMethodName(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return resolvesToNonFsLocal(callee,node)?"":callee.name}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression)return"";const name=(0,eslint_devkit_1.propertyName)(callee);if(name===null)return"";const objectName=callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.object.name:"";if(objectName==="fs"||objectName==="fsPromises")return name;const scope=sourceCode.getScope(node);return(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs")||(0,eslint_devkit_1.isModuleBinding)(callee,scope,"fs/promises")?name:""}function collectConditionCalls(node,out,visited=new Set){if(visited.has(node))return;visited.add(node);const inner=(0,eslint_devkit_1.unwrapTypeSyntax)(node);switch(inner.type){case eslint_devkit_1.AST_NODE_TYPES.CallExpression:out.push(inner);if(inner.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){collectConditionCalls(inner.callee.object,out,visited)}return;case eslint_devkit_1.AST_NODE_TYPES.UnaryExpression:case eslint_devkit_1.AST_NODE_TYPES.AwaitExpression:collectConditionCalls(inner.argument,out,visited);return;case eslint_devkit_1.AST_NODE_TYPES.LogicalExpression:case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:collectConditionCalls(inner.left,out,visited);collectConditionCalls(inner.right,out,visited);return;case eslint_devkit_1.AST_NODE_TYPES.ConditionalExpression:collectConditionCalls(inner.test,out,visited);return;case eslint_devkit_1.AST_NODE_TYPES.ChainExpression:collectConditionCalls(inner.expression,out,visited);return;case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:collectConditionCalls(inner.object,out,visited);return;case eslint_devkit_1.AST_NODE_TYPES.Identifier:{const init=(0,const_value_1.constInitializerOf)(sourceCode,inner);if(init!==null)collectConditionCalls(init,out,visited);return}}}function sameTarget(checkArg,useArg){const check=(0,eslint_devkit_1.unwrapTypeSyntax)(checkArg);const use=(0,eslint_devkit_1.unwrapTypeSyntax)(useArg);return sourceCode.getText(check).replace(/\s/g,"")===sourceCode.getText(use).replace(/\s/g,"")}function checkMethodOf(call){if(resolvesToNonFsLocal(call.callee,call))return"";return calleeName(call.callee)}function precededByAccessCheck(use,useArg){let child=use;let parent=use.parent;for(;parent;child=parent,parent=child.parent){if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.BlockStatement&&parent.type!==eslint_devkit_1.AST_NODE_TYPES.Program){continue}const statements=parent.body;const before=statements.slice(0,statements.indexOf(child));for(const statement of before){if(statement.type!==eslint_devkit_1.AST_NODE_TYPES.ExpressionStatement)continue;const expression=(0,eslint_devkit_1.unwrapTypeSyntax)(statement.expression);const call=(0,eslint_devkit_1.unwrapTypeSyntax)(expression.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression?expression.argument:expression);if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)continue;const method=checkMethodOf(call);const checkArg=call.arguments[0];if(ACCESS_CHECKS.has(method)&&checkMethods.has(method)&&checkArg!==void 0&&sameTarget(checkArg,useArg)){return true}}}return false}function hasRecursiveOption(node){return node.arguments.some(argument=>argument.type===eslint_devkit_1.AST_NODE_TYPES.ObjectExpression&&argument.properties.some(property=>property.type===eslint_devkit_1.AST_NODE_TYPES.Property&&(0,eslint_devkit_1.objectKeyName)(property)==="recursive"&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&property.value.value===true))}function checkCallExpression(node){const useMethodName=usedMethodName(node);if(!RISKY_USE_METHODS.has(useMethodName)){return}if(MKDIR_METHODS.has(useMethodName)&&hasRecursiveOption(node)){return}const rawUseArg=node.arguments[0];if(!rawUseArg)return;const useArg=(0,eslint_devkit_1.unwrapTypeSyntax)(rawUseArg);if(reachesPerUserRoot(useArg))return;if(precededByAccessCheck(node,useArg)){reportToctou(node);return}let current=node.parent;while(current){if(current.type==="IfStatement"){const conditionCalls=[];collectConditionCalls(current.test,conditionCalls);for(const condition of conditionCalls){const checkMethodName=checkMethodOf(condition);if(checkMethods.has(checkMethodName)&&isSecurityRelevantWindow(checkMethodName,useMethodName)){const checkArg=condition.arguments[0];if(checkArg&&sameTarget(checkArg,useArg)){reportToctou(node);return}}if(condition.callee.type==="MemberExpression"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(condition.callee),["isFile","isDirectory"])&&condition.callee.object.type==="Identifier"){const variable=(0,provenance_1.findVariable)(sourceCode,condition.callee.object);if(variable&&variable.defs.length>0){const def=variable.defs[0];const declared=def.type==="Variable"?(0,eslint_devkit_1.unwrapTypeSyntax)(def.node.init):null;const init=declared?.type===eslint_devkit_1.AST_NODE_TYPES.AwaitExpression?(0,eslint_devkit_1.unwrapTypeSyntax)(declared.argument):declared;if(init?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression){const statMethod=calleeName(init.callee);if(["statSync","lstatSync","stat","lstat"].includes(statMethod)){const statArg=init.arguments[0];if(statArg&&sameTarget(statArg,useArg)){reportToctou(node);return}}}}}}}current=current.parent}}function reportToctou(node){context.report({node,messageId:"toctouVulnerability"})}return{before(){const[options={}]=currentOptions();const{ignoreInTests=true,fsMethods=DEFAULT_FS_METHODS}=options||{};checkMethods=new Set(fsMethods.map(entry=>entry.split(".").at(-1)));const filename=context.filename;const isTestFile=ignoreInTests&&(0,eslint_devkit_1.isTestFilePath)(filename);if(isTestFile){return false}sourceCode=context.sourceCode;EXISTENCE_CHECKS=new Set(["existsSync","exists"]);READ_ONLY_USES=new Set(["readFileSync","readFile"]);return true},CallExpression:checkCallExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnboundedDecompression=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const ZLIB_MODULE=/^(node:)?zlib$/;const ASYNC_DECOMPRESSORS=new Set(["gunzip","inflate","inflateRaw","unzip","brotliDecompress","zstdDecompress"]);const SYNC_DECOMPRESSORS=new Set(["gunzipSync","inflateSync","inflateRawSync","unzipSync","brotliDecompressSync","zstdDecompressSync"]);exports.noUnboundedDecompression=(0,eslint_devkit_1.createRule)({name:"no-unbounded-decompression",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unbounded-decompression.md",description:"Require a maxOutputLength ceiling on zlib one-shot decompression",cwe:"CWE-409",cvss:7.5},hasSuggestions:false,messages:{unboundedDecompression:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unbounded decompression",cwe:"CWE-409",description:"zlib.{{fn}}() buffers the whole decompressed result in memory with no maxOutputLength cap. A few KB of crafted input can expand to gigabytes and exhaust the heap (decompression bomb).",severity:"HIGH",fix:"Pass an explicit ceiling: zlib.{{fn}}(input, { maxOutputLength: 10 * 1024 * 1024 }, \u2026)",documentationLink:"https://nodejs.org/api/zlib.html#class-options"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow unbounded decompression in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function isZlibSpecifier(node){return node?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"&&ZLIB_MODULE.test(node.value)}function extraZlibPath(identifier,scope){let variable;for(let s=scope;s;s=s.upper){variable=s.set.get(identifier.name);if(variable)break}const def=variable?.defs[0];if(!variable||!def)return null;if(def.node.type===eslint_devkit_1.AST_NODE_TYPES.TSImportEqualsDeclaration&&def.node.moduleReference.type===eslint_devkit_1.AST_NODE_TYPES.TSExternalModuleReference){return isZlibSpecifier(def.node.moduleReference.expression)?[]:null}if(def.node.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator)return null;const init=def.node.init;if(init?.type!==eslint_devkit_1.AST_NODE_TYPES.AwaitExpression||init.argument.type!==eslint_devkit_1.AST_NODE_TYPES.ImportExpression||!isZlibSpecifier(init.argument.source)){return null}if(variable.references.filter(ref=>ref.isWrite()).length!==1){return null}const id=def.node.id;if(id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return[];if(id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return null;for(const property of id.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const key=(0,eslint_devkit_1.objectKeyName)(property);if(key!==null&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===identifier.name){return[key]}}return null}function zlibPath(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding!==void 0){return binding.module==="zlib"?binding.path:null}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return extraZlibPath(callee,scope)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=(0,eslint_devkit_1.propertyName)(callee);const base=extraZlibPath(callee.object,scope);return name!==null&&base!==null?[...base,name]:null}return null}function decompressorName(node){const path=zlibPath(node.callee,context.sourceCode.getScope(node));if(path===null||path.length!==1)return null;const[name]=path;return ASYNC_DECOMPRESSORS.has(name)||SYNC_DECOMPRESSORS.has(name)?name:null}function isLiteralPayload(argument){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;return argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&argument.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&argument.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&argument.callee.object.name==="Buffer"&&argument.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal}function outputCap(options_){let capped=false;for(const property of options_.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return"unknown";const named=(0,eslint_devkit_1.objectKeyName)(property);if(named==="maxOutputLength")capped=true}return capped?"capped":"uncapped"}function judge(node){const fn=decompressorName(node);if(fn===null)return;const args=node.arguments;const payload=args[0];if(payload===void 0)return;if(isLiteralPayload(payload))return;const isAsync=ASYNC_DECOMPRESSORS.has(fn);if(isAsync&&args.length<2)return;const candidates=isAsync?args.slice(1,args.length-1):args.slice(1);if(candidates.length>1)return;const optionsArgument=candidates[0];if(optionsArgument!==void 0){if(optionsArgument.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;if(outputCap(optionsArgument)!=="uncapped")return}context.report({node,messageId:"unboundedDecompression",data:{fn}})}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename)},CallExpression(node){if(isTestFile)return;judge(node)}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnboundedDecompression=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const ZLIB_MODULE=/^(node:)?zlib$/;const ASYNC_DECOMPRESSORS=new Set(["gunzip","inflate","inflateRaw","unzip","brotliDecompress","zstdDecompress"]);const SYNC_DECOMPRESSORS=new Set(["gunzipSync","inflateSync","inflateRawSync","unzipSync","brotliDecompressSync","zstdDecompressSync"]);exports.noUnboundedDecompression=(0,eslint_devkit_1.createRule)({name:"no-unbounded-decompression",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unbounded-decompression.md",description:"Require a maxOutputLength ceiling on zlib one-shot decompression",cwe:"CWE-409",cvss:7.5},hasSuggestions:false,messages:{unboundedDecompression:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Unbounded decompression",cwe:"CWE-409",description:"zlib.{{fn}}() buffers the whole decompressed result in memory with no maxOutputLength cap. A few KB of crafted input can expand to gigabytes and exhaust the heap (decompression bomb).",severity:"HIGH",fix:"Pass an explicit ceiling: zlib.{{fn}}(input, { maxOutputLength: 10 * 1024 * 1024 }, \u2026)",documentationLink:"https://nodejs.org/api/zlib.html#class-options"})},schema:[{type:"object",properties:{allowInTests:{type:"boolean",default:false,description:"Allow unbounded decompression in test files"}},additionalProperties:false}]},defaultOptions:[{allowInTests:false}],createOnce(context,currentOptions){let isTestFile;function isZlibSpecifier(node){const specifier=(0,eslint_devkit_1.staticString)(node);return specifier!==null&&ZLIB_MODULE.test(specifier)}function extraZlibPath(identifier,scope){let variable;for(let s=scope;s;s=s.upper){variable=s.set.get(identifier.name);if(variable)break}const def=variable?.defs[0];if(!variable||!def)return null;if(def.node.type!==eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator)return null;const init=def.node.init;if(init?.type!==eslint_devkit_1.AST_NODE_TYPES.AwaitExpression||init.argument.type!==eslint_devkit_1.AST_NODE_TYPES.ImportExpression||!isZlibSpecifier(init.argument.source)){return null}if(variable.references.filter(ref=>ref.isWrite()).length!==1){return null}const id=def.node.id;if(id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return[];if(id.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectPattern)return null;for(const property of id.properties){if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property)continue;const key=(0,eslint_devkit_1.objectKeyName)(property);if(key!==null&&property.value.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&property.value.name===identifier.name){return[key]}}return null}function zlibPath(callee,scope){const binding=(0,eslint_devkit_1.resolveModuleBinding)(callee,scope);if(binding!==void 0){return binding.module==="zlib"?binding.path:null}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return extraZlibPath(callee,scope)}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const name=(0,eslint_devkit_1.propertyName)(callee);const base=extraZlibPath(callee.object,scope);return name!==null&&base!==null?[...base,name]:null}return null}function decompressorName(node){const path=zlibPath(node.callee,context.sourceCode.getScope(node));if(path===null||path.length!==1)return null;const[name]=path;return ASYNC_DECOMPRESSORS.has(name)||SYNC_DECOMPRESSORS.has(name)?name:null}function isLiteralPayload(argument){if(argument.type===eslint_devkit_1.AST_NODE_TYPES.Literal)return true;return argument.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&argument.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&argument.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&argument.callee.object.name==="Buffer"&&argument.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal}function outputCap(options_){let capped=false;for(const property of options_.properties){if(property.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return"unknown";const named=(0,eslint_devkit_1.objectKeyName)(property);if(named==="maxOutputLength")capped=true}return capped?"capped":"uncapped"}function judge(node){const fn=decompressorName(node);if(fn===null)return;const args=node.arguments;const payload=args[0];if(payload===void 0)return;if(isLiteralPayload(payload))return;const isAsync=ASYNC_DECOMPRESSORS.has(fn);if(isAsync&&args.length<2)return;const optionsArgument=isAsync&&args.length===2?void 0:args[1];if(optionsArgument!==void 0){if(optionsArgument.type!==eslint_devkit_1.AST_NODE_TYPES.ObjectExpression)return;if(outputCap(optionsArgument)!=="uncapped")return}context.report({node,messageId:"unboundedDecompression",data:{fn}})}return{before(){const[options={}]=currentOptions();const{allowInTests=false}=options;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename)},CallExpression(node){if(isTestFile)return;judge(node)}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeBufferAlloc=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");const UNSAFE_ALLOCATORS=new Set(["allocUnsafe","allocUnsafeSlow"]);const SIZED_ALLOCATORS=new Set(["Array","Buffer","Uint8Array","Uint16Array","Uint32Array","Int8Array","Int16Array","Int32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","ArrayBuffer","SharedArrayBuffer"]);function looksNumeric(node,countNames){switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Literal:return typeof node.value==="number";case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return["+","-","*","/","%","<<",">>",">>>"].includes(node.operator);case eslint_devkit_1.AST_NODE_TYPES.Identifier:return countNames.has(node.name.toLowerCase());case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{const prop=(0,eslint_devkit_1.propertyName)(node);return prop!==null&&countNames.has(prop.toLowerCase())}case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{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==="Math"){return true}const name=calleeName(node.callee);return name!==null&&/^(read|len|size|count|decode|parse)/i.test(name)}default:return false}}function toLowerSet(names){return new Set(names.map(n=>n.toLowerCase()))}const COUNT_NAMES=new Set(["length","len","size","count","n","num","total","capacity","bytelength"]);const BUFFER_ALLOCATORS=new Set(["alloc","allocUnsafe","allocUnsafeSlow"]);const WIRE_NAMES=new Set(["chunk","chunks","buffer","buf","payload","frame","packet","raw","message","msg"]);const REQUEST_ROOTS=new Set(["req","request","ctx","event"]);function isWriteMethod(name){return name==="fill"||name==="set"||name.startsWith("write")}const DESTINATION_ARGUMENT_CALLS=new Set(["copy","randomFill","randomFillSync"]);const METADATA_PROPERTIES=new Set(["length","byteLength","byteOffset","buffer"]);const WRITE_WIDTHS=new Map([["writeUInt8",1],["writeInt8",1],["writeUInt16LE",2],["writeUInt16BE",2],["writeInt16LE",2],["writeInt16BE",2],["writeUInt32LE",4],["writeUInt32BE",4],["writeInt32LE",4],["writeInt32BE",4],["writeFloatLE",4],["writeFloatBE",4],["writeDoubleLE",8],["writeDoubleBE",8],["writeBigInt64LE",8],["writeBigInt64BE",8],["writeBigUInt64LE",8],["writeBigUInt64BE",8]]);const MAX_TRACKED_ALLOCATION=4096;const BUFFER_MODULES=new Set(["buffer","node:buffer"]);const CRYPTO_MODULES=new Set(["crypto","node:crypto"]);const RANDOM_FILL_CALLS=new Set(["randomFill","randomFillSync"]);function isCryptoModuleRequire(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.arguments[0].value==="string"&&CRYPTO_MODULES.has(node.arguments[0].value)}function isBufferModuleRequire(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.arguments[0].value==="string"&&BUFFER_MODULES.has(node.arguments[0].value)}function isBufferObject(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="Buffer";return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node)==="Buffer"&&isBufferModuleRequire(node.object)}function isInsideLoop(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement){return true}current=current.parent}return false}function coversWholeBuffer(call,method){if(method==="fill")return true;const width=WRITE_WIDTHS.get(method);if(width!==void 0){const offset2=call.arguments[1];return offset2!==void 0&&offset2.type!==eslint_devkit_1.AST_NODE_TYPES.Literal&&isInsideLoop(call)}if(call.arguments.length===1)return true;const offset=call.arguments[1];return offset.type!==eslint_devkit_1.AST_NODE_TYPES.Literal&&isInsideLoop(call)}function fixedWriteSpan(call,method){const width=WRITE_WIDTHS.get(method);if(width===void 0)return null;const offset=call.arguments[1];if(offset===void 0)return{start:0,end:width};if(offset.type!==eslint_devkit_1.AST_NODE_TYPES.Literal||typeof offset.value!=="number"){return null}return{start:offset.value,end:offset.value+width}}function calleeName(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return callee.name;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier){return callee.property.name}return(0,eslint_devkit_1.propertyName)(callee)}return null}function declaredName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&node.id)return node.id.name;const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){return parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?parent.id.name:null}if((parent?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition||parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property)&&!parent.computed){const key=parent.key;return key.name}return null}exports.noUnsafeBufferAlloc=(0,eslint_devkit_1.createRule)({name:"no-unsafe-buffer-alloc",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unsafe-buffer-alloc.md",description:"Disallow `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()`, which return uninitialized memory",cwe:"CWE-908",cweJustification:"CWE-908 (Use of Uninitialized Resource) \u2014 allocUnsafe returns a view over non-zeroed heap memory; any byte not overwritten before the buffer is read or transmitted discloses prior process memory.",cvss:7.5,confidence:"high"},messages:{unsafeAlloc:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Uninitialized Buffer Allocation",cwe:"CWE-908",cvss:7.5,description:"`Buffer.allocUnsafe(size)` returns memory that has not been zeroed. Every byte not overwritten before the buffer is read or sent leaks whatever the allocator previously stored there.",severity:"HIGH",fix:"Use `Buffer.alloc(size)` (zero-filled), or keep `allocUnsafe` only where the very next statement overwrites the whole buffer \u2014 `Buffer.allocUnsafe(size).fill(0)` is accepted by this rule.",documentationLink:"https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize"}),unsafeAllocSlow:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Uninitialized Buffer Allocation (allocUnsafeSlow)",cwe:"CWE-908",cvss:7.5,description:"`Buffer.allocUnsafeSlow(size)` allocates outside the shared pool but is equally uninitialized \u2014 the returned bytes are whatever was last in that memory.",severity:"HIGH",fix:"Use `Buffer.alloc(size)`, or append `.fill(0)` to zero the allocation at the call site.",documentationLink:"https://nodejs.org/api/buffer.html#static-method-bufferallocunsafeslowsize"}),useSafeAlloc:"Replace with `Buffer.alloc()` (zero-filled).",unboundedAllocation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Allocation Sized By Untrusted Input",cwe:"CWE-789",cvss:7.5,description:'The allocation size is read off the wire, so the peer picks it. For `new Array(n)` the hazard is a narrow band, not "large n": V8 keeps a packed backing store only up to ~33.5M elements, and a length just under that turns a 12-byte length prefix into a 229MB allocation (measured: `new Array(3e7)` = 228.9MB in 20.7ms). Past the threshold V8 switches the array to dictionary mode and the allocation costs nothing at all (`new Array(4e7)` and `new Array(1e9)` are both 0.0MB in ~0.005ms). A typed allocation \u2014 `Buffer.alloc(n)`, `new Uint8Array(n)` \u2014 has no such threshold and commits n bytes at any n.',severity:"HIGH",fix:'Clamp the length against the maximum the protocol actually permits, before allocating: `if (length > MAX_LENGTH) throw new Error("too long")`, or `new Array(Math.min(length, MAX_LENGTH))`. A guard that only rejects implausibly huge values is not a fix for `new Array` \u2014 those are the sizes V8 makes free. The damaging lengths are the plausible ones just below the packed-elements limit.',documentationLink:"https://cwe.mitre.org/data/definitions/789.html"})},schema:[{type:"object",properties:{wireNames:{type:"array",items:{type:"string"},default:[...WIRE_NAMES],description:"Binding names that carry bytes off the wire. Replaces the default; pass [] to turn the name arm off."},requestRootNames:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Root identifiers treated as a request. Replaces the default."},countNames:{type:"array",items:{type:"string"},default:[...COUNT_NAMES],description:"Identifiers that hold an allocation size rather than a payload. Replaces the default."}},additionalProperties:false}]},defaultOptions:[{}],createOnce(context,currentOptions){let sourceCode;let vocab;let wireParams;let pendingAllocations;let pendingCallSites;function readsWire(node,depth=0){if(depth>10)return false;const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return readsWire(bare,depth+1);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(node.name==="Buffer"){const bound=(0,provenance_1.findVariable)(sourceCode,node);if(bound===null||bound.defs.length===0)return false;if(bound.defs[0].type==="ImportBinding")return false}const lower=node.name.toLowerCase();if(vocab.wireNames.has(lower)||vocab.requestRoots.has(lower)){const bound=(0,provenance_1.findVariable)(sourceCode,node);const def=bound===null?void 0:bound.defs[0];if(def!==void 0&&def.type==="Variable"&&def.node.init!==null&&def.node.init!==void 0){return readsWire(def.node.init,depth+1)}return true}const owner=enclosingFunction(node);if(owner!==null){const name=declaredName(owner);const indices=name===null?void 0:wireParams.get(name);if(indices!==void 0){const index=paramIndexOf(node,owner);if(index!==null&&indices.has(index))return true}}const variable=(0,provenance_1.findVariable)(sourceCode,node);const lastWrite=(variable?.references??[]).map(reference=>reference.writeExpr).filter(write=>write!=null).filter(write=>write.range[1]<=node.range[0]).sort((a,b)=>a.range[1]-b.range[1]).at(-1);return lastWrite!==void 0&&readsWire(lastWrite,depth+1)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:if((0,eslint_devkit_1.readsRequestShape)(node,sourceCode))return true;return readsWire(node.object,depth+1);case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return node.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&readsWire(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return readsWire(node.callee,depth+1)||node.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&readsWire(argument,depth+1));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return readsWire(node.left,depth+1)||readsWire(node.right,depth+1);default:return false}}function enclosingFunction(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return current}current=current.parent}return null}function paramIndexOf(node,owner){const params=owner.params;const index=params.findIndex(param=>param.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&param.name===node.name);return index===-1?null:index}function isClamped(size){if(size.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&size.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&size.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&size.callee.object.name==="Math"&&(0,eslint_devkit_1.propertyName)(size.callee)==="min"){return size.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!readsWire(argument))}if(size.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const name=size.name;let current=size.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(mentionsInComparison(current.test,name))return true}if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){const body=current.body;if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){for(const statement of body.body){if(statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&mentionsInComparison(statement.test,name)){return true}}}return false}current=current.parent}return false}function mentionsInComparison(test,name){if(test.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return mentionsInComparison(test.left,name)||mentionsInComparison(test.right,name)}if(test.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)return false;if(!["<","<=",">",">="].includes(test.operator))return false;const named=side=>side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&side.name===name;return named(test.left)||named(test.right)}function allocationSize(node){const size=node.arguments[0];if(size===void 0||size.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return null;const callee=node.callee;if(node.type===eslint_devkit_1.AST_NODE_TYPES.NewExpression&&callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&SIZED_ALLOCATORS.has(callee.name)){return looksNumeric(size,vocab.countNames)?size:null}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Buffer"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),BUFFER_ALLOCATORS)){return size}return null}function recordCallSite(node){const name=calleeName(node.callee);if(name===null)return;node.arguments.forEach((argument,index)=>{if(argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement)return;if(!readsWire(argument))return;const indices=wireParams.get(name)??new Set;indices.add(index);wireParams.set(name,indices)})}function judgeAllocation(node,size){if(isClamped(size))return;if(!readsWire(size))return;context.report({node,messageId:"unboundedAllocation"})}function classifyUse(identifier){const parent=identifier.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===identifier){if(parent.computed){const grandparent2=parent.parent;const isWrite=grandparent2.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&grandparent2.left===parent;if(!isWrite)return"read";return parent.property.type!==eslint_devkit_1.AST_NODE_TYPES.Literal&&isInsideLoop(parent)?"covering":"partial"}if(parent.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return"read";const name=parent.property.name;if(METADATA_PROPERTIES.has(name))return"metadata";const grandparent=parent.parent;if(grandparent.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||grandparent.callee!==parent||!isWriteMethod(name)){return"read"}return coversWholeBuffer(grandparent,name)?"covering":"partial"}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===identifier){const method=destinationArgumentCallee(parent.callee);if(method===null)return"read";return coversWholeBuffer(parent,method)?"covering":"partial"}return"read"}function destinationArgumentCallee(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),DESTINATION_ARGUMENT_CALLS)){return(0,eslint_devkit_1.propertyName)(callee)}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!RANDOM_FILL_CALLS.has(callee.name)){return null}const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(variable===null||variable.defs.length===0)return null;const def=variable.defs[0];if(def.type==="ImportBinding"){const declaration=def.parent;return declaration.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&CRYPTO_MODULES.has(declaration.source.value)?callee.name:null}return def.type==="Variable"&&def.node.init!==null&&isCryptoModuleRequire(def.node.init)?callee.name:null}function isCoveredBeforeRead(call){const parent=call.parent;let target;let variable;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===call&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){target=parent.id;variable=context.sourceCode.getDeclaredVariables(parent)[0]}else if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.operator==="="&&parent.right===call&&parent.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){target=parent.left;variable=(0,provenance_1.findVariable)(context.sourceCode,target)??void 0}if(target===void 0||variable===void 0){return false}const uses=variable.references.filter(reference=>reference.identifier!==target&&reference.identifier.range[0]>call.range[1]).sort((a,b)=>a.identifier.range[0]-b.identifier.range[0]);const covered=byteMapFor(call);let remaining=covered===null?-1:covered.length;for(const use of uses){const kind=classifyUse(use.identifier);if(kind==="metadata")continue;if(kind==="partial"){if(covered!==null){remaining-=markFixedWrite(covered,use.identifier);if(remaining===0)return true}continue}return kind==="covering"}return false}function byteMapFor(call){const argument=call.arguments[0];if(argument===void 0||argument.type===eslint_devkit_1.AST_NODE_TYPES.SpreadElement){return null}const resolved=(0,const_value_1.resolveConstant)(sourceCode,argument);if(resolved===null||typeof resolved.value!=="number")return null;const size=resolved.value;if(!Number.isInteger(size)||size<=0||size>MAX_TRACKED_ALLOCATION){return null}return new Uint8Array(size)}function markFixedWrite(covered,identifier){const member=identifier.parent;if(member.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||member.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return 0}const call=member.parent;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return 0;const span=fixedWriteSpan(call,member.property.name);if(span===null||span.start<0||span.end>covered.length)return 0;let added=0;for(let index=span.start;index<span.end;index+=1){if(covered[index]===0){covered[index]=1;added+=1}}return added}function unsafeAllocator(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(!isBufferObject(callee.object))return null;const name=callee.computed?(0,const_value_1.resolveConstantString)(sourceCode,callee.property)?.value:callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property.name:void 0;return name!==void 0&&UNSAFE_ALLOCATORS.has(name)?name:null}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(variable===null||variable.defs.length===0)return null;const def=variable.defs[0];if(def.type!=="Variable"||def.node.init===null)return null;if(!isBufferObject(def.node.init))return null;const property=def.name.parent;if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed||property.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return null}return UNSAFE_ALLOCATORS.has(property.key.name)?property.key.name:null}function isFilledInPlace(node){const parent=node.parent;if(parent?.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||parent.object!==node||parent.computed||parent.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||parent.property.name!=="fill"){return false}const grandparent=parent.parent;return grandparent?.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&grandparent.callee===parent}return{before(){const[options={}]=currentOptions();sourceCode=context.sourceCode;vocab={wireNames:toLowerSet(options.wireNames??[...WIRE_NAMES]),requestRoots:toLowerSet(options.requestRootNames??[...REQUEST_ROOTS]),countNames:toLowerSet(options.countNames??[...COUNT_NAMES])};wireParams=new Map;pendingAllocations=[];pendingCallSites=[]},NewExpression(node){pendingCallSites.push(node);const size=allocationSize(node);if(size!==null)pendingAllocations.push({node,size})},"Program:exit"(){for(const call of pendingCallSites)recordCallSite(call);for(const{node,size}of pendingAllocations)judgeAllocation(node,size)},CallExpression(node){pendingCallSites.push(node);const size=allocationSize(node);if(size!==null)pendingAllocations.push({node,size});const callee=node.callee;const allocator=unsafeAllocator(callee);if(allocator===null)return;if(isFilledInPlace(node))return;if(isCoveredBeforeRead(node))return;const rewritable=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property:null;context.report({node,messageId:allocator==="allocUnsafe"?"unsafeAlloc":"unsafeAllocSlow",...rewritable===null?{}:{suggest:[{messageId:"useSafeAlloc",fix:fixer=>fixer.replaceText(rewritable,"alloc")}]}})}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeBufferAlloc=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const provenance_1=require("../../utils/provenance");const UNSAFE_ALLOCATORS=new Set(["allocUnsafe","allocUnsafeSlow"]);const SIZED_ALLOCATORS=new Set(["Array","Buffer","Uint8Array","Uint16Array","Uint32Array","Int8Array","Int16Array","Int32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array","ArrayBuffer","SharedArrayBuffer"]);function looksNumeric(node,countNames){switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return["+","-","*","/","%","<<",">>",">>>"].includes(node.operator);case eslint_devkit_1.AST_NODE_TYPES.Identifier:return countNames.has(node.name.toLowerCase());case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:{const prop=(0,eslint_devkit_1.propertyName)(node);return prop!==null&&countNames.has(prop.toLowerCase())}case eslint_devkit_1.AST_NODE_TYPES.CallExpression:{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==="Math"){return true}const name=calleeName(node.callee);return name!==null&&/^(read|len|size|count|decode|parse)/i.test(name)}default:return false}}function toLowerSet(names){return new Set(names.map(n=>n.toLowerCase()))}const COUNT_NAMES=new Set(["length","len","size","count","n","num","total","capacity","bytelength"]);const BUFFER_ALLOCATORS=new Set(["alloc","allocUnsafe","allocUnsafeSlow"]);const WIRE_NAMES=new Set(["chunk","chunks","buffer","buf","payload","frame","packet","raw","message","msg"]);const REQUEST_ROOTS=new Set(["req","request","ctx","event"]);function isWriteMethod(name){return name==="fill"||name==="set"||name.startsWith("write")}const DESTINATION_ARGUMENT_CALLS=new Set(["copy","randomFill","randomFillSync","getRandomValues"]);const METADATA_PROPERTIES=new Set(["length","byteLength","byteOffset","buffer"]);const WRITE_WIDTHS=new Map([["writeUInt8",1],["writeInt8",1],["writeUInt16LE",2],["writeUInt16BE",2],["writeInt16LE",2],["writeInt16BE",2],["writeUInt32LE",4],["writeUInt32BE",4],["writeInt32LE",4],["writeInt32BE",4],["writeFloatLE",4],["writeFloatBE",4],["writeDoubleLE",8],["writeDoubleBE",8],["writeBigInt64LE",8],["writeBigInt64BE",8],["writeBigUInt64LE",8],["writeBigUInt64BE",8]]);const MAX_TRACKED_ALLOCATION=4096;const ASSIGNING_OPERATORS=new Set(["=","??=","||=","&&="]);const BUFFER_MODULES=new Set(["buffer","node:buffer"]);const CRYPTO_MODULES=new Set(["crypto","node:crypto"]);const RANDOM_FILL_CALLS=new Set(["randomFill","randomFillSync","getRandomValues"]);function isCryptoModuleRequire(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.arguments[0].value==="string"&&CRYPTO_MODULES.has(node.arguments[0].value)}function isBufferModuleRequire(node){return node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof node.arguments[0].value==="string"&&BUFFER_MODULES.has(node.arguments[0].value)}function isBufferObject(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name==="Buffer";return node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node)==="Buffer"&&isBufferModuleRequire(node.object)}function isInsideLoop(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.ForStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.ForInStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.WhileStatement||current.type===eslint_devkit_1.AST_NODE_TYPES.DoWhileStatement){return true}current=current.parent}return false}function calleeName(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return callee.name;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){const named=(0,eslint_devkit_1.propertyName)(callee);if(named!==null)return named;const{property}=callee;return property.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier?property.name:null}return null}function declaredName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration&&node.id)return node.id.name;const parent=node.parent;if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){return parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?parent.id.name:null}if(parent?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition&&parent.kind==="constructor"){const owner=parent.parent.parent;return owner.id?.name??declaredName(owner)}if((parent?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition||parent?.type===eslint_devkit_1.AST_NODE_TYPES.Property)&&!parent.computed){const key=parent.key;return key.name}return null}exports.noUnsafeBufferAlloc=(0,eslint_devkit_1.createRule)({name:"no-unsafe-buffer-alloc",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",hasSuggestions:true,docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unsafe-buffer-alloc.md",description:"Disallow `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()`, which return uninitialized memory",cwe:"CWE-908",cweJustification:"CWE-908 (Use of Uninitialized Resource) \u2014 allocUnsafe returns a view over non-zeroed heap memory; any byte not overwritten before the buffer is read or transmitted discloses prior process memory.",cvss:7.5,confidence:"high"},messages:{unsafeAlloc:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Uninitialized Buffer Allocation",cwe:"CWE-908",cvss:7.5,description:"`Buffer.allocUnsafe(size)` returns memory that has not been zeroed. Every byte not overwritten before the buffer is read or sent leaks whatever the allocator previously stored there.",severity:"HIGH",fix:"Use `Buffer.alloc(size)` (zero-filled), or keep `allocUnsafe` only where the very next statement overwrites the whole buffer \u2014 `Buffer.allocUnsafe(size).fill(0)` is accepted by this rule.",documentationLink:"https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize"}),unsafeAllocSlow:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Uninitialized Buffer Allocation (allocUnsafeSlow)",cwe:"CWE-908",cvss:7.5,description:"`Buffer.allocUnsafeSlow(size)` allocates outside the shared pool but is equally uninitialized \u2014 the returned bytes are whatever was last in that memory.",severity:"HIGH",fix:"Use `Buffer.alloc(size)`, or append `.fill(0)` to zero the allocation at the call site.",documentationLink:"https://nodejs.org/api/buffer.html#static-method-bufferallocunsafeslowsize"}),useSafeAlloc:"Replace with `Buffer.alloc()` (zero-filled).",unboundedAllocation:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Allocation Sized By Untrusted Input",cwe:"CWE-789",cvss:7.5,description:'The allocation size is read off the wire, so the peer picks it. For `new Array(n)` the hazard is a narrow band, not "large n": V8 keeps a packed backing store only up to ~33.5M elements, and a length just under that turns a 12-byte length prefix into a 229MB allocation (measured: `new Array(3e7)` = 228.9MB in 20.7ms). Past the threshold V8 switches the array to dictionary mode and the allocation costs nothing at all (`new Array(4e7)` and `new Array(1e9)` are both 0.0MB in ~0.005ms). A typed allocation \u2014 `Buffer.alloc(n)`, `new Uint8Array(n)` \u2014 has no such threshold and commits n bytes at any n.',severity:"HIGH",fix:'Clamp the length against the maximum the protocol actually permits, before allocating: `if (length > MAX_LENGTH) throw new Error("too long")`, or `new Array(Math.min(length, MAX_LENGTH))`. A guard that only rejects implausibly huge values is not a fix for `new Array` \u2014 those are the sizes V8 makes free. The damaging lengths are the plausible ones just below the packed-elements limit.',documentationLink:"https://cwe.mitre.org/data/definitions/789.html"})},schema:[{type:"object",properties:{wireNames:{type:"array",items:{type:"string"},default:[...WIRE_NAMES],description:"Binding names that carry bytes off the wire. Replaces the default; pass [] to turn the name arm off."},requestRootNames:{type:"array",items:{type:"string"},default:[...REQUEST_ROOTS],description:"Root identifiers treated as a request. Replaces the default."},countNames:{type:"array",items:{type:"string"},default:[...COUNT_NAMES],description:"Identifiers that hold an allocation size rather than a payload. Replaces the default."}},additionalProperties:false}]},defaultOptions:[{}],createOnce(context,currentOptions){let sourceCode;let vocab;let wireParams;let pendingAllocations;let pendingCallSites;function readsWire(node,seen=new Set){if(seen.has(node))return false;seen.add(node);const bare=(0,eslint_devkit_1.unwrapTypeSyntax)(node);if(bare!==node)return readsWire(bare,seen);switch(node.type){case eslint_devkit_1.AST_NODE_TYPES.Identifier:{if(node.name==="Buffer"){const bound=(0,provenance_1.findVariable)(sourceCode,node);if(bound===null||bound.defs.length===0)return false;if(bound.defs[0].type==="ImportBinding")return false}const lower=node.name.toLowerCase();if(vocab.wireNames.has(lower)||vocab.requestRoots.has(lower)){const def=(0,provenance_1.findVariable)(sourceCode,node)?.defs[0];if(def?.type!=="Variable")return true;if(def.parent.parent.type===eslint_devkit_1.AST_NODE_TYPES.ForOfStatement){return true}}const owner=enclosingFunction(node);if(owner!==null){const name=declaredName(owner);const indices=name===null?void 0:wireParams.get(name);if(indices?.has(paramIndexOf(node,owner)))return true}const variable=(0,provenance_1.findVariable)(sourceCode,node);const lastWrite=(variable?.references??[]).map(reference=>reference.writeExpr).filter(write=>write!=null).filter(write=>write.range[1]<=node.range[0]).sort((a,b)=>a.range[1]-b.range[1]).at(-1);return lastWrite!==void 0&&readsWire(lastWrite,seen)}case eslint_devkit_1.AST_NODE_TYPES.MemberExpression:if((0,eslint_devkit_1.readsRequestShape)(node,sourceCode))return true;return readsWire(node.object,seen);case eslint_devkit_1.AST_NODE_TYPES.NewExpression:return node.arguments.some(argument=>readsWire(argument,seen));case eslint_devkit_1.AST_NODE_TYPES.CallExpression:return readsWire(node.callee,seen)||node.arguments.some(argument=>readsWire(argument,seen));case eslint_devkit_1.AST_NODE_TYPES.BinaryExpression:return readsWire(node.left,seen)||readsWire(node.right,seen);default:return false}}function enclosingFunction(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){return current}current=current.parent}return null}function paramIndexOf(node,owner){const params=owner.params;return params.findIndex(param=>{const bound=param.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentPattern?param.left:param;return bound.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&bound.name===node.name})}function isClamped(size){if(size.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&size.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&size.callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&size.callee.object.name==="Math"&&(0,eslint_devkit_1.propertyName)(size.callee)==="min"){return size.arguments.some(argument=>argument.type!==eslint_devkit_1.AST_NODE_TYPES.SpreadElement&&!readsWire(argument))}if(size.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return false;const name=size.name;let current=size.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement){if(mentionsInComparison(current.test,name))return true}if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){const body=current.body;if(body.type===eslint_devkit_1.AST_NODE_TYPES.BlockStatement){for(const statement of body.body){if(statement.type===eslint_devkit_1.AST_NODE_TYPES.IfStatement&&mentionsInComparison(statement.test,name)){return true}}}return false}current=current.parent}return false}function mentionsInComparison(test,name){if(test.type===eslint_devkit_1.AST_NODE_TYPES.LogicalExpression){return mentionsInComparison(test.left,name)||mentionsInComparison(test.right,name)}if(test.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression)return false;if(!["<","<=",">",">="].includes(test.operator))return false;const named=side=>side.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&side.name===name;return named(test.left)||named(test.right)}function allocationSize(node){const size=node.arguments[0];if(size===void 0)return null;const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&SIZED_ALLOCATORS.has(callee.name)){return looksNumeric(size,vocab.countNames)?size:null}if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&callee.object.name==="Buffer"&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),BUFFER_ALLOCATORS)){return size}return null}function recordCallSite(node){const name=calleeName(node.callee);if(name===null)return;node.arguments.forEach((argument,index)=>{if(!readsWire(argument))return;const indices=wireParams.get(name)??new Set;indices.add(index);wireParams.set(name,indices)})}function judgeAllocation(node,size){if(isClamped(size))return;if(!readsWire(size))return;context.report({node,messageId:"unboundedAllocation"})}function classifyUse(identifier){const parent=identifier.parent;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===identifier){if(parent.computed){const grandparent2=parent.parent;const isWrite=grandparent2.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&grandparent2.left===parent;if(!isWrite)return"read";return parent.property.type!==eslint_devkit_1.AST_NODE_TYPES.Literal&&isInsideLoop(parent)?"covering":"partial"}const name=parent.property.name;if(METADATA_PROPERTIES.has(name))return"metadata";const grandparent=parent.parent;if(grandparent.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression||grandparent.callee!==parent||!isWriteMethod(name)){return"read"}return coversWholeBuffer(grandparent,name)?"covering":"partial"}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.arguments[0]===identifier){const method=destinationArgumentCallee(parent.callee);if(method===null)return"read";return coversWholeBuffer(parent,method)?"covering":"partial"}return"read"}function destinationArgumentCallee(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(callee),DESTINATION_ARGUMENT_CALLS)){return(0,eslint_devkit_1.propertyName)(callee)}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||!RANDOM_FILL_CALLS.has(callee.name)){return null}const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(variable===null||variable.defs.length===0)return null;const def=variable.defs[0];if(def.type==="ImportBinding"){const declaration=def.parent;return declaration.type===eslint_devkit_1.AST_NODE_TYPES.ImportDeclaration&&CRYPTO_MODULES.has(declaration.source.value)?callee.name:null}return def.type==="Variable"&&def.node.init!==null&&isCryptoModuleRequire(def.node.init)?callee.name:null}function offsetOf(argument){if(argument===void 0)return"start";const resolved=(0,const_value_1.resolveConstant)(sourceCode,argument);if(resolved===null)return null;return typeof resolved.value==="string"?"start":resolved.value}function coversWholeBuffer(call,method){const offset=offsetOf(call.arguments[1]);if(offset==="start")return!WRITE_WIDTHS.has(method);return offset===null&&isInsideLoop(call)}function fixedWriteSpan(call,method){const width=WRITE_WIDTHS.get(method);if(width===void 0)return null;const offset=offsetOf(call.arguments[1]);if(offset===null)return null;const start=offset==="start"?0:offset;return{start,end:start+width}}function isCoveredBeforeRead(call){const parent=call.parent;let variable=null;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){variable=context.sourceCode.getDeclaredVariables(parent)[0]}else if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&ASSIGNING_OPERATORS.has(parent.operator)&&parent.left.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){variable=(0,provenance_1.findVariable)(context.sourceCode,parent.left)}if(variable===null)return false;const uses=variable.references.filter(reference=>reference.identifier.range[0]>call.range[1]);const covered=byteMapFor(call);let remaining=covered===null?-1:covered.length;for(const use of uses){const kind=classifyUse(use.identifier);if(kind==="metadata")continue;if(kind==="partial"){if(covered!==null){remaining-=markFixedWrite(covered,use.identifier);if(remaining===0)return true}continue}return kind==="covering"}return false}function byteMapFor(call){const argument=call.arguments[0];if(argument===void 0)return null;const resolved=(0,const_value_1.resolveConstant)(sourceCode,argument);if(resolved===null||typeof resolved.value!=="number")return null;const size=resolved.value;if(!Number.isInteger(size)||size<=0||size>MAX_TRACKED_ALLOCATION){return null}return new Uint8Array(size)}function markFixedWrite(covered,identifier){const member=identifier.parent;if(member.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||member.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return 0}const call=member.parent;if(call.type!==eslint_devkit_1.AST_NODE_TYPES.CallExpression)return 0;const span=fixedWriteSpan(call,member.property.name);if(span===null||span.end>covered.length)return 0;let added=0;for(let index=span.start;index<span.end;index+=1){if(covered[index]===0){covered[index]=1;added+=1}}return added}function unsafeAllocator(callee){if(callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){if(!isBufferObject(callee.object))return null;const name=callee.computed?(0,const_value_1.resolveConstantString)(sourceCode,callee.property)?.value:callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property.name:void 0;return name!==void 0&&UNSAFE_ALLOCATORS.has(name)?name:null}if(callee.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier)return null;const variable=(0,provenance_1.findVariable)(sourceCode,callee);if(variable===null||variable.defs.length===0)return null;const def=variable.defs[0];if(def.type!=="Variable"||def.node.init===null)return null;if(!isBufferObject(def.node.init))return null;const property=def.name.parent;if(property.type!==eslint_devkit_1.AST_NODE_TYPES.Property||property.computed||property.key.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier){return null}return UNSAFE_ALLOCATORS.has(property.key.name)?property.key.name:null}function isFilledInPlace(node){const parent=node.parent;if(parent.type!==eslint_devkit_1.AST_NODE_TYPES.MemberExpression||parent.object!==node||parent.computed||parent.property.type!==eslint_devkit_1.AST_NODE_TYPES.Identifier||parent.property.name!=="fill"){return false}const grandparent=parent.parent;return grandparent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&grandparent.callee===parent}return{before(){const[options={}]=currentOptions();sourceCode=context.sourceCode;vocab={wireNames:toLowerSet(options.wireNames??[...WIRE_NAMES]),requestRoots:toLowerSet(options.requestRootNames??[...REQUEST_ROOTS]),countNames:toLowerSet(options.countNames??[...COUNT_NAMES])};wireParams=new Map;pendingAllocations=[];pendingCallSites=[]},NewExpression(node){pendingCallSites.push(node);const size=allocationSize(node);if(size!==null)pendingAllocations.push({node,size})},"Program:exit"(){for(const call of pendingCallSites)recordCallSite(call);for(const{node,size}of pendingAllocations)judgeAllocation(node,size)},CallExpression(node){pendingCallSites.push(node);const size=allocationSize(node);if(size!==null)pendingAllocations.push({node,size});const callee=node.callee;const allocator=unsafeAllocator(callee);if(allocator===null)return;if(isFilledInPlace(node))return;if(isCoveredBeforeRead(node))return;const rewritable=callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&!callee.computed&&callee.property.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?callee.property:null;context.report({node,messageId:allocator==="allocUnsafe"?"unsafeAlloc":"unsafeAllocSlow",...rewritable===null?{}:{suggest:[{messageId:"useSafeAlloc",fix:fixer=>fixer.replaceText(rewritable,"alloc")}]}})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDynamicRequire=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const const_value_1=require("../../utils/const-value");const DEFAULT_TAINT_SOURCES=["req","request","ctx","event","process"];exports.noUnsafeDynamicRequire=(0,eslint_devkit_2.createRule)({name:"no-unsafe-dynamic-require",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unsafe-dynamic-require.md",description:"Prevent unsafe dynamic require() calls that could enable code injection",cwe:"CWE-95",cvss:9.8},hasSuggestions:false,messages:{unsafeDynamicRequire:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic require()",cwe:"CWE-95",description:"Dynamic require() detected",severity:"CRITICAL",fix:'Use allowlist: const ALLOWED = ["mod1", "mod2"]; if (!ALLOWED.includes(name)) throw Error("Not allowed")',documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),unsafeDynamicImport:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic import()",cwe:"CWE-95",description:"import() resolves and EVALUATES the module it is given, exactly as require() does. This specifier is reachable from request or process input, so an attacker chooses which file executes.",severity:"CRITICAL",fix:'Use allowlist: const ALLOWED = { csv: "./formatters/csv" }; const specifier = ALLOWED[name]; if (!specifier) throw Error("Not allowed"); await import(specifier)',documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"})},schema:[{type:"object",properties:{allowDynamicImport:{type:"boolean",default:false},taintSources:{type:"array",items:{type:"string"},default:DEFAULT_TAINT_SOURCES,description:"Identifier roots treated as attacker-reachable (default: req, request, ctx, event, process)"},reportUnresolvedSpecifiers:{type:"boolean",default:false,description:'Report specifiers whose provenance cannot be resolved. Restores the pre-inversion "any non-literal is dangerous" behaviour.'}},additionalProperties:false}]},defaultOptions:[{allowDynamicImport:false}],createOnce(context){let readsTaintSource;let reportUnresolvedSpecifiers;let allowDynamicImport;let requireVariables;const isRequireReference=node=>{if(node.type==="Identifier"&&node.name==="require"){return true}if(node.type==="Identifier"&&requireVariables.has(node.name)){return true}return node.type==="MemberExpression"&&node.object.type==="Identifier"&&node.object.name==="module"&&(0,eslint_devkit_1.propertyName)(node)==="require"};const isDangerousSpecifier=arg=>{if(arg.type==="Literal")return false;if(arg.type==="TemplateLiteral"&&arg.expressions.length===0)return false;if((0,const_value_1.resolveConstantString)(context.sourceCode,arg)!==null)return false;if(arg.type==="Identifier"){const variable=(0,provenance_1.findVariable)(context.sourceCode,arg);if(variable?.defs.length===1&&variable.defs[0].type==="Parameter"){return reportUnresolvedSpecifiers}}if(readsTaintSource(arg))return true;return reportUnresolvedSpecifiers};return{before(){const options=context.options[0]??{};readsTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,new Set((options.taintSources??DEFAULT_TAINT_SOURCES).map(s=>s.toLowerCase())));reportUnresolvedSpecifiers=options.reportUnresolvedSpecifiers??false;allowDynamicImport=options.allowDynamicImport??false;requireVariables=new Set},VariableDeclarator(node){if(node.id.type==="Identifier"&&node.init){if(node.init.type==="Identifier"&&node.init.name==="require"){requireVariables.add(node.id.name)}if(node.init.type==="CallExpression"&&(node.init.callee.type==="Identifier"&&node.init.callee.name==="createRequire"||node.init.callee.type==="MemberExpression"&&(0,eslint_devkit_1.propertyName)(node.init.callee)==="createRequire")){requireVariables.add(node.id.name)}}},ImportExpression(node){if(allowDynamicImport)return;if(!isDangerousSpecifier(node.source))return;context.report({node,messageId:"unsafeDynamicImport"})},CallExpression(node){if(node.callee.type!=="Identifier"&&node.callee.type!=="MemberExpression"){return}if(!isRequireReference(node.callee)){return}if(node.arguments.length===0)return;const firstArg=node.arguments[0];if(firstArg.type==="SpreadElement")return;if(!isDangerousSpecifier(firstArg))return;context.report({node,messageId:"unsafeDynamicRequire"})}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noUnsafeDynamicRequire=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const eslint_devkit_2=require("@interlace/eslint-devkit");const provenance_1=require("../../utils/provenance");const const_value_1=require("../../utils/const-value");const DEFAULT_TAINT_SOURCES=["req","request","ctx","event","process"];exports.noUnsafeDynamicRequire=(0,eslint_devkit_2.createRule)({name:"no-unsafe-dynamic-require",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-unsafe-dynamic-require.md",description:"Prevent unsafe dynamic require() calls that could enable code injection",cwe:"CWE-95",cvss:9.8},hasSuggestions:false,messages:{unsafeDynamicRequire:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic require()",cwe:"CWE-95",description:"Dynamic require() detected",severity:"CRITICAL",fix:'Use allowlist: const ALLOWED = ["mod1", "mod2"]; if (!ALLOWED.includes(name)) throw Error("Not allowed")',documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"}),unsafeDynamicImport:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Dynamic import()",cwe:"CWE-95",description:"import() resolves and EVALUATES the module it is given, exactly as require() does. This specifier is reachable from request or process input, so an attacker chooses which file executes.",severity:"CRITICAL",fix:'Use allowlist: const ALLOWED = { csv: "./formatters/csv" }; const specifier = ALLOWED[name]; if (!specifier) throw Error("Not allowed"); await import(specifier)',documentationLink:"https://owasp.org/www-community/attacks/Code_Injection"})},schema:[{type:"object",properties:{allowDynamicImport:{type:"boolean",default:false},taintSources:{type:"array",items:{type:"string"},default:DEFAULT_TAINT_SOURCES,description:"Identifier roots treated as attacker-reachable (default: req, request, ctx, event, process)"},reportUnresolvedSpecifiers:{type:"boolean",default:false,description:'Report specifiers whose provenance cannot be resolved. Restores the pre-inversion "any non-literal is dangerous" behaviour.'}},additionalProperties:false}]},defaultOptions:[{allowDynamicImport:false}],createOnce(context){let readsTaintSource;let reportUnresolvedSpecifiers;let allowDynamicImport;let requireVariables;const isRequireReference=node=>{if(node.type==="Identifier"){if(node.name==="require")return true;const variable=(0,provenance_1.findVariable)(context.sourceCode,node);return variable!==null&&requireVariables.has(variable)}return node.type==="MemberExpression"&&node.object.type==="Identifier"&&node.object.name==="module"&&(0,eslint_devkit_1.propertyName)(node)==="require"};const isDangerousSpecifier=arg=>{if((0,const_value_1.resolveConstantString)(context.sourceCode,arg)!==null)return false;if((0,const_value_1.isClosedStringTableLookup)(context.sourceCode,arg))return false;if(arg.type==="Identifier"){const variable=(0,provenance_1.findVariable)(context.sourceCode,arg);if(variable?.defs.length===1&&variable.defs[0].type==="Parameter"){return reportUnresolvedSpecifiers}}if(readsTaintSource(arg))return true;return reportUnresolvedSpecifiers};return{before(){const options=context.options[0]??{};readsTaintSource=(0,provenance_1.makeReadsTaintSource)(context.sourceCode,new Set((options.taintSources??DEFAULT_TAINT_SOURCES).map(s=>s.toLowerCase())));reportUnresolvedSpecifiers=options.reportUnresolvedSpecifiers??false;allowDynamicImport=options.allowDynamicImport??false;requireVariables=new Set},VariableDeclarator(node){if(node.id.type!=="Identifier"||!node.init)return;const init=node.init;const callee=init.type==="CallExpression"?init.callee:null;const aliasesRequire=init.type==="Identifier"&&init.name==="require"||callee!==null&&((0,eslint_devkit_1.isModuleBinding)(callee,context.sourceCode.getScope(node),"module",["createRequire"])||callee.type==="Identifier"&&callee.name==="createRequire"&&!(0,provenance_1.findVariable)(context.sourceCode,callee)?.defs.length);if(!aliasesRequire)return;for(const variable of context.sourceCode.getDeclaredVariables(node)){requireVariables.add(variable)}},ImportExpression(node){if(allowDynamicImport)return;if(!isDangerousSpecifier(node.source))return;context.report({node,messageId:"unsafeDynamicImport"})},CallExpression(node){if(!isRequireReference(node.callee)){return}if(node.arguments.length===0)return;const firstArg=node.arguments[0];const specifier=firstArg.type==="SpreadElement"?firstArg.argument:firstArg;if(!isDangerousSpecifier(specifier))return;context.report({node,messageId:"unsafeDynamicRequire"})}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakCipherAlgorithm=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const WEAK_CIPHER_PATTERNS=[{pattern:/\bdes\b(?!-ede)/i,name:"DES",alternatives:["AES-256-GCM","ChaCha20-Poly1305"],replacement:"aes-256-gcm"},{pattern:/\bdes(?:-ede3?|3)\b|\b3des\b|\btripledes\b/i,name:"3DES",alternatives:["AES-256-GCM","ChaCha20-Poly1305"],replacement:"aes-256-gcm"},{pattern:/\brc4\b|\barc4\b/i,name:"RC4",alternatives:["AES-256-GCM","ChaCha20-Poly1305"],replacement:"aes-256-gcm"},{pattern:/\bblowfish\b|\bbf\b/i,name:"Blowfish",alternatives:["AES-256-GCM","ChaCha20-Poly1305"],replacement:"aes-256-gcm"},{pattern:/\brc2\b/i,name:"RC2",alternatives:["AES-256-GCM","ChaCha20-Poly1305"],replacement:"aes-256-gcm"},{pattern:/\bidea\b/i,name:"IDEA",alternatives:["AES-256-GCM","ChaCha20-Poly1305"],replacement:"aes-256-gcm"}];function findWeakCipher(value,additionalPatterns){for(const pattern of WEAK_CIPHER_PATTERNS){if(pattern.pattern.test(value)){return pattern}}for(const additionalPattern of additionalPatterns){const regex=new RegExp(`\\b${additionalPattern}\\b`,"i");if(regex.test(value)){return{pattern:regex,name:additionalPattern.toUpperCase(),alternatives:["AES-256-GCM","ChaCha20-Poly1305"],replacement:"aes-256-gcm"}}}return null}exports.noWeakCipherAlgorithm=(0,eslint_devkit_1.createRule)({name:"no-weak-cipher-algorithm",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-weak-cipher-algorithm.md",description:"Disallow weak cipher algorithms (DES, 3DES, RC4, Blowfish)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{weakCipherAlgorithm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak cipher algorithm",cwe:"CWE-327",description:"Use of weak cipher algorithm: {{algorithm}}. {{algorithm}} has known vulnerabilities and should not be used.",severity:"CRITICAL",fix:'Replace with {{replacement}}: crypto.createCipheriv("{{replacement}}", key, iv)',documentationLink:"https://owasp.org/www-community/vulnerabilities/Weak_Cryptography"}),useAes256Gcm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use AES-256-GCM",description:"Replace with AES-256-GCM for authenticated encryption",severity:"LOW",fix:'crypto.createCipheriv("aes-256-gcm", key, iv)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"}),useChaCha20:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use ChaCha20-Poly1305",description:"Replace with ChaCha20-Poly1305 for modern encryption",severity:"LOW",fix:'crypto.createCipheriv("chacha20-poly1305", key, iv)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"})},schema:[{type:"object",properties:{additionalWeakCiphers:{type:"array",items:{type:"string"},default:[],description:"Additional weak ciphers to detect"},allowInTests:{type:"boolean",default:false,description:"Allow weak ciphers in test files"}},additionalProperties:false}]},defaultOptions:[{additionalWeakCiphers:[],allowInTests:false}],createOnce(context,currentOptions){let additionalWeakCiphers;let allowInTests;let isTestFile;function checkCallExpression(node){if(isTestFile)return;const cipherMethods=new Set(["createCipher","createCipheriv","createDecipher","createDecipheriv"]);if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.namesOneOf)((0,eslint_devkit_1.propertyName)(node.callee),cipherMethods)){checkCipherArgument(node)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&cipherMethods.has(node.callee.name)){checkCipherArgument(node)}}function checkCipherArgument(node){const firstArg=node.arguments[0];if(firstArg===void 0)return;const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,firstArg);if(resolved===null)return;const weakPattern=findWeakCipher(resolved.value,additionalWeakCiphers);if(!weakPattern)return;const target=resolved.source;context.report({node:firstArg,messageId:"weakCipherAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:[{messageId:"useAes256Gcm",fix:fixer=>fixer.replaceText(target,`"aes-256-gcm"`)},{messageId:"useChaCha20",fix:fixer=>fixer.replaceText(target,`"chacha20-poly1305"`)}]})}return{before(){const[options={}]=currentOptions();({additionalWeakCiphers=[],allowInTests=false}=options);const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakCipherAlgorithm=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const module_binding_1=require("../../utils/module-binding");const WEAK_CIPHER_PATTERNS=[{pattern:/\bdes\b(?!-ede)/i,name:"DES",replacement:"aes-256-gcm"},{pattern:/\bdes(?:-ede3?|3)\b|\b3des\b|\btripledes\b/i,name:"3DES",replacement:"aes-256-gcm"},{pattern:/\brc4\b|\barc4\b/i,name:"RC4",replacement:"aes-256-gcm"},{pattern:/\bblowfish\b|\bbf\b/i,name:"Blowfish",replacement:"aes-256-gcm"},{pattern:/\brc2\b/i,name:"RC2",replacement:"aes-256-gcm"},{pattern:/\bidea\b/i,name:"IDEA",replacement:"aes-256-gcm"}];function findWeakCipher(value,additionalPatterns){for(const pattern of WEAK_CIPHER_PATTERNS){if(pattern.pattern.test(value)){return pattern}}for(const additionalPattern of additionalPatterns){const regex=new RegExp(`\\b${additionalPattern}\\b`,"i");if(regex.test(value)){return{pattern:regex,name:additionalPattern.toUpperCase(),replacement:"aes-256-gcm"}}}return null}exports.noWeakCipherAlgorithm=(0,eslint_devkit_1.createRule)({name:"no-weak-cipher-algorithm",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-weak-cipher-algorithm.md",description:"Disallow weak cipher algorithms (DES, 3DES, RC4, Blowfish)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{weakCipherAlgorithm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak cipher algorithm",cwe:"CWE-327",description:"Use of weak cipher algorithm: {{algorithm}}. {{algorithm}} has known vulnerabilities and should not be used.",severity:"CRITICAL",fix:'Replace with {{replacement}}: crypto.createCipheriv("{{replacement}}", key, iv)',documentationLink:"https://owasp.org/www-community/vulnerabilities/Weak_Cryptography"}),useAes256Gcm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use AES-256-GCM",description:"Replace with AES-256-GCM for authenticated encryption",severity:"LOW",fix:'crypto.createCipheriv("aes-256-gcm", key, iv)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"}),useChaCha20:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use ChaCha20-Poly1305",description:"Replace with ChaCha20-Poly1305 for modern encryption",severity:"LOW",fix:'crypto.createCipheriv("chacha20-poly1305", key, iv)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatecipherivalgorithm-key-iv-options"})},schema:[{type:"object",properties:{additionalWeakCiphers:{type:"array",items:{type:"string"},default:[],description:"Additional weak ciphers to detect"},allowInTests:{type:"boolean",default:false,description:"Allow weak ciphers in test files"}},additionalProperties:false}]},defaultOptions:[{additionalWeakCiphers:[],allowInTests:false}],createOnce(context,currentOptions){let additionalWeakCiphers;let allowInTests;let isTestFile;function checkCallExpression(node){if(isTestFile)return;const cipherMethods=new Set(["createCipher","createCipheriv","createDecipher","createDecipheriv"]);const calleeName=(0,module_binding_1.calleeNameOn)(node.callee,context.sourceCode.getScope(node),"crypto");if(calleeName!==null&&cipherMethods.has(calleeName)){checkCipherArgument(node)}}function checkCipherArgument(node){const firstArg=node.arguments[0];if(firstArg===void 0)return;const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,firstArg);if(resolved===null)return;const weakPattern=findWeakCipher(resolved.value,additionalWeakCiphers);if(!weakPattern)return;const target=resolved.source;context.report({node:firstArg,messageId:"weakCipherAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:[{messageId:"useAes256Gcm",fix:fixer=>fixer.replaceText(target,`"aes-256-gcm"`)},{messageId:"useChaCha20",fix:fixer=>fixer.replaceText(target,`"chacha20-poly1305"`)}]})}return{before(){const[options={}]=currentOptions();({additionalWeakCiphers=[],allowInTests=false}=options);const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakDhParameters=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const MODP_GROUP_BITS=new Map([["modp1",768],["modp2",1024],["modp5",1536],["modp14",2048],["modp15",3072],["modp16",4096],["modp17",6144],["modp18",8192]]);const WEAK_CURVES=new Set(["secp112r1","secp112r2","secp128r1","secp128r2","secp160k1","secp160r1","secp160r2","secp192k1","prime192v1","prime192v2","prime192v3","sect113r1","sect113r2","sect131r1","sect131r2","sect163k1","sect163r1","sect163r2","sect193r1","sect193r2","brainpoolP160r1","brainpoolP192r1"]);const GROUP_APIS=new Set(["getDiffieHellman","createDiffieHellmanGroup"]);const PRIME_LENGTH_APIS=new Set(["createDiffieHellman"]);const CURVE_APIS=new Set(["createECDH"]);function calleeName(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(node.callee)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.callee.name}return null}exports.noWeakDhParameters=(0,eslint_devkit_1.createRule)({name:"no-weak-dh-parameters",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-weak-dh-parameters.md",description:"Disallow Diffie-Hellman and ECDH parameters below a safe strength",cwe:"CWE-326",cvss:5.9},hasSuggestions:false,messages:{weakModpGroup:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak Diffie-Hellman group",cwe:"CWE-326",description:"MODP group {{group}} is {{bits}}-bit, below the {{minimum}}-bit floor. A named group is a fixed prime, so one precomputation breaks every session that used it \u2014 this is the Logjam attack.",severity:"MEDIUM",fix:"Use crypto.getDiffieHellman('modp14') or larger, or prefer ECDH on a modern curve",documentationLink:"https://weakdh.org"}),weakPrimeLength:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak Diffie-Hellman prime length",cwe:"CWE-326",description:"A {{bits}}-bit Diffie-Hellman prime is below the {{minimum}}-bit floor.",severity:"MEDIUM",fix:"crypto.createDiffieHellman({{minimum}})",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatediffiehellmanprimelength-generator"}),weakCurve:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak elliptic curve",cwe:"CWE-326",description:"Curve {{curve}} has a field size under 224 bits and does not offer contemporary security margins.",severity:"MEDIUM",fix:"crypto.createECDH('prime256v1'), or 'secp384r1' for a larger margin",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreateecdhcurvename"})},schema:[{type:"object",properties:{minPrimeBits:{type:"integer",minimum:0,default:2048,description:"Smallest acceptable Diffie-Hellman prime, in bits"},additionalWeakCurves:{type:"array",items:{type:"string"},default:[],description:"Curves to treat as weak beyond the built-in list"},allowInTests:{type:"boolean",default:false,description:"Allow weak parameters in test files"}},additionalProperties:false}]},defaultOptions:[{minPrimeBits:2048,additionalWeakCurves:[],allowInTests:false}],createOnce(context){let minPrimeBits;let additionalWeakCurves;let allowInTests;let weakCurves;return{before(){({minPrimeBits=2048,additionalWeakCurves=[],allowInTests=false}=context.options[0]??{});if(allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename))return false;weakCurves=new Set([...WEAK_CURVES,...additionalWeakCurves]);return true},CallExpression(node){const name=calleeName(node);if(name===null)return;const firstArg=node.arguments[0];if(firstArg===void 0)return;if((0,eslint_devkit_1.namesOneOf)(name,GROUP_APIS)){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,firstArg);if(resolved===null)return;const bits=MODP_GROUP_BITS.get(resolved.value);if(bits===void 0||bits>=minPrimeBits)return;context.report({node:firstArg,messageId:"weakModpGroup",data:{group:resolved.value,bits:String(bits),minimum:String(minPrimeBits)}});return}if((0,eslint_devkit_1.namesOneOf)(name,PRIME_LENGTH_APIS)){const resolved=(0,const_value_1.resolveConstant)(context.sourceCode,firstArg);if(resolved===null||typeof resolved.value!=="number")return;if(resolved.value>=minPrimeBits)return;context.report({node:firstArg,messageId:"weakPrimeLength",data:{bits:String(resolved.value),minimum:String(minPrimeBits)}});return}if((0,eslint_devkit_1.namesOneOf)(name,CURVE_APIS)){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,firstArg);if(resolved===null)return;if(!weakCurves.has(resolved.value))return;context.report({node:firstArg,messageId:"weakCurve",data:{curve:resolved.value}})}}}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakDhParameters=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const const_value_1=require("../../utils/const-value");const MODP_GROUP_BITS=new Map([["modp1",768],["modp2",1024],["modp5",1536],["modp14",2048],["modp15",3072],["modp16",4096],["modp17",6144],["modp18",8192]]);const WEAK_CURVES=new Set(["secp112r1","secp112r2","secp128r1","secp128r2","secp160k1","secp160r1","secp160r2","secp192k1","prime192v1","prime192v2","prime192v3","sect113r1","sect113r2","sect131r1","sect131r2","sect163k1","sect163r1","sect163r2","sect193r1","sect193r2","brainpoolP160r1","brainpoolP192r1"]);const GROUP_APIS=new Set(["getDiffieHellman","createDiffieHellmanGroup"]);const PRIME_LENGTH_APIS=new Set(["createDiffieHellman"]);const CURVE_APIS=new Set(["createECDH"]);function calleeName(node){if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(node.callee)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return node.callee.name}return null}exports.noWeakDhParameters=(0,eslint_devkit_1.createRule)({name:"no-weak-dh-parameters",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-weak-dh-parameters.md",description:"Disallow Diffie-Hellman and ECDH parameters below a safe strength",cwe:"CWE-326",cvss:5.9},hasSuggestions:false,messages:{weakModpGroup:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak Diffie-Hellman group",cwe:"CWE-326",description:"MODP group {{group}} is {{bits}}-bit, below the {{minimum}}-bit floor. A named group is a fixed prime, so one precomputation breaks every session that used it \u2014 this is the Logjam attack.",severity:"MEDIUM",fix:"Use crypto.getDiffieHellman('modp14') or larger, or prefer ECDH on a modern curve",documentationLink:"https://weakdh.org"}),weakPrimeLength:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak Diffie-Hellman prime length",cwe:"CWE-326",description:"A {{bits}}-bit Diffie-Hellman prime is below the {{minimum}}-bit floor.",severity:"MEDIUM",fix:"crypto.createDiffieHellman({{minimum}})",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatediffiehellmanprimelength-generator"}),weakCurve:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak elliptic curve",cwe:"CWE-326",description:"Curve {{curve}} has a field size under 224 bits and does not offer contemporary security margins.",severity:"MEDIUM",fix:"crypto.createECDH('prime256v1'), or 'secp384r1' for a larger margin",documentationLink:"https://nodejs.org/api/crypto.html#cryptocreateecdhcurvename"})},schema:[{type:"object",properties:{minPrimeBits:{type:"integer",minimum:0,default:2048,description:"Smallest acceptable Diffie-Hellman prime, in bits"},additionalWeakCurves:{type:"array",items:{type:"string"},default:[],description:"Curves to treat as weak beyond the built-in list"},allowInTests:{type:"boolean",default:false,description:"Allow weak parameters in test files"}},additionalProperties:false}]},defaultOptions:[{minPrimeBits:2048,additionalWeakCurves:[],allowInTests:false}],createOnce(context){let minPrimeBits;let additionalWeakCurves;let allowInTests;let weakCurves;return{before(){({minPrimeBits=2048,additionalWeakCurves=[],allowInTests=false}=context.options[0]??{});if(allowInTests&&(0,eslint_devkit_1.isTestFilePath)(context.filename))return false;weakCurves=new Set([...WEAK_CURVES,...additionalWeakCurves]);return true},CallExpression(node){const name=calleeName(node);const firstArg=node.arguments[0];if(firstArg===void 0)return;if((0,eslint_devkit_1.namesOneOf)(name,GROUP_APIS)){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,firstArg);if(resolved===null)return;const bits=MODP_GROUP_BITS.get(resolved.value);if(bits===void 0||bits>=minPrimeBits)return;context.report({node:firstArg,messageId:"weakModpGroup",data:{group:resolved.value,bits:String(bits),minimum:String(minPrimeBits)}});return}if((0,eslint_devkit_1.namesOneOf)(name,PRIME_LENGTH_APIS)){const resolved=(0,const_value_1.resolveConstant)(context.sourceCode,firstArg);if(resolved===null||typeof resolved.value!=="number")return;if(resolved.value>=minPrimeBits)return;context.report({node:firstArg,messageId:"weakPrimeLength",data:{bits:String(resolved.value),minimum:String(minPrimeBits)}});return}if((0,eslint_devkit_1.namesOneOf)(name,CURVE_APIS)){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,firstArg);if(resolved===null)return;if(!weakCurves.has(resolved.value))return;context.report({node:firstArg,messageId:"weakCurve",data:{curve:resolved.value}})}}}}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakHashAlgorithm=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const names_1=require("../../utils/names");const const_value_1=require("../../utils/const-value");const WEAK_HASH_PATTERNS=[{pattern:/\bmd5(?:withrsaencryption)?\b/i,name:"MD5",alternatives:["SHA-256","SHA-512","SHA-3"],replacement:"sha256"},{pattern:/\bmd4\b/i,name:"MD4",alternatives:["SHA-256","SHA-512","SHA-3"],replacement:"sha256"},{pattern:/\bsha1(?:withrsaencryption)?\b/i,name:"SHA-1",alternatives:["SHA-256","SHA-512","SHA-3"],replacement:"sha256"},{pattern:/\b(?:ripemd(?:160(?:withrsa)?)?|rmd160)\b/i,name:"RIPEMD",alternatives:["SHA-256","SHA-512"],replacement:"sha256"}];const DEFAULT_NON_CRYPTOGRAPHIC_NAMES=["sha","etag","cachekey","cachebuster","thumbprint","x5t"];const DEFAULT_SECURITY_USE_NAMES=["password","passwd","secret","secrets","token","tokens","signature","signing","signed","sign","hmac","credential","credentials","certificate","cert","certs","apikey","privatekey","secretkey","signingkey","encryptionkey","session","csrf","salt","jwt","nonce","integrity","auth","authorization","authenticate","otp","mfa","totp","passphrase","pincode","mnemonic","seedphrase","masterkey","securityanswer","recoverycode","backupcode"];function normalizeName(name){return name.replaceAll(/[_-]/g,"").toLowerCase()}function chainTop(node){let current=node;let parent=current.parent;while(parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee===current){current=parent;parent=current.parent;continue}break}return current}const EQUALITY_OPERATORS=new Set(["===","==","!==","!="]);function comparedName(node){const current=chainTop(node);const parent=current.parent;if(parent?.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||!EQUALITY_OPERATORS.has(parent.operator)){return null}return expressionName(parent.left===current?parent.right:parent.left)}function assignedName(node){const current=chainTop(node);const parent=current.parent;if(!parent)return null;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===current){return parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?parent.id.name:null}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.right===current){const target=parent.left;if(target.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return target.name;if(target.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(target)}return null}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.Property&&parent.value===current){if(parent.computed)return null;if(parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return parent.key.name;if(parent.key.type===eslint_devkit_1.AST_NODE_TYPES.Literal&&typeof parent.key.value==="string"){return parent.key.value}return null}return null}function expressionName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name;if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(node)}return null}function hashInputNames(node){const names=[];for(const argument of node.arguments){const name=expressionName(argument);if(name!==null)names.push(name)}let current=node;let parent=current.parent;while(parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee===current){for(const argument of parent.arguments){const name=expressionName(argument);if(name!==null)names.push(name)}current=parent;parent=current.parent;continue}break}return names}function enclosingFunctionName(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){if(current.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&current.id){return current.id.name}const owner=current.parent;if(owner?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){return owner.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?owner.id.name:null}if((owner?.type===eslint_devkit_1.AST_NODE_TYPES.Property||owner?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition)&&!owner.computed){return expressionName(owner.key)}return null}current=current.parent}return null}function findWeakHash(value,additionalPatterns){for(const pattern of WEAK_HASH_PATTERNS){if(pattern.pattern.test(value)){return pattern}}for(const additionalPattern of additionalPatterns){const regex=new RegExp(`\\b${additionalPattern}\\b`,"i");if(regex.test(value)){return{pattern:regex,name:additionalPattern.toUpperCase(),alternatives:["SHA-256","SHA-512"],replacement:"sha256"}}}return null}exports.noWeakHashAlgorithm=(0,eslint_devkit_1.createRule)({name:"no-weak-hash-algorithm",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-weak-hash-algorithm.md",description:"Disallow weak hash algorithms (MD5, SHA1, MD4)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{weakHashAlgorithm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak hash algorithm",cwe:"CWE-327",description:"Use of weak hash algorithm: {{algorithm}}. {{algorithm}} is cryptographically broken and unsuitable for security purposes.",severity:"CRITICAL",fix:'Replace with {{replacement}}: crypto.createHash("{{replacement}}").update(data). If this hash is an identifier rather than a security control \u2014 an EVALSHA key, an ETag, a cache key \u2014 store it under one of the nonCryptographicNames instead.',documentationLink:"https://owasp.org/www-community/vulnerabilities/Weak_Cryptography"}),useSha256:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-256",description:"Replace with SHA-256 for secure hashing",severity:"LOW",fix:'crypto.createHash("sha256").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"}),useSha512:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-512",description:"Replace with SHA-512 for stronger hashing",severity:"LOW",fix:'crypto.createHash("sha512").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"}),useSha3:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-3",description:"Replace with SHA-3 for latest standard",severity:"LOW",fix:'crypto.createHash("sha3-256").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"})},schema:[{type:"object",properties:{additionalWeakAlgorithms:{type:"array",items:{type:"string"},default:[],description:"Additional weak algorithms to detect"},allowInTests:{type:"boolean",default:false,description:"Allow weak hashes in test files"},nonCryptographicNames:{type:"array",items:{type:"string"},default:DEFAULT_NON_CRYPTOGRAPHIC_NAMES,description:"Assignment target names that mark a hash as an identifier rather than a security control"},securityUseNames:{type:"array",items:{type:"string"},default:DEFAULT_SECURITY_USE_NAMES,description:"Names that mark a hash as a security control (whole-word matched)"},reportUnclassifiedHashes:{type:"boolean",default:false,description:"Report weak hashes whose purpose cannot be determined. Restores the pre-inversion behaviour."}},additionalProperties:false}]},defaultOptions:[{additionalWeakAlgorithms:[],allowInTests:false,nonCryptographicNames:DEFAULT_NON_CRYPTOGRAPHIC_NAMES}],createOnce(context,currentOptions){let additionalWeakAlgorithms;let allowInTests;let nonCryptographicNames;let securityUseNames;let reportUnclassifiedHashes;let isSecurityUse;let isComparedSecurityValue;let isNonCryptographicName;let isTestFile;function isNonCryptographicUse(node){const stored=assignedName(node);if(stored!==null&&isNonCryptographicName(stored))return true;const enclosing=enclosingFunctionName(node);return enclosing!==null&&isNonCryptographicName(enclosing)}function hasSecurityUse(node){const stored=assignedName(node);if(stored!==null&&isSecurityUse(stored))return true;const compared=comparedName(node);if(compared!==null&&isComparedSecurityValue(compared))return true;for(const argument of hashInputNames(node)){if(isSecurityUse(argument))return true}if(stored!==null)return false;const enclosing=enclosingFunctionName(node);return enclosing!==null&&isSecurityUse(enclosing)}function isLocalHmacHelper(callee){const scope=context.sourceCode.getScope(callee);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===callee.name);if(!variable)continue;return variable.defs.some(def=>def.type!=="ImportBinding"&&computesHmac(def.node))}return false}function computesHmac(root){const stack=[root];while(stack.length>0){const node=stack.pop();if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isCreateHmacCall(node)){return true}for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){stack.push(child)}}}}return false}function isCreateHmacCall(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return callee.name==="createHmac"}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(callee)==="createHmac"}function canCallSha256(callee){const scope=context.sourceCode.getScope(callee);const declared=name=>{for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable)return variable.defs.length>0}return false};return declared("sha256")||!declared(callee.name)}function checkCallExpression(node){if(isTestFile)return;if(isNonCryptographicUse(node))return;if(!reportUnclassifiedHashes&&!hasSecurityUse(node))return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="createHash"){checkHashArgument(node)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="createHash"){checkHashArgument(node)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const funcName=node.callee.name.toLowerCase();if((funcName==="sha1"||funcName==="md5"||funcName==="md4")&&!isLocalHmacHelper(node.callee)){const weakPattern=findWeakHash(funcName,additionalWeakAlgorithms);context.report({node,messageId:"weakHashAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:canCallSha256(node.callee)?[{messageId:"useSha256",fix:fixer=>fixer.replaceText(node.callee,"sha256")}]:[]})}}}function checkHashArgument(node){for(const arg of node.arguments){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,arg);if(resolved===null)continue;const weakPattern=findWeakHash(resolved.value,additionalWeakAlgorithms);if(!weakPattern)continue;const target=resolved.source;context.report({node:arg,messageId:"weakHashAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:[{messageId:"useSha256",fix:fixer=>fixer.replaceText(target,`"sha256"`)},{messageId:"useSha512",fix:fixer=>fixer.replaceText(target,`"sha512"`)},{messageId:"useSha3",fix:fixer=>fixer.replaceText(target,`"sha3-256"`)}]})}}return{before(){const[options={}]=currentOptions();({additionalWeakAlgorithms=[],allowInTests=false,nonCryptographicNames=DEFAULT_NON_CRYPTOGRAPHIC_NAMES,securityUseNames=DEFAULT_SECURITY_USE_NAMES,reportUnclassifiedHashes=false}=options);isSecurityUse=(0,names_1.makeNameTest)(securityUseNames);isComparedSecurityValue=(0,names_1.makeNameTest)([...securityUseNames,"mac","digest"]);isNonCryptographicName=(0,names_1.makeNameTest)(nonCryptographicNames.map(normalizeName));const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.noWeakHashAlgorithm=void 0;const eslint_devkit_1=require("@interlace/eslint-devkit");const names_1=require("../../utils/names");const const_value_1=require("../../utils/const-value");const WEAK_HASH_PATTERNS=[{pattern:/\bmd5(?:withrsaencryption)?\b/i,name:"MD5",replacement:"sha256"},{pattern:/\bmd4\b/i,name:"MD4",replacement:"sha256"},{pattern:/\bsha-?1(?:withrsaencryption)?\b/i,name:"SHA-1",replacement:"sha256"},{pattern:/\b(?:ripemd(?:160(?:withrsa)?)?|rmd160)\b/i,name:"RIPEMD",replacement:"sha256"}];const DEFAULT_NON_CRYPTOGRAPHIC_NAMES=["sha","etag","cachekey","cachebuster","thumbprint","x5t"];const DEFAULT_SECURITY_USE_NAMES=["password","passwd","secret","secrets","token","tokens","signature","signing","signed","sign","hmac","credential","credentials","certificate","cert","certs","apikey","privatekey","secretkey","signingkey","encryptionkey","session","csrf","salt","jwt","nonce","integrity","auth","authorization","authenticate","otp","mfa","totp","passphrase","pincode","mnemonic","seedphrase","masterkey","securityanswer","recoverycode","backupcode"];function normalizeName(name){return name.replaceAll(/[_-]/g,"")}function chainTop(node){let current=node;let parent=current.parent;while(parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee===current){current=parent;parent=current.parent;continue}break}return current}const EQUALITY_OPERATORS=new Set(["===","==","!==","!="]);function comparedName(node){const current=chainTop(node);const parent=current.parent;if(parent?.type!==eslint_devkit_1.AST_NODE_TYPES.BinaryExpression||!EQUALITY_OPERATORS.has(parent.operator)){return null}return expressionName(parent.left===current?parent.right:parent.left)}function assignedName(node){const current=chainTop(node);const parent=current.parent;if(!parent)return null;if(parent.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator&&parent.init===current){return parent.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?parent.id.name:null}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.AssignmentExpression&&parent.right===current){const target=parent.left;if(target.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return target.name;if(target.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(target)}return null}if((parent.type===eslint_devkit_1.AST_NODE_TYPES.Property||parent.type===eslint_devkit_1.AST_NODE_TYPES.PropertyDefinition)&&parent.value===current){const named=(0,eslint_devkit_1.objectKeyName)(parent);if(named!==null)return named;const{key}=parent;return key.type===eslint_devkit_1.AST_NODE_TYPES.PrivateIdentifier?key.name:null}return null}function expressionName(node){if(node.type===eslint_devkit_1.AST_NODE_TYPES.Identifier)return node.name;if(node.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression){return(0,eslint_devkit_1.propertyName)(node)}return null}function hashInputNames(node){const names=[];for(const argument of node.arguments){const name=expressionName(argument);if(name!==null)names.push(name)}let current=node;let parent=current.parent;while(parent){if(parent.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&parent.object===current){current=parent;parent=current.parent;continue}if(parent.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&parent.callee===current){for(const argument of parent.arguments){const name=expressionName(argument);if(name!==null)names.push(name)}current=parent;parent=current.parent;continue}break}return names}function enclosingFunctionName(node){let current=node.parent;while(current){if(current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionDeclaration||current.type===eslint_devkit_1.AST_NODE_TYPES.FunctionExpression||current.type===eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression){if(current.type!==eslint_devkit_1.AST_NODE_TYPES.ArrowFunctionExpression&&current.id){return current.id.name}const owner=current.parent;if(owner?.type===eslint_devkit_1.AST_NODE_TYPES.VariableDeclarator){return owner.id.type===eslint_devkit_1.AST_NODE_TYPES.Identifier?owner.id.name:null}if((owner?.type===eslint_devkit_1.AST_NODE_TYPES.Property||owner?.type===eslint_devkit_1.AST_NODE_TYPES.MethodDefinition)&&!owner.computed){return expressionName(owner.key)}return null}current=current.parent}return null}function findWeakHash(value,additionalPatterns){for(const pattern of WEAK_HASH_PATTERNS){if(pattern.pattern.test(value)){return pattern}}for(const additionalPattern of additionalPatterns){const regex=new RegExp(`\\b${additionalPattern}\\b`,"i");if(regex.test(value)){return{pattern:regex,name:additionalPattern.toUpperCase(),replacement:"sha256"}}}return null}exports.noWeakHashAlgorithm=(0,eslint_devkit_1.createRule)({name:"no-weak-hash-algorithm",meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:"https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin-node-security/docs/rules/no-weak-hash-algorithm.md",description:"Disallow weak hash algorithms (MD5, SHA1, MD4)",cwe:"CWE-327",cvss:7.5},hasSuggestions:true,messages:{weakHashAlgorithm:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.SECURITY,issueName:"Weak hash algorithm",cwe:"CWE-327",description:"Use of weak hash algorithm: {{algorithm}}. {{algorithm}} is cryptographically broken and unsuitable for security purposes.",severity:"CRITICAL",fix:'Replace with {{replacement}}: crypto.createHash("{{replacement}}").update(data). If this hash is an identifier rather than a security control \u2014 an EVALSHA key, an ETag, a cache key \u2014 store it under one of the nonCryptographicNames instead.',documentationLink:"https://owasp.org/www-community/vulnerabilities/Weak_Cryptography"}),useSha256:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-256",description:"Replace with SHA-256 for secure hashing",severity:"LOW",fix:'crypto.createHash("sha256").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"}),useSha512:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-512",description:"Replace with SHA-512 for stronger hashing",severity:"LOW",fix:'crypto.createHash("sha512").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"}),useSha3:(0,eslint_devkit_1.formatLLMMessage)({icon:eslint_devkit_1.MessageIcons.INFO,issueName:"Use SHA-3",description:"Replace with SHA-3 for latest standard",severity:"LOW",fix:'crypto.createHash("sha3-256").update(data)',documentationLink:"https://nodejs.org/api/crypto.html#cryptocreatehashmethod-options"})},schema:[{type:"object",properties:{additionalWeakAlgorithms:{type:"array",items:{type:"string"},default:[],description:"Additional weak algorithms to detect"},allowInTests:{type:"boolean",default:false,description:"Allow weak hashes in test files"},nonCryptographicNames:{type:"array",items:{type:"string"},default:DEFAULT_NON_CRYPTOGRAPHIC_NAMES,description:"Assignment target names that mark a hash as an identifier rather than a security control"},securityUseNames:{type:"array",items:{type:"string"},default:DEFAULT_SECURITY_USE_NAMES,description:"Names that mark a hash as a security control (whole-word matched)"},reportUnclassifiedHashes:{type:"boolean",default:false,description:"Report weak hashes whose purpose cannot be determined. Restores the pre-inversion behaviour."}},additionalProperties:false}]},defaultOptions:[{additionalWeakAlgorithms:[],allowInTests:false,nonCryptographicNames:DEFAULT_NON_CRYPTOGRAPHIC_NAMES}],createOnce(context,currentOptions){let additionalWeakAlgorithms;let allowInTests;let nonCryptographicNames;let securityUseNames;let reportUnclassifiedHashes;let isSecurityUse;let isComparedSecurityValue;let isNonCryptographicName;let isTestFile;function isNonCryptographicUse(node){const stored=assignedName(node);if(stored!==null&&isNonCryptographicName(stored))return true;const enclosing=enclosingFunctionName(node);return enclosing!==null&&isNonCryptographicName(enclosing)}function hasSecurityUse(node){const stored=assignedName(node);if(stored!==null&&isSecurityUse(stored))return true;const compared=comparedName(node);if(compared!==null&&isComparedSecurityValue(compared))return true;for(const argument of hashInputNames(node)){if(isSecurityUse(argument))return true}if(stored!==null)return false;const enclosing=enclosingFunctionName(node);return enclosing!==null&&isSecurityUse(enclosing)}function isLocalHmacHelper(callee){const scope=context.sourceCode.getScope(callee);for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===callee.name);if(!variable)continue;return variable.defs.some(def=>computesHmac(def.node))}return false}function computesHmac(root){const stack=[root];while(stack.length>0){const node=stack.pop();if(node.type===eslint_devkit_1.AST_NODE_TYPES.CallExpression&&isCreateHmacCall(node)){return true}for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"){stack.push(child)}}}}return false}function isCreateHmacCall(node){const callee=node.callee;if(callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){return callee.name==="createHmac"}return callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(callee)==="createHmac"}function canCallSha256(callee){const scope=context.sourceCode.getScope(callee);const declared=name=>{for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable)return variable.defs.length>0}return false};return declared("sha256")||!declared(callee.name)}function checkCallExpression(node){if(isTestFile)return;if(isNonCryptographicUse(node))return;if(!reportUnclassifiedHashes&&!hasSecurityUse(node))return;if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.MemberExpression&&(0,eslint_devkit_1.propertyName)(node.callee)==="createHash"){checkHashArgument(node)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier&&node.callee.name==="createHash"){checkHashArgument(node)}if(node.callee.type===eslint_devkit_1.AST_NODE_TYPES.Identifier){const funcName=node.callee.name.toLowerCase();if((funcName==="sha1"||funcName==="md5"||funcName==="md4")&&!isLocalHmacHelper(node.callee)){const weakPattern=findWeakHash(funcName,additionalWeakAlgorithms);context.report({node,messageId:"weakHashAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:canCallSha256(node.callee)?[{messageId:"useSha256",fix:fixer=>fixer.replaceText(node.callee,"sha256")}]:[]})}}}function checkHashArgument(node){for(const arg of node.arguments){const resolved=(0,const_value_1.resolveConstantString)(context.sourceCode,arg);if(resolved===null)continue;const weakPattern=findWeakHash(resolved.value,additionalWeakAlgorithms);if(!weakPattern)continue;const target=resolved.source;context.report({node:arg,messageId:"weakHashAlgorithm",data:{algorithm:weakPattern.name,replacement:weakPattern.replacement},suggest:[{messageId:"useSha256",fix:fixer=>fixer.replaceText(target,`"sha256"`)},{messageId:"useSha512",fix:fixer=>fixer.replaceText(target,`"sha512"`)},{messageId:"useSha3",fix:fixer=>fixer.replaceText(target,`"sha3-256"`)}]})}}return{before(){const[options={}]=currentOptions();({additionalWeakAlgorithms=[],allowInTests=false,nonCryptographicNames=DEFAULT_NON_CRYPTOGRAPHIC_NAMES,securityUseNames=DEFAULT_SECURITY_USE_NAMES,reportUnclassifiedHashes=false}=options);isSecurityUse=(0,names_1.makeNameTest)(securityUseNames);isComparedSecurityValue=(0,names_1.makeNameTest)([...securityUseNames,"mac","digest"]);isNonCryptographicName=(0,names_1.makeNameTest)(nonCryptographicNames.map(normalizeName));const filename=context.filename;isTestFile=allowInTests&&(0,eslint_devkit_1.isTestFilePath)(filename)},CallExpression:checkCallExpression}}});