Merge pull request #249 from nextcloud/bump-js-libs

[stable10] Bump to newest DOMPurify release
This commit is contained in:
Morris Jobke 2017-04-21 15:44:47 -05:00 committed by GitHub
commit 8a5d586efc
3 changed files with 277 additions and 98 deletions

View File

@ -18,7 +18,7 @@
"dependencies": {
"eventsource-polyfill": "~0.*",
"github-markdown-css": "~2.*",
"dompurify": "~0.7.0",
"dompurify": "~0.8.0",
"commonmark": "~0.22.0"
}
}

View File

@ -1,4 +1,4 @@
# DOMPurify [![Bower version](https://badge.fury.io/bo/dompurify.svg)](http://badge.fury.io/bo/dompurify) · [![npm version](https://badge.fury.io/js/dompurify.svg)](http://badge.fury.io/js/dompurify) · [![Build Status](https://travis-ci.org/cure53/DOMPurify.svg?branch=master)](https://travis-ci.org/cure53/DOMPurify)
# DOMPurify [![Bower version](https://badge.fury.io/bo/dompurify.svg)](http://badge.fury.io/bo/dompurify) · [![npm version](https://badge.fury.io/js/dompurify.svg)](http://badge.fury.io/js/dompurify) · [![Build Status](https://travis-ci.org/cure53/DOMPurify.svg)](https://travis-ci.org/cure53/DOMPurify) · [![Downloads](https://img.shields.io/npm/dm/dompurify.svg)](https://www.npmjs.com/package/dompurify)
[![NPM](https://nodei.co/npm/dompurify.png)](https://nodei.co/npm/dompurify/)
@ -6,7 +6,9 @@ DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathM
It's also very simple to use and get started with.
DOMPurify is written in JavaScript and works in all modern browsers (Safari, Opera (15+), Internet Explorer (10+), Edge, Firefox and Chrome - as well as almost anything else using Blink or WebKit). It doesn't break on IE6 or other legacy browsers. It simply does nothing there. Our automated tests cover [9 different browsers](https://github.com/cure53/DOMPurify/blob/master/test/karma.conf.js#L125) right now.
DOMPurify is written in JavaScript and works in all modern browsers (Safari, Opera (15+), Internet Explorer (10+), Edge, Firefox and Chrome - as well as almost anything else using Blink or WebKit). It doesn't break on IE6 or other legacy browsers. It either uses [a fall-back](#what-about-older-browsers-like-msie8) or simply does nothing.
Our automated tests cover [12 different browsers](https://github.com/cure53/DOMPurify/blob/master/test/karma.conf.js#L153) right now. We also cover Node.js v4.0.0, v5.0.0 and v6.0.0, running DOMPurify on [jsdom](https://github.com/tmpvar/jsdom).
DOMPurify is written by security people who have vast background in web attacks and XSS. Fear not. For more details please also read about our [Security Goals & Threat Model](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model)
@ -38,6 +40,8 @@ var clean = DOMPurify.sanitize(dirty);
The resulting HTML can be written into a DOM element using `innerHTML` or the DOM using `document.write()`. That is fully up to you. But keep in mind, if you use the sanitized HTML with jQuery's very insecure `elm.html()` method, then the `SAFE_FOR_JQUERY` flag has to be set to make sure it's safe! Other than that, all is fine.
After sanitizing your markup, you can also have a look at the property `DOMPurify.removed` and find out, what elements and attributes were thrown out.
If you're using an [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) module loader like [Require.js](http://requirejs.org/), you can load this script asynchronously as well:
```javascript
@ -46,17 +50,28 @@ require(['dompurify'], function(DOMPurify) {
});
```
You can also grab the files straight from npm (requires either [io.js](https://iojs.org) or [Browserify](http://browserify.org/), **Node.js 0.x is not supported**):
DOMPurify also works server-side with node.js as well as client-side via [Browserify](http://browserify.org/) or similar translators. Node.js 0.x is not supported; either [io.js](https://iojs.org) or Node.js 4.x or newer is required.
```bash
npm install dompurify
```
```javascript
var DOMPurify = require('dompurify');
var clean = DOMPurify.sanitize(dirty);
const createDOMPurify = require('dompurify');
const jsdom = require('jsdom');
const window = jsdom.jsdom('', {
features: {
FetchExternalResources: false, // disables resource loading over HTTP / filesystem
ProcessExternalResources: false // do not execute JS within script blocks
}
}).defaultView;
const DOMPurify = createDOMPurify(window);
const clean = DOMPurify.sanitize(dirty);
```
Strictly speaking, DOMPurify creates a document without a browsing context and you can replace it with `const window = jsdom.jsdom().defaultView;`, however, the longer case protects against accidental bugs in jsdom or DOMPurify.
## Is there a demo?
Of course there is a demo! [Play with DOMPurify](https://cure53.de/purify)
@ -82,6 +97,11 @@ DOMPurify.sanitize('<UL><li><A HREF=//google.com>click</UL>'); // becomes <ul><l
DOMPurify currently supports HTML5, SVG and MathML. DOMPurify per default allows CSS, HTML custom data attributes. DOMPurify also supports the Shadow DOM - and sanitizes DOM templates recursively. DOMPurify also allows you to sanitize HTML for being used with the jQuery `$()` and `elm.html()` methods but requires the `SAFE_FOR_JQUERY` flag for that - see below.
## What about older browsers like MSIE8?
DOMPurify offers a fall-back behavior for older MSIE browsers. It uses the MSIE-only `toStaticHTML` feature to sanitize. Note however that in this fall-back mode, pretty much none of the configuration flags shown below have any effect. You need to handle that yourself.
If not even `toStaticHTML` is supported, DOMPurify does nothing at all. It simply returns exactly the string that you fed it.
## Can I configure it?
@ -115,6 +135,10 @@ var clean = DOMPurify.sanitize(dirty, {ADD_ATTR: ['my-attr']});
// prohibit HTML5 data attributes (default is true)
var clean = DOMPurify.sanitize(dirty, {ALLOW_DATA_ATTR: false});
// allow external protocol handlers in URL attributes (default is false)
// by default only http, https, ftp, ftps, tel and mailto are allowed.
var clean = DOMPurify.sanitize(dirty, {ALLOW_UNKNOWN_PROTOCOLS: true});
// return a DOM HTMLBodyElement instead of an HTML string (default is false)
var clean = DOMPurify.sanitize(dirty, {RETURN_DOM: true});
@ -136,8 +160,11 @@ var clean = DOMPurify.sanitize(dirty, {SANITIZE_DOM: false});
// discard an element's content when the element is removed (default is true)
var clean = DOMPurify.sanitize(dirty, {KEEP_CONTENT: false});
// glue elements like style, script or others to document.body and prevent unintuitive browser behavior in several edge-cases (default is false)
var clean = DOMPurify.sanitize(dirty, {FORCE_BODY: true});
```
There is even [more examples here](https://github.com/cure53/DOMPurify/tree/master/demos#what-it-this), showing how you can run, customize and configure DOMPurify to fit your needs.
There is even [more examples here](https://github.com/cure53/DOMPurify/tree/master/demos#what-is-this), showing how you can run, customize and configure DOMPurify to fit your needs.
## Hooks
@ -168,7 +195,9 @@ DOMPurify.addHook('beforeSanitizeElements', function(currentNode, data, config)
We are currently using Travis CI in combination with BrowserStack. This gives us the possibility to confirm for each and every commit that all is going according to plan in all supported browsers. Check out the build logs here: https://travis-ci.org/cure53/DOMPurify
You can further run local tests by executing `npm run-script local-test` or, in case you have a BrowserStack account with automation available, run the tests using `npm run-script ci-test`.
You can further run local tests by executing `npm test`. The tests work fine with Node.js v0.6.2 and jsdom@8.5.0.
All relevant commits will be signed with the key `0x24BB6BF4` for additional security (since 8th of April 2016).
## Security Mailing List
@ -176,15 +205,18 @@ We maintain a mailing list that notifies whenever a security-critical release of
[https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-security](https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-security)
## What's on the road-map?
We recently implemented a Hook-API allowing developers to create their own DOMPurify plugins and customize its functionality without changing the core. Thus, we are looking forward for plugins and extensions - pull requests are welcome! Oh, and we will increase the amount of browsers and HTML-mappings in our automates tests to make sure nothing slips through.
Feature releases will not be announced to this list.
## Who contributed?
Several people need to be listed here! [@garethheyes](https://twitter.com/garethheyes) for invaluable help, [@shafigullin](https://twitter.com/shafigullin) for breaking the library multiple times and thereby strengthening it, [@mmrupp](https://twitter.com/mmrupp) and [@irsdl](https://twitter.com/irsdl) for doing the same.
Several people need to be listed here!
Big thanks also go to [@asutherland](https://twitter.com/asutherland), [@mathias](https://twitter.com/mathias), [@cgvwzq](https://twitter.com/cgvwzq), [@robbertatwork](https://twitter.com/robbertatwork), [@giutro](https://twitter.com/giutro) and [@fhemberger](https://twitter.com/fhemberger)! Further, thanks [@neilj](https://twitter.com/neilj) for his code review and countless small optimizations, fixes and beautifications. Big thanks also go to [@tdeekens](https://twitter.com/tdeekens) for doing all the hard work and getting us on track with Travis CI and BrowserStack.
[@garethheyes](https://twitter.com/garethheyes) and [@filedescriptor](https://twitter.com/filedescriptor) for invaluable help, [@shafigullin](https://twitter.com/shafigullin) for breaking the library multiple times and thereby strengthening it, [@mmrupp](https://twitter.com/mmrupp) and [@irsdl](https://twitter.com/irsdl) for doing the same.
Big thanks also go to [@asutherland](https://twitter.com/asutherland), [@mathias](https://twitter.com/mathias), [@cgvwzq](https://twitter.com/cgvwzq), [@robbertatwork](https://twitter.com/robbertatwork), [@giutro](https://twitter.com/giutro) and [@fhemberger](https://twitter.com/fhemberger)!
Further, thanks [@neilj](https://twitter.com/neilj) and [@0xsobky](https://twitter.com/0xsobky) for their code reviews and countless small optimizations, fixes and beautifications.
Big thanks also go to [@tdeekens](https://twitter.com/tdeekens) for doing all the hard work and getting us on track with Travis CI and BrowserStack. And thanks to [@Joris-van-der-Wel](https://github.com/Joris-van-der-Wel) for setting up DOMPurify for jsdom and creating the additional test suite.
And last but not least, thanks to [BrowserStack](https://browserstack.com) for supporting this project with their services for free and delivering excellent, dedicated and very professional support on top of that.

View File

@ -21,7 +21,13 @@
* Version label, exposed for easier checks
* if DOMPurify is up to date or not
*/
DOMPurify.version = '0.7.3';
DOMPurify.version = '0.8.6';
/**
* Array of elements that DOMPurify removed during sanitation.
* Empty if nothing was removed.
*/
DOMPurify.removed = [];
if (!window || !window.document || window.document.nodeType !== 9) {
// not running in a browser, provide a factory function
@ -34,11 +40,11 @@
var originalDocument = document;
var DocumentFragment = window.DocumentFragment;
var HTMLTemplateElement = window.HTMLTemplateElement;
var Node = window.Node;
var NodeFilter = window.NodeFilter;
var NamedNodeMap = window.NamedNodeMap || window.MozNamedAttrMap;
var Text = window.Text;
var Comment = window.Comment;
var DOMParser = window.DOMParser;
// As per issue #47, the web-components registry is inherited by a
// new document created via createHTMLDocument. As per the spec
@ -47,7 +53,10 @@
// document, so we use that as our parent document to ensure nothing
// is inherited.
if (typeof HTMLTemplateElement === 'function') {
document = document.createElement('template').content.ownerDocument;
var template = document.createElement('template');
if (template.content && template.content.ownerDocument) {
document = template.content.ownerDocument;
}
}
var implementation = document.implementation;
var createNodeIterator = document.createNodeIterator;
@ -68,6 +77,9 @@
var _addToSet = function(set, array) {
var l = array.length;
while (l--) {
if (typeof array[l] === 'string') {
array[l] = array[l].toLowerCase();
}
set[array[l]] = true;
}
return set;
@ -112,7 +124,7 @@
// SVG
'svg','altglyph','altglyphdef','altglyphitem','animatecolor',
'animatemotion','animatetransform','circle','clippath','defs','desc',
'ellipse','font','g','glyph','glyphref','hkern','image','line',
'ellipse','filter','font','g','glyph','glyphref','hkern','image','line',
'lineargradient','marker','mask','metadata','mpath','path','pattern',
'polygon','polyline','radialgradient','rect','stop','switch','symbol',
'text','textpath','title','tref','tspan','view','vkern',
@ -121,7 +133,7 @@
'feBlend','feColorMatrix','feComponentTransfer','feComposite',
'feConvolveMatrix','feDiffuseLighting','feDisplacementMap',
'feFlood','feFuncA','feFuncB','feFuncG','feFuncR','feGaussianBlur',
'feImage','feMerge','feMergeNode','feMorphology','feOffset',
'feMerge','feMergeNode','feMorphology','feOffset',
'feSpecularLighting','feTile','feTurbulence',
//MathML
@ -146,7 +158,7 @@
'hreflang','id','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','rows',
'radiogroup','readonly','rel','required','rev','reversed','role','rows',
'rowspan','spellcheck','scope','selected','shape','size','span',
'srclang','start','src','step','style','summary','tabindex','title',
'type','usemap','valign','value','width','xmlns',
@ -169,9 +181,9 @@
'opacity','order','orient','orientation','origin','overflow','paint-order',
'path','pathlength','patterncontentunits','patterntransform','patternunits',
'points','preservealpha','r','rx','ry','radius','refx','refy','repeatcount',
'repeatdur','restart','rotate','scale','seed','shape-rendering','specularconstant',
'specularexponent','spreadmethod','stddeviation','stitchtiles','stop-color',
'stop-opacity','stroke-dasharray','stroke-dashoffset','stroke-linecap',
'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',
'surfacescale','targetx','targety','transform','text-anchor','text-decoration',
'text-rendering','textlength','u1','u2','unicode','values','viewbox',
@ -200,9 +212,15 @@
/* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */
var FORBID_ATTR = null;
/* Decide if ARIA attributes are okay */
var ALLOW_ARIA_ATTR = true;
/* Decide if custom data attributes are okay */
var ALLOW_DATA_ATTR = true;
/* Decide if unknown protocols are okay */
var ALLOW_UNKNOWN_PROTOCOLS = false;
/* Output should be safe for jQuery's $() factory? */
var SAFE_FOR_JQUERY = false;
@ -211,9 +229,17 @@
*/
var SAFE_FOR_TEMPLATES = false;
/* Specify template detection regex for SAFE_FOR_TEMPLATES mode */
var MUSTACHE_EXPR = /\{\{[\s\S]*|[\s\S]*\}\}/gm;
var ERB_EXPR = /<%[\s\S]*|[\s\S]*%>/gm;
/* Decide if document with <html>... should be returned */
var WHOLE_DOCUMENT = false;
/* Decide if all elements (e.g. style, script) must be children of
* document.body. By default, browsers might move them to document.head */
var FORCE_BODY = false;
/* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html string.
* If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead
*/
@ -239,6 +265,17 @@
'audio', 'head', 'math', 'script', 'style', 'svg', 'video'
]);
/* Tags that are safe for data: URIs */
var DATA_URI_TAGS = _addToSet({}, [
'audio', 'video', 'img', 'source', 'image'
]);
/* Attributes safe for values like "javascript:" */
var URI_SAFE_ATTRIBUTES = _addToSet({}, [
'alt','class','for','id','label','name','pattern','placeholder',
'summary','title','value','style','xmlns'
]);
/* Keep a reference to config to pass to hooks */
var CONFIG = null;
@ -267,16 +304,23 @@
_addToSet({}, cfg.FORBID_TAGS) : {};
FORBID_ATTR = 'FORBID_ATTR' in cfg ?
_addToSet({}, cfg.FORBID_ATTR) : {};
ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true
ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true
ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false
SAFE_FOR_JQUERY = cfg.SAFE_FOR_JQUERY || false; // Default false
SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false
WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false
RETURN_DOM = cfg.RETURN_DOM || false; // Default false
RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false
RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT || false; // Default false
FORCE_BODY = cfg.FORCE_BODY || false; // Default false
SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true
KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true
if (SAFE_FOR_TEMPLATES) {
ALLOW_DATA_ATTR = false;
}
if (RETURN_DOM_FRAGMENT) {
RETURN_DOM = true;
}
@ -294,6 +338,9 @@
}
_addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);
}
if (cfg.ADD_URI_SAFE_ATTR) {
_addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);
}
/* Add #text in case KEEP_CONTENT is set to true */
if (KEEP_CONTENT) { ALLOWED_TAGS['#text'] = true; }
@ -311,6 +358,7 @@
* @param a DOM node
*/
var _forceRemove = function(node) {
DOMPurify.removed.push({element: node});
try {
node.parentNode.removeChild(node);
} catch (e) {
@ -318,6 +366,20 @@
}
};
/**
* _removeAttribute
*
* @param an Attribute name
* @param a DOM node
*/
var _removeAttribute = function(name, node) {
DOMPurify.removed.push({
attribute: node.getAttributeNode(name),
from: node
});
node.removeAttribute(name);
};
/**
* _initDocument
*
@ -325,15 +387,14 @@
* @return a DOM, filled with the dirty markup
*/
var _initDocument = function(dirty) {
/* Create a HTML document using DOMParser */
/* Create a HTML document */
var doc, body;
try {
doc = new DOMParser().parseFromString(dirty, 'text/html');
} catch (e) {}
if (FORCE_BODY) {
dirty = '<remove></remove>' + dirty;
}
/* Some browsers throw, some browsers return null for the code above
DOMParser with text/html support is only in very recent browsers. */
if (!doc){
if (!doc || !doc.documentElement) {
doc = implementation.createHTMLDocument('');
body = doc.body;
body.parentNode.removeChild(body.parentNode.firstElementChild);
@ -341,13 +402,12 @@
}
/* Work on whole document or just its body */
if (typeof doc.getElementsByTagName === 'function'){
if (typeof doc.getElementsByTagName === 'function') {
return doc.getElementsByTagName(
WHOLE_DOCUMENT ? 'html' : 'body')[0];
} else {
return getElementsByTagName.call(doc,
WHOLE_DOCUMENT ? 'html' : 'body')[0];
}
return getElementsByTagName.call(doc,
WHOLE_DOCUMENT ? 'html' : 'body')[0];
};
/**
@ -389,8 +449,19 @@
return false;
};
var MUSTACHE_EXPR = /\{\{.*|.*\}\}/gm;
var ERB_EXPR = /<%.*|.*%>/gm;
/**
* _isNode
*
* @param object to check whether it's a DOM node
* @return true is object is a DOM node
*/
var _isNode = function(obj) {
return (
typeof Node === "object" ? obj instanceof Node : obj
&& typeof obj === "object" && typeof obj.nodeType === "number"
&& typeof obj.nodeName==="string"
);
};
/**
* _sanitizeElements
@ -403,6 +474,8 @@
* @return true if node was killed, false if left alive
*/
var _sanitizeElements = function(currentNode) {
var tagName, content;
/* Execute a hook if present */
_executeHook('beforeSanitizeElements', currentNode, null);
@ -413,11 +486,12 @@
}
/* Now let's check the element's type and name */
var tagName = currentNode.nodeName.toLowerCase();
tagName = currentNode.nodeName.toLowerCase();
/* Execute a hook if present */
_executeHook('uponSanitizeElement', currentNode, {
tagName: tagName
tagName: tagName,
allowedTags: ALLOWED_TAGS
});
/* Remove element if anything forbids its presence */
@ -435,17 +509,22 @@
/* Convert markup to cover jQuery behavior */
if (SAFE_FOR_JQUERY && !currentNode.firstElementChild &&
(!currentNode.content || !currentNode.content.firstElementChild)) {
(!currentNode.content || !currentNode.content.firstElementChild) &&
/</g.test(currentNode.textContent)) {
DOMPurify.removed.push({element: currentNode.cloneNode()});
currentNode.innerHTML = currentNode.textContent.replace(/</g, '&lt;');
}
/* Sanitize element content to be template-safe */
if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {
/* Get the element's text content */
var content = currentNode.textContent;
content = currentNode.textContent;
content = content.replace(MUSTACHE_EXPR, ' ');
content = content.replace(ERB_EXPR, ' ');
currentNode.textContent = content;
if (currentNode.textContent !== content) {
DOMPurify.removed.push({element: currentNode.cloneNode()});
currentNode.textContent = content;
}
}
/* Execute a hook if present */
@ -454,7 +533,9 @@
return false;
};
var DATA_ATTR = /^data-[\w.\u00B7-\uFFFF-]/;
var DATA_ATTR = /^data-[\-\w.\u00B7-\uFFFF]/;
var ARIA_ATTR = /^aria-[\-\w]+$/;
var IS_ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
var IS_SCRIPT_OR_DATA = /^(?:\w+script|data):/i;
/* This needs to be extensive thanks to Webkit/Blink's behavior */
var ATTR_WHITESPACE = /[\x00-\x20\xA0\u1680\u180E\u2000-\u2029\u205f\u3000]/g;
@ -471,27 +552,28 @@
* @return void
*/
var _sanitizeAttributes = function(currentNode) {
var attr, name, value, lcName, idAttr, attributes, hookEvent, l;
/* Execute a hook if present */
_executeHook('beforeSanitizeAttributes', currentNode, null);
var attributes = currentNode.attributes;
attributes = currentNode.attributes;
/* Check if we have attributes; if not we might have a text node */
if (!attributes) { return; }
var hookEvent = {
hookEvent = {
attrName: '',
attrValue: '',
keepAttr: true
keepAttr: true,
allowedAttributes: ALLOWED_ATTR
};
var l = attributes.length;
var attr, name, value, lcName, idAttr;
l = attributes.length;
/* Go backwards over all attributes; safely remove bad ones */
while (l--) {
attr = attributes[l];
name = attr.name;
value = attr.value;
value = attr.value.trim();
lcName = name.toLowerCase();
/* Execute a hook if present */
@ -509,11 +591,18 @@
currentNode.nodeName === 'IMG' && attributes.id) {
idAttr = attributes.id;
attributes = Array.prototype.slice.apply(attributes);
currentNode.removeAttribute('id');
currentNode.removeAttribute(name);
_removeAttribute('id', currentNode);
_removeAttribute(name, currentNode);
if (attributes.indexOf(idAttr) > l) {
currentNode.setAttribute('id', idAttr.value);
}
} else if (
// This works around a bug in Safari, where input[type=file]
// cannot be dynamically set after type has been removed
currentNode.nodeName === 'INPUT' && lcName === 'type' &&
value === 'file' && (ALLOWED_ATTR[lcName] || !FORBID_ATTR[lcName])) {
continue;
} else {
// This avoids a crash in Safari v9.0 with double-ids.
// The trick is to first set the id to be empty and then to
@ -521,7 +610,7 @@
if (name === 'id') {
currentNode.setAttribute(name, '');
}
currentNode.removeAttribute(name);
_removeAttribute(name, currentNode);
}
/* Did the hooks approve of the attribute? */
@ -536,33 +625,64 @@
continue;
}
if (
/* Check the name is permitted */
(
(ALLOWED_ATTR[lcName] && !FORBID_ATTR[lcName]) ||
/* Allow potentially valid data-* attributes
* At least one character after "-" (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
* XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804) */
(!SAFE_FOR_TEMPLATES && ALLOW_DATA_ATTR && DATA_ATTR.test(lcName))
) &&
/* Get rid of script and data URIs */
(
!IS_SCRIPT_OR_DATA.test(value.replace(ATTR_WHITESPACE,'')) ||
/* Keep image data URIs alive if src is allowed */
(lcName === 'src' && value.indexOf('data:') === 0 &&
currentNode.nodeName === 'IMG')
)
) {
/* Handle invalid data-* attribute set by try-catching it */
try {
/* Sanitize attribute content to be template-safe */
if (SAFE_FOR_TEMPLATES) {
value = value.replace(MUSTACHE_EXPR, ' ');
value = value.replace(ERB_EXPR, ' ');
}
currentNode.setAttribute(name, value);
} catch (e) {}
/* Sanitize attribute content to be template-safe */
if (SAFE_FOR_TEMPLATES) {
value = value.replace(MUSTACHE_EXPR, ' ');
value = value.replace(ERB_EXPR, ' ');
}
/* Allow valid data-* attributes: At least one character after "-"
(https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)
XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)
We don't need to check the value; it's always URI safe. */
if (ALLOW_DATA_ATTR && DATA_ATTR.test(lcName)) {
// This attribute is safe
}
else if (ALLOW_ARIA_ATTR && ARIA_ATTR.test(lcName)) {
// This attribute is safe
}
/* Otherwise, check the name is permitted */
else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {
continue;
}
/* Check value is safe. First, is attr inert? If so, is safe */
else if (URI_SAFE_ATTRIBUTES[lcName]) {
// This attribute is safe
}
/* Check no script, data or unknown possibly unsafe URI
unless we know URI values are safe for that attribute */
else if (IS_ALLOWED_URI.test(value.replace(ATTR_WHITESPACE,''))) {
// This attribute is safe
}
/* Keep image data URIs alive if src/xlink:href is allowed */
else if (
(lcName === 'src' || lcName === 'xlink:href') &&
value.indexOf('data:') === 0 &&
DATA_URI_TAGS[currentNode.nodeName.toLowerCase()]) {
// This attribute is safe
}
/* Allow unknown protocols: This provides support for links that
are handled by protocol handlers which may be unknown ahead of
time, e.g. fb:, spotify: */
else if (
ALLOW_UNKNOWN_PROTOCOLS &&
!IS_SCRIPT_OR_DATA.test(value.replace(ATTR_WHITESPACE,''))) {
// This attribute is safe
}
/* Check for binary attributes */
else if (!value) {
// binary attributes are safe at this point
}
/* Anything else, presume unsafe, do not add it back */
else {
continue;
}
/* Handle invalid data-* attribute set by try-catching it */
try {
currentNode.setAttribute(name, value);
DOMPurify.removed.pop();
} catch (e) {}
}
/* Execute a hook if present */
@ -623,27 +743,36 @@
* sanitize
* Public method providing core sanitation functionality
*
* @param {String} dirty string
* @param {String|Node} dirty string or DOM node
* @param {Object} configuration object
*/
DOMPurify.sanitize = function(dirty, cfg) {
var body, importedNode, currentNode, oldNode, nodeIterator, returnNode;
/* Make sure we have a string to sanitize.
DO NOT return early, as this will return the wrong type if
the user has requested a DOM object rather than a string */
if (!dirty) {
dirty = '';
dirty = '<!-->';
}
/* Stringify, in case dirty is an array or other object */
if (typeof dirty !== 'string') {
dirty = dirty.toString();
/* Stringify, in case dirty is an object */
if (typeof dirty !== 'string' && !_isNode(dirty)) {
if (typeof dirty.toString !== 'function') {
throw new TypeError('toString is not a function');
} else {
dirty = dirty.toString();
}
}
/* Check we can run. Otherwise fall back or ignore */
if (!DOMPurify.isSupported) {
if (typeof window.toStaticHTML === 'object'
if (typeof window.toStaticHTML === 'object'
|| typeof window.toStaticHTML === 'function') {
return window.toStaticHTML(dirty);
if (typeof dirty === 'string') {
return window.toStaticHTML(dirty);
} else if (_isNode(dirty)) {
return window.toStaticHTML(dirty.outerHTML);
}
}
return dirty;
}
@ -651,23 +780,42 @@
/* Assign config vars */
_parseConfig(cfg);
/* Exit directly if we have nothing to do */
if (!RETURN_DOM && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) {
return dirty;
/* Clean up removed elements */
DOMPurify.removed = [];
if (dirty instanceof Node) {
/* If dirty is a DOM element, append to an empty document to avoid
elements being stripped by the parser */
body = _initDocument('<!-->');
importedNode = body.ownerDocument.importNode(dirty, true);
if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {
/* Node is already a body, use as is */
body = importedNode;
} else {
body.appendChild( importedNode );
}
} else {
/* Exit directly if we have nothing to do */
if (!RETURN_DOM && !WHOLE_DOCUMENT && dirty.indexOf('<') === -1) {
return dirty;
}
/* Initialize the document to work on */
body = _initDocument(dirty);
/* Check we have a DOM node from the data */
if (!body) {
return RETURN_DOM ? null : '';
}
}
/* Initialize the document to work on */
var body = _initDocument(dirty);
/* Check we have a DOM node from the data */
if (!body) {
return RETURN_DOM ? null : '';
/* Remove first element node (ours) if FORCE_BODY is set */
if (FORCE_BODY) {
_forceRemove(body.firstChild);
}
/* Get node iterator */
var currentNode;
var oldNode;
var nodeIterator = _createIterator(body);
nodeIterator = _createIterator(body);
/* Now start iterating over the created document */
while ( (currentNode = nodeIterator.nextNode()) ) {
@ -694,7 +842,6 @@
}
/* Return sanitized string or DOM */
var returnNode;
if (RETURN_DOM) {
if (RETURN_DOM_FRAGMENT) {
@ -769,7 +916,7 @@
* @return void
*/
DOMPurify.removeAllHooks = function() {
hooks = [];
hooks = {};
};
return DOMPurify;