dompurify 0.9.0 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/purify.js DELETED
@@ -1,1004 +0,0 @@
1
- ;(function(factory) {
2
- 'use strict';
3
- /* global window: false, define: false, module: false */
4
- var root = typeof window === 'undefined' ? null : window;
5
-
6
- if (typeof define === 'function' && define.amd) {
7
- define(function(){ return factory(root); });
8
- } else if (typeof module !== 'undefined') {
9
- module.exports = factory(root);
10
- } else {
11
- root.DOMPurify = factory(root);
12
- }
13
- }(function factory(window) {
14
- 'use strict';
15
-
16
- var DOMPurify = function(window) {
17
- return factory(window);
18
- };
19
-
20
- /**
21
- * Version label, exposed for easier checks
22
- * if DOMPurify is up to date or not
23
- */
24
- DOMPurify.version = '0.9.0';
25
-
26
- /**
27
- * Array of elements that DOMPurify removed during sanitation.
28
- * Empty if nothing was removed.
29
- */
30
- DOMPurify.removed = [];
31
-
32
- if (!window || !window.document || window.document.nodeType !== 9) {
33
- // not running in a browser, provide a factory function
34
- // so that you can pass your own Window
35
- DOMPurify.isSupported = false;
36
- return DOMPurify;
37
- }
38
-
39
- var document = window.document;
40
- var originalDocument = document;
41
- var DocumentFragment = window.DocumentFragment;
42
- var HTMLTemplateElement = window.HTMLTemplateElement;
43
- var Node = window.Node;
44
- var NodeFilter = window.NodeFilter;
45
- var NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap;
46
- var Text = window.Text;
47
- var Comment = window.Comment;
48
- var DOMParser = window.DOMParser;
49
- var XMLHttpRequest = window.XMLHttpRequest;
50
- var encodeURI = window.encodeURI;
51
- var useXHR = false;
52
- var useDOMParser = false; // See comment below
53
-
54
- // As per issue #47, the web-components registry is inherited by a
55
- // new document created via createHTMLDocument. As per the spec
56
- // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)
57
- // a new empty registry is used when creating a template contents owner
58
- // document, so we use that as our parent document to ensure nothing
59
- // is inherited.
60
- if (typeof HTMLTemplateElement === 'function') {
61
- var template = document.createElement('template');
62
- if (template.content && template.content.ownerDocument) {
63
- document = template.content.ownerDocument;
64
- }
65
- }
66
- var implementation = document.implementation;
67
- var createNodeIterator = document.createNodeIterator;
68
- var getElementsByTagName = document.getElementsByTagName;
69
- var createDocumentFragment = document.createDocumentFragment;
70
- var importNode = originalDocument.importNode;
71
-
72
- var hooks = {};
73
-
74
- /**
75
- * Expose whether this browser supports running the full DOMPurify.
76
- */
77
- DOMPurify.isSupported =
78
- typeof implementation.createHTMLDocument !== 'undefined' &&
79
- document.documentMode !== 9;
80
-
81
- /* Add properties to a lookup table */
82
- var _addToSet = function(set, array) {
83
- var l = array.length;
84
- while (l--) {
85
- if (typeof array[l] === 'string') {
86
- array[l] = array[l].toLowerCase();
87
- }
88
- set[array[l]] = true;
89
- }
90
- return set;
91
- };
92
-
93
- /* Shallow clone an object */
94
- var _cloneObj = function(object) {
95
- var newObject = {};
96
- var property;
97
- for (property in object) {
98
- if (object.hasOwnProperty(property)) {
99
- newObject[property] = object[property];
100
- }
101
- }
102
- return newObject;
103
- };
104
-
105
- /**
106
- * We consider the elements and attributes below to be safe. Ideally
107
- * don't add any new ones but feel free to remove unwanted ones.
108
- */
109
-
110
- /* allowed element names */
111
- var ALLOWED_TAGS = null;
112
- var DEFAULT_ALLOWED_TAGS = _addToSet({}, [
113
-
114
- // HTML
115
- 'a','abbr','acronym','address','area','article','aside','audio','b',
116
- 'bdi','bdo','big','blink','blockquote','body','br','button','canvas',
117
- 'caption','center','cite','code','col','colgroup','content','data',
118
- 'datalist','dd','decorator','del','details','dfn','dir','div','dl','dt',
119
- 'element','em','fieldset','figcaption','figure','font','footer','form',
120
- 'h1','h2','h3','h4','h5','h6','head','header','hgroup','hr','html','i',
121
- 'img','input','ins','kbd','label','legend','li','main','map','mark',
122
- 'marquee','menu','menuitem','meter','nav','nobr','ol','optgroup',
123
- 'option','output','p','pre','progress','q','rp','rt','ruby','s','samp',
124
- 'section','select','shadow','small','source','spacer','span','strike',
125
- 'strong','style','sub','summary','sup','table','tbody','td','template',
126
- 'textarea','tfoot','th','thead','time','tr','track','tt','u','ul','var',
127
- 'video','wbr',
128
-
129
- // SVG
130
- 'svg','altglyph','altglyphdef','altglyphitem','animatecolor',
131
- 'animatemotion','animatetransform','circle','clippath','defs','desc',
132
- 'ellipse','filter','font','g','glyph','glyphref','hkern','image','line',
133
- 'lineargradient','marker','mask','metadata','mpath','path','pattern',
134
- 'polygon','polyline','radialgradient','rect','stop','switch','symbol',
135
- 'text','textpath','title','tref','tspan','view','vkern',
136
-
137
- // SVG Filters
138
- 'feBlend','feColorMatrix','feComponentTransfer','feComposite',
139
- 'feConvolveMatrix','feDiffuseLighting','feDisplacementMap',
140
- 'feFlood','feFuncA','feFuncB','feFuncG','feFuncR','feGaussianBlur',
141
- 'feMerge','feMergeNode','feMorphology','feOffset',
142
- 'feSpecularLighting','feTile','feTurbulence',
143
-
144
- //MathML
145
- 'math','menclose','merror','mfenced','mfrac','mglyph','mi','mlabeledtr',
146
- 'mmuliscripts','mn','mo','mover','mpadded','mphantom','mroot','mrow',
147
- 'ms','mpspace','msqrt','mystyle','msub','msup','msubsup','mtable','mtd',
148
- 'mtext','mtr','munder','munderover',
149
-
150
- //Text
151
- '#text'
152
- ]);
153
-
154
- /* Allowed attribute names */
155
- var ALLOWED_ATTR = null;
156
- var DEFAULT_ALLOWED_ATTR = _addToSet({}, [
157
-
158
- // HTML
159
- 'accept','action','align','alt','autocomplete','background','bgcolor',
160
- 'border','cellpadding','cellspacing','checked','cite','class','clear','color',
161
- 'cols','colspan','coords','datetime','default','dir','disabled',
162
- 'download','enctype','face','for','headers','height','hidden','high','href',
163
- 'hreflang','id','ismap','label','lang','list','loop', 'low','max',
164
- 'maxlength','media','method','min','multiple','name','noshade','novalidate',
165
- 'nowrap','open','optimum','pattern','placeholder','poster','preload','pubdate',
166
- 'radiogroup','readonly','rel','required','rev','reversed','role','rows',
167
- 'rowspan','spellcheck','scope','selected','shape','size','span',
168
- 'srclang','start','src','step','style','summary','tabindex','title',
169
- 'type','usemap','valign','value','width','xmlns',
170
-
171
- // SVG
172
- 'accent-height','accumulate','additivive','alignment-baseline',
173
- 'ascent','attributename','attributetype','azimuth','basefrequency',
174
- 'baseline-shift','begin','bias','by','clip','clip-path','clip-rule',
175
- 'color','color-interpolation','color-interpolation-filters','color-profile',
176
- 'color-rendering','cx','cy','d','dx','dy','diffuseconstant','direction',
177
- 'display','divisor','dur','edgemode','elevation','end','fill','fill-opacity',
178
- 'fill-rule','filter','flood-color','flood-opacity','font-family','font-size',
179
- 'font-size-adjust','font-stretch','font-style','font-variant','font-weight',
180
- 'fx', 'fy','g1','g2','glyph-name','glyphref','gradientunits','gradienttransform',
181
- 'image-rendering','in','in2','k','k1','k2','k3','k4','kerning','keypoints',
182
- 'keysplines','keytimes','lengthadjust','letter-spacing','kernelmatrix',
183
- 'kernelunitlength','lighting-color','local','marker-end','marker-mid',
184
- 'marker-start','markerheight','markerunits','markerwidth','maskcontentunits',
185
- 'maskunits','max','mask','mode','min','numoctaves','offset','operator',
186
- 'opacity','order','orient','orientation','origin','overflow','paint-order',
187
- 'path','pathlength','patterncontentunits','patterntransform','patternunits',
188
- 'points','preservealpha','r','rx','ry','radius','refx','refy','repeatcount',
189
- 'repeatdur','restart','result','rotate','scale','seed','shape-rendering',
190
- 'specularconstant','specularexponent','spreadmethod','stddeviation','stitchtiles',
191
- 'stop-color','stop-opacity','stroke-dasharray','stroke-dashoffset','stroke-linecap',
192
- 'stroke-linejoin','stroke-miterlimit','stroke-opacity','stroke','stroke-width',
193
- 'surfacescale','targetx','targety','transform','text-anchor','text-decoration',
194
- 'text-rendering','textlength','u1','u2','unicode','values','viewbox',
195
- 'visibility','vert-adv-y','vert-origin-x','vert-origin-y','word-spacing',
196
- 'wrap','writing-mode','xchannelselector','ychannelselector','x','x1','x2',
197
- 'y','y1','y2','z','zoomandpan',
198
-
199
- // MathML
200
- 'accent','accentunder','bevelled','close','columnsalign','columnlines',
201
- 'columnspan','denomalign','depth','display','displaystyle','fence',
202
- 'frame','largeop','length','linethickness','lspace','lquote',
203
- 'mathbackground','mathcolor','mathsize','mathvariant','maxsize',
204
- 'minsize','movablelimits','notation','numalign','open','rowalign',
205
- 'rowlines','rowspacing','rowspan','rspace','rquote','scriptlevel',
206
- 'scriptminsize','scriptsizemultiplier','selection','separator',
207
- 'separators','stretchy','subscriptshift','supscriptshift','symmetric',
208
- 'voffset',
209
-
210
- // XML
211
- 'xlink:href','xml:id','xlink:title','xml:space','xmlns:xlink'
212
- ]);
213
-
214
- /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */
215
- var FORBID_TAGS = null;
216
-
217
- /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
218
- var FORBID_ATTR = null;
219
-
220
- /* Decide if ARIA attributes are okay */
221
- var ALLOW_ARIA_ATTR = true;
222
-
223
- /* Decide if custom data attributes are okay */
224
- var ALLOW_DATA_ATTR = true;
225
-
226
- /* Decide if unknown protocols are okay */
227
- var ALLOW_UNKNOWN_PROTOCOLS = false;
228
-
229
- /* Output should be safe for jQuery's $() factory? */
230
- var SAFE_FOR_JQUERY = false;
231
-
232
- /* Output should be safe for common template engines.
233
- * This means, DOMPurify removes data attributes, mustaches and ERB
234
- */
235
- var SAFE_FOR_TEMPLATES = false;
236
-
237
- /* Specify template detection regex for SAFE_FOR_TEMPLATES mode */
238
- var MUSTACHE_EXPR = /\{\{[\s\S]*|[\s\S]*\}\}/gm;
239
- var ERB_EXPR = /<%[\s\S]*|[\s\S]*%>/gm;
240
-
241
- /* Decide if document with <html>... should be returned */
242
- var WHOLE_DOCUMENT = false;
243
-
244
- /* Track whether config is already set on this instance of DOMPurify. */
245
- var SET_CONFIG = false;
246
-
247
- /* Decide if all elements (e.g. style, script) must be children of
248
- * document.body. By default, browsers might move them to document.head */
249
- var FORCE_BODY = false;
250
-
251
- /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html string.
252
- * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
253
- */
254
- var RETURN_DOM = false;
255
-
256
- /* Decide if a DOM `DocumentFragment` should be returned, instead of a html string */
257
- var RETURN_DOM_FRAGMENT = false;
258
-
259
- /* If `RETURN_DOM` or `RETURN_DOM_FRAGMENT` is enabled, decide if the returned DOM
260
- * `Node` is imported into the current `Document`. If this flag is not enabled the
261
- * `Node` will belong (its ownerDocument) to a fresh `HTMLDocument`, created by
262
- * DOMPurify. */
263
- var RETURN_DOM_IMPORT = false;
264
-
265
- /* Output should be free from DOM clobbering attacks? */
266
- var SANITIZE_DOM = true;
267
-
268
- /* Keep element content when removing element? */
269
- var KEEP_CONTENT = true;
270
-
271
- /* Tags to ignore content of when KEEP_CONTENT is true */
272
- var FORBID_CONTENTS = _addToSet({}, [
273
- 'audio', 'head', 'math', 'script', 'style', 'template', 'svg', 'video'
274
- ]);
275
-
276
- /* Tags that are safe for data: URIs */
277
- var DATA_URI_TAGS = _addToSet({}, [
278
- 'audio', 'video', 'img', 'source', 'image'
279
- ]);
280
-
281
- /* Attributes safe for values like "javascript:" */
282
- var URI_SAFE_ATTRIBUTES = _addToSet({}, [
283
- 'alt','class','for','id','label','name','pattern','placeholder',
284
- 'summary','title','value','style','xmlns'
285
- ]);
286
-
287
- /* Keep a reference to config to pass to hooks */
288
- var CONFIG = null;
289
-
290
- /* Ideally, do not touch anything below this line */
291
- /* ______________________________________________ */
292
-
293
- var formElement = document.createElement('form');
294
-
295
- /**
296
- * _parseConfig
297
- *
298
- * @param optional config literal
299
- */
300
- var _parseConfig = function(cfg) {
301
- /* Shield configuration object from tampering */
302
- if (typeof cfg !== 'object') {
303
- cfg = {};
304
- }
305
-
306
- /* Set configuration parameters */
307
- ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ?
308
- _addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;
309
- ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ?
310
- _addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;
311
- FORBID_TAGS = 'FORBID_TAGS' in cfg ?
312
- _addToSet({}, cfg.FORBID_TAGS) : {};
313
- FORBID_ATTR = 'FORBID_ATTR' in cfg ?
314
- _addToSet({}, cfg.FORBID_ATTR) : {};
315
- ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
316
- ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
317
- ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
318
- SAFE_FOR_JQUERY = cfg.SAFE_FOR_JQUERY || false; // Default false
319
- SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
320
- WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
321
- RETURN_DOM = cfg.RETURN_DOM || false; // Default false
322
- RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
323
- RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT || false; // Default false
324
- FORCE_BODY = cfg.FORCE_BODY || false; // Default false
325
- SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
326
- KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
327
-
328
- if (SAFE_FOR_TEMPLATES) {
329
- ALLOW_DATA_ATTR = false;
330
- }
331
-
332
- if (RETURN_DOM_FRAGMENT) {
333
- RETURN_DOM = true;
334
- }
335
-
336
- /* Merge configuration parameters */
337
- if (cfg.ADD_TAGS) {
338
- if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {
339
- ALLOWED_TAGS = _cloneObj(ALLOWED_TAGS);
340
- }
341
- _addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);
342
- }
343
- if (cfg.ADD_ATTR) {
344
- if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {
345
- ALLOWED_ATTR = _cloneObj(ALLOWED_ATTR);
346
- }
347
- _addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
348
- }
349
- if (cfg.ADD_URI_SAFE_ATTR) {
350
- _addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
351
- }
352
-
353
- /* Add #text in case KEEP_CONTENT is set to true */
354
- if (KEEP_CONTENT) { ALLOWED_TAGS['#text'] = true; }
355
-
356
- // Prevent further manipulation of configuration.
357
- // Not available in IE8, Safari 5, etc.
358
- if (Object && 'freeze' in Object) { Object.freeze(cfg); }
359
-
360
- CONFIG = cfg;
361
- };
362
-
363
- /**
364
- * _forceRemove
365
- *
366
- * @param a DOM node
367
- */
368
- var _forceRemove = function(node) {
369
- DOMPurify.removed.push({element: node});
370
- try {
371
- node.parentNode.removeChild(node);
372
- } catch (e) {
373
- node.outerHTML = '';
374
- }
375
- };
376
-
377
- /**
378
- * _removeAttribute
379
- *
380
- * @param an Attribute name
381
- * @param a DOM node
382
- */
383
- var _removeAttribute = function(name, node) {
384
- DOMPurify.removed.push({
385
- attribute: node.getAttributeNode(name),
386
- from: node
387
- });
388
- node.removeAttribute(name);
389
- };
390
-
391
- /**
392
- * _initDocument
393
- *
394
- * @param a string of dirty markup
395
- * @return a DOM, filled with the dirty markup
396
- */
397
- var _initDocument = function(dirty) {
398
- /* Create a HTML document */
399
- var doc, body;
400
-
401
- /* Fill body with bogus element */
402
- if (FORCE_BODY) {
403
- dirty = '<remove></remove>' + dirty;
404
- }
405
-
406
- /* Use XHR if necessary because Safari 10.1 and newer are buggy */
407
- if (useXHR) {
408
- try {
409
- dirty = encodeURI(dirty);
410
- } catch (e) {}
411
- var xhr = new XMLHttpRequest();
412
- xhr.responseType = 'document';
413
- xhr.open('GET', 'data:text/html;charset=utf-8,' + dirty, false);
414
- xhr.send(null);
415
- doc = xhr.response;
416
- }
417
-
418
- /* Use DOMParser to workaround Firefox bug (see comment below) */
419
- if (useDOMParser) {
420
- try {
421
- doc = new DOMParser().parseFromString(dirty, 'text/html');
422
- } catch (e) {}
423
- }
424
-
425
- /* Otherwise use createHTMLDocument, because DOMParser is unsafe in
426
- Safari (see comment below) */
427
- if (!doc || !doc.documentElement) {
428
- doc = implementation.createHTMLDocument('');
429
- body = doc.body;
430
- body.parentNode.removeChild(body.parentNode.firstElementChild);
431
- body.outerHTML = dirty;
432
- }
433
-
434
- /* Work on whole document or just its body */
435
- return getElementsByTagName.call(doc,
436
- WHOLE_DOCUMENT ? 'html' : 'body')[0];
437
- };
438
-
439
- // Safari 10.1+ (unfixed as of time of writing) has a catastrophic bug in
440
- // its implementation of DOMParser such that the following executes the
441
- // JavaScript:
442
- //
443
- // new DOMParser()
444
- // .parseFromString('<svg onload=alert(document.domain)>', 'text/html');
445
- //
446
- // Later, it was also noticed that even more assumed benign and inert ways
447
- // of creating a document are now insecure thanks to Safari. So we work
448
- // around that with a feature test and use XHR to create the document in
449
- // case we really have to. That one seems safe for now.
450
- //
451
- // However, Firefox uses a different parser for innerHTML rather than
452
- // DOMParser (see https://bugzilla.mozilla.org/show_bug.cgi?id=1205631)
453
- // which means that you *must* use DOMParser, otherwise the output may
454
- // not be safe if used in a document.write context later.
455
- //
456
- // So we feature detect the Firefox bug and use the DOMParser if necessary.
457
- if (DOMPurify.isSupported) {
458
- (function () {
459
- var doc = _initDocument('<svg><g onload="this.parentNode.remove()"></g></svg>');
460
- if (!doc.querySelector('svg')) {
461
- useXHR = true;
462
- }
463
- doc = _initDocument('<svg><p><style><img src="</style><img src=x onerror=alert(1)//">');
464
- if (doc.querySelector('svg img')) {
465
- useDOMParser = true;
466
- }
467
- }());
468
- }
469
-
470
- /**
471
- * _createIterator
472
- *
473
- * @param document/fragment to create iterator for
474
- * @return iterator instance
475
- */
476
- var _createIterator = function(root) {
477
- return createNodeIterator.call(root.ownerDocument || root,
478
- root,
479
- NodeFilter.SHOW_ELEMENT
480
- | NodeFilter.SHOW_COMMENT
481
- | NodeFilter.SHOW_TEXT,
482
- function() { return NodeFilter.FILTER_ACCEPT; },
483
- false
484
- );
485
- };
486
-
487
- /**
488
- * _isClobbered
489
- *
490
- * @param element to check for clobbering attacks
491
- * @return true if clobbered, false if safe
492
- */
493
- var _isClobbered = function(elm) {
494
- if (elm instanceof Text || elm instanceof Comment) {
495
- return false;
496
- }
497
- if ( typeof elm.nodeName !== 'string'
498
- || typeof elm.textContent !== 'string'
499
- || typeof elm.removeChild !== 'function'
500
- || !(elm.attributes instanceof NamedNodeMap)
501
- || typeof elm.removeAttribute !== 'function'
502
- || typeof elm.setAttribute !== 'function'
503
- ) {
504
- return true;
505
- }
506
- return false;
507
- };
508
-
509
- /**
510
- * _isNode
511
- *
512
- * @param object to check whether it's a DOM node
513
- * @return true is object is a DOM node
514
- */
515
- var _isNode = function(obj) {
516
- return (
517
- typeof Node === "object" ? obj instanceof Node : obj
518
- && typeof obj === "object" && typeof obj.nodeType === "number"
519
- && typeof obj.nodeName==="string"
520
- );
521
- };
522
-
523
- /**
524
- * _sanitizeElements
525
- *
526
- * @protect nodeName
527
- * @protect textContent
528
- * @protect removeChild
529
- *
530
- * @param node to check for permission to exist
531
- * @return true if node was killed, false if left alive
532
- */
533
- var _sanitizeElements = function(currentNode) {
534
- var tagName, content;
535
-
536
- /* Execute a hook if present */
537
- _executeHook('beforeSanitizeElements', currentNode, null);
538
-
539
- /* Check if element is clobbered or can clobber */
540
- if (_isClobbered(currentNode)) {
541
- _forceRemove(currentNode);
542
- return true;
543
- }
544
-
545
- /* Now let's check the element's type and name */
546
- tagName = currentNode.nodeName.toLowerCase();
547
-
548
- /* Execute a hook if present */
549
- _executeHook('uponSanitizeElement', currentNode, {
550
- tagName: tagName,
551
- allowedTags: ALLOWED_TAGS
552
- });
553
-
554
- /* Remove element if anything forbids its presence */
555
- if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
556
- /* Keep content except for black-listed elements */
557
- if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]
558
- && typeof currentNode.insertAdjacentHTML === 'function') {
559
- try {
560
- currentNode.insertAdjacentHTML('AfterEnd', currentNode.innerHTML);
561
- } catch (e) {}
562
- }
563
- _forceRemove(currentNode);
564
- return true;
565
- }
566
-
567
- /* Convert markup to cover jQuery behavior */
568
- if (SAFE_FOR_JQUERY && !currentNode.firstElementChild &&
569
- (!currentNode.content || !currentNode.content.firstElementChild) &&
570
- /</g.test(currentNode.textContent)) {
571
- DOMPurify.removed.push({element: currentNode.cloneNode()});
572
- currentNode.innerHTML = currentNode.textContent.replace(/</g, '&lt;');
573
- }
574
-
575
- /* Sanitize element content to be template-safe */
576
- if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
577
- /* Get the element's text content */
578
- content = currentNode.textContent;
579
- content = content.replace(MUSTACHE_EXPR, ' ');
580
- content = content.replace(ERB_EXPR, ' ');
581
- if (currentNode.textContent !== content) {
582
- DOMPurify.removed.push({element: currentNode.cloneNode()});
583
- currentNode.textContent = content;
584
- }
585
- }
586
-
587
- /* Execute a hook if present */
588
- _executeHook('afterSanitizeElements', currentNode, null);
589
-
590
- return false;
591
- };
592
-
593
- var DATA_ATTR = /^data-[\-\w.\u00B7-\uFFFF]/;
594
- var ARIA_ATTR = /^aria-[\-\w]+$/;
595
- var IS_ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
596
- var IS_SCRIPT_OR_DATA = /^(?:\w+script|data):/i;
597
- /* This needs to be extensive thanks to Webkit/Blink's behavior */
598
- var ATTR_WHITESPACE = /[\x00-\x20\xA0\u1680\u180E\u2000-\u2029\u205f\u3000]/g;
599
-
600
- /**
601
- * _sanitizeAttributes
602
- *
603
- * @protect attributes
604
- * @protect nodeName
605
- * @protect removeAttribute
606
- * @protect setAttribute
607
- *
608
- * @param node to sanitize
609
- * @return void
610
- */
611
- var _sanitizeAttributes = function(currentNode) {
612
- var attr, name, value, lcName, idAttr, attributes, hookEvent, l;
613
- /* Execute a hook if present */
614
- _executeHook('beforeSanitizeAttributes', currentNode, null);
615
-
616
- attributes = currentNode.attributes;
617
-
618
- /* Check if we have attributes; if not we might have a text node */
619
- if (!attributes) { return; }
620
-
621
- hookEvent = {
622
- attrName: '',
623
- attrValue: '',
624
- keepAttr: true,
625
- allowedAttributes: ALLOWED_ATTR
626
- };
627
- l = attributes.length;
628
-
629
- /* Go backwards over all attributes; safely remove bad ones */
630
- while (l--) {
631
- attr = attributes[l];
632
- name = attr.name;
633
- value = attr.value.trim();
634
- lcName = name.toLowerCase();
635
-
636
- /* Execute a hook if present */
637
- hookEvent.attrName = lcName;
638
- hookEvent.attrValue = value;
639
- hookEvent.keepAttr = true;
640
- _executeHook('uponSanitizeAttribute', currentNode, hookEvent );
641
- value = hookEvent.attrValue;
642
-
643
- /* Remove attribute */
644
- // Safari (iOS + Mac), last tested v8.0.5, crashes if you try to
645
- // remove a "name" attribute from an <img> tag that has an "id"
646
- // attribute at the time.
647
- if (lcName === 'name' &&
648
- currentNode.nodeName === 'IMG' && attributes.id) {
649
- idAttr = attributes.id;
650
- attributes = Array.prototype.slice.apply(attributes);
651
- _removeAttribute('id', currentNode);
652
- _removeAttribute(name, currentNode);
653
- if (attributes.indexOf(idAttr) > l) {
654
- currentNode.setAttribute('id', idAttr.value);
655
- }
656
- } else if (
657
- // This works around a bug in Safari, where input[type=file]
658
- // cannot be dynamically set after type has been removed
659
- currentNode.nodeName === 'INPUT' && lcName === 'type' &&
660
- value === 'file' && (ALLOWED_ATTR[lcName] || !FORBID_ATTR[lcName])) {
661
- continue;
662
- } else {
663
- // This avoids a crash in Safari v9.0 with double-ids.
664
- // The trick is to first set the id to be empty and then to
665
- // remove the attribute
666
- if (name === 'id') {
667
- currentNode.setAttribute(name, '');
668
- }
669
- _removeAttribute(name, currentNode);
670
- }
671
-
672
- /* Did the hooks approve of the attribute? */
673
- if (!hookEvent.keepAttr) {
674
- continue;
675
- }
676
-
677
- /* Make sure attribute cannot clobber */
678
- if (SANITIZE_DOM &&
679
- (lcName === 'id' || lcName === 'name') &&
680
- (value in window || value in document || value in formElement)) {
681
- continue;
682
- }
683
-
684
- /* Sanitize attribute content to be template-safe */
685
- if (SAFE_FOR_TEMPLATES) {
686
- value = value.replace(MUSTACHE_EXPR, ' ');
687
- value = value.replace(ERB_EXPR, ' ');
688
- }
689
-
690
- /* Allow valid data-* attributes: At least one character after "-"
691
- (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
692
- XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
693
- We don't need to check the value; it's always URI safe. */
694
- if (ALLOW_DATA_ATTR && DATA_ATTR.test(lcName)) {
695
- // This attribute is safe
696
- }
697
- else if (ALLOW_ARIA_ATTR && ARIA_ATTR.test(lcName)) {
698
- // This attribute is safe
699
- }
700
- /* Otherwise, check the name is permitted */
701
- else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
702
- continue;
703
- }
704
- /* Check value is safe. First, is attr inert? If so, is safe */
705
- else if (URI_SAFE_ATTRIBUTES[lcName]) {
706
- // This attribute is safe
707
- }
708
- /* Check no script, data or unknown possibly unsafe URI
709
- unless we know URI values are safe for that attribute */
710
- else if (IS_ALLOWED_URI.test(value.replace(ATTR_WHITESPACE,''))) {
711
- // This attribute is safe
712
- }
713
- /* Keep image data URIs alive if src/xlink:href is allowed */
714
- else if (
715
- (lcName === 'src' || lcName === 'xlink:href') &&
716
- value.indexOf('data:') === 0 &&
717
- DATA_URI_TAGS[currentNode.nodeName.toLowerCase()]) {
718
- // This attribute is safe
719
- }
720
- /* Allow unknown protocols: This provides support for links that
721
- are handled by protocol handlers which may be unknown ahead of
722
- time, e.g. fb:, spotify: */
723
- else if (
724
- ALLOW_UNKNOWN_PROTOCOLS &&
725
- !IS_SCRIPT_OR_DATA.test(value.replace(ATTR_WHITESPACE,''))) {
726
- // This attribute is safe
727
- }
728
- /* Check for binary attributes */
729
- else if (!value) {
730
- // binary attributes are safe at this point
731
- }
732
- /* Anything else, presume unsafe, do not add it back */
733
- else {
734
- continue;
735
- }
736
-
737
- /* Handle invalid data-* attribute set by try-catching it */
738
- try {
739
- currentNode.setAttribute(name, value);
740
- DOMPurify.removed.pop();
741
- } catch (e) {}
742
- }
743
-
744
- /* Execute a hook if present */
745
- _executeHook('afterSanitizeAttributes', currentNode, null);
746
- };
747
-
748
- /**
749
- * _sanitizeShadowDOM
750
- *
751
- * @param fragment to iterate over recursively
752
- * @return void
753
- */
754
- var _sanitizeShadowDOM = function(fragment) {
755
- var shadowNode;
756
- var shadowIterator = _createIterator(fragment);
757
-
758
- /* Execute a hook if present */
759
- _executeHook('beforeSanitizeShadowDOM', fragment, null);
760
-
761
- while ( (shadowNode = shadowIterator.nextNode()) ) {
762
- /* Execute a hook if present */
763
- _executeHook('uponSanitizeShadowNode', shadowNode, null);
764
-
765
- /* Sanitize tags and elements */
766
- if (_sanitizeElements(shadowNode)) {
767
- continue;
768
- }
769
-
770
- /* Deep shadow DOM detected */
771
- if (shadowNode.content instanceof DocumentFragment) {
772
- _sanitizeShadowDOM(shadowNode.content);
773
- }
774
-
775
- /* Check attributes, sanitize if necessary */
776
- _sanitizeAttributes(shadowNode);
777
- }
778
-
779
- /* Execute a hook if present */
780
- _executeHook('afterSanitizeShadowDOM', fragment, null);
781
- };
782
-
783
- /**
784
- * _executeHook
785
- * Execute user configurable hooks
786
- *
787
- * @param {String} entryPoint Name of the hook's entry point
788
- * @param {Node} currentNode
789
- */
790
- var _executeHook = function(entryPoint, currentNode, data) {
791
- if (!hooks[entryPoint]) { return; }
792
-
793
- hooks[entryPoint].forEach(function(hook) {
794
- hook.call(DOMPurify, currentNode, data, CONFIG);
795
- });
796
- };
797
-
798
- /**
799
- * sanitize
800
- * Public method providing core sanitation functionality
801
- *
802
- * @param {String|Node} dirty string or DOM node
803
- * @param {Object} configuration object
804
- */
805
- DOMPurify.sanitize = function(dirty, cfg) {
806
- var body, importedNode, currentNode, oldNode, nodeIterator, returnNode;
807
- /* Make sure we have a string to sanitize.
808
- DO NOT return early, as this will return the wrong type if
809
- the user has requested a DOM object rather than a string */
810
- if (!dirty) {
811
- dirty = '<!-->';
812
- }
813
-
814
- /* Stringify, in case dirty is an object */
815
- if (typeof dirty !== 'string' && !_isNode(dirty)) {
816
- if (typeof dirty.toString !== 'function') {
817
- throw new TypeError('toString is not a function');
818
- } else {
819
- dirty = dirty.toString();
820
- }
821
- }
822
-
823
- /* Check we can run. Otherwise fall back or ignore */
824
- if (!DOMPurify.isSupported) {
825
- if (typeof window.toStaticHTML === 'object'
826
- || typeof window.toStaticHTML === 'function') {
827
- if (typeof dirty === 'string') {
828
- return window.toStaticHTML(dirty);
829
- } else if (_isNode(dirty)) {
830
- return window.toStaticHTML(dirty.outerHTML);
831
- }
832
- }
833
- return dirty;
834
- }
835
-
836
- /* Assign config vars */
837
- if (!SET_CONFIG) {
838
- _parseConfig(cfg);
839
- }
840
-
841
- /* Clean up removed elements */
842
- DOMPurify.removed = [];
843
-
844
- if (dirty instanceof Node) {
845
- /* If dirty is a DOM element, append to an empty document to avoid
846
- elements being stripped by the parser */
847
- body = _initDocument('<!-->');
848
- importedNode = body.ownerDocument.importNode(dirty, true);
849
- if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
850
- /* Node is already a body, use as is */
851
- body = importedNode;
852
- } else {
853
- body.appendChild(importedNode);
854
- }
855
- } else {
856
- /* Exit directly if we have nothing to do */
857
- if (!RETURN_DOM && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) {
858
- return dirty;
859
- }
860
-
861
- /* Initialize the document to work on */
862
- body = _initDocument(dirty);
863
-
864
- /* Check we have a DOM node from the data */
865
- if (!body) {
866
- return RETURN_DOM ? null : '';
867
- }
868
- }
869
-
870
- /* Remove first element node (ours) if FORCE_BODY is set */
871
- if (FORCE_BODY) {
872
- _forceRemove(body.firstChild);
873
- }
874
-
875
- /* Get node iterator */
876
- nodeIterator = _createIterator(body);
877
-
878
- /* Now start iterating over the created document */
879
- while ( (currentNode = nodeIterator.nextNode()) ) {
880
-
881
- /* Fix IE's strange behavior with manipulated textNodes #89 */
882
- if (currentNode.nodeType === 3 && currentNode === oldNode) {
883
- continue;
884
- }
885
-
886
- /* Sanitize tags and elements */
887
- if (_sanitizeElements(currentNode)) {
888
- continue;
889
- }
890
-
891
- /* Shadow DOM detected, sanitize it */
892
- if (currentNode.content instanceof DocumentFragment) {
893
- _sanitizeShadowDOM(currentNode.content);
894
- }
895
-
896
- /* Check attributes, sanitize if necessary */
897
- _sanitizeAttributes(currentNode);
898
-
899
- oldNode = currentNode;
900
- }
901
-
902
- /* Return sanitized string or DOM */
903
- if (RETURN_DOM) {
904
-
905
- if (RETURN_DOM_FRAGMENT) {
906
- returnNode = createDocumentFragment.call(body.ownerDocument);
907
-
908
- while (body.firstChild) {
909
- returnNode.appendChild(body.firstChild);
910
- }
911
- } else {
912
- returnNode = body;
913
- }
914
-
915
- if (RETURN_DOM_IMPORT) {
916
- /* adoptNode() is not used because internal state is not reset
917
- (e.g. the past names map of a HTMLFormElement), this is safe
918
- in theory but we would rather not risk another attack vector.
919
- The state that is cloned by importNode() is explicitly defined
920
- by the specs. */
921
- returnNode = importNode.call(originalDocument, returnNode, true);
922
- }
923
-
924
- return returnNode;
925
- }
926
-
927
- return WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;
928
- };
929
-
930
- /**
931
- * setConfig
932
- * Public method to set the configuration once
933
- *
934
- * @param {Object} configuration object
935
- * @return void
936
- */
937
- DOMPurify.setConfig = function(cfg) {
938
- _parseConfig(cfg);
939
- SET_CONFIG = true;
940
- };
941
-
942
- /**
943
- * clearConfig
944
- * Public method to remove the configuration
945
- *
946
- * @return void
947
- */
948
- DOMPurify.clearConfig = function() {
949
- CONFIG = null;
950
- SET_CONFIG = false;
951
- };
952
-
953
- /**
954
- * addHook
955
- * Public method to add DOMPurify hooks
956
- *
957
- * @param {String} entryPoint
958
- * @param {Function} hookFunction
959
- */
960
- DOMPurify.addHook = function(entryPoint, hookFunction) {
961
- if (typeof hookFunction !== 'function') { return; }
962
- hooks[entryPoint] = hooks[entryPoint] || [];
963
- hooks[entryPoint].push(hookFunction);
964
- };
965
-
966
- /**
967
- * removeHook
968
- * Public method to remove a DOMPurify hook at a given entryPoint
969
- * (pops it from the stack of hooks if more are present)
970
- *
971
- * @param {String} entryPoint
972
- * @return void
973
- */
974
- DOMPurify.removeHook = function(entryPoint) {
975
- if (hooks[entryPoint]) {
976
- hooks[entryPoint].pop();
977
- }
978
- };
979
-
980
- /**
981
- * removeHooks
982
- * Public method to remove all DOMPurify hooks at a given entryPoint
983
- *
984
- * @param {String} entryPoint
985
- * @return void
986
- */
987
- DOMPurify.removeHooks = function(entryPoint) {
988
- if (hooks[entryPoint]) {
989
- hooks[entryPoint] = [];
990
- }
991
- };
992
-
993
- /**
994
- * removeAllHooks
995
- * Public method to remove all DOMPurify hooks
996
- *
997
- * @return void
998
- */
999
- DOMPurify.removeAllHooks = function() {
1000
- hooks = {};
1001
- };
1002
-
1003
- return DOMPurify;
1004
- }));