File: clean_css.rb

package info (click to toggle)
ruby-sanitize 4.6.6-2.1~deb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 528 kB
  • sloc: ruby: 2,837; makefile: 5
file content (57 lines) | stat: -rw-r--r-- 1,292 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class Sanitize; module Transformers; module CSS

# Enforces a CSS whitelist on the contents of `style` attributes.
class CleanAttribute
  def initialize(sanitizer_or_config)
    if Sanitize::CSS === sanitizer_or_config
      @scss = sanitizer_or_config
    else
      @scss = Sanitize::CSS.new(sanitizer_or_config)
    end
  end

  def call(env)
    node = env[:node]

    return unless node.type == Nokogiri::XML::Node::ELEMENT_NODE &&
        node.key?('style') && !env[:is_whitelisted]

    attr = node.attribute('style')
    css  = @scss.properties(attr.value)

    if css.strip.empty?
      attr.unlink
    else
      attr.value = css
    end
  end
end

# Enforces a CSS whitelist on the contents of `<style>` elements.
class CleanElement
  def initialize(sanitizer_or_config)
    if Sanitize::CSS === sanitizer_or_config
      @scss = sanitizer_or_config
    else
      @scss = Sanitize::CSS.new(sanitizer_or_config)
    end
  end

  def call(env)
    node = env[:node]

    return unless node.type == Nokogiri::XML::Node::ELEMENT_NODE &&
        env[:node_name] == 'style'

    css = @scss.stylesheet(node.content)

    if css.strip.empty?
      node.unlink
    else
      node.children.unlink
      node << Nokogiri::XML::Text.new(css, node.document)
    end
  end
end

end; end; end