Debian Codegraph @

extensions/VisualEditor/lib/ve/src/ve.sanitize.js

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