Sha256: 5f45fa49b8b2247fe405ae28f2b4e5ee11ec28ae9836aca38cf6c9e042151983

Contents?: true

Size: 1.46 KB

Versions: 73

Compression:

Stored size: 1.46 KB

Contents

# frozen_string_literal: true

# modified from https://gist.github.com/ivan-kolmychek/ee2fdc53f3e2c637271d

module Commonmeta
  class WhitelistScrubber < Loofah::Scrubber
    def initialize(options = {})
      @direction = :bottom_up
      @tags = options[:tags]
      @attributes = options[:attributes]
    end

    def scrub(node)
      scrub_node_attributes(node) and return CONTINUE if node_allowed?(node)

      node.before node.children
      node.remove
    end

    private

    def scrub_node_attributes(node)
      unless @attributes.present? && @attributes.respond_to?(:include?)
        fallback_scrub_node_attributes(node) and return true
      end

      node.attribute_nodes.each do |attr_node|
        attr_node.remove unless @attributes.include?(attr_node.name)
      end
    end

    def allowed_not_element_node_types
      [Nokogiri::XML::Node::TEXT_NODE, Nokogiri::XML::Node::CDATA_SECTION_NODE]
    end

    def fallback_scrub_node_attributes(node)
      Loofah::HTML5::Scrub.scrub_attributes(node)
    end

    def fallback_allowed_element_detection(node)
      Loofah::HTML5::Scrub.allowed_element?(node.name)
    end

    def node_allowed?(node)
      unless @tags.present? && @tags.respond_to?(:include?)
        return fallback_allowed_element_detection(node)
      end
      return true if allowed_not_element_node_types.include?(node.type)
      return false unless node.type == Nokogiri::XML::Node::ELEMENT_NODE

      @tags.include? node.name
    end
  end
end

Version data entries

73 entries across 73 versions & 1 rubygems

Version Path
commonmeta-ruby-3.3.5 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.3.4 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.3.3 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.3.2 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.3.1 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.3 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.15 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.14 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.13 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.12 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.11 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.10 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.9 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.8 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.7 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.6 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.5 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.4 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.3 lib/commonmeta/whitelist_scrubber.rb
commonmeta-ruby-3.2.2 lib/commonmeta/whitelist_scrubber.rb