-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMLCleaner.ts
298 lines (248 loc) · 11.1 KB
/
MLCleaner.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
interface MLCleanerOptions{
allowedTags?:Array<string>|boolean|Function,
allowedAttributes?:Map<string,Array<string>>|Array<string>|boolean|Function,
disableJavaScript?:boolean,
disableDoubleEncodeAmpersands?:boolean,
stripComments?:boolean,
attemptHTMLDecode?:boolean,
decodeEntities?:boolean
}
enum MLNodeType{
COMMENT = 8,
ELEMENT = 1,
STRING = 3
}
class MLCleaner{
public static Version = "0.1.32";
private static URLCapableAttributeNames = ["lowsrc","dynsrc","href","codebase","cite","background","action","longdesc","src","profile","usemap","classid","data","formaction","icon","manifest","poster"];
private static TagsContentIgnoreEscapes = ["script","style"];
public clean(content:string, settings?:MLCleanerOptions){
settings = this.standardizeSettings(settings);
let vDoc = document.implementation.createHTMLDocument("vDoc - MLCleaner v" + MLCleaner.Version);
let templ = vDoc.createElement("template");
let final = "";
vDoc.body.appendChild(templ);
// take out sneaky chars with code 0-32
content = content.split('').filter(c => c.charCodeAt(0) > 31).join('');
content = content.replace(/((?:&#)[0]*(?:3[012]|[12][0-9]|[0-9])[^0-9];*)/gm, '');
templ.innerHTML = content;
templ.content.childNodes.forEach(c => {
if (c.nodeType === MLNodeType.COMMENT){
if (settings.stripComments === true){
templ.content.removeChild(c);
return;
}
}
else if (c.nodeType === MLNodeType.ELEMENT){
let newNode:HTMLElement = <HTMLElement>(c.cloneNode(true));
if (settings.disableJavaScript === true && c.nodeName.toLowerCase() === "script"){
templ.content.removeChild(c);
return;
}
// attributes
for (let i = newNode.attributes.length - 1 ; i >= 0 ; i-- ){
let attr = newNode.attributes[i];
let aName = attr.name;
let checkedAttr = this.checkCanAcceptAttribute(newNode.nodeName,attr,settings);
if ( checkedAttr === null ){
newNode.removeAttribute(aName);
}
else{
let k = MLCleaner.encodeHtmlTags(checkedAttr.value);
let q = MLCleaner.decodeHtmlTags(checkedAttr.value);
attr.value = k;
attr.value = checkedAttr.value;
}
}
if (Array.isArray(settings.allowedTags)){
if (settings.allowedTags.length === 0 || settings.allowedTags.indexOf(c.nodeName.toLowerCase()) === -1){
//not in array of accepted tags
let nextSib = c.nextSibling;
newNode.childNodes.forEach(cc => {
let n;
switch (cc.nodeType){
case MLNodeType.COMMENT:
n = vDoc.createComment(cc.nodeValue);
c.parentNode.insertBefore(
n,
nextSib
);
nextSib = n.nextSibling;
break;
case MLNodeType.ELEMENT:
n = this.stringToNode( this.clean( (<HTMLElement>cc).outerHTML , settings ) )[0];
c.parentNode.insertBefore(
n ,
nextSib
);
nextSib = n.nextSibling;
break;
case MLNodeType.STRING:
n = vDoc.createTextNode(cc.nodeValue);
c.parentNode.insertBefore(
n,
nextSib
);
nextSib = n.nextSibling;
break;
}
});
templ.content.removeChild(c);
return;
}
}
else if (MLCleaner.Helpers.isFunction(settings.allowedTags)){
if ((<Function>settings.allowedTags)(c) === false){
//not accepted by function
templ.content.removeChild(c);
return;
}
}
else if (MLCleaner.Helpers.isBoolean(settings.allowedTags)){
if (settings.allowedTags === false){
//dont accept any tags
templ.content.removeChild(c);
return;
}
}
if (MLCleaner.TagsContentIgnoreEscapes.indexOf(newNode.nodeName.toLowerCase()) > -1){
newNode.innerHTML = newNode.innerHTML;
}
else{
newNode.innerHTML = this.clean(newNode.innerHTML,settings);
}
templ.content.replaceChild(
newNode,
c
);
}
else if (c.nodeType === MLNodeType.STRING){
// do nothing
}
});
// if (settings.decodeEntities === true){
final = templ.innerHTML;
// }
// else{
// final = MLCleaner.encodeHtmlTags(templ.innerHTML);
// }
if (settings.disableDoubleEncodeAmpersands === true){
final = final.replace(/(?:&)([a-z#0-9A-Z]+;)/gm,'&$1');
}
// check encoded
if (settings.attemptHTMLDecode === true){
final = final.replace(/(?:&)/g,'&');
final = final.replace(/(?:<)/g,'<');
final = final.replace(/(?:>)/g,'>');
}
return final;
}
public static Helpers = {
isFunction: obj => !!(obj && obj.constructor && obj.call && obj.apply),
isBoolean: obj => (obj === true || obj === false),
isMap: obj => (obj instanceof Map),
isObject: obj => (obj !== null && typeof obj === "object"),
decodeHtmlTags: MLCleaner.decodeHtmlTags,
encodeHtmlTags: MLCleaner.encodeHtmlTags
}
private checkCanAcceptAttribute(nodeName:string,attr:Attr,settings:MLCleanerOptions):null|Attr{
let allowedAttr = settings.allowedAttributes;
// check if attr is; event-based with js disabled OR url with javascript protocol with js disabled
if (settings.disableJavaScript === true){
if (attr.name.toLowerCase().indexOf("on") === 0){
return null;
}
if ( ["srcset","archive"].indexOf(attr.name.toLowerCase()) > -1 || (attr.name.toLowerCase() === "content" && nodeName.toLowerCase() === "meta")){
let partsW = attr.value.split(' ').filter(p => p.replace(/\s/g,'').toLowerCase().indexOf('javascript:') === 0);
let partsC = attr.value.split(',').filter(p => p.replace(/\s/g,'').toLowerCase().indexOf('javascript:') === 0);
if (partsW.length > 0 || partsC.length > 0) return null;
}
if (MLCleaner.URLCapableAttributeNames.indexOf(attr.name.toLowerCase()) > -1 && attr.value.replace(/\s/g,'').toLowerCase().indexOf('javascript:') === 0){
return null;
}
// check same as above for css that accepts url() as value and has javascript protocol
if (attr.name.toLowerCase() === "style"){
let nodeStyles = this.parseCSS(attr.value);
let srcs = Array.from(nodeStyles.values()).filter(k => k.indexOf("url(javascript:") === 0);
if (srcs.length > 0) return null;
}
}
if (Array.isArray(allowedAttr)){
if (allowedAttr.indexOf(attr.name) > -1){
return attr;
}
return null;
}
else if (MLCleaner.Helpers.isBoolean(allowedAttr)){
if (allowedAttr === true){
return attr;
}
return null;
}
else if (MLCleaner.Helpers.isFunction(allowedAttr)){
let r = (<Function>allowedAttr)(nodeName,attr);
if (r !== null && r !== false){
return r;
}
return null;
}
else if (MLCleaner.Helpers.isMap(allowedAttr)){
let attrMap = (<Map<String,Array<string>>>allowedAttr);
if (attrMap.get(nodeName.toLowerCase()).indexOf(attr.name) > -1){
return attr;
}
return null;
}
return null;
}
private static decodeHtmlTags(htmlString:string){
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
return div.innerText;
}
private static encodeHtmlTags(htmlString:string){
var div = document.createElement('div');
div.innerText = htmlString.trim();
return div.innerHTML;
}
private stringToNode(htmlString:string) {
var div = document.createElement('div');
div.innerHTML = htmlString.trim();
return div.childNodes;
}
private parseCSS(styleContent) {
let doc = document.implementation.createHTMLDocument("");
let div = doc.createElement("div");
let stl = new Map<string,string>();
div.setAttribute('style',styleContent);
for(let i = 0; i < div.style.length; i++ ){
stl.set( div.style[i], div.style[div.style[i]] );
}
return stl;
};
private standardizeSettings(settings?:MLCleanerOptions):MLCleanerOptions{
let defaultSettings = {
allowedTags: ["b","i","em","strong","u"],
allowedAttributes: false,
disableJavaScript: true,
stripComments: true,
attemptHTMLDecode: false,
disableDoubleEncodeAmpersands: true,
decodeEntities: true
};
if (!settings) settings = defaultSettings;
else {
settings = Object.assign({}, defaultSettings, settings);
if (
Array.isArray(settings.allowedAttributes) === false &&
MLCleaner.Helpers.isBoolean(settings.allowedAttributes) === false &&
MLCleaner.Helpers.isFunction(settings.allowedAttributes) === false &&
MLCleaner.Helpers.isMap(settings.allowedAttributes) === false &&
MLCleaner.Helpers.isObject(settings.allowedAttributes) === true
){
settings.allowedAttributes = new Map(Object.entries(settings.allowedAttributes));
}
}
return settings;
}
}