diff --git a/app/logical/note_sanitizer.rb b/app/logical/note_sanitizer.rb index 27ca58345..9fa18cf3c 100644 --- a/app/logical/note_sanitizer.rb +++ b/app/logical/note_sanitizer.rb @@ -73,7 +73,20 @@ module NoteSanitizer at_rules: [], protocols: [], properties: ALLOWED_PROPERTIES, - } + }, + :transformers => method(:relativize_links), ) end + + def self.relativize_links(node:, **env) + return unless node.name == "a" && node.attribute("href") + + href = node.attribute("href") + url = Addressable::URI.parse(href.value).normalize + + if url.authority.in?(Danbooru.config.hostnames) + url.site = nil + href.value = url.to_s + end + end end diff --git a/config/danbooru_default_config.rb b/config/danbooru_default_config.rb index 662f79b71..bac24967e 100644 --- a/config/danbooru_default_config.rb +++ b/config/danbooru_default_config.rb @@ -20,11 +20,17 @@ module Danbooru "Find good anime art fast" end - # The hostname of the server. + # The canonical hostname of the site. def hostname Socket.gethostname end + # The list of all domain names this site is accessible under. + # Example: %w[danbooru.donmai.us sonohara.donmai.us hijiribe.donmai.us safebooru.donmai.us] + def hostnames + [hostname] + end + # Contact email address of the admin. def contact_email "webmaster@#{server_host}" diff --git a/test/unit/note_sanitizer_test.rb b/test/unit/note_sanitizer_test.rb index e87ed67d7..bebacb3ae 100644 --- a/test/unit/note_sanitizer_test.rb +++ b/test/unit/note_sanitizer_test.rb @@ -21,5 +21,12 @@ class NoteSanitizerTest < ActiveSupport::TestCase body = 'google' assert_equal('google', NoteSanitizer.sanitize(body)) end + + should "rewrite absolute links to relative links" do + Danbooru.config.stubs(:hostnames).returns(%w[danbooru.donmai.us sonohara.donmai.us hijiribe.donmai.us]) + + body = 'touhou' + assert_equal('touhou', NoteSanitizer.sanitize(body)) + end end end