All files / roosterjs-content-model-core/lib/command/createModelFromHtml sanitizeElement.ts

93.48% Statements 43/46
87.69% Branches 57/65
83.33% Functions 5/6
93.18% Lines 41/44

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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 4041x           1x                                                                                                                                                                                                                     1x                                               1x 1x   1x                                                                                                                                               1x                                                                                                               1x             82x   82x                   82x 77x 102x                       102x 98x         82x           1x             79x   79x 38x 38x 38x   38x   38x                       38x         28x       79x               21x 21x   21x 29x 29x 29x   29x 24x       24x   24x           24x               19x         21x                 24x    
import { isNodeOfType } from 'roosterjs-content-model-dom';
import type { ValueSanitizer } from 'roosterjs-content-model-types';
 
/**
 * @internal
 */
export const AllowedTags: ReadonlyArray<string> = [
    'a',
    'abbr',
    'address',
    'area',
    'article',
    'aside',
    'b',
    'bdi',
    'bdo',
    'blockquote',
    'body',
    'br',
    'button',
    'canvas',
    'caption',
    'center',
    'cite',
    'code',
    'col',
    'colgroup',
    'data',
    'datalist',
    'dd',
    'del',
    'details',
    'dfn',
    'dialog',
    'dir',
    'div',
    'dl',
    'dt',
    'em',
    'fieldset',
    'figcaption',
    'figure',
    'font',
    'footer',
    'h1',
    'h2',
    'h3',
    'h4',
    'h5',
    'h6',
    'head',
    'header',
    'hgroup',
    'hr',
    'html',
    'i',
    'img',
    'input',
    'ins',
    'kbd',
    'label',
    'legend',
    'li',
    'main',
    'map',
    'mark',
    'menu',
    'menuitem',
    'meter',
    'nav',
    'ol',
    'optgroup',
    'option',
    'output',
    'p',
    'picture',
    'pre',
    'progress',
    'q',
    'rp',
    'rt',
    'ruby',
    's',
    'samp',
    'section',
    'select',
    'small',
    'span',
    'strike',
    'strong',
    'sub',
    'summary',
    'sup',
    'table',
    'tbody',
    'td',
    'textarea',
    'tfoot',
    'th',
    'thead',
    'time',
    'tr',
    'tt',
    'u',
    'ul',
    'var',
    'wbr',
    'xmp',
];
 
/**
 * @internal
 */
export const DisallowedTags: ReadonlyArray<string> = [
    'applet',
    'audio',
    'base',
    'basefont',
    'embed',
    'frame',
    'frameset',
    'iframe',
    'link',
    'meta',
    'noscript',
    'object',
    'param',
    'script',
    'slot',
    'source',
    'style',
    'template',
    'title',
    'track',
    'video',
];
 
const VARIABLE_REGEX = /^\s*var\(\s*[a-zA-Z0-9-_]+\s*(,\s*(.*))?\)\s*$/;
const VARIABLE_PREFIX = 'var(';
 
const AllowedAttributes = [
    'accept',
    'align',
    'alt',
    'checked',
    'cite',
    'class',
    'color',
    'cols',
    'colspan',
    'contextmenu',
    'coords',
    'datetime',
    'default',
    'dir',
    'dirname',
    'disabled',
    'download',
    'face',
    'headers',
    'height',
    'hidden',
    'high',
    'href',
    'hreflang',
    'ismap',
    'kind',
    'label',
    'lang',
    'list',
    'low',
    'max',
    'maxlength',
    'media',
    'min',
    'multiple',
    'open',
    'optimum',
    'pattern',
    'placeholder',
    'readonly',
    'rel',
    'required',
    'reversed',
    'rows',
    'rowspan',
    'scope',
    'selected',
    'shape',
    'size',
    'sizes',
    'span',
    'spellcheck',
    'src',
    'srclang',
    'srcset',
    'start',
    'step',
    'style',
    'tabindex',
    'target',
    'title',
    'translate',
    'type',
    'usemap',
    'valign',
    'value',
    'width',
    'wrap',
    'bgColor',
];
 
const DefaultStyleValue: { [name: string]: string } = {
    'background-color': 'transparent',
    'border-bottom-color': 'rgb(0, 0, 0)',
    'border-bottom-style': 'none',
    'border-bottom-width': '0px',
    'border-image-outset': '0',
    'border-image-repeat': 'stretch',
    'border-image-slice': '100%',
    'border-image-source': 'none',
    'border-image-width': '1',
    'border-left-color': 'rgb(0, 0, 0)',
    'border-left-style': 'none',
    'border-left-width': '0px',
    'border-right-color': 'rgb(0, 0, 0)',
    'border-right-style': 'none',
    'border-right-width': '0px',
    'border-top-color': 'rgb(0, 0, 0)',
    'border-top-style': 'none',
    'border-top-width': '0px',
    'outline-color': 'transparent',
    'outline-style': 'none',
    'outline-width': '0px',
    overflow: 'visible',
    '-webkit-text-stroke-width': '0px',
    'word-wrap': 'break-word',
    'margin-left': '0px',
    'margin-right': '0px',
    padding: '0px',
    'padding-top': '0px',
    'padding-left': '0px',
    'padding-right': '0px',
    'padding-bottom': '0px',
    border: '0px',
    'border-top': '0px',
    'border-left': '0px',
    'border-right': '0px',
    'border-bottom': '0px',
    'vertical-align': 'baseline',
    float: 'none',
    'font-style': 'normal',
    'font-variant-ligatures': 'normal',
    'font-variant-caps': 'normal',
    'font-weight': '400',
    'letter-spacing': 'normal',
    orphans: '2',
    'text-align': 'start',
    'text-indent': '0px',
    'text-transform': 'none',
    widows: '2',
    'word-spacing': '0px',
    'white-space': 'normal',
};
 
/**
 * @internal
 */
export function sanitizeElement(
    element: HTMLElement,
    allowedTags: ReadonlyArray<string>,
    disallowedTags: ReadonlyArray<string>,
    styleSanitizers?: Readonly<Record<string, ValueSanitizer>>,
    attributeSanitizers?: Readonly<Record<string, ValueSanitizer>>
): HTMLElement | null {
    const tag = element.tagName.toLowerCase();
    const sanitizedElement =
        disallowedTags.indexOf(tag) >= 0
            ? null
            : createSanitizedElement(
                  element.ownerDocument,
                  allowedTags.indexOf(tag) >= 0 ? tag : 'span',
                  element.attributes,
                  styleSanitizers,
                  attributeSanitizers
              );
 
    if (sanitizedElement) {
        for (let child = element.firstChild; child; child = child.nextSibling) {
            const newChild = isNodeOfType(child, 'ELEMENT_NODE')
                ? sanitizeElement(
                      child,
                      allowedTags,
                      disallowedTags,
                      styleSanitizers,
                      attributeSanitizers
                  )
                : isNodeOfType(child, 'TEXT_NODE')
                ? child.cloneNode()
                : null;
 
            if (newChild) {
                sanitizedElement?.appendChild(newChild);
            }
        }
    }
 
    return sanitizedElement;
}
 
/**
 * @internal
 */
export function createSanitizedElement(
    doc: Document,
    tag: string,
    attributes: NamedNodeMap,
    styleSanitizers?: Readonly<Record<string, ValueSanitizer>>,
    attributeSanitizers?: Readonly<Record<string, ValueSanitizer>>
): HTMLElement {
    const element = doc.createElement(tag);
 
    for (let i = 0; i < attributes.length; i++) {
        const attribute = attributes[i];
        const name = attribute.name.toLowerCase().trim();
        const value = attribute.value;
 
        const sanitizer = attributeSanitizers?.[name];
        const newValue =
            name == 'style'
                ? processStyles(tag, value, styleSanitizers)
                : typeof sanitizer == 'function'
                ? sanitizer(value, tag)
                : typeof sanitizer === 'boolean'
                ? sanitizer
                    ? value
                    : null
                : AllowedAttributes.indexOf(name) >= 0 || name.indexOf('data-') == 0
                ? value
                : null;
 
        if (
            newValue !== null &&
            newValue !== undefined &&
            !newValue.match(/s\n*c\n*r\n*i\n*p\n*t\n*:/i) // match script: with any NewLine inside. Browser will ignore those NewLine char and still treat it as script prefix
        ) {
            element.setAttribute(name, newValue);
        }
    }
 
    return element;
}
 
function processStyles(
    tagName: string,
    value: string,
    styleSanitizers?: Readonly<Record<string, ValueSanitizer>>
) {
    const pairs = value.split(';');
    const result: string[] = [];
 
    pairs.forEach(pair => {
        const valueIndex = pair.indexOf(':');
        const name = pair.slice(0, valueIndex).trim();
        let value: string = pair.slice(valueIndex + 1).trim();
 
        if (name && value) {
            Iif (isCssVariable(value)) {
                value = processCssVariable(value);
            }
 
            const sanitizer = styleSanitizers?.[name];
            const sanitizedValue =
                typeof sanitizer == 'function'
                    ? sanitizer(value, tagName)
                    : sanitizer === false
                    ? null
                    : value;
 
            if (
                !!sanitizedValue &&
                sanitizedValue != 'inherit' &&
                sanitizedValue != 'initial' &&
                sanitizedValue.indexOf('expression') < 0 &&
                !name.startsWith('-') &&
                DefaultStyleValue[name] != sanitizedValue
            ) {
                result.push(`${name}:${sanitizedValue}`);
            }
        }
    });
 
    return result.join(';');
}
 
function processCssVariable(value: string): string {
    const match = VARIABLE_REGEX.exec(value);
    return match?.[2] || ''; // Without fallback value, we don't know what does the original value mean, so ignore it
}
 
function isCssVariable(value: string): boolean {
    return value.indexOf(VARIABLE_PREFIX) == 0;
}