UNPKG

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