hast-util-sanitize

utility to sanitize hast nodes

Showing:

Popularity

Downloads/wk

196K

GitHub Stars

31

Maintenance

Last Commit

3mos ago

Contributors

4

Package

Dependencies

1

Size (min+gzip)

2.0KB

License

MIT

Type Definitions

Built-In

Tree-Shakeable

No?

Categories

Readme

hast-util-sanitize

Build Coverage Downloads Size Sponsors Backers Chat

hast utility to sanitize a tree.

Install

This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.

npm:

npm install hast-util-sanitize

Use

import {u} from 'unist-builder'
import {h} from 'hastscript'
import {sanitize} from 'hast-util-sanitize'
import {toHtml} from '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

This package exports the following identifiers: sanitize, defaultSchema. There is no default export.

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 the code for defaultSchema.

To extend the standard schema with a few changes, clone defaultSchema like so:

import {h} from 'hastscript'
import deepmerge from 'deepmerge'
import {sanitize, defaultSchema} from 'hast-util-sanitize'

var schema = deepmerge(defaultSchema, {attributes: {'*': ['className']}})

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

// `tree` still has `className`.
console.log(tree)
// {
//   type: 'element',
//   tagName: 'div',
//   properties: {className: ['foo']},
//   children: []
// }
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 property name, and all other entries allowed property values.

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

attributes: {
  // …
  input: [
    ['type', 'checkbox'],
    ['disabled', true]
  ]
  // …
}

This also plays well with properties that accept space- or comma-separated values, such as class. Say you wanted to allow certain classes on span elements for syntax highlighting, that can be done like this:

// …
span: [
  ['className', 'token', 'number', 'operator']
]
// …
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, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer

Rate & Review

Great Documentation0
Easy to Use0
Performant0
Highly Customizable0
Bleeding Edge0
Responsive Maintainers0
Poor Documentation0
Hard to Use0
Slow0
Buggy0
Abandoned0
Unwelcoming Community0
100
No reviews found
Be the first to rate

Alternatives

No alternatives found

Tutorials

No tutorials found
Add a tutorial