Skip to content

Commit

Permalink
Preserve rel=me on links in rich text
Browse files Browse the repository at this point in the history
Fixes #3859
  • Loading branch information
tomhughes committed Dec 29, 2022
1 parent 600ed78 commit 6033359
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .rubocop_todo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ Minitest/EmptyLineBeforeAssertionMethods:

# Offense count: 560
Minitest/MultipleAssertions:
Max: 52
Max: 54

# Offense count: 1
# Configuration parameters: NamePrefix, ForbiddenPrefixes, AllowedMethods, MethodDefinitionMacros.
Expand Down
7 changes: 6 additions & 1 deletion config/initializers/sanitize.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
Sanitize::Config::OSM = Sanitize::Config.merge(
Sanitize::Config::RELAXED,
:elements => Sanitize::Config::RELAXED[:elements] - %w[div style],
:add_attributes => { "a" => { "rel" => "nofollow noopener noreferrer" } },
:remove_contents => %w[script style],
:transformers => lambda do |env|
env[:node].remove_class
env[:node].kwattr_remove("style", nil)
env[:node].add_class("table table-sm w-auto") if env[:node_name] == "table"

if env[:node_name] == "a"
rel = env[:node]["rel"] || ""

env[:node]["rel"] = rel.split.select { |r| r == "me" }.append("nofollow", "noopener", "noreferrer").sort.join(" ")
end
end
)
14 changes: 14 additions & 0 deletions test/lib/rich_text_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ def test_html_to_html
assert_select "a[rel='nofollow noopener noreferrer']", 1
end

r = RichText.new("html", "foo <a rel='junk me trash' href='http://example.com/'>bar</a> baz")
assert_html r do
assert_select "a", 1
assert_select "a[href='http://example.com/']", 1
assert_select "a[rel='me nofollow noopener noreferrer']", 1
end

r = RichText.new("html", "foo example@example.com bar")
assert_html r do
assert_select "a", 0
Expand Down Expand Up @@ -91,6 +98,13 @@ def test_markdown_to_html
assert_select "a[rel='nofollow noopener noreferrer']", 1
end

r = RichText.new("markdown", "foo <a rel='junk me trash' href='http://example.com/'>bar</a>) baz")
assert_html r do
assert_select "a", 1
assert_select "a[href='http://example.com/']", 1
assert_select "a[rel='me nofollow noopener noreferrer']", 1
end

r = RichText.new("markdown", "foo example@example.com bar")
assert_html r do
assert_select "a", 1
Expand Down

0 comments on commit 6033359

Please sign in to comment.