-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
sanitizer.ts
98 lines (87 loc) · 2.49 KB
/
sanitizer.ts
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import * as sanitize from 'sanitize-html';
export
interface ISanitizer {
/**
* Sanitize an HTML string.
*
* @param dirty - The dirty text.
*
* @param options - The optional sanitization options.
*
* @returns The sanitized string.
*/
sanitize(dirty: string, options?: ISanitizer.IOptions): string;
}
/**
* The namespace for `ISanitizer` related interfaces.
*/
export
namespace ISanitizer {
/**
* The options used to sanitize.
*/
export
interface IOptions {
/**
* The allowed tags.
*/
allowedTags?: string[];
/**
* The allowed attributes for a given tag.
*/
allowedAttributes?: { [key: string]: string[] };
}
}
/**
* A class to sanitize HTML strings.
*/
class Sanitizer implements ISanitizer {
/**
* Sanitize an HTML string.
*
* @param dirty - The dirty text.
*
* @param options - The optional sanitization options.
*
* @returns The sanitized string.
*/
sanitize(dirty: string, options?: ISanitizer.IOptions): string {
return sanitize(dirty, { ...this._options, ...options || {} });
}
private _options: sanitize.IOptions = {
allowedTags: sanitize.defaults.allowedTags
.concat('h1', 'h2', 'img', 'span', 'audio', 'video', 'del'),
allowedAttributes: {
// Allow the "rel" attribute for <a> tags.
'a': sanitize.defaults.allowedAttributes['a'].concat('rel'),
// Allow the "src" attribute for <img> tags.
'img': ['src', 'height', 'width', 'alt'],
// Allow "class" attribute for <code> tags.
'code': ['class'],
// Allow "class" attribute for <span> tags.
'span': ['class'],
// Allow "class" attribute for <div> tags.
'div': ['class'],
// Allow "class" attribute for <p> tags.
'p': ['class'],
// Allow "class" attribute for <pre> tags.
'pre': ['class'],
// Allow the "src" attribute for <audio> tags.
'audio': ['src', 'autoplay', 'loop', 'muted', 'controls'],
// Allow the "src" attribute for <video> tags.
'video': ['src', 'height', 'width', 'autoplay',
'loop', 'muted', 'controls']
},
transformTags: {
// Set the "rel" attribute for <a> tags to "nofollow".
'a': sanitize.simpleTransform('a', { 'rel': 'nofollow' })
}
};
}
/**
* The default instance of an `ISanitizer` meant for use by user code.
*/
export
const defaultSanitizer: ISanitizer = new Sanitizer();