sanitize 6.1.0 → 7.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -1,21 +1,10 @@
1
- Sanitize
2
- ========
1
+ # Sanitize
3
2
 
4
- Sanitize is an allowlist-based HTML and CSS sanitizer. It removes all HTML
5
- and/or CSS from a string except the elements, attributes, and properties you
6
- choose to allow.
3
+ Sanitize is an allowlist-based HTML and CSS sanitizer. It removes all HTML and/or CSS from a string except the elements, attributes, and properties you choose to allow.
7
4
 
8
- Using a simple configuration syntax, you can tell Sanitize to allow certain HTML
9
- elements, certain attributes within those elements, and even certain URL
10
- protocols within attributes that contain URLs. You can also allow specific CSS
11
- properties, @ rules, and URL protocols in elements or attributes containing CSS.
12
- Any HTML or CSS that you don't explicitly allow will be removed.
5
+ Using a simple configuration syntax, you can tell Sanitize to allow certain HTML elements, certain attributes within those elements, and even certain URL protocols within attributes that contain URLs. You can also allow specific CSS properties, @ rules, and URL protocols in elements or attributes containing CSS. Any HTML or CSS that you don't explicitly allow will be removed.
13
6
 
14
- Sanitize is based on the [Nokogiri HTML5 parser][nokogiri], which parses HTML
15
- the same way modern browsers do, and [Crass][crass], which parses CSS the same
16
- way modern browsers do. As long as your allowlist config only allows safe markup
17
- and CSS, even the most malformed or malicious input will be transformed into
18
- safe output.
7
+ Sanitize is based on the [Nokogiri HTML5 parser][nokogiri], which parses HTML the same way modern browsers do, and [Crass][crass], which parses CSS the same way modern browsers do. As long as your allowlist config only allows safe markup and CSS, even the most malformed or malicious input will be transformed into safe output.
19
8
 
20
9
  [![Gem Version](https://badge.fury.io/rb/sanitize.svg)](http://badge.fury.io/rb/sanitize)
21
10
  [![Tests](https://github.com/rgrove/sanitize/workflows/Tests/badge.svg)](https://github.com/rgrove/sanitize/actions?query=workflow%3ATests)
@@ -23,24 +12,27 @@ safe output.
23
12
  [crass]:https://github.com/rgrove/crass
24
13
  [nokogiri]:https://github.com/sparklemotion/nokogiri
25
14
 
26
- Links
27
- -----
15
+ > [!WARNING]
16
+ >
17
+ > Sanitize cannot fully sanitize the contents of `<math>` or `<svg>` elements. MathML and SVG elements are [foreign elements](https://html.spec.whatwg.org/multipage/syntax.html#foreign-elements) that don't follow normal HTML parsing rules.
18
+ >
19
+ > By default, Sanitize will remove all MathML and SVG elements. If you add MathML or SVG elements to a custom element allowlist, you may create a security vulnerability in your application.
20
+
21
+ ## Links
28
22
 
29
23
  * [Home](https://github.com/rgrove/sanitize/)
30
- * [API Docs](https://rubydoc.info/github/rgrove/sanitize/Sanitize)
24
+ * [API Docs](https://rubydoc.info/gems/sanitize/Sanitize)
31
25
  * [Issues](https://github.com/rgrove/sanitize/issues)
32
26
  * [Release History](https://github.com/rgrove/sanitize/releases)
33
27
  * [Online Demo](https://sanitize-web.fly.dev/)
34
28
 
35
- Installation
36
- -------------
29
+ ## Installation
37
30
 
38
31
  ```
39
32
  gem install sanitize
40
33
  ```
41
34
 
42
- Quick Start
43
- -----------
35
+ ## Quick Start
44
36
 
45
37
  ```ruby
46
38
  require 'sanitize'
@@ -59,8 +51,7 @@ Sanitize::CSS.stylesheet(css, Sanitize::Config::RELAXED)
59
51
  Sanitize::CSS.properties(css, Sanitize::Config::RELAXED)
60
52
  ```
61
53
 
62
- Usage
63
- -----
54
+ ## Usage
64
55
 
65
56
  Sanitize can sanitize the following types of input:
66
57
 
@@ -71,7 +62,7 @@ Sanitize can sanitize the following types of input:
71
62
  * Standalone CSS stylesheets
72
63
  * Standalone CSS properties
73
64
 
74
- > **Warning**
65
+ > [!WARNING]
75
66
  >
76
67
  > Sanitize cannot fully sanitize the contents of `<math>` or `<svg>` elements. MathML and SVG elements are [foreign elements](https://html.spec.whatwg.org/multipage/syntax.html#foreign-elements) that don't follow normal HTML parsing rules.
77
68
  >
@@ -79,31 +70,26 @@ Sanitize can sanitize the following types of input:
79
70
 
80
71
  ### HTML Fragments
81
72
 
82
- A fragment is a snippet of HTML that doesn't contain a root-level `<html>`
83
- element.
73
+ A fragment is a snippet of HTML that doesn't contain a root-level `<html>` element.
84
74
 
85
- If you don't specify any configuration options, Sanitize will use its strictest
86
- settings by default, which means it will strip all HTML and leave only safe text
87
- behind.
75
+ If you don't specify any configuration options, Sanitize will use its strictest settings by default, which means it will strip all HTML and leave only safe text behind.
88
76
 
89
77
  ```ruby
90
78
  html = '<b><a href="http://foo.com/">foo</a></b><img src="bar.jpg">'
91
79
  Sanitize.fragment(html)
92
- # => 'foo'
80
+ # => "foo"
93
81
  ```
94
82
 
95
83
  To keep certain elements, add them to the element allowlist.
96
84
 
97
85
  ```ruby
98
- Sanitize.fragment(html, :elements => ['b'])
99
- # => '<b>foo</b>'
86
+ Sanitize.fragment(html, elements: ['b'])
87
+ # => "<b>foo</b>"
100
88
  ```
101
89
 
102
90
  ### HTML Documents
103
91
 
104
- When sanitizing a document, the `<html>` element must be allowlisted. You can
105
- also set `:allow_doctype` to `true` to allow well-formed document type
106
- definitions.
92
+ When sanitizing a document, the `<html>` element must be allowlisted. You can also set `:allow_doctype` to `true` to allow well-formed document type definitions.
107
93
 
108
94
  ```ruby
109
95
  html = %[
@@ -114,23 +100,15 @@ html = %[
114
100
  ]
115
101
 
116
102
  Sanitize.document(html,
117
- :allow_doctype => true,
118
- :elements => ['html']
103
+ allow_doctype: true,
104
+ elements: ['html']
119
105
  )
120
- # => %[
121
- # <!DOCTYPE html>
122
- # <html>foo
123
- #
124
- # </html>
125
- # ]
106
+ # => "<!DOCTYPE html><html>foo\n \n</html>"
126
107
  ```
127
108
 
128
109
  ### CSS in HTML
129
110
 
130
- To sanitize CSS in an HTML fragment or document, first allowlist the `<style>`
131
- element and/or the `style` attribute. Then allowlist the CSS properties,
132
- @ rules, and URL protocols you wish to allow. You can also choose whether to
133
- allow CSS comments or browser compatibility hacks.
111
+ To sanitize CSS in an HTML fragment or document, first allowlist the `<style>` element and/or the `style` attribute. Then allowlist the CSS properties, @ rules, and URL protocols you wish to allow. You can also choose whether to allow CSS comments or browser compatibility hacks.
134
112
 
135
113
  ```ruby
136
114
  html = %[
@@ -143,11 +121,11 @@ html = %[
143
121
  ]
144
122
 
145
123
  Sanitize.fragment(html,
146
- :elements => ['div', 'style'],
147
- :attributes => {'div' => ['style']},
124
+ elements: ['div', 'style'],
125
+ attributes: {'div' => ['style']},
148
126
 
149
- :css => {
150
- :properties => ['width']
127
+ css: {
128
+ properties: ['width']
151
129
  }
152
130
  )
153
131
  #=> %[
@@ -162,8 +140,10 @@ Sanitize.fragment(html,
162
140
 
163
141
  ### Standalone CSS
164
142
 
165
- Sanitize will happily clean up a standalone CSS stylesheet or property string
166
- without needing to invoke the HTML parser.
143
+ Sanitize will happily clean up a standalone CSS stylesheet or property string without needing to invoke the HTML parser.
144
+
145
+ > [!WARNING]
146
+ > This should only be used to sanitize CSS for use in a standalone CSS file. To safely sanitize CSS for use in an HTML context, such as in a `<style>` element or a `style` attribute, you must use `Sanitize.document()` or `Sanitize.fragment()` with an appropriate allowlist as described in the previous sections. Failure to do so may enable HTML injection attacks.
167
147
 
168
148
  ```ruby
169
149
  css = %[
@@ -181,7 +161,6 @@ Sanitize::CSS.stylesheet(css, Sanitize::Config::RELAXED)
181
161
  # => %[
182
162
  #
183
163
  #
184
- #
185
164
  # a { text-decoration: none; }
186
165
  #
187
166
  # a:hover {
@@ -198,15 +177,11 @@ Sanitize::CSS.properties(%[
198
177
  #
199
178
  # text-decoration: underline;
200
179
  # ]
201
-
202
180
  ```
203
181
 
204
- Configuration
205
- -------------
182
+ ## Configuration
206
183
 
207
- In addition to the ultra-safe default settings, Sanitize comes with three other
208
- built-in configurations that you can use out of the box or adapt to meet your
209
- needs.
184
+ In addition to the ultra-safe default settings, Sanitize comes with three other built-in configurations that you can use out of the box or adapt to meet your needs.
210
185
 
211
186
  ### Sanitize::Config::RESTRICTED
212
187
 
@@ -214,16 +189,14 @@ Allows only very simple inline markup. No links, images, or block elements.
214
189
 
215
190
  ```ruby
216
191
  Sanitize.fragment(html, Sanitize::Config::RESTRICTED)
217
- # => '<b>foo</b>'
192
+ # => "<b>foo</b>"
218
193
  ```
219
194
 
220
195
  ### Sanitize::Config::BASIC
221
196
 
222
197
  Allows a variety of markup including formatting elements, links, and lists.
223
198
 
224
- Images and tables are not allowed, links are limited to FTP, HTTP, HTTPS, and
225
- mailto protocols, and a `rel="nofollow"` attribute is added to all links to
226
- mitigate SEO spam.
199
+ Images and tables are not allowed, links are limited to FTP, HTTP, HTTPS, and mailto protocols, and a `rel="nofollow"` attribute is added to all links to mitigate SEO spam.
227
200
 
228
201
  ```ruby
229
202
  Sanitize.fragment(html, Sanitize::Config::BASIC)
@@ -232,10 +205,7 @@ Sanitize.fragment(html, Sanitize::Config::BASIC)
232
205
 
233
206
  ### Sanitize::Config::RELAXED
234
207
 
235
- Allows an even wider variety of markup, including images and tables, as well as
236
- safe CSS. Links are still limited to FTP, HTTP, HTTPS, and mailto protocols,
237
- while images are limited to HTTP and HTTPS. In this mode, `rel="nofollow"` is
238
- not added to links.
208
+ Allows an even wider variety of markup, including images and tables, as well as safe CSS. Links are still limited to FTP, HTTP, HTTPS, and mailto protocols, while images are limited to HTTP and HTTPS. In this mode, `rel="nofollow"` is not added to links.
239
209
 
240
210
  ```ruby
241
211
  Sanitize.fragment(html, Sanitize::Config::RELAXED)
@@ -244,50 +214,43 @@ Sanitize.fragment(html, Sanitize::Config::RELAXED)
244
214
 
245
215
  ### Custom Configuration
246
216
 
247
- If the built-in modes don't meet your needs, you can easily specify a custom
248
- configuration:
217
+ If the built-in modes don't meet your needs, you can easily specify a custom configuration:
249
218
 
250
219
  ```ruby
251
220
  Sanitize.fragment(html,
252
- :elements => ['a', 'span'],
221
+ elements: ['a', 'span'],
253
222
 
254
- :attributes => {
255
- 'a' => ['href', 'title'],
223
+ attributes: {
224
+ 'a' => ['href', 'title'],
256
225
  'span' => ['class']
257
226
  },
258
227
 
259
- :protocols => {
228
+ protocols: {
260
229
  'a' => {'href' => ['http', 'https', 'mailto']}
261
230
  }
262
231
  )
263
232
  ```
264
233
 
265
- You can also start with one of Sanitize's built-in configurations and then
266
- customize it to meet your needs.
234
+ You can also start with one of Sanitize's built-in configurations and then customize it to meet your needs.
267
235
 
268
- The built-in configs are deeply frozen to prevent people from modifying them
269
- (either accidentally or maliciously). To customize a built-in config, create a
270
- new copy using `Sanitize::Config.merge()`, like so:
236
+ The built-in configs are deeply frozen to prevent people from modifying them (either accidentally or maliciously). To customize a built-in config, create a new copy using `Sanitize::Config.merge()`, like so:
271
237
 
272
238
  ```ruby
273
239
  # Create a customized copy of the Basic config, adding <div> and <table> to the
274
240
  # existing allowlisted elements.
275
241
  Sanitize.fragment(html, Sanitize::Config.merge(Sanitize::Config::BASIC,
276
- :elements => Sanitize::Config::BASIC[:elements] + ['div', 'table'],
277
- :remove_contents => true
242
+ elements: Sanitize::Config::BASIC[:elements] + ['div', 'table'],
243
+ remove_contents: true
278
244
  ))
279
245
  ```
280
246
 
281
- The example above adds the `<div>` and `<table>` elements to a copy of the
282
- existing list of elements in `Sanitize::Config::BASIC`. If you instead want to
283
- completely overwrite the elements array with your own, you can omit the `+`
284
- operation:
247
+ The example above adds the `<div>` and `<table>` elements to a copy of the existing list of elements in `Sanitize::Config::BASIC`. If you instead want to completely overwrite the elements array with your own, you can omit the `+` operation:
285
248
 
286
249
  ```ruby
287
250
  # Overwrite :elements instead of creating a copy with new entries.
288
251
  Sanitize.fragment(html, Sanitize::Config.merge(Sanitize::Config::BASIC,
289
- :elements => ['div', 'table'],
290
- :remove_contents => true
252
+ elements: ['div', 'table'],
253
+ remove_contents: true
291
254
  ))
292
255
  ```
293
256
 
@@ -295,66 +258,56 @@ Sanitize.fragment(html, Sanitize::Config.merge(Sanitize::Config::BASIC,
295
258
 
296
259
  #### :add_attributes (Hash)
297
260
 
298
- Attributes to add to specific elements. If the attribute already exists, it will
299
- be replaced with the value specified here. Specify all element names and
300
- attributes in lowercase.
261
+ Attributes to add to specific elements. If the attribute already exists, it will be replaced with the value specified here. Specify all element names and attributes in lowercase.
301
262
 
302
263
  ```ruby
303
- :add_attributes => {
264
+ add_attributes: {
304
265
  'a' => {'rel' => 'nofollow'}
305
266
  }
306
267
  ```
307
268
 
308
269
  #### :allow_comments (boolean)
309
270
 
310
- Whether or not to allow HTML comments. Allowing comments is strongly
311
- discouraged, since IE allows script execution within conditional comments. The
312
- default value is `false`.
271
+ Whether or not to allow HTML comments. Allowing comments is strongly discouraged, since IE allows script execution within conditional comments. The default value is `false`.
313
272
 
314
273
  #### :allow_doctype (boolean)
315
274
 
316
- Whether or not to allow well-formed HTML doctype declarations such as "<!DOCTYPE
317
- html>" when sanitizing a document. This setting is ignored when sanitizing
318
- fragments. The default value is `false`.
275
+ Whether or not to allow well-formed HTML doctype declarations such as "<!DOCTYPE html>" when sanitizing a document. This setting is ignored when sanitizing fragments. The default value is `false`.
319
276
 
320
277
  #### :attributes (Hash)
321
278
 
322
- Attributes to allow on specific elements. Specify all element names and
323
- attributes in lowercase.
279
+ Attributes to allow on specific elements. Specify all element names and attributes in lowercase.
324
280
 
325
281
  ```ruby
326
- :attributes => {
327
- 'a' => ['href', 'title'],
282
+ attributes: {
283
+ 'a' => ['href', 'title'],
328
284
  'blockquote' => ['cite'],
329
- 'img' => ['alt', 'src', 'title']
285
+ 'img' => ['alt', 'src', 'title']
330
286
  }
331
287
  ```
332
288
 
333
- If you'd like to allow certain attributes on all elements, use the symbol `:all`
334
- instead of an element name.
289
+ If you'd like to allow certain attributes on all elements, use the symbol `:all` instead of an element name.
335
290
 
336
291
  ```ruby
337
292
  # Allow the class attribute on all elements.
338
- :attributes => {
293
+ attributes: {
339
294
  :all => ['class'],
340
- 'a' => ['href', 'title']
295
+ 'a' => ['href', 'title']
341
296
  }
342
297
  ```
343
298
 
344
- To allow arbitrary HTML5 `data-*` attributes, use the symbol `:data` in place of
345
- an attribute name.
299
+ To allow arbitrary HTML5 `data-*` attributes, use the symbol `:data` in place of an attribute name.
346
300
 
347
301
  ```ruby
348
302
  # Allow arbitrary HTML5 data-* attributes on <div> elements.
349
- :attributes => {
303
+ attributes: {
350
304
  'div' => [:data]
351
305
  }
352
306
  ```
353
307
 
354
308
  #### :css (Hash)
355
309
 
356
- Hash of the following CSS config settings to be used when sanitizing CSS (either
357
- standalone or embedded in HTML).
310
+ Hash of the following CSS config settings to be used when sanitizing CSS (either standalone or embedded in HTML).
358
311
 
359
312
  ##### :css => :allow_comments (boolean)
360
313
 
@@ -362,36 +315,27 @@ Whether or not to allow CSS comments. The default value is `false`.
362
315
 
363
316
  ##### :css => :allow_hacks (boolean)
364
317
 
365
- Whether or not to allow browser compatibility hacks such as the IE `*` and `_`
366
- hacks. These are generally harmless, but technically result in invalid CSS. The
367
- default is `false`.
318
+ Whether or not to allow browser compatibility hacks such as the IE `*` and `_` hacks. These are generally harmless, but technically result in invalid CSS. The default is `false`.
368
319
 
369
320
  ##### :css => :at_rules (Array or Set)
370
321
 
371
- Names of CSS [at-rules][at-rules] to allow that may not have associated blocks,
372
- such as `import` or `charset`. Names should be specified in lowercase.
322
+ Names of CSS [at-rules][at-rules] to allow that may not have associated blocks, such as `import` or `charset`. Names should be specified in lowercase.
373
323
 
374
324
  [at-rules]:https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule
375
325
 
376
326
  ##### :css => :at_rules_with_properties (Array or Set)
377
327
 
378
- Names of CSS [at-rules][at-rules] to allow that may have associated blocks
379
- containing CSS properties. At-rules like `font-face` and `page` fall into this
380
- category. Names should be specified in lowercase.
328
+ Names of CSS [at-rules][at-rules] to allow that may have associated blocks containing CSS properties. At-rules like `font-face` and `page` fall into this category. Names should be specified in lowercase.
381
329
 
382
330
  ##### :css => :at_rules_with_styles (Array or Set)
383
331
 
384
- Names of CSS [at-rules][at-rules] to allow that may have associated blocks
385
- containing style rules. At-rules like `media` and `keyframes` fall into this
386
- category. Names should be specified in lowercase.
332
+ Names of CSS [at-rules][at-rules] to allow that may have associated blocks containing style rules. At-rules like `media` and `keyframes` fall into this category. Names should be specified in lowercase.
387
333
 
388
334
  ##### :css => :import_url_validator
389
335
 
390
- This is a `Proc` (or other callable object) that will be called and passed
391
- the URL specified for any `@import` [at-rules][at-rules].
336
+ This is a `Proc` (or other callable object) that will be called and passed the URL specified for any `@import` [at-rules][at-rules].
392
337
 
393
- You can use this to limit what can be imported, for example something
394
- like the following to limit `@import` to Google Fonts URLs:
338
+ You can use this to limit what can be imported, for example something like the following to limit `@import` to Google Fonts URLs:
395
339
 
396
340
  ```ruby
397
341
  Proc.new { |url| url.start_with?("https://fonts.googleapis.com") }
@@ -405,28 +349,26 @@ List of CSS property names to allow. Names should be specified in lowercase.
405
349
 
406
350
  URL protocols to allow in CSS URLs. Should be specified in lowercase.
407
351
 
408
- If you'd like to allow the use of relative URLs which don't have a protocol,
409
- include the symbol `:relative` in the protocol array.
352
+ If you'd like to allow the use of relative URLs which don't have a protocol, include the symbol `:relative` in the protocol array.
410
353
 
411
354
  #### :elements (Array or Set)
412
355
 
413
- Array of HTML element names to allow. Specify all names in lowercase. Any
414
- elements not in this array will be removed.
356
+ Array of HTML element names to allow. Specify all names in lowercase. Any elements not in this array will be removed.
415
357
 
416
358
  ```ruby
417
- :elements => %w[
359
+ elements: %w[
418
360
  a abbr b blockquote br cite code dd dfn dl dt em i kbd li mark ol p pre
419
361
  q s samp small strike strong sub sup time u ul var
420
362
  ]
421
363
  ```
422
364
 
423
- > **Warning**
365
+ > [!WARNING]
424
366
  >
425
367
  > Sanitize cannot fully sanitize the contents of `<math>` or `<svg>` elements. MathML and SVG elements are [foreign elements](https://html.spec.whatwg.org/multipage/syntax.html#foreign-elements) that don't follow normal HTML parsing rules.
426
368
  >
427
369
  > By default, Sanitize will remove all MathML and SVG elements. If you add MathML or SVG elements to a custom element allowlist, you must assume that any content inside them will be allowed, even if that content would otherwise be removed or escaped by Sanitize. This may create a security vulnerability in your application.
428
370
 
429
- > **Note**
371
+ > [!NOTE]
430
372
  >
431
373
  > Sanitize always removes `<noscript>` elements and their contents, even if `noscript` is in the allowlist.
432
374
  >
@@ -434,10 +376,10 @@ elements not in this array will be removed.
434
376
 
435
377
  #### :parser_options (Hash)
436
378
 
437
- [Parsing options](https://github.com/rubys/nokogumbo/tree/master#parsing-options) to be supplied to `nokogumbo`.
379
+ [Parsing options](https://nokogiri.org/tutorials/parsing_an_html5_document.html?h=parsing+options#parsing-options) to be supplied to Nokogiri.
438
380
 
439
381
  ```ruby
440
- :parser_options => {
382
+ parser_options: {
441
383
  max_errors: -1,
442
384
  max_tree_depth: -1
443
385
  }
@@ -445,81 +387,59 @@ elements not in this array will be removed.
445
387
 
446
388
  #### :protocols (Hash)
447
389
 
448
- URL protocols to allow in specific attributes. If an attribute is listed here
449
- and contains a protocol other than those specified (or if it contains no
450
- protocol at all), it will be removed.
390
+ URL protocols to allow in specific attributes. If an attribute is listed here and contains a protocol other than those specified (or if it contains no protocol at all), it will be removed.
451
391
 
452
392
  ```ruby
453
- :protocols => {
454
- 'a' => {'href' => ['ftp', 'http', 'https', 'mailto']},
455
- 'img' => {'src' => ['http', 'https']}
393
+ protocols: {
394
+ 'a' => {'href' => ['ftp', 'http', 'https', 'mailto']},
395
+ 'img' => {'src' => ['http', 'https']}
456
396
  }
457
397
  ```
458
398
 
459
- If you'd like to allow the use of relative URLs which don't have a protocol,
460
- include the symbol `:relative` in the protocol array:
399
+ If you'd like to allow the use of relative URLs which don't have a protocol, include the symbol `:relative` in the protocol array:
461
400
 
462
401
  ```ruby
463
- :protocols => {
402
+ protocols: {
464
403
  'a' => {'href' => ['http', 'https', :relative]}
465
404
  }
466
405
  ```
467
406
 
468
407
  #### :remove_contents (boolean or Array or Set)
469
408
 
470
- If this is `true`, Sanitize will remove the contents of any non-allowlisted
471
- elements in addition to the elements themselves. By default, Sanitize leaves the
472
- safe parts of an element's contents behind when the element is removed.
409
+ If this is `true`, Sanitize will remove the contents of any non-allowlisted elements in addition to the elements themselves. By default, Sanitize leaves the safe parts of an element's contents behind when the element is removed.
473
410
 
474
- If this is an Array or Set of element names, then only the contents of the
475
- specified elements (when filtered) will be removed, and the contents of all
476
- other filtered elements will be left behind.
411
+ If this is an Array or Set of element names, then only the contents of the specified elements (when filtered) will be removed, and the contents of all other filtered elements will be left behind.
477
412
 
478
- The default value is `%w[iframe math noembed noframes noscript plaintext script style svg xmp]`.
413
+ The default value can be seen in the [default config](lib/sanitize/config/default.rb).
479
414
 
480
415
  #### :transformers (Array or callable)
481
416
 
482
- Custom HTML transformer or array of custom transformers. See the Transformers
483
- section below for details.
417
+ Custom HTML transformer or array of custom transformers. See the Transformers section below for details.
484
418
 
485
419
  #### :whitespace_elements (Hash)
486
420
 
487
- Hash of element names which, when removed, should have their contents surrounded
488
- by whitespace to preserve readability.
421
+ Hash of element names which, when removed, should have their contents surrounded by whitespace to preserve readability.
489
422
 
490
- Each element name is a key pointing to another Hash, which provides the specific
491
- whitespace that should be inserted `:before` and `:after` the removed element's
492
- position. The `:after` value will only be inserted if the removed element has
493
- children, in which case it will be inserted after those children.
423
+ Each element name is a key pointing to another Hash, which provides the specific whitespace that should be inserted `:before` and `:after` the removed element's position. The `:after` value will only be inserted if the removed element has children, in which case it will be inserted after those children.
494
424
 
495
425
  ```ruby
496
- :whitespace_elements => {
497
- 'br' => { :before => "\n", :after => "" },
498
- 'div' => { :before => "\n", :after => "\n" },
499
- 'p' => { :before => "\n", :after => "\n" }
426
+ whitespace_elements: {
427
+ 'br' => { before: "\n", after: "" },
428
+ 'div' => { before: "\n", after: "\n" },
429
+ 'p' => { before: "\n", after: "\n" }
500
430
  }
501
431
  ```
502
432
 
503
- The default elements with whitespace added before and after are:
504
-
505
- ```
506
- address article aside blockquote br dd div dl dt
507
- footer h1 h2 h3 h4 h5 h6 header hgroup hr li nav
508
- ol p pre section ul
509
-
510
- ```
433
+ The default elements with whitespace added before and after can be seen in [the default config](lib/sanitize/config/default.rb).
511
434
 
512
435
  ## Transformers
513
436
 
514
- Transformers allow you to filter and modify HTML nodes using your own custom
515
- logic, on top of (or instead of) Sanitize's core filter. A transformer is any
516
- object that responds to `call()` (such as a lambda or proc).
437
+ Transformers allow you to filter and modify HTML nodes using your own custom logic, on top of (or instead of) Sanitize's core filter. A transformer is any object that responds to `call()` (such as a lambda or proc).
517
438
 
518
- To use one or more transformers, pass them to the `:transformers` config
519
- setting. You may pass a single transformer or an array of transformers.
439
+ To use one or more transformers, pass them to the `:transformers` config setting. You may pass a single transformer or an array of transformers.
520
440
 
521
441
  ```ruby
522
- Sanitize.fragment(html, :transformers => [
442
+ Sanitize.fragment(html, transformers: [
523
443
  transformer_one,
524
444
  transformer_two
525
445
  ])
@@ -527,56 +447,31 @@ Sanitize.fragment(html, :transformers => [
527
447
 
528
448
  ### Input
529
449
 
530
- Each transformer's `call()` method will be called once for each node in the HTML
531
- (including elements, text nodes, comments, etc.), and will receive as an
532
- argument a Hash that contains the following items:
450
+ Each transformer's `call()` method will be called once for each node in the HTML (including elements, text nodes, comments, etc.), and will receive as an argument a Hash that contains the following items:
533
451
 
534
452
  * **:config** - The current Sanitize configuration Hash.
535
453
 
536
- * **:is_allowlisted** - `true` if the current node has been allowlisted by a
537
- previous transformer, `false` otherwise. It's generally bad form to remove
538
- a node that a previous transformer has allowlisted.
454
+ * **:is_allowlisted** - `true` if the current node has been allowlisted by a previous transformer, `false` otherwise. It's generally bad form to remove a node that a previous transformer has allowlisted.
539
455
 
540
- * **:node** - A `Nokogiri::XML::Node` object representing an HTML node. The
541
- node may be an element, a text node, a comment, a CDATA node, or a document
542
- fragment. Use Nokogiri's inspection methods (`element?`, `text?`, etc.) to
543
- selectively ignore node types you aren't interested in.
456
+ * **:node** - A `Nokogiri::XML::Node` object representing an HTML node. The node may be an element, a text node, a comment, a CDATA node, or a document fragment. Use Nokogiri's inspection methods (`element?`, `text?`, etc.) to selectively ignore node types you aren't interested in.
544
457
 
545
- * **:node_allowlist** - Set of `Nokogiri::XML::Node` objects in the current
546
- document that have been allowlisted by previous transformers, if any. It's
547
- generally bad form to remove a node that a previous transformer has
548
- allowlisted.
458
+ * **:node_allowlist** - Set of `Nokogiri::XML::Node` objects in the current document that have been allowlisted by previous transformers, if any. It's generally bad form to remove a node that a previous transformer has allowlisted.
549
459
 
550
- * **:node_name** - The name of the current HTML node, always lowercase (e.g.
551
- "div" or "span"). For non-element nodes, the name will be something like
552
- "text", "comment", "#cdata-section", "#document-fragment", etc.
460
+ * **:node_name** - The name of the current HTML node, always lowercase (e.g. "div" or "span"). For non-element nodes, the name will be something like "text", "comment", "#cdata-section", "#document-fragment", etc.
553
461
 
554
462
  ### Output
555
463
 
556
- A transformer doesn't have to return anything, but may optionally return a Hash,
557
- which may contain the following items:
464
+ A transformer doesn't have to return anything, but may optionally return a Hash, which may contain the following items:
558
465
 
559
- * **:node_allowlist** - Array or Set of specific `Nokogiri::XML::Node`
560
- objects to add to the document's allowlist, bypassing the current Sanitize
561
- config. These specific nodes and all their attributes will be allowlisted,
562
- but their children will not be.
466
+ * **:node_allowlist** - Array or Set of specific `Nokogiri::XML::Node` objects to add to the document's allowlist, bypassing the current Sanitize config. These specific nodes and all their attributes will be allowlisted, but their children will not be.
563
467
 
564
- If a transformer returns anything other than a Hash, the return value will be
565
- ignored.
468
+ If a transformer returns anything other than a Hash, the return value will be ignored.
566
469
 
567
470
  ### Processing
568
471
 
569
- Each transformer has full access to the `Nokogiri::XML::Node` that's passed into
570
- it and to the rest of the document via the node's `document()` method. Any
571
- changes made to the current node or to the document will be reflected instantly
572
- in the document and passed on to subsequently called transformers and to
573
- Sanitize itself. A transformer may even call Sanitize internally to perform
574
- custom sanitization if needed.
472
+ Each transformer has full access to the `Nokogiri::XML::Node` that's passed into it and to the rest of the document via the node's `document()` method. Any changes made to the current node or to the document will be reflected instantly in the document and passed on to subsequently called transformers and to Sanitize itself. A transformer may even call Sanitize internally to perform custom sanitization if needed.
575
473
 
576
- Nodes are passed into transformers in the order in which they're traversed.
577
- Sanitize performs top-down traversal, meaning that nodes are traversed in the
578
- same order you'd read them in the HTML, starting at the top node, then its first
579
- child, and so on.
474
+ Nodes are passed into transformers in the order in which they're traversed. Sanitize performs top-down traversal, meaning that nodes are traversed in the same order you'd read them in the HTML, starting at the top node, then its first child, and so on.
580
475
 
581
476
  ```ruby
582
477
  html = %[
@@ -595,81 +490,76 @@ transformer = lambda do |env|
595
490
  end
596
491
 
597
492
  # Prints "header", "span", "strong", "p", "footer".
598
- Sanitize.fragment(html, :transformers => transformer)
493
+ Sanitize.fragment(html, transformers: transformer)
599
494
  ```
600
495
 
601
- Transformers have a tremendous amount of power, including the power to
602
- completely bypass Sanitize's built-in filtering. Be careful! Your safety is in
603
- your own hands.
496
+ Transformers have a tremendous amount of power, including the power to completely bypass Sanitize's built-in filtering. Be careful! Your safety is in your own hands.
604
497
 
605
498
  ### Example: Transformer to allow image URLs by domain
606
499
 
607
- The following example demonstrates how to remove image elements unless they use
608
- a relative URL or are hosted on a specific domain. It assumes that the `<img>`
609
- element and its `src` attribute are already allowlisted.
500
+ The following example demonstrates how to remove image elements unless they use a relative URL or are hosted on a specific domain. It assumes that the `<img>` element and its `src` attribute are already allowlisted.
610
501
 
611
502
  ```ruby
612
- require 'uri'
503
+ require "uri"
613
504
 
614
505
  image_allowlist_transformer = lambda do |env|
615
506
  # Ignore everything except <img> elements.
616
- return unless env[:node_name] == 'img'
507
+ return unless env[:node_name] == "img"
617
508
 
618
- node = env[:node]
619
- image_uri = URI.parse(node['src'])
509
+ node = env[:node]
510
+ image_uri = URI.parse(node["src"])
620
511
 
621
512
  # Only allow relative URLs or URLs with the example.com domain. The
622
513
  # image_uri.host.nil? check ensures that protocol-relative URLs like
623
- # "//evil.com/foo.jpg".
624
- unless image_uri.host == 'example.com' || (image_uri.host.nil? && image_uri.relative?)
625
- node.unlink # `Nokogiri::XML::Node#unlink` removes a node from the document
514
+ # "//evil.com/foo.jpg" are not allowed.
515
+ unless image_uri.host == "example.com"
516
+ unless image_uri.host.nil? && image_uri.relative?
517
+ node.unlink # `Nokogiri::XML::Node#unlink` removes a node from the document
518
+ end
626
519
  end
627
520
  end
628
521
  ```
629
522
 
630
523
  ### Example: Transformer to allow YouTube video embeds
631
524
 
632
- The following example demonstrates how to create a transformer that will safely
633
- allow valid YouTube video embeds without having to allow other kinds of embedded
634
- content, which would be the case if you tried to do this by just allowing all
635
- `<iframe>` elements:
525
+ The following example demonstrates how to create a transformer that will safely allow valid YouTube video embeds without having to allow other kinds of embedded content, which would be the case if you tried to do this by just allowing all `<iframe>` elements:
636
526
 
637
527
  ```ruby
638
528
  youtube_transformer = lambda do |env|
639
- node = env[:node]
529
+ node = env[:node]
640
530
  node_name = env[:node_name]
641
531
 
642
532
  # Don't continue if this node is already allowlisted or is not an element.
643
533
  return if env[:is_allowlisted] || !node.element?
644
534
 
645
535
  # Don't continue unless the node is an iframe.
646
- return unless node_name == 'iframe'
536
+ return unless node_name == "iframe"
647
537
 
648
538
  # Verify that the video URL is actually a valid YouTube video URL.
649
- return unless node['src'] =~ %r|\A(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/|
539
+ return unless %r{\A(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/}.match?(node["src"])
650
540
 
651
541
  # We're now certain that this is a YouTube embed, but we still need to run
652
542
  # it through a special Sanitize step to ensure that no unwanted elements or
653
543
  # attributes that don't belong in a YouTube embed can sneak in.
654
544
  Sanitize.node!(node, {
655
- :elements => %w[iframe],
545
+ elements: %w[iframe],
656
546
 
657
- :attributes => {
658
- 'iframe' => %w[allowfullscreen frameborder height src width]
547
+ attributes: {
548
+ "iframe" => %w[allowfullscreen frameborder height src width]
659
549
  }
660
550
  })
661
551
 
662
552
  # Now that we're sure that this is a valid YouTube embed and that there are
663
553
  # no unwanted elements or attributes hidden inside it, we can tell Sanitize
664
554
  # to allowlist the current node.
665
- {:node_allowlist => [node]}
555
+ {node_allowlist: [node]}
666
556
  end
667
557
 
668
558
  html = %[
669
559
  <iframe width="420" height="315" src="//www.youtube.com/embed/dQw4w9WgXcQ"
670
560
  frameborder="0" allowfullscreen></iframe>
671
- ]
561
+ ].strip
672
562
 
673
- Sanitize.fragment(html, :transformers => youtube_transformer)
563
+ Sanitize.fragment(html, transformers: youtube_transformer)
674
564
  # => '<iframe width="420" height="315" src="//www.youtube.com/embed/dQw4w9WgXcQ" frameborder="0" allowfullscreen=""></iframe>'
675
565
  ```