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