-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathno-append-html.js
60 lines (55 loc) · 1.81 KB
/
no-append-html.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
'use strict';
const utils = require( '../utils.js' );
// htmlStrings or jQuery collections
const htmlOrCollectionMethods = [ 'append', 'prepend', 'before', 'after', 'replaceWith' ];
// htmlStrings, selectors or jQuery collections
const htmlOrSelectorOrCollectionMethods = [ 'add', 'appendTo', 'prependTo', 'insertBefore', 'insertAfter' ];
const allMethods = htmlOrCollectionMethods.concat( htmlOrSelectorOrCollectionMethods );
function alljQueryOrEmpty( context, node ) {
if ( node.type === 'ConditionalExpression' ) {
return alljQueryOrEmpty( context, node.consequent ) &&
alljQueryOrEmpty( context, node.alternate );
} else if ( node.type === 'Literal' ) {
return node.value === null || (
typeof node.value === 'string' && node.value.match( /^\s*$/ )
);
} else if ( node.type === 'Identifier' && node.name === 'undefined' ) {
return true;
} else {
return utils.isjQuery( context, node );
}
}
module.exports = {
meta: {
type: 'suggestion',
docs: {
description: 'Disallows using ' + allMethods.map( utils.jQueryCollectionLink ).join( '/' ) +
' to inject HTML, in order to prevent possible XSS bugs.'
},
schema: []
},
create: ( context ) => ( {
'CallExpression:exit': ( node ) => {
if ( !(
node.callee.type === 'MemberExpression' &&
allMethods.includes( node.callee.property.name )
) ) {
return;
}
if ( node.arguments.every( ( arg ) => alljQueryOrEmpty( context, arg ) ) ) {
return;
}
if ( htmlOrSelectorOrCollectionMethods.includes( node.callee.property.name ) ) {
if ( node.arguments.every( ( arg ) => !utils.isHtmlString( arg ) ) ) {
return;
}
}
if ( utils.isjQuery( context, node.callee ) ) {
context.report( {
node,
message: 'Avoid injection of possibly unescaped HTML. Create DOM elements instead, or use .text.'
} );
}
}
} )
};