diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index e8212609..00000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,22 +0,0 @@ -version: 2 -jobs: - build: - docker: - - image: circleci/node:8-browsers - steps: - - checkout - - run: - name: update-npm - command: 'sudo npm install -g npm@5' - - restore_cache: - key: dependency-cache-{{ checksum "package.json" }} - - run: - name: install-npm-wee - command: npm install - - save_cache: - key: dependency-cache-{{ checksum "package.json" }} - paths: - - ./node_modules - - run: - name: test - command: npm test diff --git a/.eslintignore b/.eslintignore index 76add878..3c3629e6 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,2 +1 @@ node_modules -dist \ No newline at end of file diff --git a/.eslintrc b/.eslintrc index faf286d2..cd04aaec 100644 --- a/.eslintrc +++ b/.eslintrc @@ -1,6 +1,13 @@ { "extends": "apostrophe", "rules": { - "no-useless-escape": 1 + "no-console": [ + "error", + { + "allow": [ + "warn" + ] + } + ] } } diff --git a/.gitignore b/.gitignore index 42da1d19..d8dd031f 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,6 @@ package-lock.json npm-debug.log *.DS_Store node_modules -dist +.idea # We do not commit CSS, only LESS public/css/*.css diff --git a/CHANGELOG.md b/CHANGELOG.md index 13363156..e5785af0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,61 +1,248 @@ -## Changelog +# Changelog -1.27.4 (2020-08-26): +## 2.17.0 (2025-05-14) + +- Add `preserveEscapedAttributes`, allowing attributes on escaped disallowed tags to be retained. Thanks to [Ben Elliot](https://github.com/benelliott) for this new option. + +## 2.16.0 (2025-04-16) + +- Add `onOpenTag` and `onCloseTag` events to enable advanced filtering to hook into the parser. Thanks to [Rimvydas Naktinis](https://github.com/naktinis). + +## 2.15.0 (2025-03-19) + +- Allow keeping tag content when discarding with exclusive filter by returning `"excludeTag"`. Thanks to [rChaoz](https://github.com/rChaoz). + +## 2.14.0 (2024-12-18) + +- Fix adding text with `transformTags` in cases where it originally had no text child elements. Thanks to [f0x](https://cthu.lu). + +## 2.13.1 (2024-10-03) + +- Fix to allow regex in `allowedClasses` wildcard whitelist. Thanks to `anak-dev`. + +## 2.13.0 (2024-03-20) + +- Documentation update regarding minimum supported TypeScript version. + +- Added disallowedTagsMode: `completelyDiscard` option to remove the content also in HTML. Thanks to [Gauav Kumar](https://github.com/gkumar9891) for this addition. + +## 2.12.1 (2024-02-22) + +- 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. + +## 2.12.0 (2024-02-21) + +- 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. + +- Clarified the use of SVGs with a new test and changes to documentation. Thanks to [Gauav Kumar](https://github.com/gkumar9891) for the contribution. + +- Do not process source maps when processing style tags with PostCSS. + +## 2.11.0 (2023-06-21) + +- Fix to allow `false` in `allowedClasses` attributes. Thanks to [Kevin Jiang](https://github.com/KevinSJ) for this fix! +- Upgrade mocha version +- Apply small linter fixes in tests +- Add `.idea` temp files to `.gitignore` +- Thanks to [Vitalii Shpital](https://github.com/VitaliiShpital) for the updates! +- Show parseStyleAttributes warning in browser only. Thanks to [mog422](https://github.com/mog422) for this update! +- 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! + +## 2.10.0 (2023-02-17) + +- 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) +- 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. + +## 2.9.0 (2023-01-27) + +- 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). + +## 2.8.1 (2022-12-21) + +- If the argument is a number, convert it to a string, for backwards compatibility. Thanks to [Alexander Schranz](https://github.com/alexander-schranz). + +## 2.8.0 (2022-12-12) + +- Upgrades `htmlparser2` to new major version `^8.0.0`. Thanks to [Kedar Chandrayan](https://github.com/kedarchandrayan) for this contribution. + +## 2.7.3 (2022-10-24) + +- 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. + +## 2.7.2 (2022-09-15) + +- 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 +[Kedar Chandrayan](https://github.com/kedarchandrayan) for the report and the fix. + +## 2.7.1 (2022-07-20) + +- Protocol-relative URLs are properly supported for script tags. Thanks to [paweljq](https://github.com/paweljq). +- 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. + +## 2.7.0 (2022-02-04) + +- Allows a more sensible set of default attributes on `` tags. Thanks to [Zade Viggers](https://github.com/zadeviggers). + +## 2.6.1 (2021-12-08) + +- Fixes style filtering to retain `!important` when used. +- 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). + +## 2.6.0 (2021-11-23) + +- Support for regular expressions in the `allowedClasses` option. Thanks to [Alex Rantos](https://github.com/alex-rantos). + +## 2.5.3 (2021-11-02): + +- Fixed bug introduced by klona 2.0.5, by removing klona entirely. + +## 2.5.2 (2021-10-13): + +- 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. +- Documented that all text content is escaped. Thanks to Siddharth Singh. + +## 2.5.1 (2021-09-14): +- 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. + +## 2.5.0 (2021-09-08): + +- New `allowedScriptHostnames` option, it enables you to specify which hostnames are allowed in a script tag. +- 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. +- Updates whitelist to allowlist. + +## 2.4.0 (2021-05-19): +- Added support for class names with wildcards in `allowedClasses`. Thanks to [zhangbenber](https://github.com/zhangbenber) for the contribution. + +## 2.3.3 (2021-03-19): +- 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. +- Added a security note about the known risks associated with using the `parser` option, especially `decodeEntities: false`. See the documentation. + +## 2.3.2 (2021-01-26): + +- 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. +- Updates README `yarn add` syntax. Thanks to [Tagir Khadshiev](https://github.com/Aspedm) for the contribution. + +## 2.3.1 (2021-01-22): +- 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. + +## 2.3.0 (2020-12-16): +- Upgrades `htmlparser2` to new major version `^6.0.0`. Thanks to [Bogdan Chadkin](https://github.com/TrySound) for the contribution. + +## 2.2.0 (2020-12-02): +- Adds a note to the README about Typescript support (or the lack-thereof). +- Adds `tel` to the default `allowedSchemes`. Thanks to [Arne Herbots](https://github.com/aHerbots) for this contribution. + +## 2.1.2 (2020-11-04): +- Fixes typos and inconsistencies in the README. Thanks to [Eric Lefevre-Ardant](https://github.com/elefevre) for this contribution. + +## 2.1.1 (2020-10-21): +- Fixes a bug when using `allowedClasses` with an `'*'` wildcard selector. Thanks to [Clemens Damke](https://github.com/Cortys) for this contribution. +- Updates mocha to 7.x to resolve security warnings. + +## 2.1.0 (2020-10-07): +- `sup` added to the default allowed tags list. Thanks to [Julian Lam](https://github.com/julianlam) for the contribution. +- Updates default `allowedTags` README documentation. Thanks to [Marco Arduini](https://github.com/nerfologist) for the contribution. + +## 2.0.0 (2020-09-23): +- `nestingLimit` option added. +- Updates ESLint config package and fixes warnings. +- Upgrade `is-plain-object` package with named export. Thanks to [Bogdan Chadkin](https://github.com/TrySound) for the contribution. +- Upgrade `postcss` package and drop Node 11 and Node 13 support (enforced by postcss). + +### Backwards compatibility breaks: +- 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. +- On the server side, Node.js 10 or higher is required. +- 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. + +## 2.0.0-rc.2 (2020-09-09): +- Always use existing `has` function rather than duplicating it. + +## 2.0.0-rc.1 (2020-08-26): +- Upgrade `klona` package. Thanks to [Bogdan Chadkin](https://github.com/TrySound) for the contribution. + +## 2.0.0-beta.2: +- Add `files` to `package.json` to prevent publishing unnecessary files to npm #392. Thanks to [styfle](https://github.com/styfle) for the contribution. +- Removes `iframe` and `nl` from default allowed tags. Adds most innocuous tags to the default `allowedTags` array. +- Fixes a bug when using `transformTags` with out `textFilter`. Thanks to [Andrzej Porebski](https://github.com/andpor) for the help with a failing test. + +## 2.0.0-beta: +- 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. +- Replaces lodash with utility packages: klona, is-plain-object, deepmerge, escape-string-regexp. +- 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 +value into a text node could be vulnerable to code execution. +- Updates code to use modern features including `const`/`let` variable assignment. +- ESLint clean up. +- Updates `is-plain-object` to the 4.x major version. +- Updates `srcset` to the 3.x major version. + +Thanks to [Bogdan Chadkin](https://github.com/TrySound) for contributions to this major version update. + +## 1.27.5 (2020-09-23): +- Updates README to include ES modules syntax. + +## 1.27.4 (2020-08-26): - Fixes an IE11 regression from using `Array.prototype.includes`, replacing it with `Array.prototype.indexOf`. -1.27.3 (2020-08-12): +## 1.27.3 (2020-08-12): - Fixes a bug when using `transformTags` with out `textFilter`. Thanks to [Andrzej Porebski](https://github.com/andpor) for the help with a failing test. -1.27.2 (2020-07-29): +## 1.27.2 (2020-07-29): - Fixes CHANGELOG links. Thanks to [Alex Mayer](https://github.com/amayer5125) for the contribution. - Replaces `srcset` with `parse-srcset`. Thanks to [Massimiliano Mirra](https://github.com/bard) for the contribution. -1.27.1 (2020-07-15): +## 1.27.1 (2020-07-15): - Removes the unused chalk dependency. - Adds configuration for a Github stale bot. - Replace `xtend` package with native `Object.assign`. -1.27.0: +## 1.27.0: - 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. -1.26.0: +## 1.26.0: - 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. -1.25.0: +## 1.25.0: - Adds `enforceHtmlBoundary` option to process code bounded by the `html` tag, discarding any code outside of those tags. - 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. - 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. -1.24.0: +## 1.24.0: - 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. - Adds `abbr` to the default `allowedTags` for better accessibility support. Thanks to [Will Farrell](https://github.com/willfarrell) for the contribution. - 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. -1.23.0: +## 1.23.0: - Adds eslint configuration and adds eslint to test script. - 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. - Adds the `tagName` (HTML element name) as a second parameter passed to `textFilter`. Thanks to [Slava](https://github.com/slavaGanzin) for the contribution. -1.22.1: Increases the patch version of `lodash.mergewith` to enforce an audit fix. +## 1.22.1: +ncreases the patch version of `lodash.mergewith` to enforce an audit fix. -1.22.0: 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. +## 1.22.0: +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. -1.21.1: fixed issue with bad `main` setting in package.json that broke 1.21.0. +## 1.21.1: +fixed issue with bad `main` setting in package.json that broke 1.21.0. -1.21.0: 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. +## 1.21.0: +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. -1.20.1: Fix failing tests, add CircleCI config +## 1.20.1: +Fix failing tests, add CircleCI config -1.20.0: 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. +## 1.20.0: +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. -1.19.3: 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). +## 1.19.3: +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). -1.19.2: +## 1.19.2: * Switched out the heavy `postcss` dependency for the lightweight `css-tree` module. No API changes. Thanks to Justin Braithwaite. * Various doc updates. Thanks to Pulkit Aggarwal and Cody Robertson. -1.19.1: +## 1.19.1: * `"` characters are now entity-escaped only when they appear in attribute values, reducing the verbosity of the resulting markup. @@ -67,85 +254,105 @@ When `decodeEntities: true` is in effect (the default), this is not a problem be 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. -1.19.0: +## 1.19.0: * 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. -1.18.5: +## 1.18.5: * Stop double encoding ampersands on HTML entities. Thanks to Will Gibson. -1.18.4: +## 1.18.4: * Removed incorrect `browser` key, restoring frontend build. Thanks to Felix Becker. -1.18.3: +## 1.18.3: * `iframe` is an allowed tag by default, to better facilitate typical use cases and the use of the `allowedIframeHostnames` option. * Documentation improvements. * More browser packaging improvements. * Protocol-relative URLs are properly supported for iframe tags. -1.18.2: +## 1.18.2: * Travis tests passing. * Fixed another case issue — and instituted Travis CI testing so this doesn't happen again. Sorry for the hassle. -1.18.1: +## 1.18.1: * A file was required with incorrect case, breaking the library on case sensitive filesystems such as Linux. Fixed. -1.18.0: +## 1.18.0: * 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. * 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. * Fixed a bug in the npm test procedure. -1.17.0: 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. +## 1.17.0: +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. -1.16.3: don't throw away the browserified versions before publishing them. `prepare` is not a good place to `make clean`, it runs after `prepublish`. +## 1.16.3: +Don't throw away the browserified versions before publishing them. `prepare` is not a good place to `make clean`, it runs after `prepublish`. -1.16.2: `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. +## 1.16.2: +`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. 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. -1.16.1: changelog formatting only. +## 1.16.1: +changelog formatting only. -1.16.0: support for sanitizing inline CSS styles, by specifying the allowed attributes and a regular expression for each. Thanks to Cameron Will and Michael Loschiavo. +## 1.16.0: +support for sanitizing inline CSS styles, by specifying the allowed attributes and a regular expression for each. Thanks to Cameron Will and Michael Loschiavo. -1.15.0: 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. +## 1.15.0: +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. -1.14.3: inadvertent removal of lodash regexp quote dependency in 1.14.2 has been corrected. +## 1.14.3: +inadvertent removal of lodash regexp quote dependency in 1.14.2 has been corrected. -1.14.2: 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. +## 1.14.2: +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. -1.14.1: documented `allowProtocolRelative` option. No code changes from 1.14.0, released a few moments ago. +## 1.14.1: +documented `allowProtocolRelative` option. No code changes from 1.14.0, released a few moments ago. -1.14.0: 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. +## 1.14.0: +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. -1.13.0: `transformTags` can now add text to an element that initially had none. Thanks to Dushyant Singh. +## 1.13.0: +`transformTags` can now add text to an element that initially had none. Thanks to Dushyant Singh. -1.12.0: option to build for browser-side use. Thanks to Michael Blum. +## 1.12.0: +option to build for browser-side use. Thanks to Michael Blum. -1.11.4: fixed crash when `__proto__` is a tag name. Now using a safe check for the existence of properties in all cases. Thanks to Andrew Krasichkov. +## 1.11.4: +fixed crash when `__proto__` is a tag name. Now using a safe check for the existence of properties in all cases. Thanks to Andrew Krasichkov. 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. -1.11.3: bumped `htmlparser2` version to address crashing bug in older version. Thanks to e-jigsaw. +## 1.11.3: +bumped `htmlparser2` version to address crashing bug in older version. Thanks to e-jigsaw. -1.11.2: fixed README typo that interfered with readability due to markdown issues. No code changes. Thanks to Mikael Korpela. Also improved code block highlighting in README. Thanks to Alex Siman. +## 1.11.2: +fixed README typo that interfered with readability due to markdown issues. No code changes. Thanks to Mikael Korpela. Also improved code block highlighting in README. Thanks to Alex Siman. -1.11.1: fixed a regression introduced in 1.11.0 which caused the closing tag of the parent of a `textarea` tag to be lost. Thanks to Stefano Sala, who contributed the missing test. +## 1.11.1: +fixed a regression introduced in 1.11.0 which caused the closing tag of the parent of a `textarea` tag to be lost. Thanks to Stefano Sala, who contributed the missing test. -1.11.0: added the `nonTextTags` option, with tests. +## 1.11.0: +added the `nonTextTags` option, with tests. -1.10.1: documentation cleanup. No code changes. Thanks to Rex Schrader. +## 1.10.1: +documentation cleanup. No code changes. Thanks to Rex Schrader. -1.10.0: `allowedAttributes` now allows you to allow attributes for all tags by specifying `*` as the tag name. Thanks to Zdravko Georgiev. +## 1.10.0: +`allowedAttributes` now allows you to allow attributes for all tags by specifying `*` as the tag name. Thanks to Zdravko Georgiev. -1.9.0: `parser` option allows options to be passed directly to `htmlparser`. Thanks to Danny Scott. +## 1.9.0: +`parser` option allows options to be passed directly to `htmlparser`. Thanks to Danny Scott. -1.8.0: +## 1.8.0: * `transformTags` now accepts the `*` wildcard to transform all tags. Thanks to Jamy Timmermans. @@ -153,70 +360,99 @@ Fixed XSS attack vector via `textarea` tags (when explicitly allowed). Decided t * 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. -1.7.2: removed `array-includes` dependency in favor of `indexOf`, which is a little more verbose but slightly faster and doesn't require a shim. Thanks again to Joseph Dykstra. - -1.7.1: removed lodash dependency, adding lighter dependencies and polyfills in its place. Thanks to Joseph Dykstra. +## 1.7.2: +removed `array-includes` dependency in favor of `indexOf`, which is a little more verbose but slightly faster and doesn't require a shim. Thanks again to Joseph Dykstra. -1.7.0: introduced `allowedSchemesByTag` option. Thanks to Cameron Will. +## 1.7.1: +removed lodash dependency, adding lighter dependencies and polyfills in its place. Thanks to Joseph Dykstra. -1.6.1: the string `'undefined'` (as opposed to `undefined`) is perfectly valid text and shouldn't be expressly converted to the empty string. +## 1.7.0: +introduced `allowedSchemesByTag` option. Thanks to Cameron Will. -1.6.0: added `textFilter` option. Thanks to Csaba Palfi. +## 1.6.1: +the string `'undefined'` (as opposed to `undefined`) is perfectly valid text and shouldn't be expressly converted to the empty string. -1.5.3: do not escape special characters inside a script or style element, if they are allowed. This is consistent with the way browsers parse them; nothing closes them except the appropriate closing tag for the entire element. Of course, this only comes into play if you actually choose to allow those tags. Thanks to aletorrado. +## 1.6.0: +added `textFilter` option. Thanks to Csaba Palfi. -1.5.2: guard checks for allowed attributes correctly to avoid an undefined property error. Thanks to Zeke. +## 1.5.3: +do not escape special characters inside a script or style element, if they are allowed. This is consistent with the way browsers parse them; nothing closes them except the appropriate closing tag for the entire element. Of course, this only comes into play if you actually choose to allow those tags. Thanks to aletorrado. -1.5.1: updated to htmlparser2 1.8.x. Started using the `decodeEntities` option, which allows us to pass our filter evasion tests without the need to recursively invoke the filter. +## 1.5.2: +guard checks for allowed attributes correctly to avoid an undefined property error. Thanks to Zeke. -1.5.0: support for `*` wildcards in allowedAttributes. With tests. Thanks to Calvin Montgomery. +## 1.5.1: +updated to htmlparser2 1.8.x. Started using the `decodeEntities` option, which allows us to pass our filter evasion tests without the need to recursively invoke the filter. -1.4.3: invokes itself recursively until the markup stops changing to guard against [this issue](https://github.com/fb55/htmlparser2/issues/105). Bump to htmlparser2 version 3.7.x. +## 1.5.0: +support for `*` wildcards in allowedAttributes. With tests. Thanks to Calvin Montgomery. -1.4.1, 1.4.2: more tests. +## 1.4.3: +invokes itself recursively until the markup stops changing to guard against [this issue](https://github.com/fb55/htmlparser2/issues/105). Bump to htmlparser2 version 3.7.x. -1.4.0: ability to allow all attributes or tags through by setting `allowedAttributes` and/or `allowedTags` to false. Thanks to Anand Thakker. +## 1.4.1, 1.4.2: +more tests. -1.3.0: `attribs` now available on frames passed to exclusive filter. +## 1.4.0: +ability to allow all attributes or tags through by setting `allowedAttributes` and/or `allowedTags` to false. Thanks to Anand Thakker. -1.2.3: fixed another possible XSS attack vector; no definitive exploit was found but it looks possible. [See this issue.](https://github.com/punkave/sanitize-html/pull/20) Thanks to Jim O'Brien. +## 1.3.0: +`attribs` now available on frames passed to exclusive filter. -1.2.2: reject `javascript:` URLs when disguised with an internal comment. This is probably not respected by browsers anyway except when inside an XML data island element, which you almost certainly are not allowing in your `allowedTags`, but we aim to be thorough. Thanks to Jim O'Brien. +## 1.2.3: +fixed another possible XSS attack vector; no definitive exploit was found but it looks possible. [See this issue.](https://github.com/punkave/sanitize-html/pull/20) Thanks to Jim O'Brien. -1.2.1: fixed crashing bug when presented with bad markup. The bug was in the `exclusiveFilter` mechanism. Unit test added. Thanks to Ilya Kantor for catching it. +## 1.2.2: +reject `javascript:` URLs when disguised with an internal comment. This is probably not respected by browsers anyway except when inside an XML data island element, which you almost certainly are not allowing in your `allowedTags`, but we aim to be thorough. Thanks to Jim O'Brien. -1.2.0: +## 1.2.1: +fixed crashing bug when presented with bad markup. The bug was in the `exclusiveFilter` mechanism. Unit test added. Thanks to Ilya Kantor for catching it. +## 1.2.0: * The `allowedClasses` option now allows you to permit CSS classes in a fine-grained way. * 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. -1.1.7: use `he` for entity decoding, because it is more actively maintained. +## 1.1.7: +use `he` for entity decoding, because it is more actively maintained. -1.1.6: `allowedSchemes` option for those who want to permit `data` URLs and such. +## 1.1.6: +`allowedSchemes` option for those who want to permit `data` URLs and such. -1.1.5: just a packaging thing. +## 1.1.5: +just a packaging thing. -1.1.4: custom exclusion filter. +## 1.1.4: +custom exclusion filter. -1.1.3: moved to lodash. 1.1.2 pointed to the wrong version of lodash. +## 1.1.3: +moved to lodash. 1.1.2 pointed to the wrong version of lodash. -1.1.0: the `transformTags` option was added. Thanks to [kl3ryk](https://github.com/kl3ryk). +## 1.1.0: +the `transformTags` option was added. Thanks to [kl3ryk](https://github.com/kl3ryk). -1.0.3: fixed several more javascript URL attack vectors after [studying the XSS filter evasion cheat sheet](https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet) to better understand my enemy. Whitespace characters (codes from 0 to 32), which browsers ignore in URLs in certain cases allowing the "javascript" scheme to be snuck in, are now stripped out when checking for naughty URLs. Thanks again to [pinpickle](https://github.com/pinpickle). +## 1.0.3: +fixed several more javascript URL attack vectors after [studying the XSS filter evasion cheat sheet](https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet) to better understand my enemy. Whitespace characters (codes from 0 to 32), which browsers ignore in URLs in certain cases allowing the "javascript" scheme to be snuck in, are now stripped out when checking for naughty URLs. Thanks again to [pinpickle](https://github.com/pinpickle). -1.0.2: fixed a javascript URL attack vector. naughtyHref must entity-decode URLs and also check for mixed-case scheme names. Thanks to [pinpickle](https://github.com/pinpickle). +## 1.0.2: +fixed a javascript URL attack vector. naughtyHref must entity-decode URLs and also check for mixed-case scheme names. Thanks to [pinpickle](https://github.com/pinpickle). -1.0.1: Doc tweaks. +## 1.0.1: +Doc tweaks. -1.0.0: If the style tag is disallowed, then its content should be dumped, so that it doesn't appear as text. We were already doing this for script tags, however in both cases the content is now preserved if the tag is explicitly allowed. +## 1.0.0: +If the style tag is disallowed, then its content should be dumped, so that it doesn't appear as text. We were already doing this for script tags, however in both cases the content is now preserved if the tag is explicitly allowed. We're rocking our tests and have been working great in production for months, so: declared 1.0.0 stable. -0.1.3: do not double-escape entities in attributes or text. Turns out the "text" provided by htmlparser2 is already escaped. +## 0.1.3: +do not double-escape entities in attributes or text. Turns out the "text" provided by htmlparser2 is already escaped. -0.1.2: packaging error meant it wouldn't install properly. +## 0.1.2: +packaging error meant it wouldn't install properly. -0.1.1: discard the text of script tags. +## 0.1.1: +discard the text of script tags. -0.1.0: initial release. +## 0.1.0: +initial release. diff --git a/README.md b/README.md index f811acd1..6600332a 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,15 @@ # sanitize-html -[![CircleCI](https://circleci.com/gh/apostrophecms/sanitize-html/tree/main.svg?style=svg)](https://circleci.com/gh/apostrophecms/sanitize-html/tree/main) - -`sanitize-html` provides a simple HTML sanitizer with a clear API. +sanitize-html provides a simple HTML sanitizer with a clear API. -`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. +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. -`sanitize-html` allows you to specify the tags you want to permit, and the permitted attributes for each of those tags. +sanitize-html allows you to specify the tags you want to permit, and the permitted +attributes for each of those tags. If an attribute is a known non-boolean value, +and it is empty, it will be removed. For example `checked` can be empty, but `href` +cannot. If a tag is not permitted, the contents of the tag are not discarded. There are some exceptions to this, discussed below in the "Discarding the entire contents @@ -21,10 +22,27 @@ The syntax of poorly closed `p` and `img` elements is cleaned up. Allowing particular urls as a `src` to an iframe tag by filtering hostnames is also supported. HTML comments are not preserved. +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 (`"` --> `"`). ## Requirements -`sanitize-html` is intended for use with Node. That's pretty much it. All of its npm dependencies are pure JavaScript. `sanitize-html` is built on the excellent `htmlparser2` module. +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. + +### Regarding TypeScript + +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. +```bash +npm install -D @types/sanitize-html +``` +If `esModuleInterop=true` is not set in your `tsconfig.json` file, you have to import it with: + +```javascript +import * as sanitizeHtml from 'sanitize-html'; +``` + +When using TypeScript, there is a minimum supported version of >=4.5 because of a dependency on the `htmlparser2` types. + +Any questions or problems while using `@types/sanitize-html` should be directed to its maintainers as directed by that project's contribution guidelines. ## How to use @@ -34,29 +52,24 @@ HTML comments are not preserved. 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! -* Clone repository -* Run npm install and build / minify: +* Install the package: ```bash -npm install -npm run minify +npm install sanitize-html +``` +or +``` +yarn add sanitize-html ``` -You'll find the minified and unminified versions of sanitize-html (with all its dependencies included) in the dist/ directory. - -Use it in the browser: +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. -```html - - - - - - -``` +Once built and linked in the browser with other project Javascript, it can be used to sanitize HTML strings in front end code: ```javascript -var html = "hello world"; +import sanitizeHtml from 'sanitize-html'; + +const html = "hello world"; console.log(sanitizeHtml(html)); console.log(sanitizeHtml("")); console.log(sanitizeHtml("console.log('hello world')")); @@ -71,20 +84,28 @@ Install module from console: npm install sanitize-html ``` -Use it in your node app: +Import the module: ```js -var sanitizeHtml = require('sanitize-html'); +// In ES modules +import sanitizeHtml from 'sanitize-html'; -var dirty = 'some really tacky HTML'; -var clean = sanitizeHtml(dirty); +// Or in CommonJS +const sanitizeHtml = require('sanitize-html'); ``` -That will allow our default list of allowed tags and attributes through. It's a nice set, but probably not quite what you want. So: +Use it in your JavaScript app: + +```js +const dirty = 'some really tacky HTML'; +const clean = sanitizeHtml(dirty); +``` + +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: ```js // Allow only a super restricted set of tags and attributes -clean = sanitizeHtml(dirty, { +const clean = sanitizeHtml(dirty, { allowedTags: [ 'b', 'i', 'em', 'strong', 'a' ], allowedAttributes: { 'a': [ 'href' ] @@ -95,43 +116,95 @@ clean = sanitizeHtml(dirty, { Boom! -#### "I like your set but I want to add one more tag. Is there a convenient way?" Sure: - -```js -clean = sanitizeHtml(dirty, { - allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]) -}); -``` - -If you do not specify `allowedTags` or `allowedAttributes` our default list is applied. So if you really want an empty list, specify one. - -#### "What are the default options?" - -```js -allowedTags: [ 'h3', 'h4', 'h5', 'h6', 'blockquote', 'p', 'a', 'ul', 'ol', - 'nl', 'li', 'b', 'i', 'strong', 'em', 'strike', 'abbr', 'code', 'hr', 'br', 'div', - 'table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td', 'pre', 'iframe' ], +### Default options + +```js +allowedTags: [ + "address", "article", "aside", "footer", "header", "h1", "h2", "h3", "h4", + "h5", "h6", "hgroup", "main", "nav", "section", "blockquote", "dd", "div", + "dl", "dt", "figcaption", "figure", "hr", "li", "main", "ol", "p", "pre", + "ul", "a", "abbr", "b", "bdi", "bdo", "br", "cite", "code", "data", "dfn", + "em", "i", "kbd", "mark", "q", "rb", "rp", "rt", "rtc", "ruby", "s", "samp", + "small", "span", "strong", "sub", "sup", "time", "u", "var", "wbr", "caption", + "col", "colgroup", "table", "tbody", "td", "tfoot", "th", "thead", "tr" +], +nonBooleanAttributes: [ + 'abbr', 'accept', 'accept-charset', 'accesskey', 'action', + 'allow', 'alt', 'as', 'autocapitalize', 'autocomplete', + 'blocking', 'charset', 'cite', 'class', 'color', 'cols', + 'colspan', 'content', 'contenteditable', 'coords', 'crossorigin', + 'data', 'datetime', 'decoding', 'dir', 'dirname', 'download', + 'draggable', 'enctype', 'enterkeyhint', 'fetchpriority', 'for', + 'form', 'formaction', 'formenctype', 'formmethod', 'formtarget', + 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', + 'http-equiv', 'id', 'imagesizes', 'imagesrcset', 'inputmode', + 'integrity', 'is', 'itemid', 'itemprop', 'itemref', 'itemtype', + 'kind', 'label', 'lang', 'list', 'loading', 'low', 'max', + 'maxlength', 'media', 'method', 'min', 'minlength', 'name', + 'nonce', 'optimum', 'pattern', 'ping', 'placeholder', 'popover', + 'popovertarget', 'popovertargetaction', 'poster', 'preload', + 'referrerpolicy', 'rel', 'rows', 'rowspan', 'sandbox', 'scope', + 'shape', 'size', 'sizes', 'slot', 'span', 'spellcheck', 'src', + 'srcdoc', 'srclang', 'srcset', 'start', 'step', 'style', + 'tabindex', 'target', 'title', 'translate', 'type', 'usemap', + 'value', 'width', 'wrap', + // Event handlers + 'onauxclick', 'onafterprint', 'onbeforematch', 'onbeforeprint', + 'onbeforeunload', 'onbeforetoggle', 'onblur', 'oncancel', + 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', + 'oncontextlost', 'oncontextmenu', 'oncontextrestored', 'oncopy', + 'oncuechange', 'oncut', 'ondblclick', 'ondrag', 'ondragend', + 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', + 'ondrop', 'ondurationchange', 'onemptied', 'onended', + 'onerror', 'onfocus', 'onformdata', 'onhashchange', 'oninput', + 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', + 'onlanguagechange', 'onload', 'onloadeddata', 'onloadedmetadata', + 'onloadstart', 'onmessage', 'onmessageerror', 'onmousedown', + 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', + 'onmouseover', 'onmouseup', 'onoffline', 'ononline', 'onpagehide', + 'onpageshow', 'onpaste', 'onpause', 'onplay', 'onplaying', + 'onpopstate', 'onprogress', 'onratechange', 'onreset', 'onresize', + 'onrejectionhandled', 'onscroll', 'onscrollend', + 'onsecuritypolicyviolation', 'onseeked', 'onseeking', 'onselect', + 'onslotchange', 'onstalled', 'onstorage', 'onsubmit', 'onsuspend', + 'ontimeupdate', 'ontoggle', 'onunhandledrejection', 'onunload', + 'onvolumechange', 'onwaiting', 'onwheel' +], disallowedTagsMode: 'discard', allowedAttributes: { a: [ 'href', 'name', 'target' ], - // We don't currently allow img itself by default, but this - // would make sense if we did. You could add srcset here, - // and if you do the URL is checked for safety - img: [ 'src' ] + // We don't currently allow img itself by default, but + // these attributes would make sense if we did. + img: [ 'src', 'srcset', 'alt', 'title', 'width', 'height', 'loading' ] }, // Lots of these won't come up by default because we don't allow them selfClosing: [ 'img', 'br', 'hr', 'area', 'base', 'basefont', 'input', 'link', 'meta' ], // URL schemes we permit -allowedSchemes: [ 'http', 'https', 'ftp', 'mailto' ], +allowedSchemes: [ 'http', 'https', 'ftp', 'mailto', 'tel' ], allowedSchemesByTag: {}, allowedSchemesAppliedToAttributes: [ 'href', 'src', 'cite' ], allowProtocolRelative: true, -enforceHtmlBoundary: false +enforceHtmlBoundary: false, +parseStyleAttributes: true +``` + +### Common use cases + +#### "I like your set but I want to add one more tag. Is there a convenient way?" + +Sure: + +```js +const clean = sanitizeHtml(dirty, { + allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'img' ]) +}); ``` +If you do not specify `allowedTags` or `allowedAttributes`, our default list is applied. So if you really want an empty list, specify one. + #### "What if I want to allow all tags or all attributes?" -Simple! instead of leaving `allowedTags` or `allowedAttributes` out of the options, set either +Simple! Instead of leaving `allowedTags` or `allowedAttributes` out of the options, set either one or both to `false`: ```js @@ -139,6 +212,26 @@ allowedTags: false, allowedAttributes: false ``` +#### "What if I want to allow empty attributes, even for cases like href that normally don't make sense?" + +Very simple! Set `nonBooleanAttributes` to `[]`. + +```js +nonBooleanAttributes: [] +``` + +#### "What if I want to remove all empty attributes, including valid ones?" + +Also very simple! Set `nonBooleanAttributes` to `['*']`. + +**Note**: This will break common valid cases like `checked` and `selected`, so this is +unlikely to be what you want. For most ordinary HTML use, it is best to avoid making +this change. + +```js +nonBooleanAttributes: ['*'] +``` + #### "What if I don't want to allow *any* tags?" Also simple! Set `allowedTags` to `[]` and `allowedAttributes` to `{}`. @@ -148,15 +241,17 @@ allowedTags: [], allowedAttributes: {} ``` -### "What if I want disallowed tags to be escaped rather than discarded?" +#### "What if I want disallowed tags to be escaped rather than discarded?" -If you set `disallowedTagsMode` to `discard` (the default), disallowed tags are discarded. Any text content or subtags is still included, depending on whether the individual subtags are allowed. +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. -If you set `disallowedTagsMode` to `escape`, the disallowed tags are escaped rather than discarded. Any text or subtags is handled normally. +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. + +If you set `disallowedTagsMode` to `escape`, the disallowed tags are escaped rather than discarded. Any text or subtags are handled normally. 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. -### "What if I want to allow only specific values on some attributes?" +#### "What if I want to allow only specific values on some attributes?" 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"`: @@ -174,6 +269,21 @@ allowedAttributes: { 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. +#### "What if I want to maintain the original case for SVG elements and attributes?" + +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. + +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. + +```js +allowedTags: [ 'svg', 'g', 'defs', 'linearGradient', 'stop', 'circle' ], +allowedAttributes: false, +parser: { + lowerCaseTags: false, + lowerCaseAttributeNames: false +} +``` + ### Wildcards for attributes You can use the `*` wildcard to allow all attributes with a certain prefix: @@ -191,9 +301,80 @@ allowedAttributes: { '*': [ 'href', 'align', 'alt', 'center', 'bgcolor' ] } ``` + +## Additional options + +### Allowed CSS Classes + +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. + +This implies that the `class` attribute is allowed on that element. + +```javascript +// Allow only a restricted set of CSS classes and only on the p tag +const clean = sanitizeHtml(dirty, { + allowedTags: [ 'p', 'em', 'strong' ], + allowedClasses: { + 'p': [ 'fancy', 'simple' ] + } +}); +``` + +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: + +```js +allowedClasses: { + 'code': [ 'language-*', 'lang-*' ], + '*': [ 'fancy', 'simple' ] +} +``` + +Furthermore, regular expressions are supported too: + +```js +allowedClasses: { + p: [ /^regex\d{2}$/ ] +} +``` + +If `allowedClasses` for a certain tag is `false`, all the classes for this tag will be allowed. + +> 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. + +### Allowed CSS Styles + +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. + +**You must also use `allowedAttributes`** to activate the `style` attribute for the relevant elements. Otherwise this feature will never come into play. + +**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." + +**URLs in inline styles are NOT filtered by any mechanism other than your regular expression.** + +```javascript +const clean = sanitizeHtml(dirty, { + allowedTags: ['p'], + allowedAttributes: { + 'p': ["style"], + }, + allowedStyles: { + '*': { + // Match HEX and RGB + 'color': [/^#(0x)?[0-9a-f]+$/i, /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/], + 'text-align': [/^left$/, /^right$/, /^center$/], + // Match any number with px, em, or % + 'font-size': [/^\d+(?:px|em|%)$/] + }, + 'p': { + 'font-size': [/^\d+rem$/] + } + } + }); +``` + ### Discarding text outside of `````` tags -Some text editing applications generate HTML to allow copying over to a web application. These can sometimes include undesireable 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. +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. Setting this option to true will instruct sanitize-html to discard all characters outside of `html` tag boundaries -- before `` and after `` tags. @@ -203,17 +384,19 @@ enforceHtmlBoundary: true ### htmlparser2 Options -`santizeHtml` is built on `htmlparser2`. By default the only option passed down is `decodeEntities: true` You can set the options to pass by using the parser option. +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. -```js -clean = sanitizeHtml(dirty, { +**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. + +```javascript +const clean = sanitizeHtml(dirty, { allowedTags: ['a'], parser: { lowerCaseTags: true } }); ``` -See the [htmlparser2 wiki] (https://github.com/fb55/htmlparser2/wiki/Parser-options) for the full list of possible options. +See the [htmlparser2 wiki](https://github.com/fb55/htmlparser2/wiki/Parser-options) for the full list of possible options. ### Transformations @@ -222,7 +405,7 @@ What if you want to add or change an attribute? What if you want to transform on The easiest way (will change all `ol` tags to `ul` tags): ```js -clean = sanitizeHtml(dirty, { +const clean = sanitizeHtml(dirty, { transformTags: { 'ol': 'ul', } @@ -232,11 +415,10 @@ clean = sanitizeHtml(dirty, { The most advanced usage: ```js -clean = sanitizeHtml(dirty, { +const clean = sanitizeHtml(dirty, { transformTags: { 'ol': function(tagName, attribs) { // My own custom magic goes here - return { tagName: 'ul', attribs: { @@ -253,7 +435,7 @@ You can specify the `*` wildcard instead of a tag name to transform all tags. 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: ```js -clean = sanitizeHtml(dirty, { +const clean = sanitizeHtml(dirty, { transformTags: { 'ol': sanitizeHtml.simpleTransform('ul', {class: 'foo'}), } @@ -271,7 +453,7 @@ The last parameter (`shouldMerge`) is set to `true` by default. When `true`, `si You can also add or modify the text contents of a tag: ```js -clean = sanitizeHtml(dirty, { +const clean = sanitizeHtml(dirty, { transformTags: { 'a': function(tagName, attribs) { return { @@ -312,6 +494,21 @@ sanitizeHtml( ); ``` +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: + +```js +sanitizeHtml( + 'This is a bad link and a good link', + { + exclusiveFilter: function(frame) { + // the href attribute is removed by the URL protocol check + return frame.tag === 'a' && !frame.attribs.href ? 'excludeTag' : false; + } + } +); +// Output: 'This is a bad link and a good link' +``` + The `frame` object supplied to the callback provides the following attributes: - `tag`: The tag name, i.e. `'img'`. @@ -345,7 +542,7 @@ Note that the text passed to the `textFilter` method is already escaped for safe ### Iframe Filters -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. +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. 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. @@ -368,8 +565,8 @@ Note that if unspecified, relative URLs will be allowed by default if no hostnam For example: -```js -clean = sanitizeHtml('

', { +```javascript +const clean = sanitizeHtml('

', { allowedTags: [ 'p', 'em', 'strong', 'iframe' ], allowedClasses: { 'p': [ 'fancy', 'simple' ], @@ -383,8 +580,8 @@ clean = sanitizeHtml('

', { +```javascript +const clean = sanitizeHtml('

', { allowedTags: [ 'p', 'em', 'strong', 'iframe' ], allowedClasses: { 'p': [ 'fancy', 'simple' ], @@ -398,8 +595,8 @@ clean = sanitizeHtml('

', { +```javascript +const clean = sanitizeHtml('

', { allowedTags: [ 'p', 'em', 'strong', 'iframe' ], allowedClasses: { 'p': [ 'fancy', 'simple' ], @@ -415,8 +612,9 @@ will return an empty iframe tag. If you want to allow any subdomain of any level you can provide the domain in `allowedIframeDomains` -```js -clean = sanitizeHtml('

', { +```javascript +// This iframe markup will pass through as safe. +const clean = sanitizeHtml('

', { allowedTags: [ 'p', 'em', 'strong', 'iframe' ], allowedClasses: { 'p': [ 'fancy', 'simple' ], @@ -429,58 +627,35 @@ clean = sanitizeHtml('

', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] + allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] }), '' ); }); - it('Should remove iframe src urls that are not included in whitelisted hostnames', function() { + it('Should remove iframe src urls that are not included in allowedIframeHostnames', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] + allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] }), '' ); }); it('Should not allow iframe urls that do not have proper hostname', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] + allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] }), '' ); }); it('Should allow iframe through if no hostname option is set', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] } }), '' ); }); - it('Should allow domains in an iframe that are whitelisted', function() { + it('Should allow domains in an iframe that are in allowedIframeDomains', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeDomains: ['zoom.us'] + allowedIframeDomains: [ 'zoom.us' ] }), '' ); }); - it('Should allow second-level domains in an iframe that are whitelisted', function() { + it('Should allow second-level domains in an iframe that are in allowedIframeDomains', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeDomains: ['zoom.us'] + allowedIframeDomains: [ 'zoom.us' ] }), '' ); }); - it('Should remove iframe src urls that are not included in whitelisted domains', function() { + it('Should remove iframe src urls that are not included in allowedIframeDomains', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeDomains: ['vimeo.com'] + allowedIframeDomains: [ 'vimeo.com' ] }), '' ); }); - it('Should remove iframe src urls with host that ends as whitelisted domains ' + - ' but not preceeded with a dot', function() { + it('Should remove iframe src urls with host that ends as allowed domains but not preceded with a dot', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeDomains: ['zoom.us'] + allowedIframeDomains: [ 'zoom.us' ] }), '' ); }); - it('Should allow hostnames in an iframe that are whitelisted in allowedIframeHostnames ' + - 'and are not whitelisted in allowedIframeDomains', function() { + it('Should allow hostnames in an iframe that are in allowedIframeHostnames and are not in allowedIframeDomains', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'], - allowedIframeDomains: ['zoom.us'] + allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ], + allowedIframeDomains: [ 'zoom.us' ] }), '' ); }); - it('Should allow hostnames in an iframe that are not whitelisted in allowedIframeHostnames ' + - 'and are whitelisted in allowedIframeDomains', function() { + it('Should allow hostnames in an iframe that are not in allowedIframeHostnames ' + + 'and are allowlisted in allowedIframeDomains', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'], - allowedIframeDomains: ['zoom.us'] + allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ], + allowedIframeDomains: [ 'zoom.us' ] }), '' ); }); it('Should allow relative URLs for iframes by default', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] } }), '' ); @@ -952,11 +1313,11 @@ describe('sanitizeHtml', function() { it('Should allow relative URLs for iframes', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, allowIframeRelativeUrls: true }), '' @@ -965,124 +1326,124 @@ describe('sanitizeHtml', function() { it('Should remove relative URLs for iframes', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, allowIframeRelativeUrls: false }), '' ); }); - it('Should remove relative URLs for iframes when whitelisted hostnames specified', function() { + it('Should remove relative URLs for iframes when other hostnames are specified in allowedIframeHostnames', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeHostnames: ['www.youtube.com'] + allowedIframeHostnames: [ 'www.youtube.com' ] }), '' ); }); - it('Should allow relative and whitelisted hostname URLs for iframes', function() { + it('Should allow relative and allowlisted hostname URLs for iframes', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, allowIframeRelativeUrls: true, - allowedIframeHostnames: ['www.youtube.com'] + allowedIframeHostnames: [ 'www.youtube.com' ] }), '' ); }); it('Should allow protocol-relative URLs for the right domain for iframes', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] + allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] }), '' ); }); it('Should not allow protocol-relative iframe urls that do not have proper hostname', function() { assert.equal( sanitizeHtml('', { - allowedTags: ['p', 'iframe', 'a', 'img', 'i'], + allowedTags: [ 'p', 'iframe', 'a', 'img', 'i' ], allowedAttributes: { - iframe: ['src', 'href'], - a: ['src', 'href'], - img: ['src'] + iframe: [ 'src', 'href' ], + a: [ 'src', 'href' ], + img: [ 'src' ] }, - allowedIframeHostnames: ['www.youtube.com', 'player.vimeo.com'] + allowedIframeHostnames: [ 'www.youtube.com', 'player.vimeo.com' ] }), '' ); }); it('Should only allow attributes to have any combination of specific values', function() { assert.equal( - sanitizeHtml('', { - allowedTags: sanitizeHtml.defaults.allowedTags.concat(['iframe']), + sanitizeHtml('', { + allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'iframe' ]), allowedAttributes: { iframe: [ { name: 'sandbox', multiple: true, - values: ['allow-popups', 'allow-same-origin', 'allow-scripts'] + values: [ 'allow-popups', 'allow-same-origin', 'allow-scripts' ] }, 'allowfullscreen' ] } - }), ''); + }), ''); }); it('Should only allow attributes that match a specific value', function() { assert.equal( - sanitizeHtml('', { - allowedTags: sanitizeHtml.defaults.allowedTags.concat(['iframe']), + sanitizeHtml('', { + allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'iframe' ]), allowedAttributes: { iframe: [ { name: 'sandbox', multiple: false, - values: ['allow-popups', 'allow-same-origin', 'allow-scripts'] + values: [ 'allow-popups', 'allow-same-origin', 'allow-scripts' ] } ] } - }), ''); + }), ''); } ); it('Should not allow cite urls that do not have an allowed scheme', function() { assert.equal( - sanitizeHtml('HTTPHTTPSMAILTOTELFTPDATALDAPACROBATVBSCRIPTFILERLOGINWEBCALJAVASCRIPTMMS', { - allowedTags: sanitizeHtml.defaults.allowedTags.concat(['q']), - allowedAttributes: { q: ['cite'] }, - allowedSchemes: sanitizeHtml.defaults.allowedSchemes.concat(['tel']) - }), 'HTTPHTTPSMAILTOTELFTPDATALDAPACROBATVBSCRIPTFILERLOGINWEBCALJAVASCRIPTMMS'); + sanitizeHtml('HTTPHTTPSMAILTOTELms-calculatorFTPDATALDAPACROBATVBSCRIPTFILERLOGINWEBCALJAVASCRIPTMMS', { + allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'q' ]), + allowedAttributes: { q: [ 'cite' ] }, + allowedSchemes: sanitizeHtml.defaults.allowedSchemes.concat([ 'tel' ]) + }), 'HTTPHTTPSMAILTOTELms-calculatorFTPDATALDAPACROBATVBSCRIPTFILERLOGINWEBCALJAVASCRIPTMMS'); }); it('Should encode &, <, > and where necessary, "', function() { assert.equal(sanitizeHtml('"< & >" cool', { - allowedTags: ['span'], + allowedTags: [ 'span' ], allowedAttributes: { - span: ['class'] + span: [ 'class' ] } }), '"< & >" cool'); }); it('Should not pass through &0; unescaped if decodeEntities is true (the default)', function() { - assert.equal(sanitizeHtml('', { allowedTags: ['img'] }), ''); + assert.equal(sanitizeHtml('', { allowedTags: [ 'img' ] }), ''); }); it('Should not double encode ampersands on HTML entities if decodeEntities is false (TODO more tests, this is too loose to rely upon)', function() { - var textIn = 'This & & that ® ± OK?'; - var expectedResult = 'This & & that ® ± OK?'; - var sanitizeHtmlOptions = { + const textIn = 'This & & that ® ± OK?'; + const expectedResult = 'This & & that ® ± OK?'; + const sanitizeHtmlOptions = { parser: { decodeEntities: false } @@ -1102,19 +1463,19 @@ describe('sanitizeHtml', function() { // } // }), ''); // }); - it('should escape markup not whitelisted and all its children in recursive mode', function() { + it('should escape markup not allowlisted and all its children in recursive mode', function() { assert.equal( sanitizeHtml('

Hello

World

', { disallowedTagsMode: 'recursiveEscape' }), '
<wiggly>Hello<p>World</p></wiggly>
' ); }); - it('should escape markup not whitelisted and but not its children', function() { + it('should escape markup not allowlisted and but not its children', function() { assert.equal( sanitizeHtml('
Hello

World

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

World

</wiggly>
' ); }); - it('should escape markup even when deocdeEntities is false', function() { + it('should escape markup even when decodeEntities is false', function() { assert.equal( sanitizeHtml('Hello', { disallowedTagsMode: 'escape', @@ -1123,16 +1484,368 @@ describe('sanitizeHtml', function() { '<wiggly>Hello</wiggly>' ); }); - it('should escape markup not whitelisted even within allowed markup', function() { + it('should escape markup not allowlisted even within allowed markup', function() { assert.equal( sanitizeHtml('
Hello

World

JS
', { disallowedTagsMode: 'recursiveEscape' }), '
<wiggly>Hello<p>World</p><tiggly>JS</tiggly></wiggly>
' ); }); - it('should escape markup not whitelisted even within allowed markup, but not the allowed markup itself', function() { + it('should escape markup not allowlisted even within allowed markup, but not the allowed markup itself', function() { assert.equal( sanitizeHtml('
Hello

World

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

World

<tiggly>JS</tiggly></wiggly>
' ); }); + it('allows markup of depth 6 with a nestingLimit of depth 6', function() { + assert.equal( + sanitizeHtml('
', { nestingLimit: 6 }), + '
' + ); + }); + it('disallows markup of depth 7 with a nestingLimit of depth 6', function() { + assert.equal( + // 7 divs here + sanitizeHtml('
nested text
', { nestingLimit: 6 }), + // only 6 kept + '
nested text
' + ); + }); + it('should not allow simple append attacks on iframe hostname validation', function() { + assert.equal( + sanitizeHtml('' + ); + }); + it('should not allow IDNA (Internationalized Domain Name) iframe validation bypass attacks', function() { + assert.equal( + sanitizeHtml('' + ); + }); + it('should parse path-rooted relative URLs sensibly', function() { + assert.equal( + sanitizeHtml(''), + '' + ); + }); + it('should parse bare relative URLs sensibly', function() { + assert.equal( + sanitizeHtml(''), + '' + ); + }); + it('should parse ../ relative URLs sensibly', function() { + assert.equal( + sanitizeHtml(''), + '' + ); + }); + it('should parse protocol relative URLs sensibly', function() { + assert.equal( + sanitizeHtml(''), + '' + ); + }); + it('should reject attempts to hack our use of a relative: protocol in our test base URL', function() { + assert.equal( + sanitizeHtml('' + ); + }); + it('Should prevent hostname bypass using protocol-relative src', function () { + assert.strictEqual( + sanitizeHtml('', { + allowedTags: [ 'iframe' ], + allowedAttributes: { + iframe: [ 'src' ] + }, + allowedIframeHostnames: [ 'www.youtube.com' ], + allowIframeRelativeUrls: true + }), '' + ); + assert.strictEqual( + sanitizeHtml('', { + allowedTags: [ 'iframe' ], + allowedAttributes: { + iframe: [ 'src' ] + }, + allowedIframeHostnames: [ 'www.youtube.com' ], + allowIframeRelativeUrls: true + }), '' + ); + const linefeed = decodeURIComponent('%0A'); + assert.strictEqual( + sanitizeHtml('', { + allowedTags: [ 'iframe' ], + allowedAttributes: { + iframe: [ 'src' ] + }, + allowedIframeHostnames: [ 'www.youtube.com' ], + allowIframeRelativeUrls: true + }), '' + ); + const creturn = decodeURIComponent('%0D'); + assert.strictEqual( + sanitizeHtml('', { + allowedTags: [ 'iframe' ], + allowedAttributes: { + iframe: [ 'src' ] + }, + allowedIframeHostnames: [ 'www.youtube.com' ], + allowIframeRelativeUrls: true + }), '' + ); + const tab = decodeURIComponent('%09'); + assert.strictEqual( + sanitizeHtml('', { + allowedTags: [ 'iframe' ], + allowedAttributes: { + iframe: [ 'src' ] + }, + allowedIframeHostnames: [ 'www.youtube.com' ], + allowIframeRelativeUrls: true + }), '' + ); + }); + it('Should allow protocol-relative URLs for script tag', function() { + assert.equal( + sanitizeHtml('', { + allowedTags: [ 'script' ], + allowedAttributes: { + script: [ 'src' ] + + } + }), '' + ); + }); + it('should not automatically attach close tag for escaped tags in escape mode', function() { + assert.equal(sanitizeHtml('Hello', { + disallowedTagsMode: 'escape' + }), '<test>Hello'); + }); + it('should not automatically attach close tag for escaped tags in recursiveEscape mode', function() { + assert.equal(sanitizeHtml('Hello', { + disallowedTagsMode: 'recursiveEscape' + }), '<test><test><test><test><test>Hello'); + }); + it('should discard unclosed disallowed tags', function() { + assert.equal(sanitizeHtml('Hello', { + disallowedTagsMode: 'discard' + }), 'Hello'); + }); + it('should remove non-boolean attributes that are empty', function() { + assert.equal(sanitizeHtml('hello', { + }), 'hello'); + }); + it('should not remove non-boolean attributes that are empty when disabled', function() { + assert.equal(sanitizeHtml('hello', { + nonBooleanAttributes: [] + }), 'hello'); + }); + it('should not remove boolean attributes that are empty', function() { + assert.equal(sanitizeHtml('', { + allowedTags: 'input', + allowedAttributes: { + input: [ 'checked', 'form', 'type' ] + } + }), ''); + }); + it('should remove boolean attributes that are empty when wildcard * passed in', function() { + assert.equal(sanitizeHtml('', { + allowedTags: 'input', + allowedAttributes: { + input: [ 'checked', 'form', 'type' ] + }, + nonBooleanAttributes: [ '*' ] + }), ''); + }); + it('should not remove empty alt attribute value by default', function() { + assert.equal(sanitizeHtml('', { + allowedAttributes: { img: [ 'alt', 'src' ] }, + allowedTags: [ 'img' ] + }), ''); + }); + it('should convert the implicit empty alt attribute value to be an empty string by default', function() { + assert.equal(sanitizeHtml('', { + allowedAttributes: { img: [ 'alt', 'src' ] }, + allowedTags: [ 'img' ] + }), ''); + }); + it('should not remove empty alt attribute value by default when an empty nonBooleanAttributes option passed in', function() { + assert.equal(sanitizeHtml('', { + allowedAttributes: { img: [ 'alt', 'src' ] }, + allowedTags: [ 'img' ], + nonBooleanAttributes: [] + }), ''); + }); + it('should not remove the empty attributes specified in allowedEmptyAttributes option', function() { + assert.equal(sanitizeHtml('', { + allowedAttributes: { img: [ 'alt', 'src' ] }, + allowedTags: [ 'img' ], + allowedEmptyAttributes: [ 'alt', 'src' ] + }), ''); + }); + it('should remove all the empty attributes when an empty allowedEmptyAttributes option passed in', function() { + assert.equal(sanitizeHtml('', { + allowedAttributes: { img: [ 'alt', 'src' ] }, + allowedTags: [ 'img' ], + allowedEmptyAttributes: [] + }), ''); + }); + it('should support SVG tags', () => { + assert.equal(sanitizeHtml('', { + allowedTags: [ 'svg', 'g', 'defs', 'linearGradient', 'stop', 'circle' ], + allowedAttributes: false, + parser: { + lowerCaseTags: false, + lowerCaseAttributeNames: false + } + }), ''); + }); + it('should not process style sourceMappingURL with postCSS', () => { + assert.equal(sanitizeHtml('', { + allowedAttributes: { + ...sanitizeHtml.defaults.allowedAttributes, + a: [ 'style' ] + } + }), ''); + }); + it('should completely remove disallowed tags with nested content', () => { + const inputHtml = '
Some Text

Allowed content

More allowed content Another Text
'; + const expectedOutput = '

Allowed content

More allowed content'; + const sanitizedHtml = sanitizeHtml(inputHtml, { + allowedTags: [ 'p', 'span' ], + disallowedTagsMode: 'completelyDiscard' + }); + assert.equal(sanitizedHtml, expectedOutput); + }); + it('should remove top level tag\'s content', () => { + const inputHtml = 'Some Text

paragraph content

content'; + const expectedOutput = '

paragraph content

'; + const sanitizedHtml = sanitizeHtml(inputHtml, { + allowedTags: [ 'p' ], + disallowedTagsMode: 'completelyDiscard' + }); + assert.equal(sanitizedHtml, expectedOutput); + }); + it('should completely remove disallowed tag with unclosed tag', () => { + const inputHtml = '
Some Text

paragraph content

some text'; + const expectedOutput = '

paragraph content

'; + const sanitizedHtml = sanitizeHtml(inputHtml, { + allowedTags: [ 'p' ], + disallowedTagsMode: 'completelyDiscard' + }); + + assert.equal(sanitizedHtml, expectedOutput); + }); + it('should transform text content of tags even if they originally had none', () => { + const inputHtml = '
'; + const expectedOutput = 'new content'; + const sanitizedHtml = sanitizeHtml(inputHtml, { + allowedTags: [], + transformTags: { + div: () => ({ text: 'new content' }) + } + }); + + assert.equal(sanitizedHtml, expectedOutput); + }); + it('should call onOpenTag and onCloseTag callbacks', () => { + const onOpenTag = sinon.spy(); + const onCloseTag = sinon.spy(); + const inputHtml = '
Some Text

paragraph content

some text

'; + sanitizeHtml(inputHtml, { + allowedTags: [ 'p' ], + onOpenTag, + onCloseTag + }); + assert.equal(onOpenTag.callCount, 3); + assert.equal(onOpenTag.getCall(0).calledWith('div', { id: 'one' }), true); + assert.equal(onOpenTag.getCall(1).calledWith('p', { id: 'two' }), true); + assert.equal(onOpenTag.getCall(2).calledWith('p', { id: 'three' }), true); + assert.equal(onCloseTag.callCount, 3); + assert.equal(onCloseTag.getCall(0).calledWith('p', false), true); + assert.equal(onCloseTag.getCall(1).calledWith('p', true), true); + assert.equal(onCloseTag.getCall(2).calledWith('div', false), true); + }); + it('should insert spaces between removed tags whose content we keep', () => { + const inputHtml = 'Text's here
it's here

it's there

and also here'; + const expectedOutput = 'Text\'s here it\'s here it\'s there and also here'; + const allowedTags = [ 'b' ]; + let addSpace = false; + const sanitizedHtml = sanitizeHtml( + inputHtml, + { + allowedTags, + onOpenTag: (tag) => { + addSpace = !allowedTags.includes(tag); + }, + onCloseTag: (tag) => { + addSpace = !allowedTags.includes(tag); + }, + textFilter: (text) => { + if (addSpace) { + addSpace = false; + return ' ' + text; + } + return text; + } + } + ); + assert.equal(sanitizedHtml, expectedOutput); + }); + it('should not preserve attributes on escaped disallowed tags when `preserveEscapedAttributes` is false', () => { + const inputHtml = '
Some Text
'; + const expectedOutput = '<div>Some Text</div>'; + const sanitizedHtml = sanitizeHtml(inputHtml, { + allowedTags: [], + disallowedTagsMode: 'escape', + preserveEscapedAttributes: false + }); + + assert.equal(sanitizedHtml, expectedOutput); + }); + it('should preserve attributes on escaped disallowed tags when `preserveEscapedAttributes` is true', () => { + const inputHtml = '
Some Text
'; + const expectedOutput = '<div class="foo">Some Text</div>'; + const sanitizedHtml = sanitizeHtml(inputHtml, { + allowedTags: [], + disallowedTagsMode: 'escape', + preserveEscapedAttributes: true + }); + + assert.equal(sanitizedHtml, expectedOutput); + }); + it('should ignore the `preserveEscapedAttributes` option when discarding diallowed tags (rather than escaping)', () => { + const inputHtml = '
Some Text
'; + const sanitizedHtmlPreservedAttrsTrue = sanitizeHtml(inputHtml, { + allowedTags: [], + disallowedTagsMode: 'discard', + preserveEscapedAttributes: true + }); + const sanitizedHtmlPreservedAttrsFalse = sanitizeHtml(inputHtml, { + allowedTags: [], + disallowedTagsMode: 'discard', + preserveEscapedAttributes: false + }); + + assert.equal(sanitizedHtmlPreservedAttrsTrue, sanitizedHtmlPreservedAttrsFalse); + }); });