(defaultDoc: any, unsafeHtmlInput: string)
| 300 | * the DOM in a browser environment. |
| 301 | */ |
| 302 | export 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 | |
| 346 | function clearInertBodyElement(inertBodyElement: HTMLElement): void { |
| 347 | const parent = getTemplateContent(inertBodyElement) || inertBodyElement; |
no test coverage detected