FEATURE: Remove user IDs from internal URLs. (#7406)

FEATURE: Remove user IDs from internal URLs. (#7406)

diff --git a/lib/cooked_post_processor.rb b/lib/cooked_post_processor.rb
index 17ae738..2094913 100644
--- a/lib/cooked_post_processor.rb
+++ b/lib/cooked_post_processor.rb
@@ -40,6 +40,7 @@ class CookedPostProcessor
       post_process_images
       post_process_quotes
       optimize_urls
+      remove_user_ids
       update_post_image
       enforce_nofollow
       pull_hotlinked_images(bypass_bump)
@@ -595,6 +596,19 @@ class CookedPostProcessor
     end
   end
 
+  def remove_user_ids
+    @doc.css("a[href]").each do |a|
+      uri = URI(a["href"])
+      next if uri.hostname != Discourse.current_hostname
+
+      query = Rack::Utils.parse_nested_query(uri.query)
+      next if !query.delete("u")
+
+      uri.query = query.map { |k, v| "#{k}=#{v}" }.join("&").presence
+      a["href"] = uri.to_s
+    end
+  end
+
   def enforce_nofollow
     if !@cooking_options[:omit_nofollow] && SiteSetting.add_rel_nofollow_to_user_content
       PrettyText.add_rel_nofollow_to_user_content(@doc)
diff --git a/spec/components/cooked_post_processor_spec.rb b/spec/components/cooked_post_processor_spec.rb
index 9ff50b2..352cc68 100644
--- a/spec/components/cooked_post_processor_spec.rb
+++ b/spec/components/cooked_post_processor_spec.rb
@@ -1037,6 +1037,30 @@ describe CookedPostProcessor do
 
   end
 
+  context "#remove_user_ids" do
+    let(:topic) { Fabricate(:topic) }
+
+    let(:post) do
+      Fabricate(:post, raw: <<~RAW)
+        link to a topic: #{topic.url}?u=foo
+
+        a tricky link to a topic: #{topic.url}?bob=bob;u=sam&jane=jane
+
+        link to an external topic: https://google.com/?u=bar
+      RAW
+    end
+
+    let(:cpp) { CookedPostProcessor.new(post, disable_loading_image: true) }
+
+    it "does remove user ids" do
+      cpp.remove_user_ids
+
+      expect(cpp.html).to have_tag('a', with: { href: topic.url })
+      expect(cpp.html).to have_tag('a', with: { href: "#{topic.url}?bob=bob&jane=jane" })
+      expect(cpp.html).to have_tag('a', with: { href: "https://google.com/?u=bar" })
+    end
+  end
+
   context "#pull_hotlinked_images" do
 
     let(:post) { build(:post, created_at: 20.days.ago) }

GitHub sha: b706a1b0

1 Like