Skip to content

Commit

Permalink
feat: sanitize links in alt of img tag
Browse files Browse the repository at this point in the history
  • Loading branch information
taleksei committed Aug 30, 2023
1 parent 7848491 commit bed389b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/string_tools.rb
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ def call(env)
normalize_link node, 'href'
when 'img'
normalize_link node, 'src'
remove_links node, 'alt'
end
end

Expand All @@ -210,6 +211,14 @@ def normalize_link(node, attr_name)
rescue Addressable::URI::InvalidURIError
node.swap node.children
end

def remove_links(node, attr_name)
return unless node[attr_name]

node[attr_name] = node[attr_name].gsub(URI::DEFAULT_PARSER.make_regexp, '').squish

node.remove_attribute(attr_name) if node[attr_name].empty?
end
end

class IframeNormalizer
Expand Down
12 changes: 12 additions & 0 deletions spec/string_tools_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,18 @@
expect(sanitized_string).to eq('<style type="text/css">body{color: red;}</style>')
end

it 'removes links in alt attribute of img tag' do
origin_str = '<img scr="http://test.test" alt="http://test.test test https://test.test alt">'
sanitized_string = described_class.sanitize(origin_str, 'img' => %w(scr alt))
expect(sanitized_string).to eq('<img scr="http://test.test" alt="test alt">')
end

it 'removes alt attribute of img tag if empty value' do
origin_str = '<img scr="http://test.test" alt="http://test.test">'
sanitized_string = described_class.sanitize(origin_str, 'img' => %w(scr alt))
expect(sanitized_string).to eq('<img scr="http://test.test">')
end

context 'multiple invocations of the method' do
it 'does not mess up default config' do
origin_str = '<p style="text-align: center;" title="foobar"></p>'
Expand Down

0 comments on commit bed389b

Please sign in to comment.