├── .eslintignore ├── .eslintrc ├── .github └── stale.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── index.js ├── logos ├── logo-box-builtby.png └── logo-box-madefor.png ├── package.json └── test └── test.js /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "apostrophe", 3 | "rules": { 4 | "no-console": [ 5 | "error", 6 | { 7 | "allow": [ 8 | "warn" 9 | ] 10 | } 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 60 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 14 5 | # Issues with these labels will never be considered stale 6 | exemptLabels: 7 | - pinned 8 | - security 9 | - documentation 10 | - bug 11 | - "v2" 12 | # Label to use when marking an issue as stale 13 | staleLabel: stale 14 | # Comment to post when marking an issue as stale. Set to `false` to disable 15 | markComment: > 16 | This issue has been automatically marked as stale because it has not had 17 | recent activity. It will be closed if no further activity occurs. Thank you 18 | for your contributions. 19 | # Comment to post when closing a stale issue. Set to `false` to disable 20 | closeComment: false 21 | 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | package-lock.json 2 | npm-debug.log 3 | *.DS_Store 4 | node_modules 5 | .idea 6 | # We do not commit CSS, only LESS 7 | public/css/*.css 8 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 2.17.0 (2025-05-14) 4 | 5 | - Add `preserveEscapedAttributes`, allowing attributes on escaped disallowed tags to be retained. Thanks to [Ben Elliot](https://github.com/benelliott) for this new option. 6 | 7 | ## 2.16.0 (2025-04-16) 8 | 9 | - Add `onOpenTag` and `onCloseTag` events to enable advanced filtering to hook into the parser. Thanks to [Rimvydas Naktinis](https://github.com/naktinis). 10 | 11 | ## 2.15.0 (2025-03-19) 12 | 13 | - Allow keeping tag content when discarding with exclusive filter by returning `"excludeTag"`. Thanks to [rChaoz](https://github.com/rChaoz). 14 | 15 | ## 2.14.0 (2024-12-18) 16 | 17 | - Fix adding text with `transformTags` in cases where it originally had no text child elements. Thanks to [f0x](https://cthu.lu). 18 | 19 | ## 2.13.1 (2024-10-03) 20 | 21 | - Fix to allow regex in `allowedClasses` wildcard whitelist. Thanks to `anak-dev`. 22 | 23 | ## 2.13.0 (2024-03-20) 24 | 25 | - Documentation update regarding minimum supported TypeScript version. 26 | 27 | - Added disallowedTagsMode: `completelyDiscard` option to remove the content also in HTML. Thanks to [Gauav Kumar](https://github.com/gkumar9891) for this addition. 28 | 29 | ## 2.12.1 (2024-02-22) 30 | 31 | - Do not parse sourcemaps in `post-css`. This fixes a vulnerability in which information about the existence or non-existence of files on a server could be disclosed via properly crafted HTML input when the `style` attribute is allowed by the configuration. Thanks to the [Snyk Security team](https://snyk.io/) for the disclosure and to [Dylan Armstrong](https://dylan.is/) for the fix. 32 | 33 | ## 2.12.0 (2024-02-21) 34 | 35 | - Introduced the `allowedEmptyAttributes` option, enabling explicit specification of empty string values for select attributes, with the default attribute set to `alt`. Thanks to [Na](https://github.com/zhna123) for the contribution. 36 | 37 | - Clarified the use of SVGs with a new test and changes to documentation. Thanks to [Gauav Kumar](https://github.com/gkumar9891) for the contribution. 38 | 39 | - Do not process source maps when processing style tags with PostCSS. 40 | 41 | ## 2.11.0 (2023-06-21) 42 | 43 | - Fix to allow `false` in `allowedClasses` attributes. Thanks to [Kevin Jiang](https://github.com/KevinSJ) for this fix! 44 | - Upgrade mocha version 45 | - Apply small linter fixes in tests 46 | - Add `.idea` temp files to `.gitignore` 47 | - Thanks to [Vitalii Shpital](https://github.com/VitaliiShpital) for the updates! 48 | - Show parseStyleAttributes warning in browser only. Thanks to [mog422](https://github.com/mog422) for this update! 49 | - Remove empty non-boolean attributes via an exhaustive, configurable list of known non-boolean attributes. [Thanks to Dylan Armstrong](https://github.com/dylanarmstrong) for this update! 50 | 51 | ## 2.10.0 (2023-02-17) 52 | 53 | - Fix auto-adding escaped closing tags. In other words, do not add implied closing tags to disallowed tags when `disallowedTagMode` is set to any variant of `escape` -- just escape the disallowed tags that are present. This fixes [issue #464](https://github.com/apostrophecms/sanitize-html/issues/464). Thanks to [Daniel Liebner](https://github.com/dliebner) 54 | - Add `tagAllowed()` helper function which takes a tag name and checks it against `options.allowedTags` and returns `true` if the tag is allowed and `false` if it is not. 55 | 56 | ## 2.9.0 (2023-01-27) 57 | 58 | - Add option parseStyleAttributes to skip style parsing. This fixes [issue #547](https://github.com/apostrophecms/sanitize-html/issues/547). Thanks to [Bert Verhelst](https://github.com/bertyhell). 59 | 60 | ## 2.8.1 (2022-12-21) 61 | 62 | - If the argument is a number, convert it to a string, for backwards compatibility. Thanks to [Alexander Schranz](https://github.com/alexander-schranz). 63 | 64 | ## 2.8.0 (2022-12-12) 65 | 66 | - Upgrades `htmlparser2` to new major version `^8.0.0`. Thanks to [Kedar Chandrayan](https://github.com/kedarchandrayan) for this contribution. 67 | 68 | ## 2.7.3 (2022-10-24) 69 | 70 | - If allowedTags is falsy but not exactly `false`, then do not assume that all tags are allowed. Rather, allow no tags in this case, to be on the safe side. This matches the existing documentation and fixes [issue #176](https://github.com/apostrophecms/sanitize-html/issues/176). Thanks to [Kedar Chandrayan](https://github.com/kedarchandrayan) for the fix. 71 | 72 | ## 2.7.2 (2022-09-15) 73 | 74 | - Closing tags must agree with opening tags. This fixes [issue #549](https://github.com/apostrophecms/sanitize-html/issues/549), in which closing tags not associated with any permitted opening tag could be passed through. No known exploit exists, but it's better not to permit this. Thanks to 75 | [Kedar Chandrayan](https://github.com/kedarchandrayan) for the report and the fix. 76 | 77 | ## 2.7.1 (2022-07-20) 78 | 79 | - Protocol-relative URLs are properly supported for script tags. Thanks to [paweljq](https://github.com/paweljq). 80 | - A denial-of-service vulnerability has been fixed by replacing global regular expression replacement logic for comment removal with a new implementation. Thanks to Nariyoshi Chida of NTT Security Japan for pointing out the issue. 81 | 82 | ## 2.7.0 (2022-02-04) 83 | 84 | - Allows a more sensible set of default attributes on `` tags. Thanks to [Zade Viggers](https://github.com/zadeviggers). 85 | 86 | ## 2.6.1 (2021-12-08) 87 | 88 | - Fixes style filtering to retain `!important` when used. 89 | - Fixed trailing text bug on `transformTags` options that was reported on [issue #506](https://github.com/apostrophecms/sanitize-html/issues/506). Thanks to [Alex Rantos](https://github.com/alex-rantos). 90 | 91 | ## 2.6.0 (2021-11-23) 92 | 93 | - Support for regular expressions in the `allowedClasses` option. Thanks to [Alex Rantos](https://github.com/alex-rantos). 94 | 95 | ## 2.5.3 (2021-11-02): 96 | 97 | - Fixed bug introduced by klona 2.0.5, by removing klona entirely. 98 | 99 | ## 2.5.2 (2021-10-13): 100 | 101 | - Nullish HTML input now returns an empty string. Nullish value may be explicit `null`, `undefined` or implicit `undefined` when value is not provided. Thanks to Artem Kostiuk for the contribution. 102 | - Documented that all text content is escaped. Thanks to Siddharth Singh. 103 | 104 | ## 2.5.1 (2021-09-14): 105 | - The `allowedScriptHostnames` and `allowedScriptDomains` options now implicitly purge the inline content of all script tags, not just those with `src` attributes. This behavior was already strongly implied by the fact that they purged it in the case where a `src` attribute was actually present, and is necessary for the feature to provide any real security. Thanks to Grigorii Duca for pointing out the issue. 106 | 107 | ## 2.5.0 (2021-09-08): 108 | 109 | - New `allowedScriptHostnames` option, it enables you to specify which hostnames are allowed in a script tag. 110 | - New `allowedScriptDomains` option, it enables you to specify which domains are allowed in a script tag. Thank you to [Yorick Girard](https://github.com/yorickgirard) for this and the `allowedScriptHostnames` contribution. 111 | - Updates whitelist to allowlist. 112 | 113 | ## 2.4.0 (2021-05-19): 114 | - Added support for class names with wildcards in `allowedClasses`. Thanks to [zhangbenber](https://github.com/zhangbenber) for the contribution. 115 | 116 | ## 2.3.3 (2021-03-19): 117 | - Security fix: `allowedSchemes` and related options did not properly block schemes containing a hyphen, plus sign, period or digit, such as `ms-calculator:`. Thanks to Lukas Euler for pointing out the issue. 118 | - Added a security note about the known risks associated with using the `parser` option, especially `decodeEntities: false`. See the documentation. 119 | 120 | ## 2.3.2 (2021-01-26): 121 | 122 | - Additional fixes for iframe validation exploits. Prevent exploits based on browsers' tolerance of the use of "\" rather than "/" and the presence of whitespace at this point in the URL. Thanks to Ron Masas of [Checkmarx](https://www.checkmarx.com/) for pointing out the issue and writing unit tests. 123 | - Updates README `yarn add` syntax. Thanks to [Tagir Khadshiev](https://github.com/Aspedm) for the contribution. 124 | 125 | ## 2.3.1 (2021-01-22): 126 | - Uses the standard WHATWG URL parser to stop IDNA (Internationalized Domain Name) attacks on the iframe hostname validator. Thanks to Ron Masas of [Checkmarx](https://www.checkmarx.com/) for pointing out the issue and suggesting the use of the WHATWG parser. 127 | 128 | ## 2.3.0 (2020-12-16): 129 | - Upgrades `htmlparser2` to new major version `^6.0.0`. Thanks to [Bogdan Chadkin](https://github.com/TrySound) for the contribution. 130 | 131 | ## 2.2.0 (2020-12-02): 132 | - Adds a note to the README about Typescript support (or the lack-thereof). 133 | - Adds `tel` to the default `allowedSchemes`. Thanks to [Arne Herbots](https://github.com/aHerbots) for this contribution. 134 | 135 | ## 2.1.2 (2020-11-04): 136 | - Fixes typos and inconsistencies in the README. Thanks to [Eric Lefevre-Ardant](https://github.com/elefevre) for this contribution. 137 | 138 | ## 2.1.1 (2020-10-21): 139 | - Fixes a bug when using `allowedClasses` with an `'*'` wildcard selector. Thanks to [Clemens Damke](https://github.com/Cortys) for this contribution. 140 | - Updates mocha to 7.x to resolve security warnings. 141 | 142 | ## 2.1.0 (2020-10-07): 143 | - `sup` added to the default allowed tags list. Thanks to [Julian Lam](https://github.com/julianlam) for the contribution. 144 | - Updates default `allowedTags` README documentation. Thanks to [Marco Arduini](https://github.com/nerfologist) for the contribution. 145 | 146 | ## 2.0.0 (2020-09-23): 147 | - `nestingLimit` option added. 148 | - Updates ESLint config package and fixes warnings. 149 | - Upgrade `is-plain-object` package with named export. Thanks to [Bogdan Chadkin](https://github.com/TrySound) for the contribution. 150 | - Upgrade `postcss` package and drop Node 11 and Node 13 support (enforced by postcss). 151 | 152 | ### Backwards compatibility breaks: 153 | - There is no build. You should no longer directly link to a sanitize-html file directly in the browser as it is using modern Javascript that is not fully supported by all major browsers (depending on your definition). You should now include sanitize-html in your project build for this purpose if you have one. 154 | - On the server side, Node.js 10 or higher is required. 155 | - The default `allowedTags` array was updated significantly. This mostly added HTML tags to be more comprehensive by default. You should review your projects and consider the `allowedTags` defaults if you are not already overriding them. 156 | 157 | ## 2.0.0-rc.2 (2020-09-09): 158 | - Always use existing `has` function rather than duplicating it. 159 | 160 | ## 2.0.0-rc.1 (2020-08-26): 161 | - Upgrade `klona` package. Thanks to [Bogdan Chadkin](https://github.com/TrySound) for the contribution. 162 | 163 | ## 2.0.0-beta.2: 164 | - Add `files` to `package.json` to prevent publishing unnecessary files to npm #392. Thanks to [styfle](https://github.com/styfle) for the contribution. 165 | - Removes `iframe` and `nl` from default allowed tags. Adds most innocuous tags to the default `allowedTags` array. 166 | - Fixes a bug when using `transformTags` with out `textFilter`. Thanks to [Andrzej Porebski](https://github.com/andpor) for the help with a failing test. 167 | 168 | ## 2.0.0-beta: 169 | - Moves the `index.js` file to the project root and removes all build steps within the package. Going forward, it is up to the developer to include sanitize-html in their project builds as-needed. This removes major points of conflict with project code and frees this module to not worry about myriad build-related questions. 170 | - Replaces lodash with utility packages: klona, is-plain-object, deepmerge, escape-string-regexp. 171 | - Makes custom tag transformations less error-prone by escaping frame `innerText`. Thanks to [Mike Samuel](https://github.com/mikesamuel) for the contribution. Prior to this patch, tag transformations which turned an attribute 172 | value into a text node could be vulnerable to code execution. 173 | - Updates code to use modern features including `const`/`let` variable assignment. 174 | - ESLint clean up. 175 | - Updates `is-plain-object` to the 4.x major version. 176 | - Updates `srcset` to the 3.x major version. 177 | 178 | Thanks to [Bogdan Chadkin](https://github.com/TrySound) for contributions to this major version update. 179 | 180 | ## 1.27.5 (2020-09-23): 181 | - Updates README to include ES modules syntax. 182 | 183 | ## 1.27.4 (2020-08-26): 184 | - Fixes an IE11 regression from using `Array.prototype.includes`, replacing it with `Array.prototype.indexOf`. 185 | 186 | ## 1.27.3 (2020-08-12): 187 | - Fixes a bug when using `transformTags` with out `textFilter`. Thanks to [Andrzej Porebski](https://github.com/andpor) for the help with a failing test. 188 | 189 | ## 1.27.2 (2020-07-29): 190 | - Fixes CHANGELOG links. Thanks to [Alex Mayer](https://github.com/amayer5125) for the contribution. 191 | - Replaces `srcset` with `parse-srcset`. Thanks to [Massimiliano Mirra](https://github.com/bard) for the contribution. 192 | 193 | ## 1.27.1 (2020-07-15): 194 | - Removes the unused chalk dependency. 195 | - Adds configuration for a Github stale bot. 196 | - Replace `xtend` package with native `Object.assign`. 197 | 198 | ## 1.27.0: 199 | - Adds the `allowedIframeDomains` option. This works similar to `allowedIframeHostnames`, where you would set it to an array of web domains. It would then permit any hostname on those domains to be used in iframe `src` attributes. Thanks to [Stanislav Kravchenko](https://github.com/StanisLove) for the contribution. 200 | 201 | ## 1.26.0: 202 | - Adds the `option` element to the default `nonTextTagsArray` of tags with contents that aren't meant to be displayed visually as text. This can be overridden with the `nonTextTags` option. 203 | 204 | ## 1.25.0: 205 | - Adds `enforceHtmlBoundary` option to process code bounded by the `html` tag, discarding any code outside of those tags. 206 | - Migrates to the main lodash package from the per method packages since they are deprecated and cause code duplication. Thanks to [Merceyz](https://github.com/merceyz) for the contribution. 207 | - Adds a warning when `style` and `script` tags are allowed, as they are inherently vulnerable to being used in XSS attacks. That warning can be disabled by including the option `allowVulnerableTags: true` so this choice is knowing and explicit. 208 | 209 | ## 1.24.0: 210 | - Fixes a bug where self-closing tags resulted in deletion with `disallowedTagsMode: 'escape'` set. Thanks to [Thiago Negri](https://github.com/thiago-negri) for the contribution. 211 | - Adds `abbr` to the default `allowedTags` for better accessibility support. Thanks to [Will Farrell](https://github.com/willfarrell) for the contribution. 212 | - Adds a `mediaChildren` property to the `frame` object in custom filters. This allows you to check for links or other parent tags that contain self-contained media to prevent collapse, regardless of whether there is also text inside. Thanks to [axdg](https://github.com/axdg) for the initial implementation and [Marco Arduini](https://github.com/nerfologist) for a failing test contribution. 213 | 214 | ## 1.23.0: 215 | - Adds eslint configuration and adds eslint to test script. 216 | - Sets `sideEffects: false` on package.json to allow module bundlers like webpack tree-shake this module and all the dependencies from client build. Thanks to [Egor Voronov](https://github.com/egorvoronov) for the contribution. 217 | - Adds the `tagName` (HTML element name) as a second parameter passed to `textFilter`. Thanks to [Slava](https://github.com/slavaGanzin) for the contribution. 218 | 219 | ## 1.22.1: 220 | ncreases the patch version of `lodash.mergewith` to enforce an audit fix. 221 | 222 | ## 1.22.0: 223 | bumped `htmlparser2` dependency to the 4.x series. This fixes longstanding bugs and should cause no bc breaks for this module, since the only bc breaks upstream are in regard to features we don't expose in this module. 224 | 225 | ## 1.21.1: 226 | fixed issue with bad `main` setting in package.json that broke 1.21.0. 227 | 228 | ## 1.21.0: 229 | new `disallowedTagsMode` option can be set to `escape` to escape disallowed tags rather than discarding them. Any subtags are handled as usual. If you want to recursively escape them too, you can set `disallowedTagsMode` to `recursiveEscape`. Thanks to Yehonatan Zecharia for this contribution. 230 | 231 | ## 1.20.1: 232 | Fix failing tests, add CircleCI config 233 | 234 | ## 1.20.0: 235 | reduced size of npm package via the `files` key; we only need to publish what's in `dist`. Thanks to Steven. There should be zero impact on behavior, minor version bump is precautionary. 236 | 237 | ## 1.19.3: 238 | reverted to `postcss` due to a [reported issue with `css-tree` that might or might not have XSS implications](https://github.com/punkave/sanitize-html/issues/269). 239 | 240 | ## 1.19.2: 241 | 242 | * Switched out the heavy `postcss` dependency for the lightweight `css-tree` module. No API changes. Thanks to Justin Braithwaite. 243 | * Various doc updates. Thanks to Pulkit Aggarwal and Cody Robertson. 244 | 245 | ## 1.19.1: 246 | 247 | * `"` characters are now entity-escaped only when they appear in attribute values, reducing the verbosity of the resulting markup. 248 | 249 | * Fixed a regression introduced in version 1.18.5 in the handling of markup that looks similar to a valid entity, but isn't. The bogus entity was passed through intact, i.e. `&0;` did not become `&0;` as it should have. This fix has been made for the default parser settings only. There is no fix yet for those who wish to enable `decodeEntities: false`. That will require improving the alternative encoder in the `escapeHtml` function to only pass 100% valid entities. 250 | 251 | **For those using the default `parser` settings this bug is fixed.** Read on if you are using alternative `parser` settings. 252 | 253 | When `decodeEntities: true` is in effect (the default), this is not a problem because we only have to encode `& < > "` and we always encode those things. 254 | 255 | There is currently a commented-out test which verifies one example of the problem when `decodeEntities` is false. However a correct implementation would need to not only pass that simple example but correctly escape all invalid entities, and not escape those that are valid. 256 | 257 | ## 1.19.0: 258 | 259 | * New `allowIframeRelativeUrls` option. It defaults to `true` unless `allowedIframeHostnames` is present, in which case it defaults to false, for backwards compatibility with existing behavior in both cases; however you can now set the option explicitly to allow both certain hostnames and relative URLs. Thanks to Rick Martin. 260 | 261 | ## 1.18.5: 262 | 263 | * Stop double encoding ampersands on HTML entities. Thanks to Will Gibson. 264 | 265 | ## 1.18.4: 266 | 267 | * Removed incorrect `browser` key, restoring frontend build. Thanks to Felix Becker. 268 | 269 | ## 1.18.3: 270 | 271 | * `iframe` is an allowed tag by default, to better facilitate typical use cases and the use of the `allowedIframeHostnames` option. 272 | * Documentation improvements. 273 | * More browser packaging improvements. 274 | * Protocol-relative URLs are properly supported for iframe tags. 275 | 276 | ## 1.18.2: 277 | 278 | * Travis tests passing. 279 | * Fixed another case issue — and instituted Travis CI testing so this doesn't happen again. Sorry for the hassle. 280 | 281 | ## 1.18.1: 282 | 283 | * A file was required with incorrect case, breaking the library on case sensitive filesystems such as Linux. Fixed. 284 | 285 | ## 1.18.0: 286 | 287 | * The new `allowedSchemesAppliedToAttributes` option. This determines which attributes are validated as URLs, replacing the old hardcoded list of `src` and `href` only. The default list now includes `cite`. Thanks to ml-dublin for this contribution. 288 | * It is now easy to configure a specific list of allowed values for an attribute. When configuring `allowedAttributes`, rather than listing an attribute name, simply list an object with an attribute `name` property and an allowed `values` array property. You can also add `multiple: true` to allow multiple space-separated allowed values in the attribute, otherwise the attribute must match one and only one of the allowed values. Thanks again to ml-dublin for this contribution. 289 | * Fixed a bug in the npm test procedure. 290 | 291 | ## 1.17.0: 292 | The new `allowedIframeHostnames` option. If present, this must be an array, and only iframe `src` URLs hostnames (complete hostnames; domain name matches are not enough) that appear on this list are allowed. You must also configure `hostname` as an allowed attribute for `iframe`. Thanks to Ryan Verys for this contribution. 293 | 294 | ## 1.16.3: 295 | Don't throw away the browserified versions before publishing them. `prepare` is not a good place to `make clean`, it runs after `prepublish`. 296 | 297 | ## 1.16.2: 298 | `sanitize-html` is now compiled with `babel`. An npm `prepublish` script takes care of this at `npm publish` time, so the latest code should always be compiled to operate all the way back to ES5 browsers and earlier versions of Node. Thanks to Ayushya Jaiswal. 299 | 300 | Please note that running `sanitize-html` in the browser is usually a security hole. Are you trusting the browser? Anyone could bypass that using the network panel. Sanitization is almost always best done on servers and that is the primary use case for this module. 301 | 302 | ## 1.16.1: 303 | changelog formatting only. 304 | 305 | ## 1.16.0: 306 | support for sanitizing inline CSS styles, by specifying the allowed attributes and a regular expression for each. Thanks to Cameron Will and Michael Loschiavo. 307 | 308 | ## 1.15.0: 309 | if configured as an allowed attribute (not the default), check for naughty URLs in `srcset` attributes. Thanks to Mike Samuel for the nudge to do this and to Sindre Sorhus for the `srcset` module. 310 | 311 | ## 1.14.3: 312 | inadvertent removal of lodash regexp quote dependency in 1.14.2 has been corrected. 313 | 314 | ## 1.14.2: 315 | protocol-relative URL detection must spot URLs starting with `\\` rather than `//` due to ages-old tolerance features of web browsers, intended for sleepy Windows developers. Thanks to Martin Bajanik. 316 | 317 | ## 1.14.1: 318 | documented `allowProtocolRelative` option. No code changes from 1.14.0, released a few moments ago. 319 | 320 | ## 1.14.0: 321 | the new `allowProtocolRelative` option, which is set to `true` by default, allows you to decline to accept URLs that start with `//` and thus point to a different host using the current protocol. If you do **not** want to permit this, set this option to `false`. This is fully backwards compatible because the default behavior is to allow them. Thanks to Luke Bernard. 322 | 323 | ## 1.13.0: 324 | `transformTags` can now add text to an element that initially had none. Thanks to Dushyant Singh. 325 | 326 | ## 1.12.0: 327 | option to build for browser-side use. Thanks to Michael Blum. 328 | 329 | ## 1.11.4: 330 | 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. 331 | 332 | Fixed 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. 333 | 334 | ## 1.11.3: 335 | bumped `htmlparser2` version to address crashing bug in older version. Thanks to e-jigsaw. 336 | 337 | ## 1.11.2: 338 | 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. 339 | 340 | ## 1.11.1: 341 | 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. 342 | 343 | ## 1.11.0: 344 | added the `nonTextTags` option, with tests. 345 | 346 | ## 1.10.1: 347 | documentation cleanup. No code changes. Thanks to Rex Schrader. 348 | 349 | ## 1.10.0: 350 | `allowedAttributes` now allows you to allow attributes for all tags by specifying `*` as the tag name. Thanks to Zdravko Georgiev. 351 | 352 | ## 1.9.0: 353 | `parser` option allows options to be passed directly to `htmlparser`. Thanks to Danny Scott. 354 | 355 | ## 1.8.0: 356 | 357 | * `transformTags` now accepts the `*` wildcard to transform all tags. Thanks to Jamy Timmermans. 358 | 359 | * Text that has been modified by `transformTags` is then passed through `textFilter`. Thanks to Pavlo Yurichuk. 360 | 361 | * 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. 362 | 363 | ## 1.7.2: 364 | 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. 365 | 366 | ## 1.7.1: 367 | removed lodash dependency, adding lighter dependencies and polyfills in its place. Thanks to Joseph Dykstra. 368 | 369 | ## 1.7.0: 370 | introduced `allowedSchemesByTag` option. Thanks to Cameron Will. 371 | 372 | ## 1.6.1: 373 | the string `'undefined'` (as opposed to `undefined`) is perfectly valid text and shouldn't be expressly converted to the empty string. 374 | 375 | ## 1.6.0: 376 | added `textFilter` option. Thanks to Csaba Palfi. 377 | 378 | ## 1.5.3: 379 | 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. 380 | 381 | ## 1.5.2: 382 | guard checks for allowed attributes correctly to avoid an undefined property error. Thanks to Zeke. 383 | 384 | ## 1.5.1: 385 | 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. 386 | 387 | ## 1.5.0: 388 | support for `*` wildcards in allowedAttributes. With tests. Thanks to Calvin Montgomery. 389 | 390 | ## 1.4.3: 391 | 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. 392 | 393 | ## 1.4.1, 1.4.2: 394 | more tests. 395 | 396 | ## 1.4.0: 397 | ability to allow all attributes or tags through by setting `allowedAttributes` and/or `allowedTags` to false. Thanks to Anand Thakker. 398 | 399 | ## 1.3.0: 400 | `attribs` now available on frames passed to exclusive filter. 401 | 402 | ## 1.2.3: 403 | 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. 404 | 405 | ## 1.2.2: 406 | 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. 407 | 408 | ## 1.2.1: 409 | 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. 410 | 411 | ## 1.2.0: 412 | * The `allowedClasses` option now allows you to permit CSS classes in a fine-grained way. 413 | 414 | * 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. 415 | 416 | ## 1.1.7: 417 | use `he` for entity decoding, because it is more actively maintained. 418 | 419 | ## 1.1.6: 420 | `allowedSchemes` option for those who want to permit `data` URLs and such. 421 | 422 | ## 1.1.5: 423 | just a packaging thing. 424 | 425 | ## 1.1.4: 426 | custom exclusion filter. 427 | 428 | ## 1.1.3: 429 | moved to lodash. 1.1.2 pointed to the wrong version of lodash. 430 | 431 | ## 1.1.0: 432 | the `transformTags` option was added. Thanks to [kl3ryk](https://github.com/kl3ryk). 433 | 434 | ## 1.0.3: 435 | 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). 436 | 437 | ## 1.0.2: 438 | 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). 439 | 440 | ## 1.0.1: 441 | Doc tweaks. 442 | 443 | ## 1.0.0: 444 | 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. 445 | 446 | We're rocking our tests and have been working great in production for months, so: declared 1.0.0 stable. 447 | 448 | ## 0.1.3: 449 | do not double-escape entities in attributes or text. Turns out the "text" provided by htmlparser2 is already escaped. 450 | 451 | ## 0.1.2: 452 | packaging error meant it wouldn't install properly. 453 | 454 | ## 0.1.1: 455 | discard the text of script tags. 456 | 457 | ## 0.1.0: 458 | initial release. 459 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013, 2014, 2015 P'unk Avenue LLC 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sanitize-html 2 | 3 | 4 | 5 | sanitize-html provides a simple HTML sanitizer with a clear API. 6 | 7 | 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. 8 | 9 | sanitize-html allows you to specify the tags you want to permit, and the permitted 10 | attributes for each of those tags. If an attribute is a known non-boolean value, 11 | and it is empty, it will be removed. For example `checked` can be empty, but `href` 12 | cannot. 13 | 14 | If a tag is not permitted, the contents of the tag are not discarded. There are 15 | some exceptions to this, discussed below in the "Discarding the entire contents 16 | of a disallowed tag" section. 17 | 18 | The syntax of poorly closed `p` and `img` elements is cleaned up. 19 | 20 | `href` attributes are validated to ensure they only contain `http`, `https`, `ftp` and `mailto` URLs. Relative URLs are also allowed. Ditto for `src` attributes. 21 | 22 | Allowing particular urls as a `src` to an iframe tag by filtering hostnames is also supported. 23 | 24 | HTML comments are not preserved. 25 | Additionally, `sanitize-html` escapes _ALL_ text content - this means that ampersands, greater-than, and less-than signs are converted to their equivalent HTML character references (`&` --> `&`, `<` --> `<`, and so on). Additionally, in attribute values, quotation marks are escaped as well (`"` --> `"`). 26 | 27 | ## Requirements 28 | 29 | sanitize-html is intended for use with Node.js and supports Node 10+. All of its npm dependencies are pure JavaScript. sanitize-html is built on the excellent `htmlparser2` module. 30 | 31 | ### Regarding TypeScript 32 | 33 | sanitize-html is not written in TypeScript and there is no plan to directly support it. There is a community supported typing definition, [`@types/sanitize-html`](https://www.npmjs.com/package/@types/sanitize-html), however. 34 | ```bash 35 | npm install -D @types/sanitize-html 36 | ``` 37 | If `esModuleInterop=true` is not set in your `tsconfig.json` file, you have to import it with: 38 | 39 | ```javascript 40 | import * as sanitizeHtml from 'sanitize-html'; 41 | ``` 42 | 43 | When using TypeScript, there is a minimum supported version of >=4.5 because of a dependency on the `htmlparser2` types. 44 | 45 | Any questions or problems while using `@types/sanitize-html` should be directed to its maintainers as directed by that project's contribution guidelines. 46 | 47 | ## How to use 48 | 49 | ### Browser 50 | 51 | *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. 52 | 53 | But, 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! 54 | 55 | * Install the package: 56 | 57 | ```bash 58 | npm install sanitize-html 59 | ``` 60 | or 61 | ``` 62 | yarn add sanitize-html 63 | ``` 64 | 65 | The primary change in the 2.x version of sanitize-html is that it no longer includes a build that is ready for browser use. Developers are expected to include sanitize-html in their project builds (e.g., webpack) as they would any other dependency. So while sanitize-html is no longer ready to link to directly in HTML, developers can now more easily process it according to their needs. 66 | 67 | Once built and linked in the browser with other project Javascript, it can be used to sanitize HTML strings in front end code: 68 | 69 | ```javascript 70 | import sanitizeHtml from 'sanitize-html'; 71 | 72 | const html = "hello world"; 73 | console.log(sanitizeHtml(html)); 74 | console.log(sanitizeHtml("")); 75 | console.log(sanitizeHtml("console.log('hello world')")); 76 | console.log(sanitizeHtml("")); 77 | ``` 78 | 79 | ### Node (Recommended) 80 | 81 | Install module from console: 82 | 83 | ```bash 84 | npm install sanitize-html 85 | ``` 86 | 87 | Import the module: 88 | 89 | ```js 90 | // In ES modules 91 | import sanitizeHtml from 'sanitize-html'; 92 | 93 | // Or in CommonJS 94 | const sanitizeHtml = require('sanitize-html'); 95 | ``` 96 | 97 | Use it in your JavaScript app: 98 | 99 | ```js 100 | const dirty = 'some really tacky HTML'; 101 | const clean = sanitizeHtml(dirty); 102 | ``` 103 | 104 | That will allow our [default list of allowed tags and attributes](#default-options) through. It's a nice set, but probably not quite what you want. So: 105 | 106 | ```js 107 | // Allow only a super restricted set of tags and attributes 108 | const clean = sanitizeHtml(dirty, { 109 | allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ], 110 | allowedAttributes: { 111 | 'a': [ 'href' ] 112 | }, 113 | allowedIframeHostnames: ['www.youtube.com'] 114 | }); 115 | ``` 116 | 117 | Boom! 118 | 119 | ### Default options 120 | 121 | ```js 122 | allowedTags: [ 123 | "address", "article", "aside", "footer", "header", "h1", "h2", "h3", "h4", 124 | "h5", "h6", "hgroup", "main", "nav", "section", "blockquote", "dd", "div", 125 | "dl", "dt", "figcaption", "figure", "hr", "li", "main", "ol", "p", "pre", 126 | "ul", "a", "abbr", "b", "bdi", "bdo", "br", "cite", "code", "data", "dfn", 127 | "em", "i", "kbd", "mark", "q", "rb", "rp", "rt", "rtc", "ruby", "s", "samp", 128 | "small", "span", "strong", "sub", "sup", "time", "u", "var", "wbr", "caption", 129 | "col", "colgroup", "table", "tbody", "td", "tfoot", "th", "thead", "tr" 130 | ], 131 | nonBooleanAttributes: [ 132 | 'abbr', 'accept', 'accept-charset', 'accesskey', 'action', 133 | 'allow', 'alt', 'as', 'autocapitalize', 'autocomplete', 134 | 'blocking', 'charset', 'cite', 'class', 'color', 'cols', 135 | 'colspan', 'content', 'contenteditable', 'coords', 'crossorigin', 136 | 'data', 'datetime', 'decoding', 'dir', 'dirname', 'download', 137 | 'draggable', 'enctype', 'enterkeyhint', 'fetchpriority', 'for', 138 | 'form', 'formaction', 'formenctype', 'formmethod', 'formtarget', 139 | 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 140 | 'http-equiv', 'id', 'imagesizes', 'imagesrcset', 'inputmode', 141 | 'integrity', 'is', 'itemid', 'itemprop', 'itemref', 'itemtype', 142 | 'kind', 'label', 'lang', 'list', 'loading', 'low', 'max', 143 | 'maxlength', 'media', 'method', 'min', 'minlength', 'name', 144 | 'nonce', 'optimum', 'pattern', 'ping', 'placeholder', 'popover', 145 | 'popovertarget', 'popovertargetaction', 'poster', 'preload', 146 | 'referrerpolicy', 'rel', 'rows', 'rowspan', 'sandbox', 'scope', 147 | 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 148 | 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'style', 149 | 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 150 | 'value', 'width', 'wrap', 151 | // Event handlers 152 | 'onauxclick', 'onafterprint', 'onbeforematch', 'onbeforeprint', 153 | 'onbeforeunload', 'onbeforetoggle', 'onblur', 'oncancel', 154 | 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', 155 | 'oncontextlost', 'oncontextmenu', 'oncontextrestored', 'oncopy', 156 | 'oncuechange', 'oncut', 'ondblclick', 'ondrag', 'ondragend', 157 | 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 158 | 'ondrop', 'ondurationchange', 'onemptied', 'onended', 159 | 'onerror', 'onfocus', 'onformdata', 'onhashchange', 'oninput', 160 | 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 161 | 'onlanguagechange', 'onload', 'onloadeddata', 'onloadedmetadata', 162 | 'onloadstart', 'onmessage', 'onmessageerror', 'onmousedown', 163 | 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 164 | 'onmouseover', 'onmouseup', 'onoffline', 'ononline', 'onpagehide', 165 | 'onpageshow', 'onpaste', 'onpause', 'onplay', 'onplaying', 166 | 'onpopstate', 'onprogress', 'onratechange', 'onreset', 'onresize', 167 | 'onrejectionhandled', 'onscroll', 'onscrollend', 168 | 'onsecuritypolicyviolation', 'onseeked', 'onseeking', 'onselect', 169 | 'onslotchange', 'onstalled', 'onstorage', 'onsubmit', 'onsuspend', 170 | 'ontimeupdate', 'ontoggle', 'onunhandledrejection', 'onunload', 171 | 'onvolumechange', 'onwaiting', 'onwheel' 172 | ], 173 | disallowedTagsMode: 'discard', 174 | allowedAttributes: { 175 | a: [ 'href', 'name', 'target' ], 176 | // We don't currently allow img itself by default, but 177 | // these attributes would make sense if we did. 178 | img: [ 'src', 'srcset', 'alt', 'title', 'width', 'height', 'loading' ] 179 | }, 180 | // Lots of these won't come up by default because we don't allow them 181 | selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ], 182 | // URL schemes we permit 183 | allowedSchemes: [ 'http', 'https', 'ftp', 'mailto', 'tel' ], 184 | allowedSchemesByTag: {}, 185 | allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ], 186 | allowProtocolRelative: true, 187 | enforceHtmlBoundary: false, 188 | parseStyleAttributes: true 189 | ``` 190 | 191 | ### Common use cases 192 | 193 | #### "I like your set but I want to add one more tag. Is there a convenient way?" 194 | 195 | Sure: 196 | 197 | ```js 198 | const clean = sanitizeHtml(dirty, { 199 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]) 200 | }); 201 | ``` 202 | 203 | If you do not specify `allowedTags` or `allowedAttributes`, our default list is applied. So if you really want an empty list, specify one. 204 | 205 | #### "What if I want to allow all tags or all attributes?" 206 | 207 | Simple! Instead of leaving `allowedTags` or `allowedAttributes` out of the options, set either 208 | one or both to `false`: 209 | 210 | ```js 211 | allowedTags: false, 212 | allowedAttributes: false 213 | ``` 214 | 215 | #### "What if I want to allow empty attributes, even for cases like href that normally don't make sense?" 216 | 217 | Very simple! Set `nonBooleanAttributes` to `[]`. 218 | 219 | ```js 220 | nonBooleanAttributes: [] 221 | ``` 222 | 223 | #### "What if I want to remove all empty attributes, including valid ones?" 224 | 225 | Also very simple! Set `nonBooleanAttributes` to `['*']`. 226 | 227 | **Note**: This will break common valid cases like `checked` and `selected`, so this is 228 | unlikely to be what you want. For most ordinary HTML use, it is best to avoid making 229 | this change. 230 | 231 | ```js 232 | nonBooleanAttributes: ['*'] 233 | ``` 234 | 235 | #### "What if I don't want to allow *any* tags?" 236 | 237 | Also simple! Set `allowedTags` to `[]` and `allowedAttributes` to `{}`. 238 | 239 | ```js 240 | allowedTags: [], 241 | allowedAttributes: {} 242 | ``` 243 | 244 | #### "What if I want disallowed tags to be escaped rather than discarded?" 245 | 246 | If you set `disallowedTagsMode` to `discard` (the default), disallowed tags are discarded. Any text content or subtags are still included, depending on whether the individual subtags are allowed. 247 | 248 | If you set `disallowedTagsMode` to `completelyDiscard`, disallowed tags and any content they contain are discarded. Any subtags are still included, as long as those individual subtags are allowed. 249 | 250 | If you set `disallowedTagsMode` to `escape`, the disallowed tags are escaped rather than discarded. Any text or subtags are handled normally. 251 | 252 | If you set `disallowedTagsMode` to `recursiveEscape`, the disallowed tags are escaped rather than discarded, and the same treatment is applied to all subtags, whether otherwise allowed or not. 253 | 254 | #### "What if I want to allow only specific values on some attributes?" 255 | 256 | When configuring the attribute in `allowedAttributes` simply use an object with attribute `name` and an allowed `values` array. In the following example `sandbox="allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-scripts"` would become `sandbox="allow-popups allow-scripts"`: 257 | 258 | ```js 259 | allowedAttributes: { 260 | iframe: [ 261 | { 262 | name: 'sandbox', 263 | multiple: true, 264 | values: ['allow-popups', 'allow-same-origin', 'allow-scripts'] 265 | } 266 | ] 267 | } 268 | ``` 269 | 270 | With `multiple: true`, several allowed values may appear in the same attribute, separated by spaces. Otherwise the attribute must exactly match one and only one of the allowed values. 271 | 272 | #### "What if I want to maintain the original case for SVG elements and attributes?" 273 | 274 | If you're incorporating SVG elements like `linearGradient` into your content and notice that they're not rendering as expected due to case sensitivity issues, it's essential to prevent `sanitize-html` from converting element and attribute names to lowercase. This situation often arises when SVGs fail to display correctly because their case-sensitive tags, such as `linearGradient` and attributes like `viewBox`, are inadvertently lowercased. 275 | 276 | To address this, ensure you set `lowerCaseTags: false` and `lowerCaseAttributeNames: false` in the parser options of your sanitize-html configuration. This adjustment stops the library from altering the case of your tags and attributes, preserving the integrity of your SVG content. 277 | 278 | ```js 279 | allowedTags: [ 'svg', 'g', 'defs', 'linearGradient', 'stop', 'circle' ], 280 | allowedAttributes: false, 281 | parser: { 282 | lowerCaseTags: false, 283 | lowerCaseAttributeNames: false 284 | } 285 | ``` 286 | 287 | ### Wildcards for attributes 288 | 289 | You can use the `*` wildcard to allow all attributes with a certain prefix: 290 | 291 | ```js 292 | allowedAttributes: { 293 | a: [ 'href', 'data-*' ] 294 | } 295 | ``` 296 | 297 | Also you can use the `*` as name for a tag, to allow listed attributes to be valid for any tag: 298 | 299 | ```js 300 | allowedAttributes: { 301 | '*': [ 'href', 'align', 'alt', 'center', 'bgcolor' ] 302 | } 303 | ``` 304 | 305 | ## Additional options 306 | 307 | ### Allowed CSS Classes 308 | 309 | If 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. 310 | 311 | This implies that the `class` attribute is allowed on that element. 312 | 313 | ```javascript 314 | // Allow only a restricted set of CSS classes and only on the p tag 315 | const clean = sanitizeHtml(dirty, { 316 | allowedTags: [ 'p', 'em', 'strong' ], 317 | allowedClasses: { 318 | 'p': [ 'fancy', 'simple' ] 319 | } 320 | }); 321 | ``` 322 | 323 | Similar to `allowedAttributes`, you can use `*` to allow classes with a certain prefix, or use `*` as a tag name to allow listed classes to be valid for any tag: 324 | 325 | ```js 326 | allowedClasses: { 327 | 'code': [ 'language-*', 'lang-*' ], 328 | '*': [ 'fancy', 'simple' ] 329 | } 330 | ``` 331 | 332 | Furthermore, regular expressions are supported too: 333 | 334 | ```js 335 | allowedClasses: { 336 | p: [ /^regex\d{2}$/ ] 337 | } 338 | ``` 339 | 340 | If `allowedClasses` for a certain tag is `false`, all the classes for this tag will be allowed. 341 | 342 | > Note: It is advised that your regular expressions always begin with `^` so that you are requiring a known prefix. A regular expression with neither `^` nor `$` just requires that something appear in the middle. 343 | 344 | ### Allowed CSS Styles 345 | 346 | If you wish to allow specific CSS _styles_ on a particular element, you can do that with the `allowedStyles` option. Simply declare your desired attributes as regular expression options within an array for the given attribute. Specific elements will inherit allowlisted attributes from the global (`*`) attribute. Any other CSS classes are discarded. 347 | 348 | **You must also use `allowedAttributes`** to activate the `style` attribute for the relevant elements. Otherwise this feature will never come into play. 349 | 350 | **When constructing regular expressions, don't forget `^` and `$`.** It's not enough to say "the string should contain this." It must also say "and only this." 351 | 352 | **URLs in inline styles are NOT filtered by any mechanism other than your regular expression.** 353 | 354 | ```javascript 355 | const clean = sanitizeHtml(dirty, { 356 | allowedTags: ['p'], 357 | allowedAttributes: { 358 | 'p': ["style"], 359 | }, 360 | allowedStyles: { 361 | '*': { 362 | // Match HEX and RGB 363 | 'color': [/^#(0x)?[0-9a-f]+$/i, /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/], 364 | 'text-align': [/^left$/, /^right$/, /^center$/], 365 | // Match any number with px, em, or % 366 | 'font-size': [/^\d+(?:px|em|%)$/] 367 | }, 368 | 'p': { 369 | 'font-size': [/^\d+rem$/] 370 | } 371 | } 372 | }); 373 | ``` 374 | 375 | ### Discarding text outside of `````` tags 376 | 377 | Some text editing applications generate HTML to allow copying over to a web application. These can sometimes include undesirable control characters after terminating `html` tag. By default sanitize-html will not discard these characters, instead returning them in sanitized string. This behaviour can be modified using `enforceHtmlBoundary` option. 378 | 379 | Setting this option to true will instruct sanitize-html to discard all characters outside of `html` tag boundaries -- before `` and after `` tags. 380 | 381 | ```js 382 | enforceHtmlBoundary: true 383 | ``` 384 | 385 | ### htmlparser2 Options 386 | 387 | sanitize-html 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. 388 | 389 | **Security note: changing the `parser` settings can be risky.** In particular, `decodeEntities: false` has known security concerns and a complete test suite does not exist for every possible combination of settings when used with `sanitize-html`. If security is your goal we recommend you use the defaults rather than changing `parser`, except for the `lowerCaseTags` option. 390 | 391 | ```javascript 392 | const clean = sanitizeHtml(dirty, { 393 | allowedTags: ['a'], 394 | parser: { 395 | lowerCaseTags: true 396 | } 397 | }); 398 | ``` 399 | See the [htmlparser2 wiki](https://github.com/fb55/htmlparser2/wiki/Parser-options) for the full list of possible options. 400 | 401 | ### Transformations 402 | 403 | What if you want to add or change an attribute? What if you want to transform one tag to another? No problem, it's simple! 404 | 405 | The easiest way (will change all `ol` tags to `ul` tags): 406 | 407 | ```js 408 | const clean = sanitizeHtml(dirty, { 409 | transformTags: { 410 | 'ol': 'ul', 411 | } 412 | }); 413 | ``` 414 | 415 | The most advanced usage: 416 | 417 | ```js 418 | const clean = sanitizeHtml(dirty, { 419 | transformTags: { 420 | 'ol': function(tagName, attribs) { 421 | // My own custom magic goes here 422 | return { 423 | tagName: 'ul', 424 | attribs: { 425 | class: 'foo' 426 | } 427 | }; 428 | } 429 | } 430 | }); 431 | ``` 432 | 433 | You can specify the `*` wildcard instead of a tag name to transform all tags. 434 | 435 | There 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: 436 | 437 | ```js 438 | const clean = sanitizeHtml(dirty, { 439 | transformTags: { 440 | 'ol': sanitizeHtml.simpleTransform('ul', {class: 'foo'}), 441 | } 442 | }); 443 | ``` 444 | 445 | The `simpleTransform` helper method has 3 parameters: 446 | 447 | ```js 448 | simpleTransform(newTag, newAttributes, shouldMerge) 449 | ``` 450 | 451 | The 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. 452 | 453 | You can also add or modify the text contents of a tag: 454 | 455 | ```js 456 | const clean = sanitizeHtml(dirty, { 457 | transformTags: { 458 | 'a': function(tagName, attribs) { 459 | return { 460 | tagName: 'a', 461 | text: 'Some text' 462 | }; 463 | } 464 | } 465 | }); 466 | ``` 467 | For example, you could transform a link element with missing anchor text: 468 | ```js 469 | 470 | ``` 471 | To a link with anchor text: 472 | ```js 473 | Some text 474 | ``` 475 | 476 | ### Filters 477 | 478 | You can provide a filter function to remove unwanted tags. Let's suppose we need to remove empty `a` tags like: 479 | 480 | ```html 481 | 482 | ``` 483 | 484 | We can do that with the following filter: 485 | 486 | ```js 487 | sanitizeHtml( 488 | '

This is
Linux

', 489 | { 490 | exclusiveFilter: function(frame) { 491 | return frame.tag === 'a' && !frame.text.trim(); 492 | } 493 | } 494 | ); 495 | ``` 496 | 497 | The filter function can also return the string `"excludeTag"` to only remove the tag, while keeping its content. For example, you can remove tags for anchors with invalid links: 498 | 499 | ```js 500 | sanitizeHtml( 501 | 'This is a bad link and a good link', 502 | { 503 | exclusiveFilter: function(frame) { 504 | // the href attribute is removed by the URL protocol check 505 | return frame.tag === 'a' && !frame.attribs.href ? 'excludeTag' : false; 506 | } 507 | } 508 | ); 509 | // Output: 'This is a bad link and a good link' 510 | ``` 511 | 512 | The `frame` object supplied to the callback provides the following attributes: 513 | 514 | - `tag`: The tag name, i.e. `'img'`. 515 | - `attribs`: The tag's attributes, i.e. `{ src: "/path/to/tux.png" }`. 516 | - `text`: The text content of the tag. 517 | - `mediaChildren`: Immediate child tags that are likely to represent self-contained media (e.g., `img`, `video`, `picture`, `iframe`). See the `mediaTags` variable in `src/index.js` for the full list. 518 | - `tagPosition`: The index of the tag's position in the result string. 519 | 520 | You can also process all text content with a provided filter function. Let's say we want an ellipsis instead of three dots. 521 | 522 | ```html 523 |

some text...

524 | ``` 525 | 526 | We can do that with the following filter: 527 | 528 | ```js 529 | sanitizeHtml( 530 | '

some text...

', 531 | { 532 | textFilter: function(text, tagName) { 533 | if (['a'].indexOf(tagName) > -1) return //Skip anchor tags 534 | 535 | return text.replace(/\.\.\./, '…'); 536 | } 537 | } 538 | ); 539 | ``` 540 | 541 | Note 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`. 542 | 543 | ### Iframe Filters 544 | 545 | If you would like to allow iframe tags but want to control the domains that are allowed through, you can provide an array of hostnames and/or array of domains that you would like to allow as iframe sources. This hostname is a property in the options object passed as an argument to the sanitize-html function. 546 | 547 | These arrays will be checked against the html that is passed to the function and return only `src` urls that include the allowed hostnames or domains in the object. The url in the html that is passed must be formatted correctly (valid hostname) as an embedded iframe otherwise the module will strip out the src from the iframe. 548 | 549 | Make sure to pass a valid hostname along with the domain you wish to allow, i.e.: 550 | 551 | ```js 552 | allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'], 553 | allowedIframeDomains: ['zoom.us'] 554 | ``` 555 | 556 | You may also specify whether or not to allow relative URLs as iframe sources. 557 | 558 | ```js 559 | allowIframeRelativeUrls: true 560 | ``` 561 | 562 | Note that if unspecified, relative URLs will be allowed by default if no hostname or domain filter is provided but removed by default if a hostname or domain filter is provided. 563 | 564 | **Remember that the `iframe` tag must be allowed as well as the `src` attribute.** 565 | 566 | For example: 567 | 568 | ```javascript 569 | const clean = sanitizeHtml('

', { 570 | allowedTags: [ 'p', 'em', 'strong', 'iframe' ], 571 | allowedClasses: { 572 | 'p': [ 'fancy', 'simple' ], 573 | }, 574 | allowedAttributes: { 575 | 'iframe': ['src'] 576 | }, 577 | allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] 578 | }); 579 | ``` 580 | 581 | will pass through as safe whereas: 582 | 583 | ```javascript 584 | const clean = sanitizeHtml('

', { 585 | allowedTags: [ 'p', 'em', 'strong', 'iframe' ], 586 | allowedClasses: { 587 | 'p': [ 'fancy', 'simple' ], 588 | }, 589 | allowedAttributes: { 590 | 'iframe': ['src'] 591 | }, 592 | allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] 593 | }); 594 | ``` 595 | 596 | or 597 | 598 | ```javascript 599 | const clean = sanitizeHtml('

', { 600 | allowedTags: [ 'p', 'em', 'strong', 'iframe' ], 601 | allowedClasses: { 602 | 'p': [ 'fancy', 'simple' ], 603 | }, 604 | allowedAttributes: { 605 | 'iframe': ['src'] 606 | }, 607 | allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] 608 | }); 609 | ``` 610 | 611 | will return an empty iframe tag. 612 | 613 | If you want to allow any subdomain of any level you can provide the domain in `allowedIframeDomains` 614 | 615 | ```javascript 616 | // This iframe markup will pass through as safe. 617 | const clean = sanitizeHtml('

', { 618 | allowedTags: [ 'p', 'em', 'strong', 'iframe' ], 619 | allowedClasses: { 620 | 'p': [ 'fancy', 'simple' ], 621 | }, 622 | allowedAttributes: { 623 | 'iframe': ['src'] 624 | }, 625 | allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'], 626 | allowedIframeDomains: ['zoom.us'] 627 | }); 628 | ``` 629 | 630 | ### Script Filters 631 | 632 | Similarly to iframes you can allow a script tag on a list of allowlisted domains 633 | 634 | ```js 635 | const clean = sanitizeHtml('', { 636 | allowedTags: ['script'], 637 | allowedAttributes: { 638 | script: ['src'] 639 | }, 640 | allowedScriptDomains: ['authorized.com'], 641 | }) 642 | ``` 643 | 644 | You can allow a script tag on a list of allowlisted hostnames too 645 | 646 | ```js 647 | const clean = sanitizeHtml('', { 648 | allowedTags: ['script'], 649 | allowedAttributes: { 650 | script: ['src'] 651 | }, 652 | allowedScriptHostnames: [ 'www.authorized.com' ], 653 | }) 654 | ``` 655 | 656 | ### Allowed URL schemes 657 | 658 | By default, we allow the following URL schemes in cases where `href`, `src`, etc. are allowed: 659 | 660 | ```js 661 | [ 'http', 'https', 'ftp', 'mailto' ] 662 | ``` 663 | 664 | You can override this if you want to: 665 | 666 | ```js 667 | sanitizeHtml( 668 | // teeny-tiny valid transparent GIF in a data URL 669 | '', 670 | { 671 | allowedTags: [ 'img', 'p' ], 672 | allowedSchemes: [ 'data', 'http' ] 673 | } 674 | ); 675 | ``` 676 | 677 | You can also allow a scheme for a particular tag only: 678 | 679 | ```js 680 | allowedSchemes: [ 'http', 'https' ], 681 | allowedSchemesByTag: { 682 | img: [ 'data' ] 683 | } 684 | ``` 685 | 686 | And you can forbid the use of protocol-relative URLs (starting with `//`) to access another site using the current protocol, which is allowed by default: 687 | 688 | ```js 689 | allowProtocolRelative: false 690 | ``` 691 | 692 | ### Discarding the entire contents of a disallowed tag 693 | 694 | Normally, 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. 695 | 696 | The exceptions are: 697 | 698 | `style`, `script`, `textarea`, `option` 699 | 700 | If you wish to replace this list, for instance to discard whatever is found 701 | inside a `noscript` tag, use the `nonTextTags` option: 702 | 703 | ```js 704 | nonTextTags: [ 'style', 'script', 'textarea', 'option', 'noscript' ] 705 | ``` 706 | 707 | Note 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. 708 | 709 | The content still gets escaped properly, with the exception of the `script` and 710 | `style` tags. *Allowing either `script` or `style` leaves you open to XSS 711 | attacks. Don't do that* unless you have good reason to trust their origin. 712 | sanitize-html will log a warning if these tags are allowed, which can be 713 | disabled with the `allowVulnerableTags: true` option. 714 | 715 | ### Choose what to do with disallowed tags 716 | 717 | Instead of discarding, or keeping text only, you may enable escaping of the entire content: 718 | 719 | ```js 720 | disallowedTagsMode: 'escape' 721 | ``` 722 | 723 | This will transform `content` to `<disallowed>content</disallowed>` 724 | 725 | Valid values are: `'discard'` (default), `'completelyDiscard'` (remove disallowed tag's content), `'escape'` (escape the tag) and `'recursiveEscape'` (to escape the tag and all its content). 726 | 727 | #### Discard disallowed but the inner content of disallowed tags is kept. 728 | 729 | If you set `disallowedTagsMode` to `discard`, disallowed tags are discarded but the inner content of disallowed tags is kept. 730 | 731 | ```js 732 | disallowedTagsMode: 'discard' 733 | ``` 734 | This will transform `content` to `content` 735 | 736 | #### Discard entire content of a disallowed tag 737 | 738 | If you set `disallowedTagsMode` to `completelyDiscard`, disallowed tags and any text they contain are discarded. This also discards top-level text. Any subtags are still included, as long as those individual subtags are allowed. 739 | 740 | ```js 741 | disallowedTagsMode: 'completelyDiscard' 742 | ``` 743 | 744 | This will transform `content content ` to `content` 745 | 746 | #### Escape the disallowed tag and all its children even for allowed tags. 747 | 748 | if you set `disallowedTagsMode` to `recursiveEscape`, disallowed tags and their children will be escaped even for allowed tags: 749 | 750 | ```js 751 | disallowedTagsMode: `recursiveEscape` 752 | ``` 753 | 754 | This will transform `hello

world

` to `<disallowed>hello<p>world</p></disallowed>` 755 | 756 | #### Escape the disallowed tag, including all its attributes. 757 | 758 | By default, attributes are not preserved when tags are escaped. You can set `preserveEscapedAttributes` to `true` to 759 | keep the attributes, which will also be escaped and therefore have no effect on the browser. 760 | 761 | ```js 762 | preserveEscapedAttributes: true 763 | ``` 764 | 765 | ### Ignore style attribute contents 766 | 767 | Instead of discarding faulty style attributes, you can allow them by disabling the parsing of style attributes: 768 | 769 | ```js 770 | parseStyleAttributes: false 771 | ``` 772 | 773 | This will transform `
content
` to `
content
` instead of stripping it: `
content
` 774 | 775 | By default the parseStyleAttributes option is true. 776 | 777 | When you disable parsing of the style attribute (`parseStyleAttributes: false`) and you pass in options for the allowedStyles property, an error will be thrown. This combination is not permitted. 778 | 779 | we recommend sanitizing content server-side in a Node.js environment, as you cannot trust a browser to sanitize things anyway. Consider what a malicious user could do via the network panel, 780 | the browser console, or just by writing scripts that submit content similar to what your JavaScript submits. But if you really need to run it on the client in the browser, 781 | you may find you need to disable parseStyleAttributes. This is subject to change as it is [an upstream issue with postcss](https://github.com/postcss/postcss/issues/1727), not sanitize-html itself. 782 | 783 | ### Restricting deep nesting 784 | 785 | You can limit the depth of HTML tags in the document with the `nestingLimit` option: 786 | 787 | ```javascript 788 | nestingLimit: 6 789 | ``` 790 | 791 | This will prevent the user from nesting tags more than 6 levels deep. Tags deeper than that are stripped out exactly as if they were disallowed. Note that this means text is preserved in the usual ways where appropriate. 792 | 793 | ### Advanced filtering 794 | 795 | For more advanced filtering you can hook directly into the parsing process using tag open and tag close events. 796 | 797 | The `onOpenTag` event is triggered when an opening tag is encountered. It has two arguments: 798 | - `tagName`: The name of the tag. 799 | - `attribs`: An object containing the tag's attributes, e.g. `{ src: "/path/to/tux.png" }`. 800 | 801 | The `onCloseTag` event is triggered when a closing tag is encountered. It has the following arguments: 802 | - `tagName`: The name of the tag. 803 | - `isImplied`: A boolean indicating whether the closing tag is implied (e.g. `

foo

bar`) or explicit (e.g. `

foo

bar

`). 804 | 805 | For example, you may want to add spaces around a removed tag, like this: 806 | ```js 807 | const allowedTags = [ 'b' ]; 808 | let addSpace = false; 809 | const sanitizedHtml = sanitizeHtml( 810 | 'There should be

spaces

between these words.', 811 | { 812 | allowedTags, 813 | onOpenTag: (tagName, attribs) => { 814 | addSpace = !allowedTags.includes(tagName); 815 | }, 816 | onCloseTag: (tagName, isImplied) => { 817 | addSpace = !allowedTags.includes(tagName); 818 | }, 819 | textFilter: (text) => { 820 | if (addSpace) { 821 | addSpace = false; 822 | return ' ' + text; 823 | } 824 | return text; 825 | } 826 | } 827 | ); 828 | ``` 829 | 830 | In this example, we are setting a flag when a tag that will be removed has been opened or closed. Then we use the `textFilter` to modify the text to include spaces. The example should produce: 831 | ``` 832 | There should be spaces between these words. 833 | ``` 834 | 835 | This is a simplified example that is not meant to be production-ready. For your specific case, you may want to keep track of currently open tags, using the open and close events to push and pop items on the stack, or only insert spaces next to a subset of disallowed tags. 836 | 837 | ## About ApostropheCMS 838 | 839 | sanitize-html was created at [P'unk Avenue](https://punkave.com) for use in [ApostropheCMS](https://apostrophecms.com), an open-source content management system built on Node.js. If you like sanitize-html you should definitely check out ApostropheCMS. 840 | 841 | ## Support 842 | 843 | Feel free to open issues on [github](https://github.com/apostrophecms/sanitize-html). 844 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const htmlparser = require('htmlparser2'); 2 | const escapeStringRegexp = require('escape-string-regexp'); 3 | const { isPlainObject } = require('is-plain-object'); 4 | const deepmerge = require('deepmerge'); 5 | const parseSrcset = require('parse-srcset'); 6 | const { parse: postcssParse } = require('postcss'); 7 | // Tags that can conceivably represent stand-alone media. 8 | const mediaTags = [ 9 | 'img', 'audio', 'video', 'picture', 'svg', 10 | 'object', 'map', 'iframe', 'embed' 11 | ]; 12 | // Tags that are inherently vulnerable to being used in XSS attacks. 13 | const vulnerableTags = [ 'script', 'style' ]; 14 | 15 | function each(obj, cb) { 16 | if (obj) { 17 | Object.keys(obj).forEach(function (key) { 18 | cb(obj[key], key); 19 | }); 20 | } 21 | } 22 | 23 | // Avoid false positives with .__proto__, .hasOwnProperty, etc. 24 | function has(obj, key) { 25 | return ({}).hasOwnProperty.call(obj, key); 26 | } 27 | 28 | // Returns those elements of `a` for which `cb(a)` returns truthy 29 | function filter(a, cb) { 30 | const n = []; 31 | each(a, function(v) { 32 | if (cb(v)) { 33 | n.push(v); 34 | } 35 | }); 36 | return n; 37 | } 38 | 39 | function isEmptyObject(obj) { 40 | for (const key in obj) { 41 | if (has(obj, key)) { 42 | return false; 43 | } 44 | } 45 | return true; 46 | } 47 | 48 | function stringifySrcset(parsedSrcset) { 49 | return parsedSrcset.map(function(part) { 50 | if (!part.url) { 51 | throw new Error('URL missing'); 52 | } 53 | 54 | return ( 55 | part.url + 56 | (part.w ? ` ${part.w}w` : '') + 57 | (part.h ? ` ${part.h}h` : '') + 58 | (part.d ? ` ${part.d}x` : '') 59 | ); 60 | }).join(', '); 61 | } 62 | 63 | module.exports = sanitizeHtml; 64 | 65 | // A valid attribute name. 66 | // We use a tolerant definition based on the set of strings defined by 67 | // html.spec.whatwg.org/multipage/parsing.html#before-attribute-name-state 68 | // and html.spec.whatwg.org/multipage/parsing.html#attribute-name-state . 69 | // The characters accepted are ones which can be appended to the attribute 70 | // name buffer without triggering a parse error: 71 | // * unexpected-equals-sign-before-attribute-name 72 | // * unexpected-null-character 73 | // * unexpected-character-in-attribute-name 74 | // We exclude the empty string because it's impossible to get to the after 75 | // attribute name state with an empty attribute name buffer. 76 | const VALID_HTML_ATTRIBUTE_NAME = /^[^\0\t\n\f\r /<=>]+$/; 77 | 78 | // Ignore the _recursing flag; it's there for recursive 79 | // invocation as a guard against this exploit: 80 | // https://github.com/fb55/htmlparser2/issues/105 81 | 82 | function sanitizeHtml(html, options, _recursing) { 83 | if (html == null) { 84 | return ''; 85 | } 86 | if (typeof html === 'number') { 87 | html = html.toString(); 88 | } 89 | 90 | let result = ''; 91 | // Used for hot swapping the result variable with an empty string in order to "capture" the text written to it. 92 | let tempResult = ''; 93 | 94 | function Frame(tag, attribs) { 95 | const that = this; 96 | this.tag = tag; 97 | this.attribs = attribs || {}; 98 | this.tagPosition = result.length; 99 | this.text = ''; // Node inner text 100 | this.openingTagLength = 0; 101 | this.mediaChildren = []; 102 | 103 | this.updateParentNodeText = function() { 104 | if (stack.length) { 105 | const parentFrame = stack[stack.length - 1]; 106 | parentFrame.text += that.text; 107 | } 108 | }; 109 | 110 | this.updateParentNodeMediaChildren = function() { 111 | if (stack.length && mediaTags.includes(this.tag)) { 112 | const parentFrame = stack[stack.length - 1]; 113 | parentFrame.mediaChildren.push(this.tag); 114 | } 115 | }; 116 | } 117 | 118 | options = Object.assign({}, sanitizeHtml.defaults, options); 119 | options.parser = Object.assign({}, htmlParserDefaults, options.parser); 120 | 121 | const tagAllowed = function (name) { 122 | return options.allowedTags === false || (options.allowedTags || []).indexOf(name) > -1; 123 | }; 124 | 125 | // vulnerableTags 126 | vulnerableTags.forEach(function (tag) { 127 | if (tagAllowed(tag) && !options.allowVulnerableTags) { 128 | console.warn(`\n\n⚠️ Your \`allowedTags\` option includes, \`${tag}\`, which is inherently\nvulnerable to XSS attacks. Please remove it from \`allowedTags\`.\nOr, to disable this warning, add the \`allowVulnerableTags\` option\nand ensure you are accounting for this risk.\n\n`); 129 | } 130 | }); 131 | 132 | // Tags that contain something other than HTML, or where discarding 133 | // the text when the tag is disallowed makes sense for other reasons. 134 | // If we are not allowing these tags, we should drop their content too. 135 | // For other tags you would drop the tag but keep its content. 136 | const nonTextTagsArray = options.nonTextTags || [ 137 | 'script', 138 | 'style', 139 | 'textarea', 140 | 'option' 141 | ]; 142 | let allowedAttributesMap; 143 | let allowedAttributesGlobMap; 144 | if (options.allowedAttributes) { 145 | allowedAttributesMap = {}; 146 | allowedAttributesGlobMap = {}; 147 | each(options.allowedAttributes, function(attributes, tag) { 148 | allowedAttributesMap[tag] = []; 149 | const globRegex = []; 150 | attributes.forEach(function(obj) { 151 | if (typeof obj === 'string' && obj.indexOf('*') >= 0) { 152 | globRegex.push(escapeStringRegexp(obj).replace(/\\\*/g, '.*')); 153 | } else { 154 | allowedAttributesMap[tag].push(obj); 155 | } 156 | }); 157 | if (globRegex.length) { 158 | allowedAttributesGlobMap[tag] = new RegExp('^(' + globRegex.join('|') + ')$'); 159 | } 160 | }); 161 | } 162 | const allowedClassesMap = {}; 163 | const allowedClassesGlobMap = {}; 164 | const allowedClassesRegexMap = {}; 165 | each(options.allowedClasses, function(classes, tag) { 166 | // Implicitly allows the class attribute 167 | if (allowedAttributesMap) { 168 | if (!has(allowedAttributesMap, tag)) { 169 | allowedAttributesMap[tag] = []; 170 | } 171 | allowedAttributesMap[tag].push('class'); 172 | } 173 | 174 | allowedClassesMap[tag] = classes; 175 | 176 | if (Array.isArray(classes)) { 177 | const globRegex = []; 178 | allowedClassesMap[tag] = []; 179 | allowedClassesRegexMap[tag] = []; 180 | classes.forEach(function(obj) { 181 | if (typeof obj === 'string' && obj.indexOf('*') >= 0) { 182 | globRegex.push(escapeStringRegexp(obj).replace(/\\\*/g, '.*')); 183 | } else if (obj instanceof RegExp) { 184 | allowedClassesRegexMap[tag].push(obj); 185 | } else { 186 | allowedClassesMap[tag].push(obj); 187 | } 188 | }); 189 | if (globRegex.length) { 190 | allowedClassesGlobMap[tag] = new RegExp('^(' + globRegex.join('|') + ')$'); 191 | } 192 | } 193 | }); 194 | 195 | const transformTagsMap = {}; 196 | let transformTagsAll; 197 | each(options.transformTags, function(transform, tag) { 198 | let transFun; 199 | if (typeof transform === 'function') { 200 | transFun = transform; 201 | } else if (typeof transform === 'string') { 202 | transFun = sanitizeHtml.simpleTransform(transform); 203 | } 204 | if (tag === '*') { 205 | transformTagsAll = transFun; 206 | } else { 207 | transformTagsMap[tag] = transFun; 208 | } 209 | }); 210 | 211 | let depth; 212 | let stack; 213 | let skipMap; 214 | let transformMap; 215 | let skipText; 216 | let skipTextDepth; 217 | let addedText = false; 218 | 219 | initializeState(); 220 | 221 | const parser = new htmlparser.Parser({ 222 | onopentag: function(name, attribs) { 223 | if (options.onOpenTag) { 224 | options.onOpenTag(name, attribs); 225 | } 226 | 227 | // If `enforceHtmlBoundary` is `true` and this has found the opening 228 | // `html` tag, reset the state. 229 | if (options.enforceHtmlBoundary && name === 'html') { 230 | initializeState(); 231 | } 232 | 233 | if (skipText) { 234 | skipTextDepth++; 235 | return; 236 | } 237 | const frame = new Frame(name, attribs); 238 | stack.push(frame); 239 | 240 | let skip = false; 241 | const hasText = !!frame.text; 242 | let transformedTag; 243 | if (has(transformTagsMap, name)) { 244 | transformedTag = transformTagsMap[name](name, attribs); 245 | 246 | frame.attribs = attribs = transformedTag.attribs; 247 | 248 | if (transformedTag.text !== undefined) { 249 | frame.innerText = transformedTag.text; 250 | } 251 | 252 | if (name !== transformedTag.tagName) { 253 | frame.name = name = transformedTag.tagName; 254 | transformMap[depth] = transformedTag.tagName; 255 | } 256 | } 257 | if (transformTagsAll) { 258 | transformedTag = transformTagsAll(name, attribs); 259 | 260 | frame.attribs = attribs = transformedTag.attribs; 261 | if (name !== transformedTag.tagName) { 262 | frame.name = name = transformedTag.tagName; 263 | transformMap[depth] = transformedTag.tagName; 264 | } 265 | } 266 | 267 | if (!tagAllowed(name) || (options.disallowedTagsMode === 'recursiveEscape' && !isEmptyObject(skipMap)) || (options.nestingLimit != null && depth >= options.nestingLimit)) { 268 | skip = true; 269 | skipMap[depth] = true; 270 | if (options.disallowedTagsMode === 'discard' || options.disallowedTagsMode === 'completelyDiscard') { 271 | if (nonTextTagsArray.indexOf(name) !== -1) { 272 | skipText = true; 273 | skipTextDepth = 1; 274 | } 275 | } 276 | } 277 | depth++; 278 | if (skip) { 279 | if (options.disallowedTagsMode === 'discard' || options.disallowedTagsMode === 'completelyDiscard') { 280 | // We want the contents but not this tag 281 | if (frame.innerText && !hasText) { 282 | const escaped = escapeHtml(frame.innerText); 283 | if (options.textFilter) { 284 | result += options.textFilter(escaped, name); 285 | } else { 286 | result += escaped; 287 | } 288 | addedText = true; 289 | } 290 | return; 291 | } 292 | tempResult = result; 293 | result = ''; 294 | } 295 | result += '<' + name; 296 | 297 | if (name === 'script') { 298 | if (options.allowedScriptHostnames || options.allowedScriptDomains) { 299 | frame.innerText = ''; 300 | } 301 | } 302 | 303 | const isBeingEscaped = skip && (options.disallowedTagsMode === 'escape' || options.disallowedTagsMode === 'recursiveEscape'); 304 | const shouldPreserveEscapedAttributes = isBeingEscaped && options.preserveEscapedAttributes; 305 | 306 | if (shouldPreserveEscapedAttributes) { 307 | each(attribs, function(value, a) { 308 | result += ' ' + a + '="' + escapeHtml((value || ''), true) + '"'; 309 | }); 310 | } else if (!allowedAttributesMap || has(allowedAttributesMap, name) || allowedAttributesMap['*']) { 311 | each(attribs, function(value, a) { 312 | if (!VALID_HTML_ATTRIBUTE_NAME.test(a)) { 313 | // This prevents part of an attribute name in the output from being 314 | // interpreted as the end of an attribute, or end of a tag. 315 | delete frame.attribs[a]; 316 | return; 317 | } 318 | // If the value is empty, check if the attribute is in the allowedEmptyAttributes array. 319 | // If it is not in the allowedEmptyAttributes array, and it is a known non-boolean attribute, delete it 320 | // List taken from https://html.spec.whatwg.org/multipage/indices.html#attributes-3 321 | if (value === '' && (!options.allowedEmptyAttributes.includes(a)) && 322 | (options.nonBooleanAttributes.includes(a) || options.nonBooleanAttributes.includes('*'))) { 323 | delete frame.attribs[a]; 324 | return; 325 | } 326 | // check allowedAttributesMap for the element and attribute and modify the value 327 | // as necessary if there are specific values defined. 328 | let passedAllowedAttributesMapCheck = false; 329 | if (!allowedAttributesMap || 330 | (has(allowedAttributesMap, name) && allowedAttributesMap[name].indexOf(a) !== -1) || 331 | (allowedAttributesMap['*'] && allowedAttributesMap['*'].indexOf(a) !== -1) || 332 | (has(allowedAttributesGlobMap, name) && allowedAttributesGlobMap[name].test(a)) || 333 | (allowedAttributesGlobMap['*'] && allowedAttributesGlobMap['*'].test(a))) { 334 | passedAllowedAttributesMapCheck = true; 335 | } else if (allowedAttributesMap && allowedAttributesMap[name]) { 336 | for (const o of allowedAttributesMap[name]) { 337 | if (isPlainObject(o) && o.name && (o.name === a)) { 338 | passedAllowedAttributesMapCheck = true; 339 | let newValue = ''; 340 | if (o.multiple === true) { 341 | // verify the values that are allowed 342 | const splitStrArray = value.split(' '); 343 | for (const s of splitStrArray) { 344 | if (o.values.indexOf(s) !== -1) { 345 | if (newValue === '') { 346 | newValue = s; 347 | } else { 348 | newValue += ' ' + s; 349 | } 350 | } 351 | } 352 | } else if (o.values.indexOf(value) >= 0) { 353 | // verified an allowed value matches the entire attribute value 354 | newValue = value; 355 | } 356 | value = newValue; 357 | } 358 | } 359 | } 360 | if (passedAllowedAttributesMapCheck) { 361 | if (options.allowedSchemesAppliedToAttributes.indexOf(a) !== -1) { 362 | if (naughtyHref(name, value)) { 363 | delete frame.attribs[a]; 364 | return; 365 | } 366 | } 367 | 368 | if (name === 'script' && a === 'src') { 369 | 370 | let allowed = true; 371 | 372 | try { 373 | const parsed = parseUrl(value); 374 | 375 | if (options.allowedScriptHostnames || options.allowedScriptDomains) { 376 | const allowedHostname = (options.allowedScriptHostnames || []).find(function (hostname) { 377 | return hostname === parsed.url.hostname; 378 | }); 379 | const allowedDomain = (options.allowedScriptDomains || []).find(function(domain) { 380 | return parsed.url.hostname === domain || parsed.url.hostname.endsWith(`.${domain}`); 381 | }); 382 | allowed = allowedHostname || allowedDomain; 383 | } 384 | } catch (e) { 385 | allowed = false; 386 | } 387 | 388 | if (!allowed) { 389 | delete frame.attribs[a]; 390 | return; 391 | } 392 | } 393 | 394 | if (name === 'iframe' && a === 'src') { 395 | let allowed = true; 396 | try { 397 | const parsed = parseUrl(value); 398 | 399 | if (parsed.isRelativeUrl) { 400 | // default value of allowIframeRelativeUrls is true 401 | // unless allowedIframeHostnames or allowedIframeDomains specified 402 | allowed = has(options, 'allowIframeRelativeUrls') 403 | ? options.allowIframeRelativeUrls 404 | : (!options.allowedIframeHostnames && !options.allowedIframeDomains); 405 | } else if (options.allowedIframeHostnames || options.allowedIframeDomains) { 406 | const allowedHostname = (options.allowedIframeHostnames || []).find(function (hostname) { 407 | return hostname === parsed.url.hostname; 408 | }); 409 | const allowedDomain = (options.allowedIframeDomains || []).find(function(domain) { 410 | return parsed.url.hostname === domain || parsed.url.hostname.endsWith(`.${domain}`); 411 | }); 412 | allowed = allowedHostname || allowedDomain; 413 | } 414 | } catch (e) { 415 | // Unparseable iframe src 416 | allowed = false; 417 | } 418 | if (!allowed) { 419 | delete frame.attribs[a]; 420 | return; 421 | } 422 | } 423 | if (a === 'srcset') { 424 | try { 425 | let parsed = parseSrcset(value); 426 | parsed.forEach(function(value) { 427 | if (naughtyHref('srcset', value.url)) { 428 | value.evil = true; 429 | } 430 | }); 431 | parsed = filter(parsed, function(v) { 432 | return !v.evil; 433 | }); 434 | if (!parsed.length) { 435 | delete frame.attribs[a]; 436 | return; 437 | } else { 438 | value = stringifySrcset(filter(parsed, function(v) { 439 | return !v.evil; 440 | })); 441 | frame.attribs[a] = value; 442 | } 443 | } catch (e) { 444 | // Unparseable srcset 445 | delete frame.attribs[a]; 446 | return; 447 | } 448 | } 449 | if (a === 'class') { 450 | const allowedSpecificClasses = allowedClassesMap[name]; 451 | const allowedWildcardClasses = allowedClassesMap['*']; 452 | const allowedSpecificClassesGlob = allowedClassesGlobMap[name]; 453 | const allowedSpecificClassesRegex = allowedClassesRegexMap[name]; 454 | const allowedWildcardClassesRegex = allowedClassesRegexMap['*']; 455 | const allowedWildcardClassesGlob = allowedClassesGlobMap['*']; 456 | const allowedClassesGlobs = [ 457 | allowedSpecificClassesGlob, 458 | allowedWildcardClassesGlob 459 | ] 460 | .concat(allowedSpecificClassesRegex, allowedWildcardClassesRegex) 461 | .filter(function (t) { 462 | return t; 463 | }); 464 | if (allowedSpecificClasses && allowedWildcardClasses) { 465 | value = filterClasses(value, deepmerge(allowedSpecificClasses, allowedWildcardClasses), allowedClassesGlobs); 466 | } else { 467 | value = filterClasses(value, allowedSpecificClasses || allowedWildcardClasses, allowedClassesGlobs); 468 | } 469 | if (!value.length) { 470 | delete frame.attribs[a]; 471 | return; 472 | } 473 | } 474 | if (a === 'style') { 475 | if (options.parseStyleAttributes) { 476 | try { 477 | const abstractSyntaxTree = postcssParse(name + ' {' + value + '}', { map: false }); 478 | const filteredAST = filterCss(abstractSyntaxTree, options.allowedStyles); 479 | 480 | value = stringifyStyleAttributes(filteredAST); 481 | 482 | if (value.length === 0) { 483 | delete frame.attribs[a]; 484 | return; 485 | } 486 | } catch (e) { 487 | if (typeof window !== 'undefined') { 488 | console.warn('Failed to parse "' + name + ' {' + value + '}' + '", If you\'re running this in a browser, we recommend to disable style parsing: options.parseStyleAttributes: false, since this only works in a node environment due to a postcss dependency, More info: https://github.com/apostrophecms/sanitize-html/issues/547'); 489 | } 490 | delete frame.attribs[a]; 491 | return; 492 | } 493 | } else if (options.allowedStyles) { 494 | throw new Error('allowedStyles option cannot be used together with parseStyleAttributes: false.'); 495 | } 496 | } 497 | result += ' ' + a; 498 | if (value && value.length) { 499 | result += '="' + escapeHtml(value, true) + '"'; 500 | } else if (options.allowedEmptyAttributes.includes(a)) { 501 | result += '=""'; 502 | } 503 | } else { 504 | delete frame.attribs[a]; 505 | } 506 | }); 507 | } 508 | if (options.selfClosing.indexOf(name) !== -1) { 509 | result += ' />'; 510 | } else { 511 | result += '>'; 512 | if (frame.innerText && !hasText && !options.textFilter) { 513 | result += escapeHtml(frame.innerText); 514 | addedText = true; 515 | } 516 | } 517 | if (skip) { 518 | result = tempResult + escapeHtml(result); 519 | tempResult = ''; 520 | } 521 | frame.openingTagLength = result.length - frame.tagPosition; 522 | }, 523 | ontext: function(text) { 524 | if (skipText) { 525 | return; 526 | } 527 | const lastFrame = stack[stack.length - 1]; 528 | let tag; 529 | 530 | if (lastFrame) { 531 | tag = lastFrame.tag; 532 | // If inner text was set by transform function then let's use it 533 | text = lastFrame.innerText !== undefined ? lastFrame.innerText : text; 534 | } 535 | 536 | if (options.disallowedTagsMode === 'completelyDiscard' && !tagAllowed(tag)) { 537 | text = ''; 538 | } else if ((options.disallowedTagsMode === 'discard' || options.disallowedTagsMode === 'completelyDiscard') && ((tag === 'script') || (tag === 'style'))) { 539 | // htmlparser2 gives us these as-is. Escaping them ruins the content. Allowing 540 | // script tags is, by definition, game over for XSS protection, so if that's 541 | // your concern, don't allow them. The same is essentially true for style tags 542 | // which have their own collection of XSS vectors. 543 | result += text; 544 | } else if (!addedText) { 545 | const escaped = escapeHtml(text, false); 546 | if (options.textFilter) { 547 | result += options.textFilter(escaped, tag); 548 | } else { 549 | result += escaped; 550 | } 551 | } 552 | if (stack.length) { 553 | const frame = stack[stack.length - 1]; 554 | frame.text += text; 555 | } 556 | }, 557 | onclosetag: function(name, isImplied) { 558 | if (options.onCloseTag) { 559 | options.onCloseTag(name, isImplied); 560 | } 561 | 562 | if (skipText) { 563 | skipTextDepth--; 564 | if (!skipTextDepth) { 565 | skipText = false; 566 | } else { 567 | return; 568 | } 569 | } 570 | 571 | const frame = stack.pop(); 572 | if (!frame) { 573 | // Do not crash on bad markup 574 | return; 575 | } 576 | 577 | if (frame.tag !== name) { 578 | // Another case of bad markup. 579 | // Push to stack, so that it will be used in future closing tags. 580 | stack.push(frame); 581 | return; 582 | } 583 | 584 | skipText = options.enforceHtmlBoundary ? name === 'html' : false; 585 | depth--; 586 | const skip = skipMap[depth]; 587 | if (skip) { 588 | delete skipMap[depth]; 589 | if (options.disallowedTagsMode === 'discard' || options.disallowedTagsMode === 'completelyDiscard') { 590 | frame.updateParentNodeText(); 591 | return; 592 | } 593 | tempResult = result; 594 | result = ''; 595 | } 596 | 597 | if (transformMap[depth]) { 598 | name = transformMap[depth]; 599 | delete transformMap[depth]; 600 | } 601 | 602 | if (options.exclusiveFilter) { 603 | const filterResult = options.exclusiveFilter(frame); 604 | if (filterResult === 'excludeTag') { 605 | if (skip) { 606 | // no longer escaping the tag since it's not added at all 607 | result = tempResult; 608 | tempResult = ''; 609 | } 610 | // remove the opening tag from the result 611 | result = result.substring(0, frame.tagPosition) + result.substring(frame.tagPosition + frame.openingTagLength); 612 | return; 613 | } else if (filterResult) { 614 | result = result.substring(0, frame.tagPosition); 615 | return; 616 | } 617 | } 618 | 619 | frame.updateParentNodeMediaChildren(); 620 | frame.updateParentNodeText(); 621 | 622 | if ( 623 | // Already output /> 624 | options.selfClosing.indexOf(name) !== -1 || 625 | // Escaped tag, closing tag is implied 626 | (isImplied && !tagAllowed(name) && [ 'escape', 'recursiveEscape' ].indexOf(options.disallowedTagsMode) >= 0) 627 | ) { 628 | if (skip) { 629 | result = tempResult; 630 | tempResult = ''; 631 | } 632 | return; 633 | } 634 | 635 | result += ''; 636 | if (skip) { 637 | result = tempResult + escapeHtml(result); 638 | tempResult = ''; 639 | } 640 | addedText = false; 641 | } 642 | }, options.parser); 643 | parser.write(html); 644 | parser.end(); 645 | 646 | return result; 647 | 648 | function initializeState() { 649 | result = ''; 650 | depth = 0; 651 | stack = []; 652 | skipMap = {}; 653 | transformMap = {}; 654 | skipText = false; 655 | skipTextDepth = 0; 656 | } 657 | 658 | function escapeHtml(s, quote) { 659 | if (typeof (s) !== 'string') { 660 | s = s + ''; 661 | } 662 | if (options.parser.decodeEntities) { 663 | s = s.replace(/&/g, '&').replace(//g, '>'); 664 | if (quote) { 665 | s = s.replace(/"/g, '"'); 666 | } 667 | } 668 | // TODO: this is inadequate because it will pass `&0;`. This approach 669 | // will not work, each & must be considered with regard to whether it 670 | // is followed by a 100% syntactically valid entity or not, and escaped 671 | // if it is not. If this bothers you, don't set parser.decodeEntities 672 | // to false. (The default is true.) 673 | s = s.replace(/&(?![a-zA-Z0-9#]{1,20};)/g, '&') // Match ampersands not part of existing HTML entity 674 | .replace(//g, '>'); 676 | if (quote) { 677 | s = s.replace(/"/g, '"'); 678 | } 679 | return s; 680 | } 681 | 682 | function naughtyHref(name, href) { 683 | // Browsers ignore character codes of 32 (space) and below in a surprising 684 | // number of situations. Start reading here: 685 | // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Embedded_tab 686 | // eslint-disable-next-line no-control-regex 687 | href = href.replace(/[\x00-\x20]+/g, ''); 688 | // Clobber any comments in URLs, which the browser might 689 | // interpret inside an XML data island, allowing 690 | // a javascript: URL to be snuck through 691 | while (true) { 692 | const firstIndex = href.indexOf('', firstIndex + 4); 697 | if (lastIndex === -1) { 698 | break; 699 | } 700 | href = href.substring(0, firstIndex) + href.substring(lastIndex + 3); 701 | } 702 | // Case insensitive so we don't get faked out by JAVASCRIPT #1 703 | // Allow more characters after the first so we don't get faked 704 | // out by certain schemes browsers accept 705 | const matches = href.match(/^([a-zA-Z][a-zA-Z0-9.\-+]*):/); 706 | if (!matches) { 707 | // Protocol-relative URL starting with any combination of '/' and '\' 708 | if (href.match(/^[/\\]{2}/)) { 709 | return !options.allowProtocolRelative; 710 | } 711 | 712 | // No scheme 713 | return false; 714 | } 715 | const scheme = matches[1].toLowerCase(); 716 | 717 | if (has(options.allowedSchemesByTag, name)) { 718 | return options.allowedSchemesByTag[name].indexOf(scheme) === -1; 719 | } 720 | 721 | return !options.allowedSchemes || options.allowedSchemes.indexOf(scheme) === -1; 722 | } 723 | 724 | function parseUrl(value) { 725 | value = value.replace(/^(\w+:)?\s*[\\/]\s*[\\/]/, '$1//'); 726 | if (value.startsWith('relative:')) { 727 | // An attempt to exploit our workaround for base URLs being 728 | // mandatory for relative URL validation in the WHATWG 729 | // URL parser, reject it 730 | throw new Error('relative: exploit attempt'); 731 | } 732 | // naughtyHref is in charge of whether protocol relative URLs 733 | // are cool. Here we are concerned just with allowed hostnames and 734 | // whether to allow relative URLs. 735 | // 736 | // Build a placeholder "base URL" against which any reasonable 737 | // relative URL may be parsed successfully 738 | let base = 'relative://relative-site'; 739 | for (let i = 0; (i < 100); i++) { 740 | base += `/${i}`; 741 | } 742 | 743 | const parsed = new URL(value, base); 744 | 745 | const isRelativeUrl = parsed && parsed.hostname === 'relative-site' && parsed.protocol === 'relative:'; 746 | return { 747 | isRelativeUrl, 748 | url: parsed 749 | }; 750 | } 751 | /** 752 | * Filters user input css properties by allowlisted regex attributes. 753 | * Modifies the abstractSyntaxTree object. 754 | * 755 | * @param {object} abstractSyntaxTree - Object representation of CSS attributes. 756 | * @property {array[Declaration]} abstractSyntaxTree.nodes[0] - Each object cointains prop and value key, i.e { prop: 'color', value: 'red' }. 757 | * @param {object} allowedStyles - Keys are properties (i.e color), value is list of permitted regex rules (i.e /green/i). 758 | * @return {object} - The modified tree. 759 | */ 760 | function filterCss(abstractSyntaxTree, allowedStyles) { 761 | if (!allowedStyles) { 762 | return abstractSyntaxTree; 763 | } 764 | 765 | const astRules = abstractSyntaxTree.nodes[0]; 766 | let selectedRule; 767 | 768 | // Merge global and tag-specific styles into new AST. 769 | if (allowedStyles[astRules.selector] && allowedStyles['*']) { 770 | selectedRule = deepmerge( 771 | allowedStyles[astRules.selector], 772 | allowedStyles['*'] 773 | ); 774 | } else { 775 | selectedRule = allowedStyles[astRules.selector] || allowedStyles['*']; 776 | } 777 | 778 | if (selectedRule) { 779 | abstractSyntaxTree.nodes[0].nodes = astRules.nodes.reduce(filterDeclarations(selectedRule), []); 780 | } 781 | 782 | return abstractSyntaxTree; 783 | } 784 | 785 | /** 786 | * Extracts the style attributes from an AbstractSyntaxTree and formats those 787 | * values in the inline style attribute format. 788 | * 789 | * @param {AbstractSyntaxTree} filteredAST 790 | * @return {string} - Example: "color:yellow;text-align:center !important;font-family:helvetica;" 791 | */ 792 | function stringifyStyleAttributes(filteredAST) { 793 | return filteredAST.nodes[0].nodes 794 | .reduce(function(extractedAttributes, attrObject) { 795 | extractedAttributes.push( 796 | `${attrObject.prop}:${attrObject.value}${attrObject.important ? ' !important' : ''}` 797 | ); 798 | return extractedAttributes; 799 | }, []) 800 | .join(';'); 801 | } 802 | 803 | /** 804 | * Filters the existing attributes for the given property. Discards any attributes 805 | * which don't match the allowlist. 806 | * 807 | * @param {object} selectedRule - Example: { color: red, font-family: helvetica } 808 | * @param {array} allowedDeclarationsList - List of declarations which pass the allowlist. 809 | * @param {object} attributeObject - Object representing the current css property. 810 | * @property {string} attributeObject.type - Typically 'declaration'. 811 | * @property {string} attributeObject.prop - The CSS property, i.e 'color'. 812 | * @property {string} attributeObject.value - The corresponding value to the css property, i.e 'red'. 813 | * @return {function} - When used in Array.reduce, will return an array of Declaration objects 814 | */ 815 | function filterDeclarations(selectedRule) { 816 | return function (allowedDeclarationsList, attributeObject) { 817 | // If this property is allowlisted... 818 | if (has(selectedRule, attributeObject.prop)) { 819 | const matchesRegex = selectedRule[attributeObject.prop].some(function(regularExpression) { 820 | return regularExpression.test(attributeObject.value); 821 | }); 822 | 823 | if (matchesRegex) { 824 | allowedDeclarationsList.push(attributeObject); 825 | } 826 | } 827 | return allowedDeclarationsList; 828 | }; 829 | } 830 | 831 | function filterClasses(classes, allowed, allowedGlobs) { 832 | if (!allowed) { 833 | // The class attribute is allowed without filtering on this tag 834 | return classes; 835 | } 836 | classes = classes.split(/\s+/); 837 | return classes.filter(function(clss) { 838 | return allowed.indexOf(clss) !== -1 || allowedGlobs.some(function(glob) { 839 | return glob.test(clss); 840 | }); 841 | }).join(' '); 842 | } 843 | } 844 | 845 | // Defaults are accessible to you so that you can use them as a starting point 846 | // programmatically if you wish 847 | 848 | const htmlParserDefaults = { 849 | decodeEntities: true 850 | }; 851 | sanitizeHtml.defaults = { 852 | allowedTags: [ 853 | // Sections derived from MDN element categories and limited to the more 854 | // benign categories. 855 | // https://developer.mozilla.org/en-US/docs/Web/HTML/Element 856 | // Content sectioning 857 | 'address', 'article', 'aside', 'footer', 'header', 858 | 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 859 | 'main', 'nav', 'section', 860 | // Text content 861 | 'blockquote', 'dd', 'div', 'dl', 'dt', 'figcaption', 'figure', 862 | 'hr', 'li', 'menu', 'ol', 'p', 'pre', 'ul', 863 | // Inline text semantics 864 | 'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite', 'code', 'data', 'dfn', 865 | 'em', 'i', 'kbd', 'mark', 'q', 866 | 'rb', 'rp', 'rt', 'rtc', 'ruby', 867 | 's', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr', 868 | // Table content 869 | 'caption', 'col', 'colgroup', 'table', 'tbody', 'td', 'tfoot', 'th', 870 | 'thead', 'tr' 871 | ], 872 | // Tags that cannot be boolean 873 | nonBooleanAttributes: [ 874 | 'abbr', 'accept', 'accept-charset', 'accesskey', 'action', 875 | 'allow', 'alt', 'as', 'autocapitalize', 'autocomplete', 876 | 'blocking', 'charset', 'cite', 'class', 'color', 'cols', 877 | 'colspan', 'content', 'contenteditable', 'coords', 'crossorigin', 878 | 'data', 'datetime', 'decoding', 'dir', 'dirname', 'download', 879 | 'draggable', 'enctype', 'enterkeyhint', 'fetchpriority', 'for', 880 | 'form', 'formaction', 'formenctype', 'formmethod', 'formtarget', 881 | 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 882 | 'http-equiv', 'id', 'imagesizes', 'imagesrcset', 'inputmode', 883 | 'integrity', 'is', 'itemid', 'itemprop', 'itemref', 'itemtype', 884 | 'kind', 'label', 'lang', 'list', 'loading', 'low', 'max', 885 | 'maxlength', 'media', 'method', 'min', 'minlength', 'name', 886 | 'nonce', 'optimum', 'pattern', 'ping', 'placeholder', 'popover', 887 | 'popovertarget', 'popovertargetaction', 'poster', 'preload', 888 | 'referrerpolicy', 'rel', 'rows', 'rowspan', 'sandbox', 'scope', 889 | 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', 890 | 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'style', 891 | 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', 892 | 'value', 'width', 'wrap', 893 | // Event handlers 894 | 'onauxclick', 'onafterprint', 'onbeforematch', 'onbeforeprint', 895 | 'onbeforeunload', 'onbeforetoggle', 'onblur', 'oncancel', 896 | 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', 897 | 'oncontextlost', 'oncontextmenu', 'oncontextrestored', 'oncopy', 898 | 'oncuechange', 'oncut', 'ondblclick', 'ondrag', 'ondragend', 899 | 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 900 | 'ondrop', 'ondurationchange', 'onemptied', 'onended', 901 | 'onerror', 'onfocus', 'onformdata', 'onhashchange', 'oninput', 902 | 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 903 | 'onlanguagechange', 'onload', 'onloadeddata', 'onloadedmetadata', 904 | 'onloadstart', 'onmessage', 'onmessageerror', 'onmousedown', 905 | 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 906 | 'onmouseover', 'onmouseup', 'onoffline', 'ononline', 'onpagehide', 907 | 'onpageshow', 'onpaste', 'onpause', 'onplay', 'onplaying', 908 | 'onpopstate', 'onprogress', 'onratechange', 'onreset', 'onresize', 909 | 'onrejectionhandled', 'onscroll', 'onscrollend', 910 | 'onsecuritypolicyviolation', 'onseeked', 'onseeking', 'onselect', 911 | 'onslotchange', 'onstalled', 'onstorage', 'onsubmit', 'onsuspend', 912 | 'ontimeupdate', 'ontoggle', 'onunhandledrejection', 'onunload', 913 | 'onvolumechange', 'onwaiting', 'onwheel' 914 | ], 915 | disallowedTagsMode: 'discard', 916 | allowedAttributes: { 917 | a: [ 'href', 'name', 'target' ], 918 | // We don't currently allow img itself by default, but 919 | // these attributes would make sense if we did. 920 | img: [ 'src', 'srcset', 'alt', 'title', 'width', 'height', 'loading' ] 921 | }, 922 | allowedEmptyAttributes: [ 923 | 'alt' 924 | ], 925 | // Lots of these won't come up by default because we don't allow them 926 | selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ], 927 | // URL schemes we permit 928 | allowedSchemes: [ 'http', 'https', 'ftp', 'mailto', 'tel' ], 929 | allowedSchemesByTag: {}, 930 | allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ], 931 | allowProtocolRelative: true, 932 | enforceHtmlBoundary: false, 933 | parseStyleAttributes: true, 934 | preserveEscapedAttributes: false 935 | }; 936 | 937 | sanitizeHtml.simpleTransform = function(newTagName, newAttribs, merge) { 938 | merge = (merge === undefined) ? true : merge; 939 | newAttribs = newAttribs || {}; 940 | 941 | return function(tagName, attribs) { 942 | let attrib; 943 | if (merge) { 944 | for (attrib in newAttribs) { 945 | attribs[attrib] = newAttribs[attrib]; 946 | } 947 | } else { 948 | attribs = newAttribs; 949 | } 950 | 951 | return { 952 | tagName: newTagName, 953 | attribs: attribs 954 | }; 955 | }; 956 | }; 957 | -------------------------------------------------------------------------------- /logos/logo-box-builtby.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apostrophecms/sanitize-html/86efc067a63515e08ecfc47f94d8bca0e3715030/logos/logo-box-builtby.png -------------------------------------------------------------------------------- /logos/logo-box-madefor.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/apostrophecms/sanitize-html/86efc067a63515e08ecfc47f94d8bca0e3715030/logos/logo-box-madefor.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sanitize-html", 3 | "version": "2.17.0", 4 | "description": "Clean up user-submitted HTML, preserving allowlisted elements and allowlisted attributes on a per-element basis", 5 | "sideEffects": false, 6 | "main": "index.js", 7 | "files": [ 8 | "index.js" 9 | ], 10 | "scripts": { 11 | "test": "npx eslint . && mocha test/test.js" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/apostrophecms/sanitize-html.git" 16 | }, 17 | "keywords": [ 18 | "html", 19 | "parser", 20 | "sanitizer", 21 | "sanitize" 22 | ], 23 | "author": "Apostrophe Technologies, Inc.", 24 | "license": "MIT", 25 | "dependencies": { 26 | "deepmerge": "^4.2.2", 27 | "escape-string-regexp": "^4.0.0", 28 | "htmlparser2": "^8.0.0", 29 | "is-plain-object": "^5.0.0", 30 | "parse-srcset": "^1.0.2", 31 | "postcss": "^8.3.11" 32 | }, 33 | "devDependencies": { 34 | "eslint": "^7.3.1", 35 | "eslint-config-apostrophe": "^3.4.0", 36 | "eslint-config-standard": "^14.1.1", 37 | "eslint-plugin-import": "^2.25.2", 38 | "eslint-plugin-node": "^11.1.0", 39 | "eslint-plugin-promise": "^4.2.1", 40 | "eslint-plugin-standard": "^4.0.1", 41 | "mocha": "^10.2.0", 42 | "sinon": "^9.0.2" 43 | } 44 | } -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | const assert = require('assert'); 2 | const sinon = require('sinon'); 3 | 4 | describe('sanitizeHtml', function() { 5 | let sanitizeHtml; 6 | it('should be successfully initialized', function() { 7 | sanitizeHtml = require('../index.js'); 8 | }); 9 | it('should escape self closing tags', () => { 10 | assert.equal(sanitizeHtml('before after', { 11 | disallowedTagsMode: 'escape', 12 | allowedTags: [], 13 | allowedAttributes: false 14 | }), 'before <img src="test.png" /> after'); 15 | }); 16 | it('should handle numbers as strings', () => { 17 | assert.equal(sanitizeHtml(5, { 18 | allowedTags: [ 'b', 'em', 'i', 's', 'small', 'strong', 'sub', 'sup', 'time', 'u' ], 19 | allowedAttributes: {}, 20 | disallowedTagsMode: 'recursiveEscape' 21 | }), '5'); 22 | }); 23 | it('should pass through simple, well-formed markup', function() { 24 | assert.equal(sanitizeHtml('

Hello there

'), '

Hello there

'); 25 | }); 26 | it('should not pass through any text outside html tag boundary since html tag is found and option is ON', function() { 27 | assert.equal(sanitizeHtml('Text before html tag

Hello there

Text after html tag!P�X��[

paragraph after closing html

', { 28 | enforceHtmlBoundary: true 29 | } 30 | ), '

Hello there

'); 31 | }); 32 | it('should pass through text outside html tag boundary since option is OFF', function() { 33 | assert.equal(sanitizeHtml('Text before html tag

Hello there

Text after html tag!P�X��[

paragraph after closing html

', { 34 | enforceHtmlBoundary: false 35 | } 36 | ), 'Text before html tag

Hello there

Text after html tag!P�X��[

paragraph after closing html

'); 37 | }); 38 | it('should pass through text outside html tag boundary since option is ON but html tag is not found', function() { 39 | assert.equal(sanitizeHtml('Text before div tag

Hello there

Text after div tag!P�X��[

paragraph after closing div

', { 40 | enforceHtmlBoundary: true 41 | } 42 | ), 'Text before div tag

Hello there

Text after div tag!P�X��[

paragraph after closing div

'); 43 | }); 44 | it('should pass through all markup if allowedTags and allowedAttributes are set to false', function() { 45 | assert.equal(sanitizeHtml('
hello
', { 46 | allowedTags: false, 47 | allowedAttributes: false 48 | }), '
hello
'); 49 | }); 50 | it('should not pass through any markup if allowedTags is set to undefined (falsy but not exactly false)', function() { 51 | assert.equal(sanitizeHtml('
hello
', { 52 | allowedTags: undefined 53 | }), 'hello'); 54 | }); 55 | it('should not pass through any markup if allowedTags is set to 0 (falsy but not exactly false)', function() { 56 | assert.equal(sanitizeHtml('
hello
', { 57 | allowedTags: 0 58 | }), 'hello'); 59 | }); 60 | it('should not pass through any markup if allowedTags is set to null (falsy but not exactly false)', function() { 61 | assert.equal(sanitizeHtml('
hello
', { 62 | allowedTags: null 63 | }), 'hello'); 64 | }); 65 | it('should not pass through any markup if allowedTags is set to empty string (falsy but not exactly false)', function() { 66 | assert.equal(sanitizeHtml('
hello
', { 67 | allowedTags: '' 68 | }), 'hello'); 69 | }); 70 | it('should respect text nodes at top level', function() { 71 | assert.equal(sanitizeHtml('Blah blah blah

Whee!

'), 'Blah blah blah

Whee!

'); 72 | }); 73 | it('should return an empty string when input is explicit "undefined"', function() { 74 | assert.equal(sanitizeHtml(undefined), ''); 75 | }); 76 | it('should return an empty string when input is explicit "null"', function() { 77 | assert.equal(sanitizeHtml(null), ''); 78 | }); 79 | it('should return an empty string when input is not provided', function() { 80 | assert.equal(sanitizeHtml(), ''); 81 | }); 82 | it('should return an empty string when input is an empty string', function() { 83 | assert.equal(sanitizeHtml(''), ''); 84 | }); 85 | it('should reject markup not allowlisted without destroying its text', function() { 86 | assert.equal(sanitizeHtml('
Hello
'), '
Hello
'); 87 | }); 88 | it('should escape markup not allowlisted', function() { 89 | assert.equal(sanitizeHtml('
Hello
', { disallowedTagsMode: 'escape' }), '
<wiggly>Hello</wiggly>
'); 90 | }); 91 | it('should accept a custom list of allowed tags', function() { 92 | assert.equal(sanitizeHtml('Cheese', { allowedTags: [ 'blue', 'green' ] }), 'Cheese'); 93 | }); 94 | it('should reject attributes not allowlisted', function() { 95 | assert.equal(sanitizeHtml('foo'), 'foo'); 96 | }); 97 | it('should accept a custom list of allowed attributes per element', function() { 98 | assert.equal(sanitizeHtml('foo', { allowedAttributes: { a: [ 'href', 'whizbang' ] } }), 'foo'); 99 | }); 100 | it('should clean up unclosed img tags and p tags', function() { 101 | assert.equal(sanitizeHtml('

Whee

Again

Wowcool', { 102 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]) 103 | }), '

Whee

Again

Wowcool

'); 104 | }); 105 | it('should reject hrefs that are not relative, ftp, http, https or mailto', function() { 106 | assert.equal(sanitizeHtml('googlehttps googleftpmailtorelativejavascript'), 'googlehttps googleftpmailtorelativejavascript'); 107 | }); 108 | it('should cope identically with capitalized attributes and tags and should tolerate capitalized schemes', function() { 109 | assert.equal(sanitizeHtml('googlehttps googleftpmailtorelativejavascript'), 'googlehttps googleftpmailtorelativejavascript'); 110 | }); 111 | it('should drop the content of script elements', function() { 112 | assert.equal(sanitizeHtml('

Paragraph

'), '

Paragraph

'); 113 | }); 114 | it('should drop the content of style elements', function() { 115 | assert.equal(sanitizeHtml('

Paragraph

'), '

Paragraph

'); 116 | }); 117 | it('should drop the content of textarea elements', function() { 118 | assert.equal(sanitizeHtml('

Paragraph

'), '

Paragraph

'); 119 | }); 120 | it('should drop the content of option elements', function() { 121 | assert.equal(sanitizeHtml('

Paragraph

'), '

Paragraph

'); 122 | }); 123 | it('should drop the content of textarea elements but keep the closing parent tag, when nested', function() { 124 | assert.equal(sanitizeHtml('

Paragraph

'), '

Paragraph

'); 125 | }); 126 | it('should retain the content of fibble elements by default', function() { 127 | assert.equal(sanitizeHtml('Nifty

Paragraph

'), 'Nifty

Paragraph

'); 128 | }); 129 | it('should discard the content of fibble elements if specified for nonTextTags', function() { 130 | assert.equal(sanitizeHtml('Nifty

Paragraph

', { nonTextTags: [ 'fibble' ] }), '

Paragraph

'); 131 | }); 132 | it('should retain allowed tags within a fibble element if fibble is not specified for nonTextTags', function() { 133 | assert.equal(sanitizeHtml('Nifty

Paragraph

', {}), 'Nifty

Paragraph

'); 134 | }); 135 | it('should discard allowed tags within a fibble element if fibble is specified for nonTextTags', function() { 136 | assert.equal(sanitizeHtml('Nifty

Paragraph

', { nonTextTags: [ 'fibble' ] }), '

Paragraph

'); 137 | }); 138 | it('should preserve textarea content if textareas are allowed', function() { 139 | assert.equal(sanitizeHtml('

Paragraph

', { 140 | allowedTags: [ 'textarea', 'p' ] 141 | }), '

Paragraph

'); 142 | }); 143 | it('should preserve entities as such', function() { 144 | assert.equal(sanitizeHtml('<Kapow!>'), '<Kapow!>'); 145 | }); 146 | it('should dump closing tags which do not have any opening tags.', function() { 147 | assert.equal(sanitizeHtml('
/'); 150 | 151 | assert.equal(sanitizeHtml('/'); 154 | }); 155 | it('should tolerate not closed p tags', function() { 156 | assert.equal(sanitizeHtml('

inner text 1

inner text 2

inner text 3

'), '

inner text 1

inner text 2

inner text 3

'); 157 | }); 158 | it('should escape not closed p tags, if not in allowedTags array', function() { 159 | assert.equal(sanitizeHtml('

inner text 1

inner text 2

inner text 3

', { 160 | allowedTags: [ 'div' ] 161 | }), '
inner text 1inner text 2inner text 3
'); 162 | }); 163 | it('should dump comments', function() { 164 | assert.equal(sanitizeHtml('

Whee

'), '

Whee

'); 165 | }); 166 | it('should dump a sneaky encoded javascript url', function() { 167 | assert.equal(sanitizeHtml('Hax'), 'Hax'); 168 | }); 169 | it('should dump an uppercase javascript url', function() { 170 | assert.equal(sanitizeHtml('Hax'), 'Hax'); 171 | }); 172 | it('should dump a javascript URL with a comment in the middle (probably only respected by browsers in XML data islands, but just in case someone enables those)', function() { 173 | assert.equal(sanitizeHtml('Hax'), 'Hax'); 174 | }); 175 | it('should not mess up a hashcode with a : in it', function() { 176 | assert.equal(sanitizeHtml('Hi'), 'Hi'); 177 | }); 178 | it('should dump character codes 1-32 before testing scheme', function() { 179 | assert.equal(sanitizeHtml('Hax'), 'Hax'); 180 | }); 181 | it('should dump character codes 1-32 even when escaped with padding rather than trailing ;', function() { 182 | assert.equal(sanitizeHtml('Hax'), 'Hax'); 183 | // This one is weird, but the browser does not interpret it 184 | // as a scheme, so we're OK. That character is 65535, not null. I 185 | // think it's a limitation of the entities module 186 | assert.equal(sanitizeHtml('Hax'), 'Hax'); 187 | }); 188 | it('should still like nice schemes', function() { 189 | assert.equal(sanitizeHtml('Hi'), 'Hi'); 190 | }); 191 | it('should still like nice relative URLs', function() { 192 | assert.equal(sanitizeHtml('Hi'), 'Hi'); 193 | }); 194 | it('should replace ol to ul', function() { 195 | assert.equal(sanitizeHtml('
  1. Hello world
', { transformTags: { ol: 'ul' } }), ''); 196 | }); 197 | it('should replace ol to ul and add class attribute with foo value', function() { 198 | assert.equal(sanitizeHtml('
  1. Hello world
', { 199 | transformTags: { ol: sanitizeHtml.simpleTransform('ul', { class: 'foo' }) }, 200 | allowedAttributes: { ul: [ 'class' ] } 201 | }), ''); 202 | }); 203 | it('should replace ol to ul, left attributes foo and bar untouched, remove baz attribute and add class attributte with foo value', function() { 204 | assert.equal(sanitizeHtml('
  1. Hello world
', { 205 | transformTags: { ol: sanitizeHtml.simpleTransform('ul', { class: 'foo' }) }, 206 | allowedAttributes: { ul: [ 'foo', 'bar', 'class' ] } 207 | }), ''); 208 | }); 209 | it('should replace ol to ul and replace all attributes to class attribute with foo value', function() { 210 | assert.equal(sanitizeHtml('
  1. Hello world
', { 211 | transformTags: { ol: sanitizeHtml.simpleTransform('ul', { class: 'foo' }, false) }, 212 | allowedAttributes: { ul: [ 'foo', 'bar', 'class' ] } 213 | }), ''); 214 | }); 215 | it('should replace ol to ul and add attribute class with foo value and attribute bar with bar value', function() { 216 | assert.equal(sanitizeHtml('
  1. Hello world
', { 217 | transformTags: { 218 | ol: function(tagName, attribs) { 219 | attribs.class = 'foo'; 220 | attribs.bar = 'bar'; 221 | return { 222 | tagName: 'ul', 223 | attribs: attribs 224 | }; 225 | } 226 | }, 227 | allowedAttributes: { ul: [ 'bar', 'class' ] } 228 | }), ''); 229 | }); 230 | 231 | it('should replace text and attributes when they are changed by transforming function', function () { 232 | assert.equal(sanitizeHtml('some text', { 233 | transformTags: { 234 | a: function (tagName, attribs) { 235 | return { 236 | tagName: tagName, 237 | attribs: attribs, 238 | text: '' 239 | }; 240 | } 241 | } 242 | }), ''); 243 | }); 244 | it('should replace text and attributes when they are changed by transforming function and textFilter is set', function () { 245 | assert.equal(sanitizeHtml('some text', { 246 | transformTags: { 247 | a: function (tagName, attribs) { 248 | return { 249 | tagName: tagName, 250 | attribs: attribs, 251 | text: 'some text need"tofiltered' 252 | }; 253 | } 254 | }, 255 | textFilter: function (text, tagName) { 256 | return text.replace(/\s/g, '_'); 257 | } 258 | }), 'some_text_need"to<be>filtered'); 259 | }); 260 | 261 | it('should replace text and attributes when they are changed by transforming function and textFilter is not set', function () { 262 | assert.equal(sanitizeHtml('some text', { 263 | transformTags: { 264 | a: function (tagName, attribs) { 265 | return { 266 | tagName: tagName, 267 | attribs: attribs, 268 | text: 'some good text' 269 | }; 270 | } 271 | } 272 | }), 'some good text'); 273 | }); 274 | 275 | it('should preserve trailing text when replacing the tagName and adding new text via transforming function', function () { 276 | assert.equal(sanitizeHtml('

text before
text after

', { 277 | transformTags: { 278 | br: function (_tagName, _attribs) { 279 | return { 280 | tagName: 'span', 281 | text: ' ' 282 | }; 283 | } 284 | } 285 | }), '

text before text after

'); 286 | }); 287 | 288 | it('should add new text when not initially set and replace attributes when they are changed by transforming function', function () { 289 | assert.equal(sanitizeHtml('', { 290 | transformTags: { 291 | a: function (tagName, attribs) { 292 | return { 293 | tagName: tagName, 294 | attribs: attribs, 295 | text: 'some new text' 296 | }; 297 | } 298 | } 299 | }), 'some new text'); 300 | }); 301 | 302 | it('should preserve text when initially set and replace attributes when they are changed by transforming function', function () { 303 | assert.equal(sanitizeHtml('some initial text', { 304 | transformTags: { 305 | a: function (tagName, attribs) { 306 | return { 307 | tagName: tagName, 308 | attribs: attribs 309 | }; 310 | } 311 | } 312 | }), 'some initial text'); 313 | }); 314 | 315 | it('should skip an empty link', function() { 316 | assert.strictEqual( 317 | sanitizeHtml('

This is
Linux

', { 318 | exclusiveFilter: function (frame) { 319 | return frame.tag === 'a' && !frame.text.trim(); 320 | } 321 | }), 322 | '

This is
Linux

' 323 | ); 324 | }); 325 | 326 | it('Should expose a node\'s inner text and inner HTML to the filter', function() { 327 | assert.strictEqual( 328 | sanitizeHtml('

12
3

', { 329 | exclusiveFilter: function(frame) { 330 | if (frame.tag === 'p') { 331 | assert.strictEqual(frame.text, '124'); 332 | } else if (frame.tag === 'a') { 333 | assert.strictEqual(frame.text, '3'); 334 | return true; 335 | } else if (frame.tag === 'br') { 336 | assert.strictEqual(frame.text, ''); 337 | } else { 338 | assert.fail('p, a, br', frame.tag); 339 | } 340 | return false; 341 | } 342 | }), 343 | '

124

' 344 | ); 345 | }); 346 | 347 | it('Should collapse nested empty elements', function() { 348 | assert.strictEqual( 349 | sanitizeHtml('


', { 350 | exclusiveFilter: function(frame) { 351 | return (frame.tag === 'a' || frame.tag === 'p') && !frame.text.trim(); 352 | } 353 | }), 354 | '' 355 | ); 356 | }); 357 | 358 | it('Should find child media elements that are in allowedTags', function() { 359 | const markup = ''; 360 | const sansVideo = ''; 361 | const sanitizedMarkup = sanitizeHtml(markup, { 362 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), 363 | exclusiveFilter: function(frame) { 364 | if (frame.tag === 'a') { 365 | // eslint-disable-next-line no-console 366 | assert(frame.mediaChildren.length === 1); 367 | } 368 | 369 | return (frame.tag === 'a') && !frame.text.trim() && !frame.mediaChildren.length; 370 | } 371 | }); 372 | 373 | assert.strictEqual(sanitizedMarkup, sansVideo); 374 | }); 375 | 376 | it('Exclusive filter should not affect elements which do not match the filter condition', function () { 377 | assert.strictEqual( 378 | sanitizeHtml('I love Linux OS', 379 | { 380 | exclusiveFilter: function (frame) { 381 | return (frame.tag === 'a') && !frame.text.trim(); 382 | } 383 | }), 384 | 'I love Linux OS' 385 | ); 386 | }); 387 | 388 | it('Exclusive filter should not run for discarded tags', function () { 389 | assert.strictEqual( 390 | sanitizeHtml('this tag is discarded', 391 | { 392 | exclusiveFilter: function () { 393 | throw Error('this should not run'); 394 | } 395 | }), 396 | 'this tag is discarded' 397 | ); 398 | }); 399 | 400 | it('should keep inner text when exclusiveFilter returns "excludeTag"', function() { 401 | assert.strictEqual( 402 | sanitizeHtml('

These links hack more hack have disallowed href protocols

', { 403 | exclusiveFilter: function (frame) { 404 | return frame.tag === 'a' && !frame.attribs.src ? 'excludeTag' : false; 405 | } 406 | }), 407 | '

These links hack more hack have disallowed href protocols

' 408 | ); 409 | }); 410 | 411 | it('should keep inner tags when exclusiveFilter returns "excludeTag"', function() { 412 | assert.strictEqual( 413 | sanitizeHtml('This div is bad
but its content

should be kept as-is

.', { 414 | exclusiveFilter: function (frame) { 415 | return frame.tag === 'div' && frame.attribs.class && /\bbad\b/.test(frame.attribs.class) ? 'excludeTag' : false; 416 | } 417 | }), 418 | 'This div is bad but its content

should be kept as-is

.' 419 | ); 420 | }); 421 | 422 | it('should work with escaped tags when exclusiveFilter returns "excludeTag"', function () { 423 | assert.strictEqual( 424 | sanitizeHtml('hello there. General Kenobi!', { 425 | disallowedTagsMode: 'escape', 426 | exclusiveFilter: function (frame) { 427 | return frame.tag === 'wiggly' ? 'excludeTag' : false; 428 | } 429 | }), 430 | 'hello there. General Kenobi!' 431 | ); 432 | }); 433 | 434 | it('should disallow data URLs with default allowedSchemes', function() { 435 | assert.equal( 436 | sanitizeHtml( 437 | // teeny-tiny valid transparent GIF in a data URL 438 | '', 439 | { 440 | allowedTags: [ 'img' ] 441 | } 442 | ), 443 | '' 444 | ); 445 | }); 446 | it('should allow data URLs with custom allowedSchemes', function() { 447 | assert.equal( 448 | sanitizeHtml( 449 | // teeny-tiny valid transparent GIF in a data URL 450 | '', 451 | { 452 | allowedTags: [ 'img', 'p' ], 453 | allowedSchemes: [ 'data', 'http' ] 454 | } 455 | ), 456 | '' 457 | ); 458 | }); 459 | it('should allow specific classes when allowlisted with allowedClasses for a single tag', function() { 460 | assert.equal( 461 | sanitizeHtml( 462 | '

whee

', 463 | { 464 | allowedTags: [ 'p' ], 465 | allowedClasses: { 466 | p: [ 'nifty' ] 467 | } 468 | } 469 | ), 470 | '

whee

' 471 | ); 472 | }); 473 | it('should allow specific classes when allowlisted with allowedClasses for all tags', function() { 474 | assert.equal( 475 | sanitizeHtml( 476 | '

whee

', 477 | { 478 | allowedTags: [ 'p', 'div' ], 479 | allowedClasses: { 480 | '*': [ 'nifty' ] 481 | } 482 | } 483 | ), 484 | '

whee

' 485 | ); 486 | }); 487 | it('should allow all classes that are allowlisted for a single tag or all tags', function() { 488 | assert.equal( 489 | sanitizeHtml( 490 | '

whee

', 491 | { 492 | allowedTags: [ 'p', 'div' ], 493 | allowedClasses: { 494 | '*': [ 'simple' ], 495 | p: [ 'nifty' ], 496 | div: [ 'dippy' ] 497 | } 498 | } 499 | ), 500 | '

whee

' 501 | ); 502 | }); 503 | it('should allow classes that match wildcards for a single tag or all tags', function() { 504 | assert.equal( 505 | sanitizeHtml( 506 | '

whee

', 507 | { 508 | allowedTags: [ 'p' ], 509 | allowedClasses: { 510 | '*': [ 'dippy-*-simple' ], 511 | p: [ 'nifty-*' ] 512 | } 513 | } 514 | ), 515 | '

whee

' 516 | ); 517 | }); 518 | it('should allow all classes if `allowedClasses` contains a single `*`', function() { 519 | assert.equal( 520 | sanitizeHtml( 521 | '

whee

', 522 | { 523 | allowedTags: [ 'p' ], 524 | allowedClasses: { 525 | '*': [ '*' ] 526 | } 527 | } 528 | ), 529 | '

whee

' 530 | ); 531 | }); 532 | it('should allow all classes for a single tag if `allowedClasses` for the tag is false', function() { 533 | assert.equal( 534 | sanitizeHtml( 535 | '

whee

', 536 | { 537 | allowedTags: [ 'p' ], 538 | allowedClasses: { 539 | p: false 540 | } 541 | } 542 | ), 543 | '

whee

' 544 | ); 545 | }); 546 | it('should allow only classes that matches `allowedClasses` regex', function() { 547 | assert.equal( 548 | sanitizeHtml( 549 | '

whee

', 550 | { 551 | allowedTags: [ 'p' ], 552 | allowedClasses: { 553 | p: [ /^nifty\d{2}$/, /^d\w{4}$/ ] 554 | } 555 | } 556 | ), 557 | '

whee

' 558 | ); 559 | }); 560 | it('should allow classes that match `allowedClasses` regex for all tags', function() { 561 | assert.equal( 562 | sanitizeHtml( 563 | '

whee

', 564 | { 565 | allowedClasses: { 566 | '*': [ /^nifty\d{2}$/, /^d\w{4}$/ ] 567 | } 568 | } 569 | ), 570 | '

whee

' 571 | ); 572 | }); 573 | it('should allow defining schemes on a per-tag basis', function() { 574 | assert.equal( 575 | sanitizeHtml( 576 | // teeny-tiny valid transparent GIF in a data URL 577 | '', 578 | { 579 | allowedTags: [ 'img', 'a' ], 580 | allowedSchemes: [ 'http' ], 581 | allowedSchemesByTag: { 582 | img: [ 'data' ], 583 | a: [ 'https' ] 584 | } 585 | } 586 | ), 587 | '' 588 | ); 589 | assert.equal( 590 | sanitizeHtml( 591 | // teeny-tiny valid transparent GIF in a data URL 592 | '', 593 | { 594 | allowedTags: [ 'img', 'a' ], 595 | allowedSchemes: [ 'http' ], 596 | allowedSchemesByTag: { 597 | img: [], 598 | a: [ 'https' ] 599 | } 600 | } 601 | ), 602 | '' 603 | ); 604 | }); 605 | it('should not act weird when the class attribute is empty', function() { 606 | assert.equal( 607 | sanitizeHtml( 608 | '

whee

', 609 | { 610 | allowedTags: [ 'p' ], 611 | allowedClasses: { 612 | p: [ 'nifty' ] 613 | } 614 | } 615 | ), 616 | '

whee

' 617 | ); 618 | }); 619 | it('should not crash on bad markup', function() { 620 | assert.equal( 621 | sanitizeHtml( 622 | '

', 631 | { 632 | allowedTags: [ 'img' ], 633 | allowedAttributes: { 634 | img: [ 'src' ] 635 | } 636 | } 637 | ), 638 | // This is weird but not dangerous. Without the " there 639 | // would probably be some way to make it come out as a 640 | // separate attribute 641 | '' 642 | ); 643 | }); 644 | 645 | it('should deliver a warning if using vulnerable tags', function() { 646 | const spy = sinon.spy(console, 'warn'); 647 | const message = '\n\n⚠️ Your `allowedTags` option includes, `style`, which is inherently\nvulnerable to XSS attacks. Please remove it from `allowedTags`.\nOr, to disable this warning, add the `allowVulnerableTags` option\nand ensure you are accounting for this risk.\n\n'; 648 | 649 | sanitizeHtml( 650 | '', 651 | { 652 | allowedTags: [ 'style' ] 653 | } 654 | ); 655 | 656 | assert(spy.calledWith(message)); 657 | // Restore the spied-upon method 658 | console.warn.restore(); 659 | }); 660 | 661 | it('should not deliver a warning if using the allowVulnerableTags option', function() { 662 | const spy = sinon.spy(console, 'warn'); 663 | 664 | sanitizeHtml( 665 | '', 666 | { 667 | allowVulnerableTags: true, 668 | allowedTags: [ 'style' ] 669 | } 670 | ); 671 | 672 | assert(spy.notCalled); 673 | // Restore the spied-upon method 674 | console.warn.restore(); 675 | }); 676 | 677 | it('should allow only approved attributes, but to any tags, if tag is declared as "*"', function() { 678 | assert.equal( 679 | sanitizeHtml( 680 | 'not listed too
', 681 | { 682 | allowedTags: [ 'table', 'img' ], 683 | allowedAttributes: { 684 | '*': [ 'bgcolor', 'align', 'src' ] 685 | } 686 | } 687 | ), 688 | '
' 689 | ); 690 | }); 691 | it('should not filter if exclusive filter does not match after transforming tags', function() { 692 | assert.equal( 693 | sanitizeHtml( 694 | 'test', 695 | { 696 | allowedTags: [ 'a' ], 697 | allowedAttributes: { a: [ 'href', 'target' ] }, 698 | transformTags: { 699 | a: function (tagName, attribs) { 700 | if (!attribs.href) { 701 | return false; 702 | } 703 | return { 704 | tagName: tagName, 705 | attribs: { 706 | target: '_blank', 707 | href: attribs.href 708 | } 709 | }; 710 | } 711 | }, 712 | exclusiveFilter: function(frame) { 713 | return frame.tag === 'a' && frame.text.trim() === 'blah'; 714 | } 715 | } 716 | ), 717 | 'test' 718 | ); 719 | }); 720 | it('should filter if exclusive filter does match after transforming tags', function() { 721 | assert.equal( 722 | sanitizeHtml( 723 | 'blah', 724 | { 725 | allowedTags: [ 'a' ], 726 | allowedAttributes: { a: [ 'href', 'target' ] }, 727 | transformTags: { 728 | a: function (tagName, attribs) { 729 | if (!attribs.href) { 730 | return false; 731 | } 732 | return { 733 | tagName: tagName, 734 | attribs: { 735 | target: '_blank', 736 | href: attribs.href 737 | } 738 | }; 739 | } 740 | }, 741 | exclusiveFilter: function(frame) { 742 | return frame.tag === 'a' && frame.text.trim() === 'blah'; 743 | } 744 | } 745 | ), 746 | '' 747 | ); 748 | }); 749 | it('should allow transform on all tags using \'*\'', function () { 750 | assert.equal( 751 | sanitizeHtml( 752 | '

Text

', 753 | { 754 | allowedTags: [ 'p' ], 755 | allowedAttributes: { p: [ 'style' ] }, 756 | transformTags: { 757 | '*': function (tagName, attribs) { 758 | return { 759 | tagName: tagName, 760 | attribs: { 761 | style: 'text-align: center' 762 | } 763 | }; 764 | } 765 | } 766 | } 767 | ), 768 | '

Text

' 769 | ); 770 | }); 771 | it('should not be faked out by double <', function() { 772 | assert.equal( 773 | sanitizeHtml('<img src="javascript:evil"/>' 774 | ), 775 | '<img src="javascript:evil"/>' 776 | ); 777 | assert.equal( 778 | sanitizeHtml('<a href="javascript:evil"/>' 779 | ), 780 | '<a href="javascript:evil"/>' 781 | ); 782 | }); 783 | it('should allow attributes to be specified as globs', function() { 784 | assert.equal( 785 | sanitizeHtml('click me', { 786 | allowedTags: [ 'a' ], 787 | allowedAttributes: { a: [ 'data-*' ] } 788 | }), 'click me' 789 | ); 790 | assert.equal( 791 | sanitizeHtml('click me', { 792 | allowedTags: [ 'a' ], 793 | allowedAttributes: { a: [ 'data-*-foo' ] } 794 | }), 'click me' 795 | ); 796 | }); 797 | it('should quote regex chars in attributes specified as globs', function() { 798 | assert.equal( 799 | sanitizeHtml('click me', { 800 | allowedTags: [ 'a' ], 801 | allowedAttributes: { a: [ 'data-b.*' ] } 802 | }), 'click me' 803 | ); 804 | }); 805 | it('should not escape inner content of script and style tags (when allowed)', function() { 806 | assert.equal( 807 | sanitizeHtml('
"normal text"
', { 808 | allowedTags: [ 'script' ] 809 | }), '"normal text"' 810 | ); 811 | assert.equal( 812 | sanitizeHtml('
"normal text"
', { 813 | allowedTags: [ 'style' ] 814 | }), '"normal text"' 815 | ); 816 | }); 817 | it('should not unescape escapes found inside script tags', function() { 818 | assert.equal( 819 | sanitizeHtml('', 820 | { 821 | allowedTags: [ 'script' ] 822 | } 823 | ), 824 | '' 825 | ); 826 | }); 827 | it('should process text nodes with provided function', function() { 828 | assert.equal( 829 | sanitizeHtml('"normal text this should be removed"', { 830 | textFilter: function(text, tagName) { 831 | return text.replace(' this should be removed', ''); 832 | } 833 | }), '"normal text"' 834 | ); 835 | }); 836 | it('should skip text nodes based on tagName', function() { 837 | assert.equal( 838 | sanitizeHtml('normal text this should be removednormal text this should be removed', { 839 | textFilter: function(text, tagName) { 840 | if (tagName === 'a') { 841 | return text; 842 | }; 843 | return text.replace(' this should be removed', ''); 844 | } 845 | }), 'normal text this should be removednormal text' 846 | ); 847 | }); 848 | it('should respect htmlparser2 options when passed in', function() { 849 | assert.equal( 850 | sanitizeHtml('I am', { 851 | allowedTags: false, 852 | allowedAttributes: false 853 | }), 854 | 'I am' 855 | ); 856 | assert.equal( 857 | sanitizeHtml('I am', { 858 | allowedTags: false, 859 | allowedAttributes: false, 860 | parser: { 861 | lowerCaseTags: false 862 | } 863 | }), 864 | 'I am' 865 | ); 866 | }); 867 | it('should not crash due to tag names that are properties of the universal Object prototype', function() { 868 | assert.equal( 869 | sanitizeHtml('!<__proto__>!'), 870 | '!<__proto__>!'); 871 | }); 872 | it('should correctly maintain escaping when allowing a nonTextTags tag other than script or style', function() { 873 | assert.equal( 874 | sanitizeHtml('!!', 875 | { allowedTags: [ 'textarea' ] } 876 | ), '!!' 877 | ); 878 | }); 879 | it('should allow protocol relative links by default', function() { 880 | assert.equal( 881 | sanitizeHtml('test'), 882 | 'test' 883 | ); 884 | }); 885 | it('should not allow protocol relative links when allowProtocolRelative is false', function() { 886 | assert.equal( 887 | sanitizeHtml('test', { allowProtocolRelative: false }), 888 | 'test' 889 | ); 890 | assert.equal( 891 | sanitizeHtml('test', { allowProtocolRelative: false }), 892 | 'test' 893 | ); 894 | assert.equal( 895 | sanitizeHtml('test', { allowProtocolRelative: false }), 896 | 'test' 897 | ); 898 | assert.equal( 899 | sanitizeHtml('test', { allowProtocolRelative: false }), 900 | 'test' 901 | ); 902 | }); 903 | it('should still allow regular relative URLs when allowProtocolRelative is false', function() { 904 | assert.equal( 905 | sanitizeHtml('test', { allowProtocolRelative: false }), 906 | 'test' 907 | ); 908 | }); 909 | it('should discard srcset by default', function() { 910 | assert.equal( 911 | sanitizeHtml('', { 912 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]) 913 | }), 914 | '' 915 | ); 916 | }); 917 | it('should accept srcset if allowed', function() { 918 | assert.equal( 919 | sanitizeHtml('', { 920 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), 921 | allowedAttributes: { img: [ 'src', 'srcset' ] } 922 | }), 923 | '' 924 | ); 925 | assert.equal( 926 | sanitizeHtml('', { 927 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), 928 | allowedAttributes: { img: [ 'src', 'srcset' ] } 929 | }), 930 | '' 931 | ); 932 | }); 933 | it('should drop bogus srcset', function() { 934 | assert.equal( 935 | sanitizeHtml('', { 936 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), 937 | allowedAttributes: { img: [ 'src', 'srcset' ] } 938 | }), 939 | '' 940 | ); 941 | }); 942 | it('should accept srcset with urls containing commas', function() { 943 | assert.equal( 944 | sanitizeHtml('', { 945 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]), 946 | allowedAttributes: { img: [ 'src', 'srcset' ] } 947 | }), 948 | '' 949 | ); 950 | }); 951 | 952 | it('text from transformTags should not specify tags', function() { 953 | const input = ''; 954 | const want = '<script>alert(1)</script>'; 955 | // Runs the sanitizer with a policy that turns an attribute into 956 | // text. A policy like this might be used to turn inputs into 957 | // inline elements that look like the original but which do not 958 | // affect form submissions. 959 | const got = sanitizeHtml( 960 | input, 961 | { 962 | allowedTags: [ 'u' ], 963 | allowedAttributes: { '*': [ 'class' ] }, 964 | transformTags: { 965 | input: function (tagName, attribs) { 966 | return { 967 | tagName: 'u', 968 | attribs: { class: 'inlined-input' }, 969 | text: attribs.value 970 | }; 971 | } 972 | } 973 | }); 974 | assert.equal(got, want); 975 | }); 976 | it('drop attribute names with meta-characters', function() { 977 | assert.equal( 978 | sanitizeHtml('alert(1)//>', { 979 | allowedTags: [ 'span' ], 980 | allowedAttributes: { span: [ 'data-*' ] } 981 | }), 982 | 'alert(1)//>' 983 | ); 984 | }); 985 | it('should sanitize styles correctly', function() { 986 | const sanitizeString = '

bestetestestestestestsettestestest

  • test
  1. test
  2. test
  3. test
  4. test

test

TESTETESTESTES

'; 987 | const expected = '

bestetestestestestestsettestestest

  • test
  1. test
  2. test
  3. test
  4. test

test

TESTETESTESTES

'; 988 | assert.equal( 989 | sanitizeHtml(sanitizeString, { 990 | allowedTags: false, 991 | allowedAttributes: { 992 | '*': [ 'dir' ], 993 | p: [ 'dir', 'style' ], 994 | li: [ 'style' ], 995 | span: [ 'style' ] 996 | }, 997 | allowedStyles: { 998 | '*': { 999 | // Matches hex 1000 | color: [ /#(0x)?[0-9a-f]+/i ], 1001 | 'text-align': [ /left/, /right/, /center/, /justify/, /initial/, /inherit/ ], 1002 | 'font-size': [ /36px/ ] 1003 | } 1004 | } 1005 | }).replace(/ /g, ''), expected.replace(/ /g, '') 1006 | ); 1007 | }); 1008 | it('Should remove empty style tags', function() { 1009 | assert.equal( 1010 | sanitizeHtml('', { 1011 | allowedTags: false, 1012 | allowedAttributes: false 1013 | }), 1014 | '' 1015 | ); 1016 | }); 1017 | it('Should remove invalid styles', function() { 1018 | assert.equal( 1019 | sanitizeHtml('', { 1020 | allowedTags: false, 1021 | allowedAttributes: { 1022 | span: [ 'style' ] 1023 | }, 1024 | allowedStyles: { 1025 | span: { 1026 | color: [ /blue/ ], 1027 | 'text-align': [ /left/ ] 1028 | } 1029 | } 1030 | }), '' 1031 | ); 1032 | }); 1033 | it('Should ignore styles when options.parseStyleAttributes is false', function() { 1034 | assert.equal( 1035 | sanitizeHtml('', { 1036 | allowedTags: false, 1037 | allowedAttributes: { 1038 | span: [ 'style' ] 1039 | }, 1040 | parseStyleAttributes: false 1041 | }), '' 1042 | ); 1043 | }); 1044 | it('Should throw an error if both allowedStyles is set and && parseStyleAttributes is set to false', function() { 1045 | try { 1046 | sanitizeHtml('', { 1047 | allowedTags: false, 1048 | allowedAttributes: { 1049 | span: [ 'style' ] 1050 | }, 1051 | allowedStyles: { 1052 | p: { 1053 | 'text-align': [ /^justify$/ ] 1054 | } 1055 | }, 1056 | parseStyleAttributes: false 1057 | }); 1058 | assert(false); 1059 | } catch (err) { 1060 | assert.equal(err.message, 'allowedStyles option cannot be used together with parseStyleAttributes: false.'); 1061 | } 1062 | }); 1063 | it('Should support !important styles', function() { 1064 | assert.equal( 1065 | sanitizeHtml('', { 1066 | allowedTags: false, 1067 | allowedAttributes: { 1068 | span: [ 'style' ] 1069 | }, 1070 | allowedStyles: { 1071 | span: { 1072 | color: [ /blue/ ] 1073 | } 1074 | } 1075 | }), '' 1076 | ); 1077 | }); 1078 | it('Should allow a specific style from global', function() { 1079 | assert.equal( 1080 | sanitizeHtml('', { 1081 | allowedTags: false, 1082 | allowedAttributes: { 1083 | span: [ 'style' ] 1084 | }, 1085 | allowedStyles: { 1086 | '*': { 1087 | color: [ /yellow/ ], 1088 | 'text-align': [ /center/ ] 1089 | }, 1090 | span: { 1091 | color: [ /green/ ], 1092 | 'font-family': [ /helvetica/ ] 1093 | } 1094 | } 1095 | }), '' 1096 | ); 1097 | }); 1098 | it('should delete the script tag', function() { 1099 | assert.equal(sanitizeHtml('', { 1100 | allowedTags: [ 'script' ], 1101 | allowVulnerableTags: true, 1102 | allowedAttributes: { 1103 | script: [ 'src' ] 1104 | }, 1105 | allowedScriptHostnames: [ 'www.authorized.com' ] 1106 | }), ''); 1107 | }); 1108 | it('should delete the script tag since src is not a valid URL', function() { 1109 | assert.equal(sanitizeHtml('', { 1110 | allowedTags: [ 'script' ], 1111 | allowVulnerableTags: true, 1112 | allowedAttributes: { 1113 | script: [ 'src' ] 1114 | }, 1115 | allowedScriptHostnames: [ 'www.unauthorized.com' ] 1116 | }), ''); 1117 | }); 1118 | it('Should allow domains in a script that are in allowedScriptDomains', function() { 1119 | assert.equal( 1120 | sanitizeHtml('', { 1121 | allowedTags: [ 'script' ], 1122 | allowedAttributes: { 1123 | script: [ 'src' ] 1124 | }, 1125 | allowedScriptDomains: [ 'authorized.com' ] 1126 | }), '' 1127 | ); 1128 | }); 1129 | it('should delete the script tag content', function() { 1130 | assert.equal(sanitizeHtml('', { 1131 | allowedTags: [ 'script' ], 1132 | allowVulnerableTags: true, 1133 | allowedAttributes: { 1134 | script: [ 'src' ] 1135 | }, 1136 | allowedScriptHostnames: [ 'www.authorized.com' ] 1137 | }), ''); 1138 | }); 1139 | it('should delete the script tag content from script tags with no src when allowedScriptHostnames is present', function() { 1140 | assert.equal(sanitizeHtml('', { 1141 | allowedTags: [ 'script' ], 1142 | allowVulnerableTags: true, 1143 | allowedAttributes: { 1144 | script: [ 'src' ] 1145 | }, 1146 | allowedScriptHostnames: [ 'www.authorized.com' ] 1147 | }), ''); 1148 | }); 1149 | it('should delete the script tag content from script tags with no src when allowedScriptDomains is present', function() { 1150 | assert.equal(sanitizeHtml('', { 1151 | allowedTags: [ 'script' ], 1152 | allowVulnerableTags: true, 1153 | allowedAttributes: { 1154 | script: [ 'src' ] 1155 | }, 1156 | allowedScriptDomains: [ 'www.authorized.com' ] 1157 | }), ''); 1158 | }); 1159 | it('Should allow hostnames in a script that are in allowedScriptHostnames', function() { 1160 | assert.equal(sanitizeHtml('', { 1161 | allowedTags: [ 'script' ], 1162 | allowVulnerableTags: true, 1163 | allowedAttributes: { 1164 | script: [ 'src' ] 1165 | }, 1166 | allowedScriptHostnames: [ 'www.authorized.com' ] 1167 | }), ''); 1168 | }); 1169 | it('Should allow hostnames in an iframe that are in allowedIframeHostnames', function() { 1170 | assert.equal( 1171 | sanitizeHtml('', { 1172 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1173 | allowedAttributes: { 1174 | iframe: [ 'src', 'href' ], 1175 | a: [ 'src', 'href' ], 1176 | img: [ 'src' ] 1177 | }, 1178 | allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] 1179 | }), '' 1180 | ); 1181 | }); 1182 | it('Should remove iframe src urls that are not included in allowedIframeHostnames', function() { 1183 | assert.equal( 1184 | sanitizeHtml('', { 1185 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1186 | allowedAttributes: { 1187 | iframe: [ 'src', 'href' ], 1188 | a: [ 'src', 'href' ], 1189 | img: [ 'src' ] 1190 | }, 1191 | allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] 1192 | }), '' 1193 | ); 1194 | }); 1195 | it('Should not allow iframe urls that do not have proper hostname', function() { 1196 | assert.equal( 1197 | sanitizeHtml('', { 1198 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1199 | allowedAttributes: { 1200 | iframe: [ 'src', 'href' ], 1201 | a: [ 'src', 'href' ], 1202 | img: [ 'src' ] 1203 | }, 1204 | allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] 1205 | }), '' 1206 | ); 1207 | }); 1208 | it('Should allow iframe through if no hostname option is set', function() { 1209 | assert.equal( 1210 | sanitizeHtml('', { 1211 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1212 | allowedAttributes: { 1213 | iframe: [ 'src', 'href' ], 1214 | a: [ 'src', 'href' ], 1215 | img: [ 'src' ] 1216 | } 1217 | }), '' 1218 | ); 1219 | }); 1220 | it('Should allow domains in an iframe that are in allowedIframeDomains', function() { 1221 | assert.equal( 1222 | sanitizeHtml('', { 1223 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1224 | allowedAttributes: { 1225 | iframe: [ 'src', 'href' ], 1226 | a: [ 'src', 'href' ], 1227 | img: [ 'src' ] 1228 | }, 1229 | allowedIframeDomains: [ 'zoom.us' ] 1230 | }), '' 1231 | ); 1232 | }); 1233 | it('Should allow second-level domains in an iframe that are in allowedIframeDomains', function() { 1234 | assert.equal( 1235 | sanitizeHtml('', { 1236 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1237 | allowedAttributes: { 1238 | iframe: [ 'src', 'href' ], 1239 | a: [ 'src', 'href' ], 1240 | img: [ 'src' ] 1241 | }, 1242 | allowedIframeDomains: [ 'zoom.us' ] 1243 | }), '' 1244 | ); 1245 | }); 1246 | it('Should remove iframe src urls that are not included in allowedIframeDomains', function() { 1247 | assert.equal( 1248 | sanitizeHtml('', { 1249 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1250 | allowedAttributes: { 1251 | iframe: [ 'src', 'href' ], 1252 | a: [ 'src', 'href' ], 1253 | img: [ 'src' ] 1254 | }, 1255 | allowedIframeDomains: [ 'vimeo.com' ] 1256 | }), '' 1257 | ); 1258 | }); 1259 | it('Should remove iframe src urls with host that ends as allowed domains but not preceded with a dot', function() { 1260 | assert.equal( 1261 | sanitizeHtml('', { 1262 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1263 | allowedAttributes: { 1264 | iframe: [ 'src', 'href' ], 1265 | a: [ 'src', 'href' ], 1266 | img: [ 'src' ] 1267 | }, 1268 | allowedIframeDomains: [ 'zoom.us' ] 1269 | }), '' 1270 | ); 1271 | }); 1272 | it('Should allow hostnames in an iframe that are in allowedIframeHostnames and are not in allowedIframeDomains', function() { 1273 | assert.equal( 1274 | sanitizeHtml('', { 1275 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1276 | allowedAttributes: { 1277 | iframe: [ 'src', 'href' ], 1278 | a: [ 'src', 'href' ], 1279 | img: [ 'src' ] 1280 | }, 1281 | allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ], 1282 | allowedIframeDomains: [ 'zoom.us' ] 1283 | }), '' 1284 | ); 1285 | }); 1286 | it('Should allow hostnames in an iframe that are not in allowedIframeHostnames ' + 1287 | 'and are allowlisted in allowedIframeDomains', function() { 1288 | assert.equal( 1289 | sanitizeHtml('', { 1290 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1291 | allowedAttributes: { 1292 | iframe: [ 'src', 'href' ], 1293 | a: [ 'src', 'href' ], 1294 | img: [ 'src' ] 1295 | }, 1296 | allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ], 1297 | allowedIframeDomains: [ 'zoom.us' ] 1298 | }), '' 1299 | ); 1300 | }); 1301 | it('Should allow relative URLs for iframes by default', function() { 1302 | assert.equal( 1303 | sanitizeHtml('', { 1304 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1305 | allowedAttributes: { 1306 | iframe: [ 'src', 'href' ], 1307 | a: [ 'src', 'href' ], 1308 | img: [ 'src' ] 1309 | } 1310 | }), '' 1311 | ); 1312 | }); 1313 | it('Should allow relative URLs for iframes', function() { 1314 | assert.equal( 1315 | sanitizeHtml('', { 1316 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1317 | allowedAttributes: { 1318 | iframe: [ 'src', 'href' ], 1319 | a: [ 'src', 'href' ], 1320 | img: [ 'src' ] 1321 | }, 1322 | allowIframeRelativeUrls: true 1323 | }), '' 1324 | ); 1325 | }); 1326 | it('Should remove relative URLs for iframes', function() { 1327 | assert.equal( 1328 | sanitizeHtml('', { 1329 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1330 | allowedAttributes: { 1331 | iframe: [ 'src', 'href' ], 1332 | a: [ 'src', 'href' ], 1333 | img: [ 'src' ] 1334 | }, 1335 | allowIframeRelativeUrls: false 1336 | }), '' 1337 | ); 1338 | }); 1339 | it('Should remove relative URLs for iframes when other hostnames are specified in allowedIframeHostnames', function() { 1340 | assert.equal( 1341 | sanitizeHtml('', { 1342 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1343 | allowedAttributes: { 1344 | iframe: [ 'src', 'href' ], 1345 | a: [ 'src', 'href' ], 1346 | img: [ 'src' ] 1347 | }, 1348 | allowedIframeHostnames: [ 'www.youtube.com' ] 1349 | }), '' 1350 | ); 1351 | }); 1352 | it('Should allow relative and allowlisted hostname URLs for iframes', function() { 1353 | assert.equal( 1354 | sanitizeHtml('', { 1355 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1356 | allowedAttributes: { 1357 | iframe: [ 'src', 'href' ], 1358 | a: [ 'src', 'href' ], 1359 | img: [ 'src' ] 1360 | }, 1361 | allowIframeRelativeUrls: true, 1362 | allowedIframeHostnames: [ 'www.youtube.com' ] 1363 | }), '' 1364 | ); 1365 | }); 1366 | it('Should allow protocol-relative URLs for the right domain for iframes', function() { 1367 | assert.equal( 1368 | sanitizeHtml('', { 1369 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1370 | allowedAttributes: { 1371 | iframe: [ 'src', 'href' ], 1372 | a: [ 'src', 'href' ], 1373 | img: [ 'src' ] 1374 | }, 1375 | allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] 1376 | }), '' 1377 | ); 1378 | }); 1379 | it('Should not allow protocol-relative iframe urls that do not have proper hostname', function() { 1380 | assert.equal( 1381 | sanitizeHtml('', { 1382 | allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], 1383 | allowedAttributes: { 1384 | iframe: [ 'src', 'href' ], 1385 | a: [ 'src', 'href' ], 1386 | img: [ 'src' ] 1387 | }, 1388 | allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] 1389 | }), '' 1390 | ); 1391 | }); 1392 | it('Should only allow attributes to have any combination of specific values', function() { 1393 | assert.equal( 1394 | sanitizeHtml('', { 1395 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'iframe' ]), 1396 | allowedAttributes: { 1397 | iframe: [ 1398 | { 1399 | name: 'sandbox', 1400 | multiple: true, 1401 | values: [ 'allow-popups', 'allow-same-origin', 'allow-scripts' ] 1402 | }, 1403 | 'allowfullscreen' 1404 | ] 1405 | } 1406 | }), ''); 1407 | }); 1408 | it('Should only allow attributes that match a specific value', function() { 1409 | assert.equal( 1410 | sanitizeHtml('', { 1411 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'iframe' ]), 1412 | allowedAttributes: { 1413 | iframe: [ 1414 | { 1415 | name: 'sandbox', 1416 | multiple: false, 1417 | values: [ 'allow-popups', 'allow-same-origin', 'allow-scripts' ] 1418 | } 1419 | ] 1420 | } 1421 | }), ''); 1422 | } 1423 | ); 1424 | it('Should not allow cite urls that do not have an allowed scheme', function() { 1425 | assert.equal( 1426 | sanitizeHtml('HTTPHTTPSMAILTOTELms-calculatorFTPDATALDAPACROBATVBSCRIPTFILERLOGINWEBCALJAVASCRIPTMMS', { 1427 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'q' ]), 1428 | allowedAttributes: { q: [ 'cite' ] }, 1429 | allowedSchemes: sanitizeHtml.defaults.allowedSchemes.concat([ 'tel' ]) 1430 | }), 'HTTPHTTPSMAILTOTELms-calculatorFTPDATALDAPACROBATVBSCRIPTFILERLOGINWEBCALJAVASCRIPTMMS'); 1431 | }); 1432 | it('Should encode &, <, > and where necessary, "', function() { 1433 | assert.equal(sanitizeHtml('"< & >" cool', { 1434 | allowedTags: [ 'span' ], 1435 | allowedAttributes: { 1436 | span: [ 'class' ] 1437 | } 1438 | }), '"< & >" cool'); 1439 | }); 1440 | it('Should not pass through &0; unescaped if decodeEntities is true (the default)', function() { 1441 | assert.equal(sanitizeHtml('', { allowedTags: [ 'img' ] }), ''); 1442 | }); 1443 | it('Should not double encode ampersands on HTML entities if decodeEntities is false (TODO more tests, this is too loose to rely upon)', function() { 1444 | const textIn = 'This & & that ® ± OK?'; 1445 | const expectedResult = 'This & & that ® ± OK?'; 1446 | const sanitizeHtmlOptions = { 1447 | parser: { 1448 | decodeEntities: false 1449 | } 1450 | }; 1451 | assert.equal(sanitizeHtml(textIn, sanitizeHtmlOptions), expectedResult); 1452 | }); 1453 | // TODO: make this test and similar tests for entities that are not 1454 | // strictly valid pass, at which point decodeEntities: false is safe 1455 | // to use. 1456 | // 1457 | // it('Should not pass through &0; (a bogus entity) unescaped if decodeEntities is false', function() { 1458 | // assert.equal(sanitizeHtml( 1459 | // '', { 1460 | // allowedTags: ['img'], 1461 | // parser: { 1462 | // decodeEntities: false 1463 | // } 1464 | // }), ''); 1465 | // }); 1466 | it('should escape markup not allowlisted and all its children in recursive mode', function() { 1467 | assert.equal( 1468 | sanitizeHtml('
Hello

World

', { disallowedTagsMode: 'recursiveEscape' }), 1469 | '
<wiggly>Hello<p>World</p></wiggly>
' 1470 | ); 1471 | }); 1472 | it('should escape markup not allowlisted and but not its children', function() { 1473 | assert.equal( 1474 | sanitizeHtml('
Hello

World

', { disallowedTagsMode: 'escape' }), 1475 | '
<wiggly>Hello

World

</wiggly>
' 1476 | ); 1477 | }); 1478 | it('should escape markup even when decodeEntities is false', function() { 1479 | assert.equal( 1480 | sanitizeHtml('Hello', { 1481 | disallowedTagsMode: 'escape', 1482 | parser: { decodeEntities: false } 1483 | }), 1484 | '<wiggly>Hello</wiggly>' 1485 | ); 1486 | }); 1487 | it('should escape markup not allowlisted even within allowed markup', function() { 1488 | assert.equal( 1489 | sanitizeHtml('
Hello

World

JS
', { disallowedTagsMode: 'recursiveEscape' }), 1490 | '
<wiggly>Hello<p>World</p><tiggly>JS</tiggly></wiggly>
' 1491 | ); 1492 | }); 1493 | it('should escape markup not allowlisted even within allowed markup, but not the allowed markup itself', function() { 1494 | assert.equal( 1495 | sanitizeHtml('
Hello

World

JS
', { disallowedTagsMode: 'escape' }), 1496 | '
<wiggly>Hello

World

<tiggly>JS</tiggly></wiggly>
' 1497 | ); 1498 | }); 1499 | it('allows markup of depth 6 with a nestingLimit of depth 6', function() { 1500 | assert.equal( 1501 | sanitizeHtml('
', { nestingLimit: 6 }), 1502 | '
' 1503 | ); 1504 | }); 1505 | it('disallows markup of depth 7 with a nestingLimit of depth 6', function() { 1506 | assert.equal( 1507 | // 7 divs here 1508 | sanitizeHtml('
nested text
', { nestingLimit: 6 }), 1509 | // only 6 kept 1510 | '
nested text
' 1511 | ); 1512 | }); 1513 | it('should not allow simple append attacks on iframe hostname validation', function() { 1514 | assert.equal( 1515 | sanitizeHtml('' 1523 | ); 1524 | }); 1525 | it('should not allow IDNA (Internationalized Domain Name) iframe validation bypass attacks', function() { 1526 | assert.equal( 1527 | sanitizeHtml('' 1535 | ); 1536 | }); 1537 | it('should parse path-rooted relative URLs sensibly', function() { 1538 | assert.equal( 1539 | sanitizeHtml(''), 1540 | '' 1541 | ); 1542 | }); 1543 | it('should parse bare relative URLs sensibly', function() { 1544 | assert.equal( 1545 | sanitizeHtml(''), 1546 | '' 1547 | ); 1548 | }); 1549 | it('should parse ../ relative URLs sensibly', function() { 1550 | assert.equal( 1551 | sanitizeHtml(''), 1552 | '' 1553 | ); 1554 | }); 1555 | it('should parse protocol relative URLs sensibly', function() { 1556 | assert.equal( 1557 | sanitizeHtml(''), 1558 | '' 1559 | ); 1560 | }); 1561 | it('should reject attempts to hack our use of a relative: protocol in our test base URL', function() { 1562 | assert.equal( 1563 | sanitizeHtml('' 1570 | ); 1571 | }); 1572 | it('Should prevent hostname bypass using protocol-relative src', function () { 1573 | assert.strictEqual( 1574 | sanitizeHtml('', { 1575 | allowedTags: [ 'iframe' ], 1576 | allowedAttributes: { 1577 | iframe: [ 'src' ] 1578 | }, 1579 | allowedIframeHostnames: [ 'www.youtube.com' ], 1580 | allowIframeRelativeUrls: true 1581 | }), '' 1582 | ); 1583 | assert.strictEqual( 1584 | sanitizeHtml('', { 1585 | allowedTags: [ 'iframe' ], 1586 | allowedAttributes: { 1587 | iframe: [ 'src' ] 1588 | }, 1589 | allowedIframeHostnames: [ 'www.youtube.com' ], 1590 | allowIframeRelativeUrls: true 1591 | }), '' 1592 | ); 1593 | const linefeed = decodeURIComponent('%0A'); 1594 | assert.strictEqual( 1595 | sanitizeHtml('', { 1596 | allowedTags: [ 'iframe' ], 1597 | allowedAttributes: { 1598 | iframe: [ 'src' ] 1599 | }, 1600 | allowedIframeHostnames: [ 'www.youtube.com' ], 1601 | allowIframeRelativeUrls: true 1602 | }), '' 1603 | ); 1604 | const creturn = decodeURIComponent('%0D'); 1605 | assert.strictEqual( 1606 | sanitizeHtml('', { 1607 | allowedTags: [ 'iframe' ], 1608 | allowedAttributes: { 1609 | iframe: [ 'src' ] 1610 | }, 1611 | allowedIframeHostnames: [ 'www.youtube.com' ], 1612 | allowIframeRelativeUrls: true 1613 | }), '' 1614 | ); 1615 | const tab = decodeURIComponent('%09'); 1616 | assert.strictEqual( 1617 | sanitizeHtml('', { 1618 | allowedTags: [ 'iframe' ], 1619 | allowedAttributes: { 1620 | iframe: [ 'src' ] 1621 | }, 1622 | allowedIframeHostnames: [ 'www.youtube.com' ], 1623 | allowIframeRelativeUrls: true 1624 | }), '' 1625 | ); 1626 | }); 1627 | it('Should allow protocol-relative URLs for script tag', function() { 1628 | assert.equal( 1629 | sanitizeHtml('', { 1630 | allowedTags: [ 'script' ], 1631 | allowedAttributes: { 1632 | script: [ 'src' ] 1633 | 1634 | } 1635 | }), '' 1636 | ); 1637 | }); 1638 | it('should not automatically attach close tag for escaped tags in escape mode', function() { 1639 | assert.equal(sanitizeHtml('Hello', { 1640 | disallowedTagsMode: 'escape' 1641 | }), '<test>Hello'); 1642 | }); 1643 | it('should not automatically attach close tag for escaped tags in recursiveEscape mode', function() { 1644 | assert.equal(sanitizeHtml('Hello', { 1645 | disallowedTagsMode: 'recursiveEscape' 1646 | }), '<test><test><test><test><test>Hello'); 1647 | }); 1648 | it('should discard unclosed disallowed tags', function() { 1649 | assert.equal(sanitizeHtml('Hello', { 1650 | disallowedTagsMode: 'discard' 1651 | }), 'Hello'); 1652 | }); 1653 | it('should remove non-boolean attributes that are empty', function() { 1654 | assert.equal(sanitizeHtml('hello', { 1655 | }), 'hello'); 1656 | }); 1657 | it('should not remove non-boolean attributes that are empty when disabled', function() { 1658 | assert.equal(sanitizeHtml('hello', { 1659 | nonBooleanAttributes: [] 1660 | }), 'hello'); 1661 | }); 1662 | it('should not remove boolean attributes that are empty', function() { 1663 | assert.equal(sanitizeHtml('', { 1664 | allowedTags: 'input', 1665 | allowedAttributes: { 1666 | input: [ 'checked', 'form', 'type' ] 1667 | } 1668 | }), ''); 1669 | }); 1670 | it('should remove boolean attributes that are empty when wildcard * passed in', function() { 1671 | assert.equal(sanitizeHtml('', { 1672 | allowedTags: 'input', 1673 | allowedAttributes: { 1674 | input: [ 'checked', 'form', 'type' ] 1675 | }, 1676 | nonBooleanAttributes: [ '*' ] 1677 | }), ''); 1678 | }); 1679 | it('should not remove empty alt attribute value by default', function() { 1680 | assert.equal(sanitizeHtml('', { 1681 | allowedAttributes: { img: [ 'alt', 'src' ] }, 1682 | allowedTags: [ 'img' ] 1683 | }), ''); 1684 | }); 1685 | it('should convert the implicit empty alt attribute value to be an empty string by default', function() { 1686 | assert.equal(sanitizeHtml('', { 1687 | allowedAttributes: { img: [ 'alt', 'src' ] }, 1688 | allowedTags: [ 'img' ] 1689 | }), ''); 1690 | }); 1691 | it('should not remove empty alt attribute value by default when an empty nonBooleanAttributes option passed in', function() { 1692 | assert.equal(sanitizeHtml('', { 1693 | allowedAttributes: { img: [ 'alt', 'src' ] }, 1694 | allowedTags: [ 'img' ], 1695 | nonBooleanAttributes: [] 1696 | }), ''); 1697 | }); 1698 | it('should not remove the empty attributes specified in allowedEmptyAttributes option', function() { 1699 | assert.equal(sanitizeHtml('', { 1700 | allowedAttributes: { img: [ 'alt', 'src' ] }, 1701 | allowedTags: [ 'img' ], 1702 | allowedEmptyAttributes: [ 'alt', 'src' ] 1703 | }), ''); 1704 | }); 1705 | it('should remove all the empty attributes when an empty allowedEmptyAttributes option passed in', function() { 1706 | assert.equal(sanitizeHtml('', { 1707 | allowedAttributes: { img: [ 'alt', 'src' ] }, 1708 | allowedTags: [ 'img' ], 1709 | allowedEmptyAttributes: [] 1710 | }), ''); 1711 | }); 1712 | it('should support SVG tags', () => { 1713 | assert.equal(sanitizeHtml('', { 1714 | allowedTags: [ 'svg', 'g', 'defs', 'linearGradient', 'stop', 'circle' ], 1715 | allowedAttributes: false, 1716 | parser: { 1717 | lowerCaseTags: false, 1718 | lowerCaseAttributeNames: false 1719 | } 1720 | }), ''); 1721 | }); 1722 | it('should not process style sourceMappingURL with postCSS', () => { 1723 | assert.equal(sanitizeHtml('', { 1724 | allowedAttributes: { 1725 | ...sanitizeHtml.defaults.allowedAttributes, 1726 | a: [ 'style' ] 1727 | } 1728 | }), ''); 1729 | }); 1730 | it('should completely remove disallowed tags with nested content', () => { 1731 | const inputHtml = '
Some Text

Allowed content

More allowed content Another Text
'; 1732 | const expectedOutput = '

Allowed content

More allowed content'; 1733 | const sanitizedHtml = sanitizeHtml(inputHtml, { 1734 | allowedTags: [ 'p', 'span' ], 1735 | disallowedTagsMode: 'completelyDiscard' 1736 | }); 1737 | assert.equal(sanitizedHtml, expectedOutput); 1738 | }); 1739 | it('should remove top level tag\'s content', () => { 1740 | const inputHtml = 'Some Text

paragraph content

content'; 1741 | const expectedOutput = '

paragraph content

'; 1742 | const sanitizedHtml = sanitizeHtml(inputHtml, { 1743 | allowedTags: [ 'p' ], 1744 | disallowedTagsMode: 'completelyDiscard' 1745 | }); 1746 | assert.equal(sanitizedHtml, expectedOutput); 1747 | }); 1748 | it('should completely remove disallowed tag with unclosed tag', () => { 1749 | const inputHtml = '
Some Text

paragraph content

some text'; 1750 | const expectedOutput = '

paragraph content

'; 1751 | const sanitizedHtml = sanitizeHtml(inputHtml, { 1752 | allowedTags: [ 'p' ], 1753 | disallowedTagsMode: 'completelyDiscard' 1754 | }); 1755 | 1756 | assert.equal(sanitizedHtml, expectedOutput); 1757 | }); 1758 | it('should transform text content of tags even if they originally had none', () => { 1759 | const inputHtml = '
'; 1760 | const expectedOutput = 'new content'; 1761 | const sanitizedHtml = sanitizeHtml(inputHtml, { 1762 | allowedTags: [], 1763 | transformTags: { 1764 | div: () => ({ text: 'new content' }) 1765 | } 1766 | }); 1767 | 1768 | assert.equal(sanitizedHtml, expectedOutput); 1769 | }); 1770 | it('should call onOpenTag and onCloseTag callbacks', () => { 1771 | const onOpenTag = sinon.spy(); 1772 | const onCloseTag = sinon.spy(); 1773 | const inputHtml = '
Some Text

paragraph content

some text

'; 1774 | sanitizeHtml(inputHtml, { 1775 | allowedTags: [ 'p' ], 1776 | onOpenTag, 1777 | onCloseTag 1778 | }); 1779 | assert.equal(onOpenTag.callCount, 3); 1780 | assert.equal(onOpenTag.getCall(0).calledWith('div', { id: 'one' }), true); 1781 | assert.equal(onOpenTag.getCall(1).calledWith('p', { id: 'two' }), true); 1782 | assert.equal(onOpenTag.getCall(2).calledWith('p', { id: 'three' }), true); 1783 | assert.equal(onCloseTag.callCount, 3); 1784 | assert.equal(onCloseTag.getCall(0).calledWith('p', false), true); 1785 | assert.equal(onCloseTag.getCall(1).calledWith('p', true), true); 1786 | assert.equal(onCloseTag.getCall(2).calledWith('div', false), true); 1787 | }); 1788 | it('should insert spaces between removed tags whose content we keep', () => { 1789 | const inputHtml = 'Text's here
it's here

it's there

and also here'; 1790 | const expectedOutput = 'Text\'s here it\'s here it\'s there and also here'; 1791 | const allowedTags = [ 'b' ]; 1792 | let addSpace = false; 1793 | const sanitizedHtml = sanitizeHtml( 1794 | inputHtml, 1795 | { 1796 | allowedTags, 1797 | onOpenTag: (tag) => { 1798 | addSpace = !allowedTags.includes(tag); 1799 | }, 1800 | onCloseTag: (tag) => { 1801 | addSpace = !allowedTags.includes(tag); 1802 | }, 1803 | textFilter: (text) => { 1804 | if (addSpace) { 1805 | addSpace = false; 1806 | return ' ' + text; 1807 | } 1808 | return text; 1809 | } 1810 | } 1811 | ); 1812 | assert.equal(sanitizedHtml, expectedOutput); 1813 | }); 1814 | it('should not preserve attributes on escaped disallowed tags when `preserveEscapedAttributes` is false', () => { 1815 | const inputHtml = '
Some Text
'; 1816 | const expectedOutput = '<div>Some Text</div>'; 1817 | const sanitizedHtml = sanitizeHtml(inputHtml, { 1818 | allowedTags: [], 1819 | disallowedTagsMode: 'escape', 1820 | preserveEscapedAttributes: false 1821 | }); 1822 | 1823 | assert.equal(sanitizedHtml, expectedOutput); 1824 | }); 1825 | it('should preserve attributes on escaped disallowed tags when `preserveEscapedAttributes` is true', () => { 1826 | const inputHtml = '
Some Text
'; 1827 | const expectedOutput = '<div class="foo">Some Text</div>'; 1828 | const sanitizedHtml = sanitizeHtml(inputHtml, { 1829 | allowedTags: [], 1830 | disallowedTagsMode: 'escape', 1831 | preserveEscapedAttributes: true 1832 | }); 1833 | 1834 | assert.equal(sanitizedHtml, expectedOutput); 1835 | }); 1836 | it('should ignore the `preserveEscapedAttributes` option when discarding diallowed tags (rather than escaping)', () => { 1837 | const inputHtml = '
Some Text
'; 1838 | const sanitizedHtmlPreservedAttrsTrue = sanitizeHtml(inputHtml, { 1839 | allowedTags: [], 1840 | disallowedTagsMode: 'discard', 1841 | preserveEscapedAttributes: true 1842 | }); 1843 | const sanitizedHtmlPreservedAttrsFalse = sanitizeHtml(inputHtml, { 1844 | allowedTags: [], 1845 | disallowedTagsMode: 'discard', 1846 | preserveEscapedAttributes: false 1847 | }); 1848 | 1849 | assert.equal(sanitizedHtmlPreservedAttrsTrue, sanitizedHtmlPreservedAttrsFalse); 1850 | }); 1851 | }); 1852 | --------------------------------------------------------------------------------