MCPcopy Create free account
hub / github.com/angular/angular / _sanitizeHtml

Function _sanitizeHtml

packages/core/src/sanitization/html_sanitizer.ts:302–344  ·  view source on GitHub ↗
(defaultDoc: any, unsafeHtmlInput: string)

Source from the content-addressed store, hash-verified

300 * the DOM in a browser environment.
301 */
302export function _sanitizeHtml(defaultDoc: any, unsafeHtmlInput: string): TrustedHTML | string {
303 let inertBodyElement: HTMLElement | null = null;
304 try {
305 inertBodyHelper = inertBodyHelper || getInertBodyHelper(defaultDoc);
306 // Make sure unsafeHtml is actually a string (TypeScript types are not enforced at runtime).
307 let unsafeHtml = unsafeHtmlInput ? String(unsafeHtmlInput) : '';
308 inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
309
310 // mXSS protection. Repeatedly parse the document to make sure it stabilizes, so that a browser
311 // trying to auto-correct incorrect HTML cannot cause formerly inert HTML to become dangerous.
312 let mXSSAttempts = 5;
313 let parsedHtml = unsafeHtml;
314
315 do {
316 if (mXSSAttempts === 0) {
317 throw new Error('Failed to sanitize html because the input is unstable');
318 }
319 mXSSAttempts--;
320
321 unsafeHtml = parsedHtml;
322 parsedHtml = inertBodyElement!.innerHTML;
323 // Discard the serialized tree before the next parse allocates another one.
324 clearInertBodyElement(inertBodyElement!);
325 inertBodyElement = null;
326 inertBodyElement = inertBodyHelper.getInertBodyElement(unsafeHtml);
327 } while (unsafeHtml !== parsedHtml);
328
329 const sanitizer = new SanitizingHtmlSerializer();
330 const safeHtml = sanitizer.sanitizeChildren(
331 (getTemplateContent(inertBodyElement!) as Element) || inertBodyElement,
332 );
333 if ((typeof ngDevMode === 'undefined' || ngDevMode) && sanitizer.sanitizedSomething) {
334 console.warn(`WARNING: sanitizing HTML stripped some content, see ${XSS_SECURITY_URL}`);
335 }
336
337 return trustedHTMLFromString(safeHtml);
338 } finally {
339 // In case anything goes wrong, clear out inertElement to reset the entire DOM structure.
340 if (inertBodyElement) {
341 clearInertBodyElement(inertBodyElement);
342 }
343 }
344}
345
346function clearInertBodyElement(inertBodyElement: HTMLElement): void {
347 const parent = getTemplateContent(inertBodyElement) || inertBodyElement;

Callers 3

sanitizeHtmlFunction · 0.90
ɵɵsanitizeHtmlFunction · 0.90
sanitizeMethod · 0.85

Calls 7

sanitizeChildrenMethod · 0.95
getInertBodyHelperFunction · 0.90
trustedHTMLFromStringFunction · 0.90
clearInertBodyElementFunction · 0.85
getTemplateContentFunction · 0.85
warnMethod · 0.65
getInertBodyElementMethod · 0.45

Tested by

no test coverage detected