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. include WebfingerHelper
  6. SUPPORTED_TYPES = %w(Application Group Organization Person Service).freeze
  7. # Does a WebFinger roundtrip on each call, unless `only_key` is true
  8. def call(uri, id: true, prefetched_body: nil, break_on_redirect: false, only_key: false)
  9. return if domain_not_allowed?(uri)
  10. return ActivityPub::TagManager.instance.uri_to_resource(uri, Account) if ActivityPub::TagManager.instance.local_uri?(uri)
  11. @json = begin
  12. if prefetched_body.nil?
  13. fetch_resource(uri, id)
  14. else
  15. body_to_json(prefetched_body, compare_id: id ? uri : nil)
  16. end
  17. end
  18. return if !supported_context? || !expected_type? || (break_on_redirect && @json['movedTo'].present?)
  19. @uri = @json['id']
  20. @username = @json['preferredUsername']
  21. @domain = Addressable::URI.parse(@uri).normalized_host
  22. return unless only_key || verified_webfinger?
  23. ActivityPub::ProcessAccountService.new.call(@username, @domain, @json, only_key: only_key)
  24. rescue Oj::ParseError
  25. nil
  26. end
  27. private
  28. def verified_webfinger?
  29. webfinger = webfinger!("acct:#{@username}@#{@domain}")
  30. confirmed_username, confirmed_domain = split_acct(webfinger.subject)
  31. return webfinger.link('self', 'href') == @uri if @username.casecmp(confirmed_username).zero? && @domain.casecmp(confirmed_domain).zero?
  32. webfinger = webfinger!("acct:#{confirmed_username}@#{confirmed_domain}")
  33. @username, @domain = split_acct(webfinger.subject)
  34. return false unless @username.casecmp(confirmed_username).zero? && @domain.casecmp(confirmed_domain).zero?
  35. return false if webfinger.link('self', 'href') != @uri
  36. true
  37. rescue Webfinger::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