Skip to content
utility to sanitize hast nodes
JavaScript
Branch: master
Clone or download
Latest commit 42b242a Jul 16, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
lib Fix breaking out of comments Jul 16, 2019
.editorconfig Update dependencies, dev-dependencies Sep 17, 2016
.gitignore Add `yarn.lock` to `.gitignore` Jun 11, 2018
.npmrc Add `.npmrc` Jun 11, 2018
.prettierignore Refactor code-style Jun 11, 2018
.travis.yml Update Travis May 26, 2019
index.js Refactor code-style Jun 11, 2018
license Move `LICENSE` > `license` Nov 7, 2018
package.json 2.0.1 Jul 16, 2019
readme.md Add notes on security Jul 16, 2019
test.js Add an extra test Jul 16, 2019

readme.md

hast-util-sanitize

Build Coverage Downloads Size Sponsors Backers Chat

hast utility to sanitize a tree.

Install

npm:

npm install hast-util-sanitize

Usage

var h = require('hastscript')
var u = require('unist-builder')
var sanitize = require('hast-util-sanitize')
var toHtml = require('hast-util-to-html')

var tree = h('div', {onmouseover: 'alert("alpha")'}, [
  h(
    'a',
    {href: 'jAva script:alert("bravo")', onclick: 'alert("charlie")'},
    'delta'
  ),
  u('text', '\n'),
  h('script', 'alert("charlie")'),
  u('text', '\n'),
  h('img', {src: 'x', onerror: 'alert("delta")'}),
  u('text', '\n'),
  h('iframe', {src: 'javascript:alert("echo")'}),
  u('text', '\n'),
  h('math', h('mi', {'xlink:href': 'data:x,<script>alert("foxtrot")</script>'}))
])

var unsanitized = toHtml(tree)
var sanitized = toHtml(sanitize(tree))

console.log(unsanitized)
console.log(sanitized)

Unsanitized:

<div onmouseover="alert(&#x22;alpha&#x22;)"><a href="jAva script:alert(&#x22;bravo&#x22;)" onclick="alert(&#x22;charlie&#x22;)">delta</a>
<script>alert("charlie")</script>
<img src="x" onerror="alert(&#x22;delta&#x22;)">
<iframe src="javascript:alert(&#x22;echo&#x22;)"></iframe>
<math><mi xlink:href="data:x,<script>alert(&#x22;foxtrot&#x22;)</script>"></mi></math></div>

Sanitized:

<div><a>delta</a>

<img src="x">

</div>

API

sanitize(tree[, schema])

Sanitize a hast tree.

Parameters
  • tree (Node) — Tree to sanitize
  • schema (Schema, optional) — Schema defining how to sanitize
Returns

Node — A new, sanitized tree.

Schema

Configuration. If not given, defaults to GitHub style sanitation. If any top-level key isn’t given, it defaults to GitHub’s style too.

For a thorough sample, see github.json.

To extend the standard schema with a few changes, clone github.json like so:

var h = require('hastscript')
var merge = require('deepmerge')
var gh = require('hast-util-sanitize/lib/github')
var sanitize = require('hast-util-sanitize')

var schema = merge(gh, {attributes: {'*': ['className']}})

var tree = sanitize(h('div', {className: ['foo']}), schema)

// `tree` still has `className`.
console.log(tree)
attributes

Map of tag names to allowed property names (Object.<Array.<string>>).

The special '*' key defines property names allowed on all elements.

One special value, namely 'data*', can be used to allow all data properties.

"attributes": {
  "a": [
    "href"
  ],
  "img": [
    "src",
    "longDesc"
  ],
  //
  "*": [
    "abbr",
    "accept",
    "acceptCharset",
    //
    "vSpace",
    "width",
    "itemProp"
  ]
}

Instead of a single string (such as type), which allows any property value of that property name, it’s also possible to provide an array (such as ['type', 'checkbox']), where the first entry is the propery name, and the other entries are allowed property values.

This is how the default GitHub schema allows only disabled checkbox inputs:

"attributes": {
  //
  "input": [
    ["type", "checkbox"],
    ["disabled", true]
  ],
  //
}
required

Map of tag names to required property names and their default property value (Object.<Object.<*>>). If the defined keys do not exist in an element’s properties, they are added and set to the specified value.

Note that properties are first checked based on the schema at attributes, so properties could be removed by that step and then added again through required.

"required": {
  "input": {
    "type": "checkbox",
    "disabled": true
  }
}
tagNames

List of allowed tag names (Array.<string>).

"tagNames": [
  "h1",
  "h2",
  "h3",
  //
  "strike",
  "summary",
  "details"
]
protocols

Map of protocols to allow in property values (Object.<Array.<string>>).

"protocols": {
  "href": [
    "http",
    "https",
    "mailto"
  ],
  //
  "longDesc": [
    "http",
    "https"
  ]
}
ancestors

Map of tag names to their required ancestor elements (Object.<Array.<string>>).

"ancestors": {
  "li": [
    "ol",
    "ul"
  ],
  //
  "tr": [
    "table"
  ]
}
clobber

List of allowed property names which can clobber (Array.<string>).

"clobber": [
  "name",
  "id"
]
clobberPrefix

Prefix to use before potentially clobbering property names (string).

"clobberPrefix": "user-content-"
strip

Names of elements to strip from the tree (Array.<string>).

By default, unsafe elements are replaced by their children. Some elements, should however be entirely stripped from the tree.

"strip": [
  "script"
]
allowComments

Whether to allow comments (boolean, default: false).

"allowComments": true
allowDoctypes

Whether to allow doctypes (boolean, default: false).

"allowDoctypes": true

Security

Improper use of hast-util-sanitize can open you up to a cross-site scripting (XSS) attack. The defaults are safe, but deviating from them is likely unsafe.

Use hast-util-sanitize after all other utilities, as other utilities are likely also unsafe.

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a Code of Conduct. By interacting with this repository, organisation, or community you agree to abide by its terms.

License

MIT © Titus Wormer

You can’t perform that action at this time.