verify_link_service.rb 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # frozen_string_literal: true
  2. class VerifyLinkService < BaseService
  3. def call(field)
  4. @link_back = ActivityPub::TagManager.instance.url_for(field.account)
  5. @url = field.value_for_verification
  6. perform_request!
  7. return unless link_back_present?
  8. field.mark_verified!
  9. rescue OpenSSL::SSL::SSLError, HTTP::Error, Addressable::URI::InvalidURIError, Mastodon::HostValidationError, Mastodon::LengthValidationError, IPAddr::AddressFamilyError => e
  10. Rails.logger.debug { "Error fetching link #{@url}: #{e}" }
  11. nil
  12. end
  13. private
  14. def perform_request!
  15. @body = Request.new(:get, @url).add_headers('Accept' => 'text/html').perform do |res|
  16. res.code == 200 ? res.body_with_limit : nil
  17. end
  18. end
  19. def link_back_present?
  20. return false if @body.blank?
  21. links = Nokogiri::HTML5(@body).xpath('//a[contains(concat(" ", normalize-space(@rel), " "), " me ")]|//link[contains(concat(" ", normalize-space(@rel), " "), " me ")]')
  22. if links.any? { |link| link['href']&.downcase == @link_back.downcase }
  23. true
  24. elsif links.empty?
  25. false
  26. else
  27. link_redirects_back?(links.first['href'])
  28. end
  29. end
  30. def link_redirects_back?(test_url)
  31. return false if test_url.blank?
  32. redirect_to_url = Request.new(:head, test_url, follow: false).perform do |res|
  33. res.headers['Location']
  34. end
  35. redirect_to_url == @link_back
  36. end
  37. end