### Install rehype-sanitize Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md Instructions for installing the rehype-sanitize package using npm, Deno, or in the browser. ```APIDOC ## Install This package is [ESM only][esm]. In Node.js (version 16+), install with [npm][]: ```sh npm install rehype-sanitize ``` In Deno with [`esm.sh`][esmsh]: ```js import rehypeSanitize from 'https://esm.sh/rehype-sanitize@6' ``` In browsers with [`esm.sh`][esmsh]: ```html ``` ``` -------------------------------- ### Install rehype-sanitize with npm Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md Install the package using npm for Node.js environments (version 16+). ```sh npm install rehype-sanitize ``` -------------------------------- ### Use rehype-sanitize Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md Example demonstrating how to use rehype-sanitize in a Node.js project to sanitize HTML content. ```APIDOC ## Use Say we have the following file `index.html`: ```html
delta
``` …and our module `example.js` looks as follows: ```js import rehypeParse from 'rehype-parse' import rehypeSanitize from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' import {read} from 'to-vfile' import {unified} from 'unified' const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeSanitize) .use(rehypeStringify) .process(await read('index.html')) console.log(String(file)) ``` Now running `node example.js` yields: ```html
delta
``` ``` -------------------------------- ### Example HTML input for sanitization Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This HTML content contains various potentially unsafe elements and attributes that will be processed by rehype-sanitize. ```html
delta
``` -------------------------------- ### Processing HTML with Rehype and Inlining a Script Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This code processes an HTML string, parses it, injects a browser script, and stringifies it back to HTML. It serves as the setup for demonstrating DOM clobbering. ```javascript /** * @typedef {import('hast').Root} Root */ import fs from 'node:fs/promises' import rehypeParse from 'rehype-parse' import rehypeStringify from 'rehype-stringify' import {unified} from 'unified' const browser = String(await fs.readFile('browser.js')) const document = `

Current

${`

${'Lorem ipsum dolor sit amet. '.repeat(20)}

`.repeat(20)}

Link to current, link to old.` const file = await unified() .use(rehypeParse, {fragment: true}) .use(function () { /** * @param {Root} tree */ return function (tree) { tree.children.push({ type: 'element', tagName: 'script', properties: {type: 'module'}, children: [{type: 'text', value: browser}] }) } }) .use(rehypeStringify) .process(document) await fs.writeFile('output.html', String(file)) ``` -------------------------------- ### Sanitized HTML output Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md The result of processing the example HTML with rehype-sanitize, showing that unsafe elements and attributes have been removed. ```html

delta
``` -------------------------------- ### Browser Script for DOM Clobbering Example Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This script is intended to be inlined into HTML. It logs the global `current` variable, which can be overshadowed by an HTML element's ID in a DOM clobbering attack. ```javascript console.log(current) ``` -------------------------------- ### Import rehype-sanitize in Browser Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md Import the package in the browser using esm.sh with bundling. ```html ``` -------------------------------- ### Import rehype-sanitize in Deno Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md Import the package in Deno using esm.sh. ```js import rehypeSanitize from 'https://esm.sh/rehype-sanitize@6' ``` -------------------------------- ### Enable Math Rendering with Rehype Katex Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This snippet shows how to enable math rendering using rehype-katex by allowing specific classes for math content in the sanitize schema. It processes an inline math code. ```javascript import rehypeKatex from 'rehype-katex' import rehypeParse from 'rehype-parse' import rehypeSanitize from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' import {unified} from 'unified' const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeKatex) .use(rehypeSanitize) .use(rehypeStringify) .process('L') console.log(String(file)) ``` -------------------------------- ### API: Options Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md Describes the Options type for configuring the sanitization schema. ```APIDOC ### `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`][hast-util-sanitize-schema]. ``` -------------------------------- ### Configure Sanitize Schema for Math Classes Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This diff shows how to configure rehype-sanitize to allow specific classes for math rendering before applying rehype-katex. It modifies the schema to include 'math-inline' and 'math-display' classes for code elements. ```diff import rehypeKatex from 'rehype-katex' import rehypeParse from 'rehype-parse' import rehypeSanitize, {defaultSchema} from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' import {unified} from 'unified' const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeSanitize, { ...defaultSchema, attributes: { ...defaultSchema.attributes, // The `language-*` regex is allowed by default. code: [['className', /^language-./, 'math-inline', 'math-display']] } }) .use(rehypeKatex) .use(rehypeStringify) .process('L') ``` -------------------------------- ### Enable Syntax Highlighting with Rehype Highlight Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This snippet demonstrates enabling syntax highlighting with rehype-highlight by configuring rehype-sanitize to allow specific language classes for code elements. It processes a JavaScript code block. ```javascript import rehypeHighlight from 'rehype-highlight' import rehypeParse from 'rehype-parse' import rehypeSanitize, {defaultSchema} from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' import {unified} from 'unified' const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeSanitize, { ...defaultSchema, attributes: { ...defaultSchema.attributes, code: [ ...(defaultSchema.attributes.code || []), // List of all allowed languages: ['className', 'language-js', 'language-css', 'language-md'] ] } }) .use(rehypeHighlight, {subset: false}) .use(rehypeStringify) .process('
console.log(1)
') console.log(String(file)) ``` -------------------------------- ### Allow All Token Classes for Safe Highlighting Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This diff shows an alternative approach to safe syntax highlighting by modifying the sanitize schema to allow all token classes used by rehype-highlight on span elements. This ensures all highlighting tokens are preserved. ```diff const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeHighlight, {subset: false}) .use(rehypeSanitize, { ...defaultSchema, attributes: { ...defaultSchema.attributes, span: [ ...(defaultSchema.attributes.span || []), // List of all allowed tokens: ['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' ] } }) .use(rehypeStringify) .process('
console.log(1)
') ``` -------------------------------- ### Sanitizing HTML with Rehype Sanitize Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This diff shows the addition of `.use(rehypeSanitize)` to the unified pipeline. This step is crucial for preventing DOM clobbering by sanitizing `id` and `name` attributes. ```diff @@ -15,6 +15,7 @@ ${`

${'Lorem ipsum dolor sit amet. '.repeat(20)}

`.repeat(20)} const file = await unified() .use(rehypeParse, {fragment: true}) + .use(rehypeSanitize) .use(function () { /** * @param {Root} tree ``` -------------------------------- ### JavaScript module for rehype-sanitize usage Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This module demonstrates how to use rehype-sanitize with rehype-parse and rehype-stringify to process an HTML file. ```js import rehypeParse from 'rehype-parse' import rehypeSanitize from 'rehype-sanitize' import rehypeStringify from 'rehype-stringify' import {read} from 'to-vfile' import {unified} from 'unified' const file = await unified() .use(rehypeParse, {fragment: true}) .use(rehypeSanitize) .use(rehypeStringify) .process(await read('index.html')) console.log(String(file)) ``` -------------------------------- ### API: defaultSchema Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md Exports the default schema used for sanitization, which follows GitHub style sanitation. ```APIDOC ## API This package exports the identifier [`defaultSchema`][api-default-schema]. The default export is [`rehypeSanitize`][api-rehype-sanitize]. ### `defaultSchema` Default schema ([`Options`][api-options]). Follows GitHub style sanitation. ``` -------------------------------- ### API: rehypeSanitize Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md The main export function to sanitize HTML. It takes an optional schema configuration. ```APIDOC ### `unified().use(rehypeSanitize[, schema])` Sanitize HTML. ###### Parameters * `options` ([`Options`][api-options], optional) — configuration ###### Returns Transform ([`Transformer`][unified-transformer]). ``` -------------------------------- ### Browser Script for Handling Sanitized Links Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This JavaScript code replaces the original browser script. It handles `hashchange` and `click` events to ensure that links pointing to sanitized IDs (prefixed with 'user-content-') correctly scroll to their targets. ```javascript /// /* eslint-env browser */ // Page load (you could wrap this in a DOM ready if the script is loaded early). hashchange() // When URL changes. window.addEventListener('hashchange', hashchange) // When on the URL already, perhaps after scrolling, and clicking again, which // doesn’t emit `hashchange`. document.addEventListener( 'click', function (event) { if ( event.target && event.target instanceof HTMLAnchorElement && event.target.href === location.href && location.hash.length > 1 ) { setImmediate(function () { if (!event.defaultPrevented) { hashchange() } }) } }, false ) function hashchange() { /** @type {string | undefined} */ let hash try { hash = decodeURIComponent(location.hash.slice(1)).toLowerCase() } catch { return } const name = 'user-content-' + hash const target = document.getElementById(name) || document.getElementsByName(name)[0] if (target) { setImmediate(function () { target.scrollIntoView() }) } } ``` -------------------------------- ### Sanitized HTML Output Source: https://github.com/rehypejs/rehype-sanitize/blob/main/readme.md This HTML shows the result after applying `rehype-sanitize`. Notice how `id` and `name` attributes are prefixed with 'user-content-' to prevent clobbering. ```html

Current

``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.