-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathjsx-no-target-blank.js
80 lines (70 loc) · 2.32 KB
/
jsx-no-target-blank.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* @fileoverview Forbid target='_blank' attribute
* @author Kevin Miller
*/
'use strict';
const docsUrl = require('../util/docsUrl');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
function isTargetBlank(attr) {
return attr.name &&
attr.name.name === 'target' &&
attr.value &&
attr.value.type === 'Literal' &&
attr.value.value.toLowerCase() === '_blank';
}
function hasExternalLink(element) {
return element.attributes.some(attr => attr.name &&
attr.name.name === 'href' &&
attr.value.type === 'Literal' &&
/^(?:\w+:|\/\/)/.test(attr.value.value));
}
function hasDynamicLink(element) {
return element.attributes.some(attr => attr.name &&
attr.name.name === 'href' &&
attr.value.type === 'JSXExpressionContainer');
}
function hasSecureRel(element) {
return element.attributes.find(attr => {
if (attr.type === 'JSXAttribute' && attr.name.name === 'rel') {
const tags = attr.value && attr.value.type === 'Literal' && attr.value.value.toLowerCase().split(' ');
return tags && (tags.indexOf('noopener') >= 0 && tags.indexOf('noreferrer') >= 0);
}
return false;
});
}
module.exports = {
meta: {
docs: {
description: 'Forbid target="_blank" attribute without rel="noopener noreferrer"',
category: 'Best Practices',
recommended: true,
url: docsUrl('jsx-no-target-blank')
},
schema: [{
type: 'object',
properties: {
enforceDynamicLinks: {
enum: ['always', 'never']
}
},
additionalProperties: false
}]
},
create: function(context) {
const configuration = context.options[0] || {};
const enforceDynamicLinks = configuration.enforceDynamicLinks || 'always';
return {
JSXAttribute: function(node) {
if (node.parent.name.name !== 'a' || !isTargetBlank(node) || hasSecureRel(node.parent)) {
return;
}
if (hasExternalLink(node.parent) || (enforceDynamicLinks === 'always' && hasDynamicLink(node.parent))) {
context.report(node, 'Using target="_blank" without rel="noopener noreferrer" ' +
'is a security risk: see https://mathiasbynens.github.io/rel-noopener');
}
}
};
}
};