fetch_remote_account_service.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # frozen_string_literal: true
  2. class ActivityPub::FetchRemoteAccountService < BaseService
  3. include JsonLdHelper
  4. include DomainControlHelper
  5. SUPPORTED_TYPES = %w(Application Group Organization Person Service).freeze
  6. # Does a WebFinger roundtrip on each call, unless `only_key` is true
  7. def call(uri, id: true, prefetched_body: nil, break_on_redirect: false, only_key: false)
  8. return if domain_not_allowed?(uri)
  9. return ActivityPub::TagManager.instance.uri_to_resource(uri, Account) if ActivityPub::TagManager.instance.local_uri?(uri)
  10. @json = begin
  11. if prefetched_body.nil?
  12. fetch_resource(uri, id)
  13. else
  14. body_to_json(prefetched_body, compare_id: id ? uri : nil)
  15. end
  16. end
  17. return if !supported_context? || !expected_type? || (break_on_redirect && @json['movedTo'].present?)
  18. @uri = @json['id']
  19. @username = @json['preferredUsername']
  20. @domain = Addressable::URI.parse(@uri).normalized_host
  21. return unless only_key || verified_webfinger?
  22. ActivityPub::ProcessAccountService.new.call(@username, @domain, @json, only_key: only_key)
  23. rescue Oj::ParseError
  24. nil
  25. end
  26. private
  27. def verified_webfinger?
  28. webfinger = Goldfinger.finger("acct:#{@username}@#{@domain}")
  29. confirmed_username, confirmed_domain = split_acct(webfinger.subject)
  30. return webfinger.link('self')&.href == @uri if @username.casecmp(confirmed_username).zero? && @domain.casecmp(confirmed_domain).zero?
  31. webfinger = Goldfinger.finger("acct:#{confirmed_username}@#{confirmed_domain}")
  32. @username, @domain = split_acct(webfinger.subject)
  33. self_reference = webfinger.link('self')
  34. return false unless @username.casecmp(confirmed_username).zero? && @domain.casecmp(confirmed_domain).zero?
  35. return false if self_reference&.href != @uri
  36. true
  37. rescue Goldfinger::Error
  38. false
  39. end
  40. def split_acct(acct)
  41. acct.gsub(/\Aacct:/, '').split('@')
  42. end
  43. def supported_context?
  44. super(@json)
  45. end
  46. def expected_type?
  47. equals_or_includes_any?(@json['type'], SUPPORTED_TYPES)
  48. end
  49. end