jsx-no-target-blank.js 11 KB

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