ElementorexCms.HTML.Sanitizer (ElementorexCms v0.1.0)

Copy Markdown View Source

Allow-list HTML sanitizer for the rich text and the HTML of documents.

The input is tokenized and rebuilt from scratch: only allowed tags are written back, each with its allowed attributes, every attribute value is validated (URLs, CSS, ids, classes...) and escaped again, and text is escaped. Nothing of the input is copied verbatim, so malformed markup cannot smuggle anything through.

Policies

  • :inline - formatting inside a line (<strong>, <em>, <a>, <br>...), for headings and buttons
  • :rich - :inline plus paragraphs, lists, quotes, <h2>-<h6>, <hr> and <pre>, for text blocks (the default)
  • :html - :rich plus layout tags, images, tables, <details> and <video>, for the HTML block

Under every policy <script>, <style>, <iframe>, <object>, <svg>, <math>, forms and their contents are removed, as are comments, event handlers (on*), phx-* bindings and URLs with schemes other than http(s), mailto and tel. Disallowed tags are removed but their text is kept.

iex> ElementorexCms.HTML.Sanitizer.sanitize(~s|<p onclick="x()">Hola <b>mundo</b><script>alert(1)</script></p>|)
"<p>Hola <b>mundo</b></p>"
iex> ElementorexCms.HTML.Sanitizer.sanitize(~s|<a href="javascript:alert(1)">x</a>|)
"<a>x</a>"

Summary

Functions

Sanitizes html with the given policy (:rich by default).

Plain text of an HTML fragment: tags removed, entities of the basic set decoded and whitespace collapsed. For excerpts, search and alt texts.

Escapes plain text as HTML, turning line breaks into <br>.

Types

policy()

@type policy() :: :inline | :rich | :html

Functions

sanitize(html, policy \\ :rich)

@spec sanitize(String.t() | nil, policy()) :: String.t()

Sanitizes html with the given policy (:rich by default).

text(html)

@spec text(String.t() | nil) :: String.t()

Plain text of an HTML fragment: tags removed, entities of the basic set decoded and whitespace collapsed. For excerpts, search and alt texts.

iex> ElementorexCms.HTML.Sanitizer.text("<p>Hola&nbsp;<b>mundo</b></p><p>!</p>")
"Hola mundo !"

text_to_html(text)

@spec text_to_html(String.t() | nil) :: String.t()

Escapes plain text as HTML, turning line breaks into <br>.

iex> ElementorexCms.HTML.Sanitizer.text_to_html("a < b\nc")
"a &lt; b<br>c"