1
1
import { visit } from 'unist-util-visit'
2
2
3
+ const permittedAttibutes = [
4
+ 'dangerouslySetInnerHTML'
5
+ ]
6
+
3
7
const dangerousAttributes = [
4
8
'onabort' , 'onafterprint' , 'onanimationend' , 'onanimationiteration' , 'onanimationstart' ,
5
9
'onbeforeprint' , 'onbeforeunload' , 'onblur' , 'oncancel' , 'oncanplay' , 'oncanplaythrough' ,
@@ -17,10 +21,27 @@ const dangerousAttributes = [
17
21
'background' , 'poster' , 'cite' , 'data' , 'ping' , 'xlink:href' , 'style' , 'srcdoc' , 'sandbox'
18
22
] . join ( '|' )
19
23
24
+ // Define an array of potentially dangerous tags
25
+ const dangerousTags = [ 'script' , 'iframe' , 'object' , 'embed' , 'link' , 'style' , 'meta' ]
26
+
20
27
export const remarkSanitize = ( ) : ( tree : Node ) => void => ( tree : any ) => {
21
28
visit ( tree , 'html' , ( node ) => {
22
- const dangerousAttrRegex = new RegExp ( `\\s*(${ dangerousAttributes } )="[^"]*"` , 'gi' )
29
+ const inputTag = node . value . toLowerCase ( )
30
+
31
+ // remove dangerous tags
32
+ if ( dangerousTags . some ( ( tag ) => inputTag . startsWith ( `<${ tag } ` ) ) ) {
33
+ node . value = ''
34
+ return
35
+ }
36
+
37
+ // remove permitted attributes
38
+ if ( permittedAttibutes . some ( ( attr ) => node . value . includes ( `${ attr } =` ) ) ) {
39
+ node . value = ''
40
+ return
41
+ }
23
42
43
+ // sanitize dangerous attributes
44
+ const dangerousAttrRegex = new RegExp ( `\\s*(${ dangerousAttributes } )="[^"]*"` , 'gi' )
24
45
if ( node . value . match ( dangerousAttrRegex ) ) {
25
46
node . value = node . value . replace ( dangerousAttrRegex , ( match : string ) => {
26
47
const attr = match . toLowerCase ( ) . trim ( )
0 commit comments