All files / src ve.sanitize.js

100% Statements 17/17
100% Branches 8/8
100% Functions 3/3
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64                              1x   114x 114x         114x           114x 56x 56x 56x   58x 58x                 1x 58x                     1x 133x 130x 3x 1x      
/*!
 * VisualEditor HTML sanitization utilities.
 *
 * @copyright See AUTHORS.txt
 */
 
/* global DOMPurify */
 
/**
 * Parse some user HTML into a sanitized node list, making it safe to load on the page
 *
 * @param {string} html
 * @param {boolean} [returnDocument] For internal use only (if true, return whole document)
 * @return {NodeList|HTMLDocument} Sanitized node list (or HTML document, for internal use only)
 */
ve.sanitizeHtml = function ( html, returnDocument ) {
	// TODO: Move MW-specific rules to ve-mw
	var addTags = [ 'figure-inline' ],
		addAttrs = [
			'srcset',
			// RDFa
			'about', 'rel', 'resource', 'property', 'content', 'datatype', 'typeof'
		];
	var options = {
		ADD_TAGS: addTags,
		ADD_ATTR: addAttrs,
		ADD_URI_SAFE_ATTR: addAttrs,
		FORBID_TAGS: [ 'style' ]
	};
	if ( !returnDocument ) {
		options.FORCE_BODY = true;
		options.RETURN_DOM_FRAGMENT = true;
		return DOMPurify.sanitize( html, options ).childNodes;
	}
	options.RETURN_DOM = true;
	return DOMPurify.sanitize( html, options ).ownerDocument;
};
 
/**
 * Parse some user HTML into a sanitized HTML document, making it safe to load on the page
 *
 * @param {string} html
 * @return {HTMLDocument}
 */
ve.sanitizeHtmlToDocument = function ( html ) {
	return ve.sanitizeHtml( html, true );
};
 
/**
 * Set an element attribute to a specific value if it is safe
 *
 * @param {HTMLElement} element Element
 * @param {string} attr Attribute
 * @param {string} val Value
 * @param {string} [fallbackVal] Optional fallback value if val is unsafe (will also be safety-checked)
 */
ve.setAttributeSafe = function ( element, attr, val, fallbackVal ) {
	if ( DOMPurify.isValidAttribute( element.tagName, attr, val ) ) {
		element.setAttribute( attr, val );
	} else if ( fallbackVal !== undefined && DOMPurify.isValidAttribute( element.tagName, attr, fallbackVal ) ) {
		element.setAttribute( attr, fallbackVal );
	}
};