All Projects → syntax-tree → hast-util-sanitize

syntax-tree / hast-util-sanitize

Licence: MIT license
utility to sanitize hast nodes

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to hast-util-sanitize

hast-util-from-dom
utility to transform a DOM tree to hast
Stars: ✭ 20 (-41.18%)
Mutual labels:  syntax-tree, util, unist, hast, hast-util
hast-util-to-html
utility to serialize hast to HTML
Stars: ✭ 47 (+38.24%)
Mutual labels:  syntax-tree, util, unist, hast, hast-util
mdast-util-to-hast
utility to transform mdast to hast
Stars: ✭ 53 (+55.88%)
Mutual labels:  syntax-tree, unist, hast, hast-util
unist-util-visit-parents
utility to recursively walk over unist nodes, with ancestral information
Stars: ✭ 25 (-26.47%)
Mutual labels:  syntax-tree, util, unist
unist-util-map
utility to create a new tree by mapping all nodes
Stars: ✭ 30 (-11.76%)
Mutual labels:  syntax-tree, util, unist
unist-util-inspect
utility to inspect nodes
Stars: ✭ 16 (-52.94%)
Mutual labels:  syntax-tree, util, unist
hast-util-reading-time
utility to estimate the reading time
Stars: ✭ 55 (+61.76%)
Mutual labels:  unist, hast, hast-util
mdast-util-to-string
utility to get the plain text content of an mdast node
Stars: ✭ 27 (-20.59%)
Mutual labels:  syntax-tree, util, unist
hast-util-to-mdast
utility to transform hast (HTML) to mdast (markdown)
Stars: ✭ 26 (-23.53%)
Mutual labels:  unist, hast, hast-util
nlcst-to-string
utility to transform an nlcst tree to a string
Stars: ✭ 16 (-52.94%)
Mutual labels:  syntax-tree, util, unist
hast-util-select
utility to add `querySelector`, `querySelectorAll`, and `matches` support for hast
Stars: ✭ 20 (-41.18%)
Mutual labels:  util, hast, hast-util
unist-builder
utility to create a new trees with a nice syntax
Stars: ✭ 52 (+52.94%)
Mutual labels:  syntax-tree, util, unist
xast
Extensible Abstract Syntax Tree
Stars: ✭ 32 (-5.88%)
Mutual labels:  syntax-tree, unist
ntast
Notion Abstract Syntax Tree specification.
Stars: ✭ 101 (+197.06%)
Mutual labels:  syntax-tree, unist
Unist Util Visit
utility to visit nodes
Stars: ✭ 101 (+197.06%)
Mutual labels:  syntax-tree, util
unist-util-select
utility to select unist nodes with CSS-like selectors
Stars: ✭ 41 (+20.59%)
Mutual labels:  util, unist
Unified
☔️ interface for parsing, inspecting, transforming, and serializing content through syntax trees
Stars: ✭ 3,036 (+8829.41%)
Mutual labels:  syntax-tree, unist
mold
✂️ Is a general library to help modify or set data within data structures and other objects.
Stars: ✭ 114 (+235.29%)
Mutual labels:  clean, sanitize
safe-marked
Markdown to HTML using marked and DOMPurify. Safe by default.
Stars: ✭ 31 (-8.82%)
Mutual labels:  xss, sanitize
sast
Parse CSS, Sass, SCSS, and Less into a unist syntax tree
Stars: ✭ 51 (+50%)
Mutual labels:  syntax-tree, unist

hast-util-sanitize

Build Coverage Downloads Size Sponsors Backers Chat

hast utility to make trees safe.

Contents

What is this?

This package is a utility that can make a tree that potentially contains dangerous user content safe for use. It defaults to what GitHub does to clean unsafe markup, but you can change that.

When should I use this?

This package is needed whenever you deal with potentially dangerous user content.

The plugin rehype-sanitize wraps this utility to also sanitize HTML at a higher-level (easier) abstraction.

Install

This package is ESM only. In Node.js (version 12.20+, 14.14+, 16.0+, or 18.0+), install with npm:

npm install hast-util-sanitize

In Deno with esm.sh:

import {sanitize} from 'https://esm.sh/hast-util-sanitize@4'

In browsers with esm.sh:

<script type="module">
  import {sanitize} from 'https://esm.sh/hast-util-sanitize@4?bundle'
</script>

Use

import {u} from 'unist-builder'
import {h} from 'hastscript'
import {sanitize} from 'hast-util-sanitize'
import {toHtml} from 'hast-util-to-html'

const 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>'}))
])

const unsanitized = toHtml(tree)
const 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 identifiers sanitize and defaultSchema. There is no default export.

sanitize(tree[, schema])

Sanitize a tree.

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

A new, sanitized, tree (Node).

Schema

Sanitation schema that defines if and how nodes and properties should be cleaned. The default schema is exported as defaultSchema, which 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' // You can use `structuredClone` in modern JS.
import {sanitize, defaultSchema} from 'hast-util-sanitize'

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

const 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 (Record<string, Array<string>>).

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

One special value, '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 (Record<string, Record<string, *>>). 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 (Record<string, Array<string>>).

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

Map of tag names to their required ancestor elements (Record<string, 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

Types

This package is fully typed with TypeScript. It exports the additional type Schema.

Compatibility

Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 12.20+, 14.14+, 16.0+, and 18.0+. Our projects sometimes work with older versions, but this is not guaranteed.

Security

By default, hast-util-sanitize will make everything safe to use. But when used incorrectly, deviating from the defaults can open you up to a cross-site scripting (XSS) attack.

Use hast-util-sanitize after the last unsafe thing: everything after it could be unsafe (but is fine if you do trust it).

Related

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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].