jsx-no-target-blank.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /**
  2. * @fileoverview Forbid target='_blank' attribute
  3. * @author Kevin Miller
  4. */
  5. 'use strict';
  6. const includes = require('array-includes');
  7. const docsUrl = require('../util/docsUrl');
  8. const linkComponentsUtil = require('../util/linkComponents');
  9. const report = require('../util/report');
  10. // ------------------------------------------------------------------------------
  11. // Rule Definition
  12. // ------------------------------------------------------------------------------
  13. function findLastIndex(arr, condition) {
  14. for (let i = arr.length - 1; i >= 0; i -= 1) {
  15. if (condition(arr[i])) {
  16. return i;
  17. }
  18. }
  19. return -1;
  20. }
  21. function attributeValuePossiblyBlank(attribute) {
  22. if (!attribute || !attribute.value) {
  23. return false;
  24. }
  25. const value = attribute.value;
  26. if (value.type === 'Literal') {
  27. return typeof value.value === 'string' && value.value.toLowerCase() === '_blank';
  28. }
  29. if (value.type === 'JSXExpressionContainer') {
  30. const expr = value.expression;
  31. if (expr.type === 'Literal') {
  32. return typeof expr.value === 'string' && expr.value.toLowerCase() === '_blank';
  33. }
  34. if (expr.type === 'ConditionalExpression') {
  35. if (expr.alternate.type === 'Literal' && expr.alternate.value && expr.alternate.value.toLowerCase() === '_blank') {
  36. return true;
  37. }
  38. if (expr.consequent.type === 'Literal' && expr.consequent.value && expr.consequent.value.toLowerCase() === '_blank') {
  39. return true;
  40. }
  41. }
  42. }
  43. return false;
  44. }
  45. function hasExternalLink(node, linkAttributes, warnOnSpreadAttributes, spreadAttributeIndex) {
  46. const linkIndex = findLastIndex(node.attributes, (attr) => attr.name && includes(linkAttributes, attr.name.name));
  47. const foundExternalLink = linkIndex !== -1 && ((attr) => attr.value && attr.value.type === 'Literal' && /^(?:\w+:|\/\/)/.test(attr.value.value))(
  48. node.attributes[linkIndex]);
  49. return foundExternalLink || (warnOnSpreadAttributes && linkIndex < spreadAttributeIndex);
  50. }
  51. function hasDynamicLink(node, linkAttributes) {
  52. const dynamicLinkIndex = findLastIndex(node.attributes, (attr) => attr.name
  53. && includes(linkAttributes, attr.name.name)
  54. && attr.value
  55. && attr.value.type === 'JSXExpressionContainer');
  56. if (dynamicLinkIndex !== -1) {
  57. return true;
  58. }
  59. }
  60. /**
  61. * Get the string(s) from a value
  62. * @param {ASTNode} value The AST node being checked.
  63. * @param {ASTNode} targetValue The AST node being checked.
  64. * @returns {string | string[] | null} The string value, or null if not a string.
  65. */
  66. function getStringFromValue(value, targetValue) {
  67. if (value) {
  68. if (value.type === 'Literal') {
  69. return value.value;
  70. }
  71. if (value.type === 'JSXExpressionContainer') {
  72. if (value.expression.type === 'TemplateLiteral') {
  73. return value.expression.quasis[0].value.cooked;
  74. }
  75. const expr = value.expression;
  76. if (expr && expr.type === 'ConditionalExpression') {
  77. const relValues = [expr.consequent.value, expr.alternate.value];
  78. if (targetValue.type === 'JSXExpressionContainer' && targetValue.expression && targetValue.expression.type === 'ConditionalExpression') {
  79. const targetTestCond = targetValue.expression.test.name;
  80. const relTestCond = value.expression.test.name;
  81. if (targetTestCond === relTestCond) {
  82. const targetBlankIndex = [targetValue.expression.consequent.value, targetValue.expression.alternate.value].indexOf('_blank');
  83. return relValues[targetBlankIndex];
  84. }
  85. }
  86. return relValues;
  87. }
  88. return expr.value;
  89. }
  90. }
  91. return null;
  92. }
  93. function hasSecureRel(node, allowReferrer, warnOnSpreadAttributes, spreadAttributeIndex) {
  94. const relIndex = findLastIndex(node.attributes, (attr) => (attr.type === 'JSXAttribute' && attr.name.name === 'rel'));
  95. const targetIndex = findLastIndex(node.attributes, (attr) => (attr.type === 'JSXAttribute' && attr.name.name === 'target'));
  96. if (relIndex === -1 || (warnOnSpreadAttributes && relIndex < spreadAttributeIndex)) {
  97. return false;
  98. }
  99. const relAttribute = node.attributes[relIndex];
  100. const targetAttributeValue = node.attributes[targetIndex] && node.attributes[targetIndex].value;
  101. const value = getStringFromValue(relAttribute.value, targetAttributeValue);
  102. return [].concat(value).every((item) => {
  103. const tags = typeof item === 'string' ? item.toLowerCase().split(' ') : false;
  104. const noreferrer = tags && tags.indexOf('noreferrer') >= 0;
  105. if (noreferrer) {
  106. return true;
  107. }
  108. const noopener = tags && tags.indexOf('noopener') >= 0;
  109. return allowReferrer && noopener;
  110. });
  111. }
  112. const messages = {
  113. noTargetBlankWithoutNoreferrer: 'Using target="_blank" without rel="noreferrer" (which implies rel="noopener") is a security risk in older browsers: see https://mathiasbynens.github.io/rel-noopener/#recommendations',
  114. noTargetBlankWithoutNoopener: 'Using target="_blank" without rel="noreferrer" or rel="noopener" (the former implies the latter and is preferred due to wider support) is a security risk: see https://mathiasbynens.github.io/rel-noopener/#recommendations',
  115. };
  116. /** @type {import('eslint').Rule.RuleModule} */
  117. module.exports = {
  118. meta: {
  119. fixable: 'code',
  120. docs: {
  121. description: 'Disallow `target="_blank"` attribute without `rel="noreferrer"`',
  122. category: 'Best Practices',
  123. recommended: true,
  124. url: docsUrl('jsx-no-target-blank'),
  125. },
  126. messages,
  127. schema: [{
  128. type: 'object',
  129. properties: {
  130. allowReferrer: {
  131. type: 'boolean',
  132. },
  133. enforceDynamicLinks: {
  134. enum: ['always', 'never'],
  135. },
  136. warnOnSpreadAttributes: {
  137. type: 'boolean',
  138. },
  139. links: {
  140. type: 'boolean',
  141. default: true,
  142. },
  143. forms: {
  144. type: 'boolean',
  145. default: false,
  146. },
  147. },
  148. additionalProperties: false,
  149. }],
  150. },
  151. create(context) {
  152. const configuration = Object.assign(
  153. {
  154. allowReferrer: false,
  155. warnOnSpreadAttributes: false,
  156. links: true,
  157. forms: false,
  158. },
  159. context.options[0]
  160. );
  161. const allowReferrer = configuration.allowReferrer;
  162. const warnOnSpreadAttributes = configuration.warnOnSpreadAttributes;
  163. const enforceDynamicLinks = configuration.enforceDynamicLinks || 'always';
  164. const linkComponents = linkComponentsUtil.getLinkComponents(context);
  165. const formComponents = linkComponentsUtil.getFormComponents(context);
  166. return {
  167. JSXOpeningElement(node) {
  168. const targetIndex = findLastIndex(node.attributes, (attr) => attr.name && attr.name.name === 'target');
  169. const spreadAttributeIndex = findLastIndex(node.attributes, (attr) => (attr.type === 'JSXSpreadAttribute'));
  170. if (linkComponents.has(node.name.name)) {
  171. if (!attributeValuePossiblyBlank(node.attributes[targetIndex])) {
  172. const hasSpread = spreadAttributeIndex >= 0;
  173. if (warnOnSpreadAttributes && hasSpread) {
  174. // continue to check below
  175. } else if ((hasSpread && targetIndex < spreadAttributeIndex) || !hasSpread || !warnOnSpreadAttributes) {
  176. return;
  177. }
  178. }
  179. const linkAttributes = linkComponents.get(node.name.name);
  180. const hasDangerousLink = hasExternalLink(node, linkAttributes, warnOnSpreadAttributes, spreadAttributeIndex)
  181. || (enforceDynamicLinks === 'always' && hasDynamicLink(node, linkAttributes));
  182. if (hasDangerousLink && !hasSecureRel(node, allowReferrer, warnOnSpreadAttributes, spreadAttributeIndex)) {
  183. const messageId = allowReferrer ? 'noTargetBlankWithoutNoopener' : 'noTargetBlankWithoutNoreferrer';
  184. const relValue = allowReferrer ? 'noopener' : 'noreferrer';
  185. report(context, messages[messageId], messageId, {
  186. node,
  187. fix(fixer) {
  188. // eslint 5 uses `node.attributes`; eslint 6+ uses `node.parent.attributes`
  189. const nodeWithAttrs = node.parent.attributes ? node.parent : node;
  190. // eslint 5 does not provide a `name` property on JSXSpreadElements
  191. const relAttribute = nodeWithAttrs.attributes.find((attr) => attr.name && attr.name.name === 'rel');
  192. if (targetIndex < spreadAttributeIndex || (spreadAttributeIndex >= 0 && !relAttribute)) {
  193. return null;
  194. }
  195. if (!relAttribute) {
  196. return fixer.insertTextAfter(nodeWithAttrs.attributes.slice(-1)[0], ` rel="${relValue}"`);
  197. }
  198. if (!relAttribute.value) {
  199. return fixer.insertTextAfter(relAttribute, `="${relValue}"`);
  200. }
  201. if (relAttribute.value.type === 'Literal') {
  202. const parts = relAttribute.value.value
  203. .split('noreferrer')
  204. .filter(Boolean);
  205. return fixer.replaceText(relAttribute.value, `"${parts.concat('noreferrer').join(' ')}"`);
  206. }
  207. if (relAttribute.value.type === 'JSXExpressionContainer') {
  208. if (relAttribute.value.expression.type === 'Literal') {
  209. if (typeof relAttribute.value.expression.value === 'string') {
  210. const parts = relAttribute.value.expression.value
  211. .split('noreferrer')
  212. .filter(Boolean);
  213. return fixer.replaceText(relAttribute.value.expression, `"${parts.concat('noreferrer').join(' ')}"`);
  214. }
  215. // for undefined, boolean, number, symbol, bigint, and null
  216. return fixer.replaceText(relAttribute.value, '"noreferrer"');
  217. }
  218. }
  219. return null;
  220. },
  221. });
  222. }
  223. }
  224. if (formComponents.has(node.name.name)) {
  225. if (!attributeValuePossiblyBlank(node.attributes[targetIndex])) {
  226. const hasSpread = spreadAttributeIndex >= 0;
  227. if (warnOnSpreadAttributes && hasSpread) {
  228. // continue to check below
  229. } else if (
  230. (hasSpread && targetIndex < spreadAttributeIndex)
  231. || !hasSpread
  232. || !warnOnSpreadAttributes
  233. ) {
  234. return;
  235. }
  236. }
  237. if (!configuration.forms || hasSecureRel(node)) {
  238. return;
  239. }
  240. const formAttributes = formComponents.get(node.name.name);
  241. if (
  242. hasExternalLink(node, formAttributes)
  243. || (enforceDynamicLinks === 'always' && hasDynamicLink(node, formAttributes))
  244. ) {
  245. const messageId = allowReferrer ? 'noTargetBlankWithoutNoopener' : 'noTargetBlankWithoutNoreferrer';
  246. report(context, messages[messageId], messageId, {
  247. node,
  248. });
  249. }
  250. }
  251. },
  252. };
  253. },
  254. };