Gathering detailed insights and metrics for rehype-sanitize
Gathering detailed insights and metrics for rehype-sanitize
Gathering detailed insights and metrics for rehype-sanitize
Gathering detailed insights and metrics for rehype-sanitize
blixify-ui-web
//TODO : Code - Remove Vfile once there is 6.0.3 //TODO : Code - Remove rehype-sanitize once react-md-editor is usable //TODO : Code - Remove lib as we should use from own package.json
rehype-ultra-super-plus
All-in-one rehype document sanitizer/enhancer.
rehype-katex-notranslate
Add the attribute translate="no" to the katex formula generated by rehype-katex to prevent the formulas from being recognized and translated by webpage translation tools.
npm install rehype-sanitize
Typescript
Module System
Node Version
NPM Version
JavaScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
177 Stars
94 Commits
4 Forks
8 Watchers
1 Branches
10 Contributors
Updated on Jul 11, 2025
Latest Version
6.0.0
Package Id
rehype-sanitize@6.0.0
Unpacked Size
20.30 kB
Size
7.17 kB
File Count
7
NPM Version
9.7.2
Node Version
20.0.0
Published on
Aug 26, 2023
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
2
rehype plugin to sanitize HTML.
This package is a unified (rehype) plugin to make sure HTML is safe.
It drops anything that isn’t explicitly allowed by a schema (defaulting to how
github.com
works).
unified is a project that transforms content with abstract syntax trees (ASTs). rehype adds support for HTML to unified. hast is the HTML AST that rehype uses. This is a rehype plugin that transforms hast.
It’s recommended to sanitize your HTML any time you do not completely trust authors or the plugins being used.
This plugin is built on hast-util-sanitize
, which cleans
hast syntax trees.
rehype focusses on making it easier to transform content by abstracting such
internals away.
This package is ESM only. In Node.js (version 16+), install with npm:
1npm install rehype-sanitize
In Deno with esm.sh
:
1import rehypeSanitize from 'https://esm.sh/rehype-sanitize@6'
In browsers with esm.sh
:
1<script type="module"> 2 import rehypeSanitize from 'https://esm.sh/rehype-sanitize@6?bundle' 3</script>
Say we have the following file index.html
:
1<div onmouseover="alert('alpha')"> 2 <a href="jAva script:alert('bravo')">delta</a> 3 <img src="x" onerror="alert('charlie')"> 4 <iframe src="javascript:alert('delta')"></iframe> 5 <math> 6 <mi xlink:href="data:x,<script>alert('echo')</script>"></mi> 7 </math> 8</div> 9<script> 10require('child_process').spawn('echo', ['hack!']); 11</script>
…and our module example.js
looks as follows:
1import rehypeParse from 'rehype-parse' 2import rehypeSanitize from 'rehype-sanitize' 3import rehypeStringify from 'rehype-stringify' 4import {read} from 'to-vfile' 5import {unified} from 'unified' 6 7const file = await unified() 8 .use(rehypeParse, {fragment: true}) 9 .use(rehypeSanitize) 10 .use(rehypeStringify) 11 .process(await read('index.html')) 12 13console.log(String(file))
Now running node example.js
yields:
1<div> 2 <a>delta</a> 3 <img src="x"> 4 5 6 7 8</div>
This package exports the identifier defaultSchema
.
The default export is rehypeSanitize
.
defaultSchema
Default schema (Options
).
Follows GitHub style sanitation.
unified().use(rehypeSanitize[, schema])
Sanitize HTML.
options
(Options
, optional)
— configurationTransform (Transformer
).
Options
Schema that defines what nodes and properties are allowed (TypeScript type).
This option is a bit advanced as it requires knowledge of syntax trees, so see
the docs for Schema
in hast-util-sanitize
.
DOM clobbering is an attack in which malicious HTML confuses an application by
naming elements, through id
or name
attributes, such that they overshadow
presumed properties in window
(the global scope in browsers).
DOM clobbering often occurs when user content is used to generate heading IDs.
To illustrate, say we have this browser.js
file:
1console.log(current)
And our module example.js
contains:
1/** 2 * @typedef {import('hast').Root} Root 3 */ 4 5import fs from 'node:fs/promises' 6import rehypeParse from 'rehype-parse' 7import rehypeStringify from 'rehype-stringify' 8import {unified} from 'unified' 9 10const browser = String(await fs.readFile('browser.js')) 11const document = `<a name="old"></a> 12<h1 id="current">Current</h1> 13${`<p>${'Lorem ipsum dolor sit amet. '.repeat(20)}</p>\n`.repeat(20)} 14<p>Link to <a href="#current">current</a>, link to <a href="#old">old</a>.` 15 16const file = await unified() 17 .use(rehypeParse, {fragment: true}) 18 .use(function () { 19 /** 20 * @param {Root} tree 21 */ 22 return function (tree) { 23 tree.children.push({ 24 type: 'element', 25 tagName: 'script', 26 properties: {type: 'module'}, 27 children: [{type: 'text', value: browser}] 28 }) 29 } 30 }) 31 .use(rehypeStringify) 32 .process(document) 33 34await fs.writeFile('output.html', String(file))
This code processes HTML, inlines our browser script into it, and writes it out.
The input HTML models how markdown often looks on platforms like GitHub, which
allow heading IDs to be generated from their text and embedded HTML (including
<a name="old"></a>
, which can be used to create anchors for renamed headings
to prevent links from breaking).
The generated HTML looks like:
1<a name="old"></a> 2<h1 id="current">Current</h1> 3<p>Lorem ipsum dolor sit amet.<!--…--></p> 4<p>Link to <a href="#current">current</a>, link to <a href="#old">old</a>.</p> 5<script type="module">console.log(current)</script>
When you run this code locally and open the generated output.html
, you can
observe that the links at the bottom work, but also that the <h1>
element
is printed to the console (the clobbering).
rehype-sanitize
solves the clobbering by prefixing every id
and name
attribute with 'user-content-'
.
Changing example.js
:
1@@ -15,6 +15,7 @@ ${`<p>${'Lorem ipsum dolor sit amet. '.repeat(20)}</p>\n`.repeat(20)} 2 3 const file = await unified() 4 .use(rehypeParse, {fragment: true}) 5+ .use(rehypeSanitize) 6 .use(function () { 7 /** 8 * @param {Root} tree
Now yields:
1-<a name="old"></a> 2-<h1 id="current">Current</h1> 3+<a name="user-content-old"></a> 4+<h1 id="user-content-current">Current</h1>
This introduces another problem as the links are now broken.
It could perhaps be solved by changing all links, but that would make the links
rather ugly, and we’d need to track what IDs we have outside of the user content
on our pages too.
Alternatively, and what arguably looks better, we could rewrite pretty links to
their safe but ugly prefixed elements.
This is what GitHub does.
Replace browser.js
with the following:
1/// <reference lib="dom" />
2/* eslint-env browser */
3
4// Page load (you could wrap this in a DOM ready if the script is loaded early).
5hashchange()
6
7// When URL changes.
8window.addEventListener('hashchange', hashchange)
9
10// When on the URL already, perhaps after scrolling, and clicking again, which
11// doesn’t emit `hashchange`.
12document.addEventListener(
13 'click',
14 function (event) {
15 if (
16 event.target &&
17 event.target instanceof HTMLAnchorElement &&
18 event.target.href === location.href &&
19 location.hash.length > 1
20 ) {
21 setImmediate(function () {
22 if (!event.defaultPrevented) {
23 hashchange()
24 }
25 })
26 }
27 },
28 false
29)
30
31function hashchange() {
32 /** @type {string | undefined} */
33 let hash
34
35 try {
36 hash = decodeURIComponent(location.hash.slice(1)).toLowerCase()
37 } catch {
38 return
39 }
40
41 const name = 'user-content-' + hash
42 const target =
43 document.getElementById(name) || document.getElementsByName(name)[0]
44
45 if (target) {
46 setImmediate(function () {
47 target.scrollIntoView()
48 })
49 }
50}
Math can be enabled in rehype by using the plugins
rehype-katex
or rehype-mathjax
.
The operate on span
s and div
s with certain classes and inject complex markup
and of inline styles, most of which this plugin will remove.
Say our module example.js
contains:
1import rehypeKatex from 'rehype-katex' 2import rehypeParse from 'rehype-parse' 3import rehypeSanitize from 'rehype-sanitize' 4import rehypeStringify from 'rehype-stringify' 5import {unified} from 'unified' 6 7const file = await unified() 8 .use(rehypeParse, {fragment: true}) 9 .use(rehypeKatex) 10 .use(rehypeSanitize) 11 .use(rehypeStringify) 12 .process('<span class="math math-inline">L</span>') 13 14console.log(String(file))
Running that yields:
1<span><span><span>LL</span><span aria-hidden="true"><span><span></span><span>L</span></span></span></span></span>
It is possible to pass a schema which allows MathML and inline styles, but it
would be complex, and allows all inline styles, which is unsafe.
Alternatively, and arguably better, would be to first sanitize the HTML,
allowing only the specific classes that rehype-katex
and rehype-mathjax
use,
and then using those plugins:
1@@ -1,7 +1,7 @@ 2 import rehypeKatex from 'rehype-katex' 3 import rehypeParse from 'rehype-parse' 4-import rehypeSanitize from 'rehype-sanitize' 5+import rehypeSanitize, {defaultSchema} from 'rehype-sanitize' 6 import rehypeStringify from 'rehype-stringify' 7 import {unified} from 'unified' 8 9 main() 10@@ -9,8 +9,21 @@ main() 11 const file = await unified() 12 .use(rehypeParse, {fragment: true}) 13+ .use(rehypeSanitize, { 14+ ...defaultSchema, 15+ attributes: { 16+ ...defaultSchema.attributes, 17+ div: [ 18+ ...(defaultSchema.attributes.div || []), 19+ ['className', 'math', 'math-display'] 20+ ], 21+ span: [ 22+ ...(defaultSchema.attributes.span || []), 23+ ['className', 'math', 'math-inline'] 24+ ] 25+ } 26+ }) 27 .use(rehypeKatex) 28- .use(rehypeSanitize) 29 .use(rehypeStringify) 30 .process('<span class="math math-inline">L</span>')
Highlighting, for example with rehype-highlight
, can be
solved similar to how math is solved (see previous example).
That is, use rehype-sanitize
and allow the classes needed for highlighting,
and highlight afterwards:
1import rehypeHighlight from 'rehype-highlight' 2import rehypeParse from 'rehype-parse' 3import rehypeSanitize, {defaultSchema} from 'rehype-sanitize' 4import rehypeStringify from 'rehype-stringify' 5import {unified} from 'unified' 6 7const file = await unified() 8 .use(rehypeParse, {fragment: true}) 9 .use(rehypeSanitize, { 10 ...defaultSchema, 11 attributes: { 12 ...defaultSchema.attributes, 13 code: [ 14 ...(defaultSchema.attributes.code || []), 15 // List of all allowed languages: 16 ['className', 'language-js', 'language-css', 'language-md'] 17 ] 18 } 19 }) 20 .use(rehypeHighlight, {subset: false}) 21 .use(rehypeStringify) 22 .process('<pre><code className="language-js">console.log(1)</code></pre>') 23 24console.log(String(file))
Alternatively, it’s possible to make highlighting safe by allowing all the classes used on tokens. Modifying the above code like so:
1 const file = await unified() 2 .use(rehypeParse, {fragment: true}) 3+ .use(rehypeHighlight, {subset: false}) 4 .use(rehypeSanitize, { 5 ...defaultSchema, 6 attributes: { 7 ...defaultSchema.attributes, 8- code: [ 9- ...(defaultSchema.attributes.code || []), 10- // List of all allowed languages: 11- ['className', 'hljs', 'language-js', 'language-css', 'language-md'] 12+ span: [ 13+ ...(defaultSchema.attributes.span || []), 14+ // List of all allowed tokens: 15+ ['className', 'hljs-addition', 'hljs-attr', 'hljs-attribute', 'hljs-built_in', 'hljs-bullet', 'hljs-char', 'hljs-code', 'hljs-comment', 'hljs-deletion', 'hljs-doctag', 'hljs-emphasis', 'hljs-formula', 'hljs-keyword', 'hljs-link', 'hljs-literal', 'hljs-meta', 'hljs-name', 'hljs-number', 'hljs-operator', 'hljs-params', 'hljs-property', 'hljs-punctuation', 'hljs-quote', 'hljs-regexp', 'hljs-section', 'hljs-selector-attr', 'hljs-selector-class', 'hljs-selector-id', 'hljs-selector-pseudo', 'hljs-selector-tag', 'hljs-string', 'hljs-strong', 'hljs-subst', 'hljs-symbol', 'hljs-tag', 'hljs-template-tag', 'hljs-template-variable', 'hljs-title', 'hljs-type', 'hljs-variable' 16+ ] 17 ] 18 } 19 }) 20- .use(rehypeHighlight, {subset: false}) 21 .use(rehypeStringify) 22 .process('<pre><code className="language-js">console.log(1)</code></pre>')
This package is fully typed with TypeScript.
It exports the additional type Options
.
Projects maintained by the unified collective are compatible with maintained versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line, rehype-sanitize@^6
,
compatible with Node.js 16.
This plugin works with rehype-parse
version 3+, rehype-stringify
version 3+,
rehype
version 5+, and unified
version 6+.
The defaults are safe but improper use of rehype-sanitize
can open you up to a
cross-site scripting (XSS) attack.
Use rehype-sanitize
after the last unsafe thing: everything after
rehype-sanitize
could be unsafe (but is fine if you do trust it).
hast-util-sanitize
— utility to sanitize hastrehype-format
— format HTMLrehype-minify
— minify HTMLSee contributing.md
in rehypejs/.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.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
security policy file detected
Details
Reason
Found 1/30 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
Project has not signed or included provenance with any releases.
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-06-30
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More