├── .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 | '
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 | ' world',
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 `
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 bespaces
Hello there
Hello there
Hello there
paragraph after closing html
', { 28 | enforceHtmlBoundary: true 29 | } 30 | ), 'Hello there
Hello there
paragraph after closing html
', { 34 | enforceHtmlBoundary: false 35 | } 36 | ), 'Text before html tagHello there
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 tagHello there
paragraph after closing div
', { 40 | enforceHtmlBoundary: true 41 | } 42 | ), 'Text before div tagHello there
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('Whee!
'), 'Blah blah blahWhee!
'); 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('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('Paragraph
'), 'NiftyParagraph
'); 128 | }); 129 | it('should discard the content of fibble elements if specified for nonTextTags', function() { 130 | assert.equal(sanitizeHtml('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('Paragraph
', {}), 'NiftyParagraph
'); 134 | }); 135 | it('should discard allowed tags within a fibble element if fibble is specified for nonTextTags', function() { 136 | assert.equal(sanitizeHtml('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('inner text 1
inner text 2
inner text 3
inner text 1
inner text 2
inner text 3
inner text 1
inner text 2
inner text 3
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('text before
text after
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('', { 318 | exclusiveFilter: function (frame) { 319 | return frame.tag === 'a' && !frame.text.trim(); 320 | } 321 | }), 322 | 'This is
Linux
12
3
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 = '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 badshould be kept as-is
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('hellowhee
', 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 | '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 | '
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('<bestetestestestestestsettestestest
'; 987 | const expected = '
- test
- test
- test
- test
test
TESTETESTESTES
bestetestestestestestsettestestest
'; 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('
- test
- test
- test
- test
test
TESTETESTESTES
HTTP
HTTPS
MAILTO
TEL
ms-calculator
FTP
DATA
LDAP
ACROBAT
VBSCRIPT
FILE
RLOGIN
WEBCAL
JAVASCRIPT
MMS', { 1427 | allowedTags: sanitizeHtml.defaults.allowedTags.concat([ 'q' ]), 1428 | allowedAttributes: { q: [ 'cite' ] }, 1429 | allowedSchemes: sanitizeHtml.defaults.allowedSchemes.concat([ 'tel' ]) 1430 | }), '
HTTP
HTTPS
MAILTO
TEL
ms-calculator
FTP
DATA
LDAP
ACROBAT
VBSCRIPT
FILE
RLOGIN
WEBCAL
JAVASCRIPT
MMS'); 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('
World
World
World
</wiggly>World
World
World
<tiggly>JS</tiggly></wiggly>