DOMPurify

DOMPurify

高效安全的DOM级XSS防护工具

DOMPurify是一款专业的DOM级XSS防护工具,适用于HTML、MathML和SVG。它可高效清理HTML字符串,去除潜在威胁,有效预防XSS攻击。这个库兼容多数现代浏览器,支持客户端和服务器端应用,并提供丰富的配置选项。作为由安全专家开发并经过严格测试的产品,DOMPurify是确保Web应用安全性的理想选择。

DOMPurifyXSSHTMLsanitizeJavaScriptGithub开源项目

DOMPurify

npm version Build and Test Downloads npm package minimized gzipped size (select exports) GitHub code size in bytes dependents

NPM

DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG.

It's also very simple to use and get started with. DOMPurify was started in February 2014 and, meanwhile, has reached version v3.1.6.

DOMPurify is written in JavaScript and works in all modern browsers (Safari (10+), Opera (15+), Edge, Firefox and Chrome - as well as almost anything else using Blink, Gecko or WebKit). It doesn't break on MSIE or other legacy browsers. It simply does nothing.

Note that DOMPurify v2.5.6 is the latest version supporting MSIE. For important security updates compatible with MSIE, please use the 2.x branch.

Our automated tests cover 19 different browsers right now, more to come. We also cover Node.js v16.x, v17.x, v18.x and v19.x, running DOMPurify on jsdom. Older Node versions are known to work as well, but hey... no guarantees.

DOMPurify is written by security people who have vast background in web attacks and XSS. Fear not. For more details please also read about our Security Goals & Threat Model. Please, read it. Like, really.

What does it do?

DOMPurify sanitizes HTML and prevents XSS attacks. You can feed DOMPurify with string full of dirty HTML and it will return a string (unless configured otherwise) with clean HTML. DOMPurify will strip out everything that contains dangerous HTML and thereby prevent XSS attacks and other nastiness. It's also damn bloody fast. We use the technologies the browser provides and turn them into an XSS filter. The faster your browser, the faster DOMPurify will be.

How do I use it?

It's easy. Just include DOMPurify on your website.

Using the unminified development version

<script type="text/javascript" src="src/purify.js"></script>

Using the minified and tested production version (source-map available)

<script type="text/javascript" src="dist/purify.min.js"></script>

Afterwards you can sanitize strings by executing the following code:

const clean = DOMPurify.sanitize(dirty);

Or maybe this, if you love working with Angular or alike:

import DOMPurify from 'dompurify'; const clean = DOMPurify.sanitize('<b>hello there</b>');

The resulting HTML can be written into a DOM element using innerHTML or the DOM using document.write(). That is fully up to you. Note that by default, we permit HTML, SVG and MathML. If you only need HTML, which might be a very common use-case, you can easily set that up as well:

const clean = DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } });

Where are the TypeScript type definitions?

They can be found here: @types/dompurify

Is there any foot-gun potential?

Well, please note, if you first sanitize HTML and then modify it afterwards, you might easily void the effects of sanitization. If you feed the sanitized markup to another library after sanitization, please be certain that the library doesn't mess around with the HTML on its own.

Okay, makes sense, let's move on

After sanitizing your markup, you can also have a look at the property DOMPurify.removed and find out, what elements and attributes were thrown out. Please do not use this property for making any security critical decisions. This is just a little helper for curious minds.

Running DOMPurify on the server

DOMPurify technically also works server-side with Node.js. Our support strives to follow the Node.js release cycle.

Running DOMPurify on the server requires a DOM to be present, which is probably no surprise. Usually, jsdom is the tool of choice and we strongly recommend to use the latest version of jsdom.

Why? Because older versions of jsdom are known to be buggy in ways that result in XSS even if DOMPurify does everything 100% correctly. There are known attack vectors in, e.g. jsdom v19.0.0 that are fixed in jsdom v20.0.0 - and we really recommend to keep jsdom up to date because of that.

Please also be aware that tools like happy-dom exist but are not considered safe at this point. Combining DOMPurify with happy-dom is currently not recommended and will likely lead to XSS.

Other than that, you are fine to use DOMPurify on the server. Probably. This really depends on jsdom or whatever DOM you utilize server-side. If you can live with that, this is how you get it to work:

npm install dompurify npm install jsdom

For jsdom (please use an up-to-date version), this should do the trick:

const createDOMPurify = require('dompurify'); const { JSDOM } = require('jsdom'); const window = new JSDOM('').window; const DOMPurify = createDOMPurify(window); const clean = DOMPurify.sanitize('<b>hello there</b>');

Or even this, if you prefer working with imports:

import { JSDOM } from 'jsdom'; import DOMPurify from 'dompurify'; const window = new JSDOM('').window; const purify = DOMPurify(window); const clean = purify.sanitize('<b>hello there</b>');

If you have problems making it work in your specific setup, consider looking at the amazing isomorphic-dompurify project which solves lots of problems people might run into.

npm install isomorphic-dompurify
import DOMPurify from 'isomorphic-dompurify'; const clean = DOMPurify.sanitize('<s>hello</s>');

Is there a demo?

Of course there is a demo! Play with DOMPurify

What if I find a security bug?

First of all, please immediately contact us via email so we can work on a fix. PGP key

Also, you probably qualify for a bug bounty! The fine folks over at Fastmail use DOMPurify for their services and added our library to their bug bounty scope. So, if you find a way to bypass or weaken DOMPurify, please also have a look at their website and the bug bounty info.

Some purification samples please?

How does purified markup look like? Well, the demo shows it for a big bunch of nasty elements. But let's also show some smaller examples!

DOMPurify.sanitize('<img src=x onerror=alert(1)//>'); // becomes <img src="x"> DOMPurify.sanitize('<svg><g/onload=alert(2)//<p>'); // becomes <svg><g></g></svg> DOMPurify.sanitize('<p>abc<iframe//src=jAva&Tab;script:alert(3)>def</p>'); // becomes <p>abc</p> DOMPurify.sanitize('<math><mi//xlink:href="data:x,<script>alert(4)</script>">'); // becomes <math><mi></mi></math> DOMPurify.sanitize('<TABLE><tr><td>HELLO</tr></TABL>'); // becomes <table><tbody><tr><td>HELLO</td></tr></tbody></table> DOMPurify.sanitize('<UL><li><A HREF=//google.com>click</UL>'); // becomes <ul><li><a href="//google.com">click</a></li></ul>

What is supported?

DOMPurify currently supports HTML5, SVG and MathML. DOMPurify per default allows CSS, HTML custom data attributes. DOMPurify also supports the Shadow DOM - and sanitizes DOM templates recursively. DOMPurify also allows you to sanitize HTML for being used with the jQuery $() and elm.html() API without any known problems.

What about legacy browsers like Internet Explorer?

DOMPurify does nothing at all. It simply returns exactly the string that you fed it. DOMPurify exposes a property called isSupported, which tells you whether it will be able to do its job, so you can come up with your own backup plan.

What about DOMPurify and Trusted Types?

In version 1.0.9, support for Trusted Types API was added to DOMPurify. In version 2.0.0, a config flag was added to control DOMPurify's behavior regarding this.

When DOMPurify.sanitize is used in an environment where the Trusted Types API is available and RETURN_TRUSTED_TYPE is set to true, it tries to return a TrustedHTML value instead of a string (the behavior for RETURN_DOM and RETURN_DOM_FRAGMENT config options does not change).

Note that in order to create a policy in trustedTypes using DOMPurify, RETURN_TRUSTED_TYPE: false is required, as createHTML expects a normal string, not TrustedHTML. The example below shows this.

window.trustedTypes!.createPolicy('default', { createHTML: (to_escape) => DOMPurify.sanitize(to_escape, { RETURN_TRUSTED_TYPE: false }), });

Can I configure DOMPurify?

Yes. The included default configuration values are pretty good already - but you can of course override them. Check out the /demos folder to see a bunch of examples on how you can customize DOMPurify.

General settings

// strip {{ ... }}, ${ ... } and <% ... %> to make output safe for template systems // be careful please, this mode is not recommended for production usage. // allowing template parsing in user-controlled HTML is not advised at all. // only use this mode if there is really no alternative. const clean = DOMPurify.sanitize(dirty, {SAFE_FOR_TEMPLATES: true}); // change how e.g. comments containing risky HTML characters are treated. // be very careful, this setting should only be set to `false` if you really only handle // HTML and nothing else, no SVG, MathML or the like. // Otherwise, changing from `true` to `false` will lead to XSS in this or some other way. const clean = DOMPurify.sanitize(dirty, {SAFE_FOR_XML: false});

Control our allow-lists and block-lists

// allow only <b> elements, very strict const clean = DOMPurify.sanitize(dirty, {ALLOWED_TAGS: ['b']}); // allow only <b> and <q> with style attributes const clean = DOMPurify.sanitize(dirty, {ALLOWED_TAGS: ['b', 'q'], ALLOWED_ATTR: ['style']}); // allow all safe HTML elements but neither SVG nor MathML // note that the USE_PROFILES setting will override the ALLOWED_TAGS setting // so don't use them together const clean = DOMPurify.sanitize(dirty, {USE_PROFILES: {html: true}}); // allow all safe SVG elements and SVG Filters, no HTML or MathML const clean = DOMPurify.sanitize(dirty, {USE_PROFILES: {svg: true, svgFilters: true}}); // allow all safe MathML elements and SVG, but no SVG Filters const clean = DOMPurify.sanitize(dirty, {USE_PROFILES: {mathMl: true, svg: true}}); // change the default namespace from HTML to something different const clean = DOMPurify.sanitize(dirty, {NAMESPACE: 'http://www.w3.org/2000/svg'}); // leave all safe HTML as it is and add <style> elements to block-list const clean = DOMPurify.sanitize(dirty, {FORBID_TAGS: ['style']}); // leave all safe HTML as it is and add style attributes to block-list const clean = DOMPurify.sanitize(dirty, {FORBID_ATTR: ['style']}); // extend the existing array of allowed tags and add <my-tag> to allow-list const clean = DOMPurify.sanitize(dirty, {ADD_TAGS: ['my-tag']}); // extend the existing array of allowed attributes and add my-attr to allow-list const clean = DOMPurify.sanitize(dirty, {ADD_ATTR: ['my-attr']}); // prohibit ARIA attributes, leave other safe HTML as is (default is true) const clean = DOMPurify.sanitize(dirty, {ALLOW_ARIA_ATTR: false}); // prohibit HTML5 data attributes, leave other safe HTML as is (default is true) const clean = DOMPurify.sanitize(dirty, {ALLOW_DATA_ATTR: false});

Control behavior relating to Custom Elements

// DOMPurify allows to define rules for Custom Elements. When using the CUSTOM_ELEMENT_HANDLING // literal, it is possible to define exactly what elements you wish to allow (by default, none are allowed). // // The same goes for their attributes. By default, the built-in or configured allow.list is used. // // You can use a RegExp literal to specify what is allowed or a predicate, examples for both can be seen below. // The default values are very restrictive to prevent accidental XSS bypasses. Handle with great care! const clean = DOMPurify.sanitize( '<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>', { CUSTOM_ELEMENT_HANDLING: { tagNameCheck: null, // no custom elements are allowed attributeNameCheck: null, // default / standard attribute allow-list is used allowCustomizedBuiltInElements: false, // no customized built-ins allowed }, } ); // <div is=""></div> const clean = DOMPurify.sanitize( '<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>', { CUSTOM_ELEMENT_HANDLING: { tagNameCheck: /^foo-/, // allow all tags starting with "foo-" attributeNameCheck: /baz/, // allow all attributes containing "baz" allowCustomizedBuiltInElements: true, // customized built-ins are allowed }, } ); // <foo-bar baz="foobar"></foo-bar><div is="foo-baz"></div> const clean = DOMPurify.sanitize( '<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>', { CUSTOM_ELEMENT_HANDLING: { tagNameCheck: (tagName) => tagName.match(/^foo-/), // allow all tags starting with "foo-" attributeNameCheck: (attr) => attr.match(/baz/), // allow all containing "baz" allowCustomizedBuiltInElements: true, // allow customized built-ins }, } ); // <foo-bar baz="foobar"></foo-bar><div is="foo-baz"></div>

Control behavior relating to URI values

// extend the existing array of elements that can use Data URIs const clean = DOMPurify.sanitize(dirty, {ADD_DATA_URI_TAGS: ['a', 'area']}); // extend the existing array of elements that are safe for URI-like values (be careful, XSS risk) const clean = DOMPurify.sanitize(dirty, {ADD_URI_SAFE_ATTR: ['my-attr']});

Control permitted attribute

编辑推荐精选

Trae

Trae

字节跳动发布的AI编程神器IDE

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

AI工具TraeAI IDE协作生产力转型热门
问小白

问小白

全能AI智能助手,随时解答生活与工作的多样问题

问小白,由元石科技研发的AI智能助手,快速准确地解答各种生活和工作问题,包括但不限于搜索、规划和社交互动,帮助用户在日常生活中提高效率,轻松管理个人事务。

热门AI助手AI对话AI工具聊天机器人
Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞智文

讯飞智文

一键生成PPT和Word,让学习生活更轻松

讯飞智文是一个利用 AI 技术的项目,能够帮助用户生成 PPT 以及各类文档。无论是商业领域的市场分析报告、年度目标制定,还是学生群体的职业生涯规划、实习避坑指南,亦或是活动策划、旅游攻略等内容,它都能提供支持,帮助用户精准表达,轻松呈现各种信息。

AI办公办公工具AI工具讯飞智文AI在线生成PPTAI撰写助手多语种文档生成AI自动配图热门
讯飞星火

讯飞星火

深度推理能力全新升级,全面对标OpenAI o1

科大讯飞的星火大模型,支持语言理解、知识问答和文本创作等多功能,适用于多种文件和业务场景,提升办公和日常生活的效率。讯飞星火是一个提供丰富智能服务的平台,涵盖科技资讯、图像创作、写作辅助、编程解答、科研文献解读等功能,能为不同需求的用户提供便捷高效的帮助,助力用户轻松获取信息、解决问题,满足多样化使用场景。

热门AI开发模型训练AI工具讯飞星火大模型智能问答内容创作多语种支持智慧生活
Spark-TTS

Spark-TTS

一种基于大语言模型的高效单流解耦语音令牌文本到语音合成模型

Spark-TTS 是一个基于 PyTorch 的开源文本到语音合成项目,由多个知名机构联合参与。该项目提供了高效的 LLM(大语言模型)驱动的语音合成方案,支持语音克隆和语音创建功能,可通过命令行界面(CLI)和 Web UI 两种方式使用。用户可以根据需求调整语音的性别、音高、速度等参数,生成高质量的语音。该项目适用于多种场景,如有声读物制作、智能语音助手开发等。

咔片PPT

咔片PPT

AI助力,做PPT更简单!

咔片是一款轻量化在线演示设计工具,借助 AI 技术,实现从内容生成到智能设计的一站式 PPT 制作服务。支持多种文档格式导入生成 PPT,提供海量模板、智能美化、素材替换等功能,适用于销售、教师、学生等各类人群,能高效制作出高品质 PPT,满足不同场景演示需求。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

热门AI辅助写作AI工具讯飞绘文内容运营AI创作个性化文章多平台分发AI助手
材料星

材料星

专业的AI公文写作平台,公文写作神器

AI 材料星,专业的 AI 公文写作辅助平台,为体制内工作人员提供高效的公文写作解决方案。拥有海量公文文库、9 大核心 AI 功能,支持 30 + 文稿类型生成,助力快速完成领导讲话、工作总结、述职报告等材料,提升办公效率,是体制打工人的得力写作神器。

openai-agents-python

openai-agents-python

OpenAI Agents SDK,助力开发者便捷使用 OpenAI 相关功能。

openai-agents-python 是 OpenAI 推出的一款强大 Python SDK,它为开发者提供了与 OpenAI 模型交互的高效工具,支持工具调用、结果处理、追踪等功能,涵盖多种应用场景,如研究助手、财务研究等,能显著提升开发效率,让开发者更轻松地利用 OpenAI 的技术优势。

下拉加载更多