{"_id":"sanitize-html-react","_rev":"3276174","name":"sanitize-html-react","description":"Modified sanitize-html for React. Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis","dist-tags":{"latest":"1.13.0"},"maintainers":[{"name":"zacharystenger","email":""}],"time":{"modified":"2024-03-21T10:27:29.000Z","created":"2016-08-29T04:44:35.221Z","1.13.0":"2016-08-29T04:44:35.221Z"},"users":{},"author":{"name":"P'unk Avenue LLC, Zachary Stenger","email":"zackstenger@gmail.com"},"repository":{"type":"git","url":"git+https://github.com/zacharystenger/sanitize-html-react.git"},"versions":{"1.13.0":{"name":"sanitize-html-react","version":"1.13.0","description":"Modified sanitize-html for React. Clean up user-submitted HTML, preserving whitelisted elements and whitelisted attributes on a per-element basis","main":"index.js","scripts":{"build":"browserify index.js > dist/sanitize-html-react.js --standalone 'sanitizeHtml'","minify":"npm run build && uglifyjs dist/sanitize-html-react.js > dist/sanitize-html-react.min.js","test":"mocha test/test.js","prebuild":"npm run test && rm -rf dist && mkdir dist"},"repository":{"type":"git","url":"git+https://github.com/zacharystenger/sanitize-html-react.git"},"keywords":["html","parser","sanitizer","html","sanitizer","apostrophe","react","jsx"],"author":{"name":"P'unk Avenue LLC, Zachary Stenger","email":"zackstenger@gmail.com"},"license":"MIT","dependencies":{"htmlparser2":"^3.9.0","regexp-quote":"0.0.0","xtend":"^4.0.0"},"devDependencies":{"browserify":"^13.0.1","mocha":"^2.5.3","uglify-js":"^2.6.2"},"gitHead":"2b527e9cdcedf9badbc626ca2ec6664ca81f444b","bugs":{"url":"https://github.com/zacharystenger/sanitize-html-react/issues"},"homepage":"https://github.com/zacharystenger/sanitize-html-react#readme","_id":"sanitize-html-react@1.13.0","_shasum":"e757b9adbaf2c8a762f3d2dff70138838e05420a","_from":".","_npmVersion":"2.11.3","_nodeVersion":"0.12.7","_npmUser":{"name":"zacharystenger","email":"zackstenger@gmail.com"},"dist":{"shasum":"e757b9adbaf2c8a762f3d2dff70138838e05420a","size":20203,"noattachment":false,"key":"/sanitize-html-react/-/sanitize-html-react-1.13.0.tgz","tarball":"http://registry.cnpm.dingdandao.com/sanitize-html-react/download/sanitize-html-react-1.13.0.tgz"},"maintainers":[{"name":"zacharystenger","email":""}],"_npmOperationalInternal":{"host":"packages-16-east.internal.npmjs.com","tmp":"tmp/sanitize-html-react-1.13.0.tgz_1472445872947_0.26636813418008387"},"directories":{},"publish_time":1472445875221,"_hasShrinkwrap":false,"_cnpm_publish_time":1472445875221,"_cnpmcore_publish_time":"2021-12-16T11:26:52.833Z"}},"readme":"This is slightly modified version of `sanitize-html` made for React. It no longer escapes the < > \" & characters because React already escapes for you as described <a href=\"https://facebook.github.io/react/docs/jsx-gotchas.html#html-entities\">here</a>. The following is the original readme for `sanitize-html`:\n\n\n# sanitize-html\n\n<a href=\"http://apostrophenow.org/\"><img src=\"https://raw.github.com/punkave/sanitize-html/master/logos/logo-box-madefor.png\" align=\"right\" /></a>\n\n`sanitize-html` provides a simple HTML sanitizer with a clear API.\n\n`sanitize-html` is tolerant. It is well suited for cleaning up HTML fragments such as those created by ckeditor and other rich text editors. It is especially handy for removing unwanted CSS when copying and pasting from Word.\n\n`sanitize-html` allows you to specify the tags you want to permit, and the permitted attributes for each of those tags.\n\nIf a tag is not permitted, the contents of the tag are still kept, except for `script`, `style` and `textarea` tags.\n\nThe syntax of poorly closed `p` and `img` elements is cleaned up.\n\n`href` attributes are validated to ensure they only contain `http`, `https`, `ftp` and `mailto` URLs. Relative URLs are also allowed. Ditto for `src` attributes.\n\nHTML comments are not preserved.\n\n## Requirements\n\n`sanitize-html` is intended for use with Node. That's pretty much it. All of its npm dependencies are pure JavaScript. `sanitize-html` is built on the excellent `htmlparser2` module.\n\n## How to use\n\n### Browser \n\n*Think first: why do you want to use it in the browser?* Remember, *servers must never trust browsers.* You can't sanitize HTML for saving on the server anywhere else but on the server.\n\nBut, perhaps you'd like to display sanitized HTML immediately in the browser for preview. Or ask the browser to do the sanitization work on every page load. You can if you want to!\n\n* Clone repository\n* Run npm install and build / minify:\n\n```bash\nnpm install\nnpm run minify\n```\n\nYou'll find the minified and unminified versions of sanitize-html (with all its dependencies included) in the dist/ directory.\n\nUse it in the browser:\n\n```html\n<html>\n    <body>\n        <script type=\"text/javascript\"  src=\"dist/sanitize-html.js\"></script>\n        <script type=\"text/javascript\" src=\"demo.js\"></script>\n    </body>\n</html>\n```\n\n```javascript\nvar html = \"<strong>hello world</strong>\";\nconsole.log(sanitizeHtml(html));\nconsole.log(sanitizeHtml(\"<img src=x onerror=alert('img') />\"));\nconsole.log(sanitizeHtml(\"console.log('hello world')\"));\nconsole.log(sanitizeHtml(\"<script>alert('hello world')</script>\"));\n```\n\n### Node (Recommended)\n\nInstall module from console:\n\n```bash\nnpm install sanitize-html\n```\n\nUse it in your node app:\n\n```js\nvar sanitizeHtml = require('sanitize-html');\n\nvar dirty = 'some really tacky HTML';\nvar clean = sanitizeHtml(dirty);\n```\n\nThat will allow our default list of allowed tags and attributes through. It's a nice set, but probably not quite what you want. So:\n\n```js\n// Allow only a super restricted set of tags and attributes\nclean = sanitizeHtml(dirty, {\n  allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ],\n  allowedAttributes: {\n    'a': [ 'href' ]\n  }\n});\n```\n\nBoom!\n\n#### \"I like your set but I want to add one more tag. Is there a convenient way?\" Sure:\n\n```js\nclean = sanitizeHtml(dirty, {\n  allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ])\n});\n```\n\nIf you do not specify `allowedTags` or `allowedAttributes` our default list is applied. So if you really want an empty list, specify one.\n\n#### \"What are the default options?\"\n\n```js\nallowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol',\n  'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'code', 'hr', 'br', 'div',\n  'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre' ],\nallowedAttributes: {\n  a: [ 'href', 'name', 'target' ],\n  // We don't currently allow img itself by default, but this\n  // would make sense if we did\n  img: [ 'src' ]\n},\n// Lots of these won't come up by default because we don't allow them\nselfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ],\n// URL schemes we permit\nallowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ],\nallowedSchemesByTag: {}\n```\n\n#### \"What if I want to allow all tags or all attributes?\"\n\nSimple! instead of leaving `allowedTags` or `allowedAttributes` out of the options, set either\none or both to `false`:\n\n```js\nallowedTags: false,\nallowedAttributes: false\n```\n\n#### \"What if I don't want to allow *any* tags?\"\n\nAlso simple!  Set your `allowedTag` and `allowedAttributes` to empty arrays (`[]`).\n\n```js\nallowedTags: [],\nallowedAttributes: []\n```\n\n### Wildcards for attributes\n\nYou can use the `*` wildcard to allow all attributes with a certain prefix:\n\n```javascript\nallowedAttributes: {\n  a: [ 'href', 'data-*' ]\n}\n```\n\nAlso you can use the `*` as name for a tag, to allow listed attributes to be valid for any tag:\n\n```javascript\nallowedAttributes: {\n  '*': [ 'href', 'align', 'alt', 'center', 'bgcolor' ]\n}\n```\n\n### htmlparser2 Options\n\n`santizeHtml` is built on `htmlparser2`. By default the only option passed down is `decodeEntities: true` You can set the options to pass by using the parser option.\n\n```javascript\nclean = sanitizeHtml(dirty, {\n  allowedTags: ['a'],\n  parser: {\n    lowerCaseTags: true\n  }\n});\n```\nSee the [htmlparser2 wiki] (https://github.com/fb55/htmlparser2/wiki/Parser-options) for the full list of possible options.\n\n### Transformations\n\nWhat if you want to add or change an attribute? What if you want to transform one tag to another? No problem, it's simple!\n\nThe easiest way (will change all `ol` tags to `ul` tags):\n\n```js\nclean = sanitizeHtml(dirty, {\n  transformTags: {\n    'ol': 'ul',\n  }\n});\n```\n\nThe most advanced usage:\n\n```js\nclean = sanitizeHtml(dirty, {\n  transformTags: {\n    'ol': function(tagName, attribs) {\n        // My own custom magic goes here\n\n        return {\n            tagName: 'ul',\n            attribs: {\n                class: 'foo'\n            }\n        };\n    }\n  }\n});\n```\n\nYou can specify the `*` wildcard instead of a tag name to transform all tags.\n\nThere is also a helper method which should be enough for simple cases in which you want to change the tag and/or add some attributes:\n\n```js\nclean = sanitizeHtml(dirty, {\n  transformTags: {\n    'ol': sanitizeHtml.simpleTransform('ul', {class: 'foo'}),\n  }\n});\n```\n\nThe `simpleTransform` helper method has 3 parameters:\n\n```js\nsimpleTransform(newTag, newAttributes, shouldMerge)\n```\n\nThe last parameter (`shouldMerge`) is set to `true` by default. When `true`, `simpleTransform` will merge the current attributes with the new ones (`newAttributes`). When `false`, all existing attributes are discarded.\n\nYou can also add or modify the text contents of a tag:\n\n```js\nclean = sanitizeHtml(dirty, {\n  transformTags: {\n    'a': function(tagName, attribs) {\n        return {\n            tagName: 'a',\n            text: 'Some text'\n        };\n    }\n  }\n});\n```\nFor example, you could transform a link element with missing anchor text:\n```js\n<a href=\"http://somelink.com\"></a>\n```\nTo a link with anchor text:\n```js\n<a href=\"http://somelink.com\">Some text</a>\n```\n\n### Filters\n\nYou can provide a filter function to remove unwanted tags. Let's suppose we need to remove empty `a` tags like:\n\n```html\n<a href=\"page.html\"></a>\n```\n\nWe can do that with the following filter:\n\n```javascript\nsanitizeHtml(\n  '<p>This is <a href=\"http://www.linux.org\"></a><br/>Linux</p>',\n  {\n    exclusiveFilter: function(frame) {\n        return frame.tag === 'a' && !frame.text.trim();\n    }\n  }\n);\n```\n\nThe `frame` object supplied to the callback provides the following attributes:\n\n - `tag`: The tag name, i.e. `'img'`.\n - `attribs`: The tag's attributes, i.e. `{ src: \"/path/to/tux.png\" }`.\n - `text`: The text content of the tag.\n - `tagPosition`: The index of the tag's position in the result string.\n\nYou can also process all text content with a provided filter function. Let's say we want an ellipsis instead of three dots.\n\n```html\n<p>some text...</p>\n```\n\nWe can do that with the following filter:\n\n```javascript\nsanitizeHtml(\n  '<p>some text...</p>',\n  {\n    textFilter: function(text) {\n      return text.replace(/\\.\\.\\./, '&hellip;');\n    }\n  }\n);\n```\n\nNote that the text passed to the `textFilter` method is already escaped for safe display as HTML. You may add markup and use entity escape sequences in your `textFilter`.\n\n### Allowed CSS Classes\n\nIf you wish to allow specific CSS classes on a particular element, you can do so with the `allowedClasses` option. Any other CSS classes are discarded.\n\nThis implies that the `class` attribute is allowed on that element.\n\n```javascript\n// Allow only a restricted set of CSS classes and only on the p tag\nclean = sanitizeHtml(dirty, {\n  allowedTags: [ 'p', 'em', 'strong' ],\n  allowedClasses: {\n    'p': [ 'fancy', 'simple' ]\n  }\n});\n```\n\n### Allowed URL schemes\n\nBy default we allow the following URL schemes in cases where `href`, `src`, etc. are allowed:\n\n```js\n[ 'http', 'https', 'ftp', 'mailto' ]\n```\n\nYou can override this if you want to:\n\n```javascript\nsanitizeHtml(\n  // teeny-tiny valid transparent GIF in a data URL\n  '<img src=\"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\" />',\n  {\n    allowedTags: [ 'img', 'p' ],\n    allowedSchemes: [ 'data', 'http' ]\n  }\n);\n```\n\nYou can also allow a scheme for a particular tag only:\n\n```javascript\nallowedSchemes: [ 'http', 'https' ],\nallowedSchemesByTag: {\n  img: [ 'data' ]\n}\n```\n\n### Discarding the entire contents of a disallowed tag\n\nNormally, with a few exceptions, if a tag is not allowed, all of the text within it is preserved, and so are any allowed tags within it.\n\nThe exceptions are:\n\n`style`, `script`, `textarea`\n\nIf you wish to expand this list, for instance to discard whatever is found inside a `noscript` tag, use the `nonTextTags` option:\n\n```javascript\nnonTextTags: [ 'style', 'script', 'textarea', 'noscript' ]\n```\n\nNote that if you use this option you are responsible for stating the entire list. This gives you the power to retain the content of `textarea`, if you want to.\n\nThe content still gets escaped properly, with the exception of the `script` and `style` tags. *Allowing either `script` or `style` leaves you open to XSS attacks. Don't do that* unless you have good reason to trust their origin.\n\n## Changelog\n\n1.13.0: `transformTags` can now add text to an element that initially had none. Thanks to Dushyant Singh.\n\n1.12.0: option to build for browser-side use. Thanks to Michael Blum.\n\n1.11.4: fixed crash when `__proto__` is a tag name. Now using a safe check for the existence of properties in all cases. Thanks to Andrew Krasichkov.\n\nFixed XSS attack vector via `textarea` tags (when explicitly allowed). Decided that `script` (obviously) and `style` (due to its own XSS vectors) cannot realistically be afforded any XSS protection if allowed, unless we add a full CSS parser. Thanks again to Andrew Krasichkov.\n\n1.11.3: bumped `htmlparser2` version to address crashing bug in older version. Thanks to e-jigsaw.\n\n1.11.2: fixed README typo that interfered with readability due to markdown issues. No code changes. Thanks to Mikael Korpela. Also improved code block highlighting in README. Thanks to Alex Siman.\n\n1.11.1: fixed a regression introduced in 1.11.0 which caused the closing tag of the parent of a `textarea` tag to be lost. Thanks to Stefano Sala, who contributed the missing test.\n\n1.11.0: added the `nonTextTags` option, with tests.\n\n1.10.1: documentation cleanup. No code changes. Thanks to Rex Schrader.\n\n1.10.0: `allowedAttributes` now allows you to allow attributes for all tags by specifying `*` as the tag name. Thanks to Zdravko Georgiev.\n\n1.9.0: `parser` option allows options to be passed directly to `htmlparser`. Thanks to Danny Scott.\n\n1.8.0:\n\n* `transformTags` now accepts the `*` wildcard to transform all tags. Thanks to Jamy Timmermans.\n\n* Text that has been modified by `transformTags` is then passed through `textFilter`. Thanks to Pavlo Yurichuk.\n\n* Content inside `textarea` is discarded if `textarea` is not allowed. I don't know why it took me this long to see that this is just common sense. Thanks to David Frank.\n\n1.7.2: removed `array-includes` dependency in favor of `indexOf`, which is a little more verbose but slightly faster and doesn't require a shim. Thanks again to Joseph Dykstra.\n\n1.7.1: removed lodash dependency, adding lighter dependencies and polyfills in its place. Thanks to Joseph Dykstra.\n\n1.7.0: introduced `allowedSchemesByTag` option. Thanks to Cameron Will.\n\n1.6.1: the string `'undefined'` (as opposed to `undefined`) is perfectly valid text and shouldn't be expressly converted to the empty string.\n\n1.6.0: added `textFilter` option. Thanks to Csaba Palfi.\n\n1.5.3: do not escape special characters inside a script or style element, if they are allowed. This is consistent with the way browsers parse them; nothing closes them except the appropriate closing tag for the entire element. Of course, this only comes into play if you actually choose to allow those tags. Thanks to aletorrado.\n\n1.5.2: guard checks for allowed attributes correctly to avoid an undefined property error. Thanks to Zeke.\n\n1.5.1: updated to htmlparser2 1.8.x. Started using the `decodeEntities` option, which allows us to pass our filter evasion tests without the need to recursively invoke the filter.\n\n1.5.0: support for `*` wildcards in allowedAttributes. With tests. Thanks to Calvin Montgomery.\n\n1.4.3: invokes itself recursively until the markup stops changing to guard against [this issue](https://github.com/fb55/htmlparser2/issues/105). Bump to htmlparser2 version 3.7.x.\n\n1.4.1, 1.4.2: more tests.\n\n1.4.0: ability to  allow all attributes or tags through by setting `allowedAttributes` and/or `allowedTags` to false. Thanks to Anand Thakker.\n\n1.3.0: `attribs` now available on frames passed to exclusive filter.\n\n1.2.3: fixed another possible XSS attack vector; no definitive exploit was found but it looks possible. [See this issue.](https://github.com/punkave/sanitize-html/pull/20) Thanks to Jim O'Brien.\n\n1.2.2: reject `javascript:` URLs when disguised with an internal comment. This is probably not respected by browsers anyway except when inside an XML data island element, which you almost certainly are not allowing in your `allowedTags`, but we aim to be thorough. Thanks to Jim O'Brien.\n\n1.2.1: fixed crashing bug when presented with bad markup. The bug was in the `exclusiveFilter` mechanism. Unit test added. Thanks to Ilya Kantor for catching it.\n\n1.2.0:\n\n* The `allowedClasses` option now allows you to permit CSS classes in a fine-grained way.\n\n* Text passed to your `exclusiveFilter` function now includes the text of child elements, making it more useful for identifying elements that truly lack any inner text.\n\n1.1.7: use `he` for entity decoding, because it is more actively maintained.\n\n1.1.6: `allowedSchemes` option for those who want to permit `data` URLs and such.\n\n1.1.5: just a packaging thing.\n\n1.1.4: custom exclusion filter.\n\n1.1.3: moved to lodash. 1.1.2 pointed to the wrong version of lodash.\n\n1.1.0: the `transformTags` option was added. Thanks to [kl3ryk](https://github.com/kl3ryk).\n\n1.0.3: fixed several more javascript URL attack vectors after [studying the XSS filter evasion cheat sheet](https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet) to better understand my enemy. Whitespace characters (codes from 0 to 32), which browsers ignore in URLs in certain cases allowing the \"javascript\" scheme to be snuck in, are now stripped out when checking for naughty URLs. Thanks again to [pinpickle](https://github.com/pinpickle).\n\n1.0.2: fixed a javascript URL attack vector. naughtyHref must entity-decode URLs and also check for mixed-case scheme names. Thanks to [pinpickle](https://github.com/pinpickle).\n\n1.0.1: Doc tweaks.\n\n1.0.0: If the style tag is disallowed, then its content should be dumped, so that it doesn't appear as text. We were already doing this for script tags, however in both cases the content is now preserved if the tag is explicitly allowed.\n\nWe're rocking our tests and have been working great in production for months, so: declared 1.0.0 stable.\n\n0.1.3: do not double-escape entities in attributes or text. Turns out the \"text\" provided by htmlparser2 is already escaped.\n\n0.1.2: packaging error meant it wouldn't install properly.\n\n0.1.1: discard the text of script tags.\n\n0.1.0: initial release.\n\n## About P'unk Avenue and Apostrophe\n\n`sanitize-html` was created at [P'unk Avenue](http://punkave.com) for use in Apostrophe, an open-source content management system built on node.js. If you like `sanitize-html` you should definitely [check out apostrophenow.org](http://apostrophenow.org). Also be sure to visit us on [github](http://github.com/punkave).\n\n## Support\n\nFeel free to open issues on [github](http://github.com/punkave/sanitize-html).\n\n<a href=\"http://punkave.com/\"><img src=\"https://raw.github.com/punkave/sanitize-html/master/logos/logo-box-builtby.png\" /></a>\n","_attachments":{},"homepage":"https://github.com/zacharystenger/sanitize-html-react#readme","bugs":{"url":"https://github.com/zacharystenger/sanitize-html-react/issues"},"license":"MIT"}