hast-util-sanitize

hast utility to sanitize nodes

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
hast-util-sanitize
3514.0.02 years ago6 years agoMinified + gzip package size for hast-util-sanitize in KB

Readme

hast-util-sanitize
!Buildbuild-badgebuild !Coveragecoverage-badgecoverage !Downloadsdownloads-badgedownloads !Sizesize-badgesize !Sponsorssponsors-badgecollective !Backersbackers-badgecollective !Chatchat-badgechat
hasthast utility to sanitize a treetree.

Install

This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.
npm install hast-util-sanitize
## Use

```js
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("alpha")"><a href="jAva script:alert("bravo")" onclick="alert("charlie")">delta</a>
<script>alert("charlie")</script>
<img src="x" onerror="alert("delta")">
<iframe src="javascript:alert("echo")"></iframe>
<math><mi xlink:href="data:x,<script>alert("foxtrot")</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 hasthast treetree.
Parameters
Returns
Nodenode — A new, sanitized treetree.

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 defaultSchemadefault-schema.
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 namesname (Object.<Array.<string>>).
The special '*' key defines property namesname allowed on all elementselement.
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 valuevalue of that property namename, 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 namesname and their default property valuevalue (Object.<Object.<*>>). If the defined keys do not exist in an elementelement’s propertiesproperties, 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 valuesvalue (Object.<Array.<string>>).
protocols: {
  href: ['http', 'https', 'mailto'],
  // …
  longDesc: ['http', 'https']
}
ancestors
Map of tag names to their required ancestorancestor elementselement (Object.<Array.<string>>).
ancestors: {
  li: ['ol', 'ul'],
  // …
  tr: ['table']
}
clobber
List of allowed property namesname which can clobber (Array.<string>).
clobber: ['name', 'id']
clobberPrefix
Prefix to use before potentially clobbering property namesname (string).
clobberPrefix: 'user-content-'
strip
Names of elementselement to strip from the treetree (Array.<string>).
By default, unsafe elements are replaced by their childrenchild. Some elements, should however be entirely stripped from the tree.
strip: ['script']
allowComments
Whether to allow commentscomment (boolean, default: false).
allowComments: true
allowDoctypes
Whether to allow doctypesdoctype (boolean, default: false).
allowDoctypes: true

Security

Improper use of hast-util-sanitize can open you up to a cross-site scripting (XSS)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.

Related

— [rehype](https://github.com/rehypejs/rehype) plugin wrapper

Contribute

See contributing.md in syntax-tree/.githubcontributing for ways to get started. See support.mdsupport for ways to get help.
This project has a code of conductcoc. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MITlicense © Titus Wormerauthor