jsx-no-target-blank.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. function getStringFromValue(value) {
  60. if (value) {
  61. if (value.type === 'Literal') {
  62. return value.value;
  63. }
  64. if (value.type === 'JSXExpressionContainer') {
  65. if (value.expression.type === 'TemplateLiteral') {
  66. return value.expression.quasis[0].value.cooked;
  67. }
  68. const expr = value.expression;
  69. return expr && (
  70. expr.type === 'ConditionalExpression'
  71. ? [expr.consequent.value, expr.alternate.value]
  72. : expr.value
  73. );
  74. }
  75. }
  76. return null;
  77. }
  78. function hasSecureRel(node, allowReferrer, warnOnSpreadAttributes, spreadAttributeIndex) {
  79. const relIndex = findLastIndex(node.attributes, (attr) => (attr.type === 'JSXAttribute' && attr.name.name === 'rel'));
  80. if (relIndex === -1 || (warnOnSpreadAttributes && relIndex < spreadAttributeIndex)) {
  81. return false;
  82. }
  83. const relAttribute = node.attributes[relIndex];
  84. const value = getStringFromValue(relAttribute.value);
  85. return [].concat(value).every((item) => {
  86. const tags = typeof item === 'string' ? item.toLowerCase().split(' ') : false;
  87. const noreferrer = tags && tags.indexOf('noreferrer') >= 0;
  88. if (noreferrer) {
  89. return true;
  90. }
  91. const noopener = tags && tags.indexOf('noopener') >= 0;
  92. return allowReferrer && noopener;
  93. });
  94. }
  95. const messages = {
  96. 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',
  97. 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',
  98. };
  99. module.exports = {
  100. meta: {
  101. fixable: 'code',
  102. docs: {
  103. description: 'Disallow `target="_blank"` attribute without `rel="noreferrer"`',
  104. category: 'Best Practices',
  105. recommended: true,
  106. url: docsUrl('jsx-no-target-blank'),
  107. },
  108. messages,
  109. schema: [{
  110. type: 'object',
  111. properties: {
  112. allowReferrer: {
  113. type: 'boolean',
  114. },
  115. enforceDynamicLinks: {
  116. enum: ['always', 'never'],
  117. },
  118. warnOnSpreadAttributes: {
  119. type: 'boolean',
  120. },
  121. links: {
  122. type: 'boolean',
  123. default: true,
  124. },
  125. forms: {
  126. type: 'boolean',
  127. default: false,
  128. },
  129. },
  130. additionalProperties: false,
  131. }],
  132. },
  133. create(context) {
  134. const configuration = Object.assign(
  135. {
  136. allowReferrer: false,
  137. warnOnSpreadAttributes: false,
  138. links: true,
  139. forms: false,
  140. },
  141. context.options[0]
  142. );
  143. const allowReferrer = configuration.allowReferrer;
  144. const warnOnSpreadAttributes = configuration.warnOnSpreadAttributes;
  145. const enforceDynamicLinks = configuration.enforceDynamicLinks || 'always';
  146. const linkComponents = linkComponentsUtil.getLinkComponents(context);
  147. const formComponents = linkComponentsUtil.getFormComponents(context);
  148. return {
  149. JSXOpeningElement(node) {
  150. const targetIndex = findLastIndex(node.attributes, (attr) => attr.name && attr.name.name === 'target');
  151. const spreadAttributeIndex = findLastIndex(node.attributes, (attr) => (attr.type === 'JSXSpreadAttribute'));
  152. if (linkComponents.has(node.name.name)) {
  153. if (!attributeValuePossiblyBlank(node.attributes[targetIndex])) {
  154. const hasSpread = spreadAttributeIndex >= 0;
  155. if (warnOnSpreadAttributes && hasSpread) {
  156. // continue to check below
  157. } else if ((hasSpread && targetIndex < spreadAttributeIndex) || !hasSpread || !warnOnSpreadAttributes) {
  158. return;
  159. }
  160. }
  161. const linkAttribute = linkComponents.get(node.name.name);
  162. const hasDangerousLink = hasExternalLink(node, linkAttribute, warnOnSpreadAttributes, spreadAttributeIndex)
  163. || (enforceDynamicLinks === 'always' && hasDynamicLink(node, linkAttribute));
  164. if (hasDangerousLink && !hasSecureRel(node, allowReferrer, warnOnSpreadAttributes, spreadAttributeIndex)) {
  165. const messageId = allowReferrer ? 'noTargetBlankWithoutNoopener' : 'noTargetBlankWithoutNoreferrer';
  166. const relValue = allowReferrer ? 'noopener' : 'noreferrer';
  167. report(context, messages[messageId], messageId, {
  168. node,
  169. fix(fixer) {
  170. // eslint 5 uses `node.attributes`; eslint 6+ uses `node.parent.attributes`
  171. const nodeWithAttrs = node.parent.attributes ? node.parent : node;
  172. // eslint 5 does not provide a `name` property on JSXSpreadElements
  173. const relAttribute = nodeWithAttrs.attributes.find((attr) => attr.name && attr.name.name === 'rel');
  174. if (targetIndex < spreadAttributeIndex || (spreadAttributeIndex >= 0 && !relAttribute)) {
  175. return null;
  176. }
  177. if (!relAttribute) {
  178. return fixer.insertTextAfter(nodeWithAttrs.attributes.slice(-1)[0], ` rel="${relValue}"`);
  179. }
  180. if (!relAttribute.value) {
  181. return fixer.insertTextAfter(relAttribute, `="${relValue}"`);
  182. }
  183. if (relAttribute.value.type === 'Literal') {
  184. const parts = relAttribute.value.value
  185. .split('noreferrer')
  186. .filter(Boolean);
  187. return fixer.replaceText(relAttribute.value, `"${parts.concat('noreferrer').join(' ')}"`);
  188. }
  189. if (relAttribute.value.type === 'JSXExpressionContainer') {
  190. if (relAttribute.value.expression.type === 'Literal') {
  191. if (typeof relAttribute.value.expression.value === 'string') {
  192. const parts = relAttribute.value.expression.value
  193. .split('noreferrer')
  194. .filter(Boolean);
  195. return fixer.replaceText(relAttribute.value.expression, `"${parts.concat('noreferrer').join(' ')}"`);
  196. }
  197. // for undefined, boolean, number, symbol, bigint, and null
  198. return fixer.replaceText(relAttribute.value, '"noreferrer"');
  199. }
  200. }
  201. return null;
  202. },
  203. });
  204. }
  205. }
  206. if (formComponents.has(node.name.name)) {
  207. if (!attributeValuePossiblyBlank(node.attributes[targetIndex])) {
  208. const hasSpread = spreadAttributeIndex >= 0;
  209. if (warnOnSpreadAttributes && hasSpread) {
  210. // continue to check below
  211. } else if (
  212. (hasSpread && targetIndex < spreadAttributeIndex)
  213. || !hasSpread
  214. || !warnOnSpreadAttributes
  215. ) {
  216. return;
  217. }
  218. }
  219. if (!configuration.forms || hasSecureRel(node)) {
  220. return;
  221. }
  222. const formAttribute = formComponents.get(node.name.name);
  223. if (
  224. hasExternalLink(node, formAttribute)
  225. || (enforceDynamicLinks === 'always' && hasDynamicLink(node, formAttribute))
  226. ) {
  227. const messageId = allowReferrer ? 'noTargetBlankWithoutNoopener' : 'noTargetBlankWithoutNoreferrer';
  228. report(context, messages[messageId], messageId, {
  229. node,
  230. });
  231. }
  232. }
  233. },
  234. };
  235. },
  236. };