fetch_remote_account_service.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # frozen_string_literal: true
  2. class ActivityPub::FetchRemoteAccountService < BaseService
  3. include JsonLdHelper
  4. # Should be called when uri has already been checked for locality
  5. # Does a WebFinger roundtrip on each call
  6. def call(uri, id: true, prefetched_body: nil)
  7. @json = if prefetched_body.nil?
  8. fetch_resource(uri, id)
  9. else
  10. body_to_json(prefetched_body)
  11. end
  12. return unless supported_context? && expected_type?
  13. @uri = @json['id']
  14. @username = @json['preferredUsername']
  15. @domain = Addressable::URI.parse(@uri).normalized_host
  16. return unless verified_webfinger?
  17. ActivityPub::ProcessAccountService.new.call(@username, @domain, @json)
  18. rescue Oj::ParseError
  19. nil
  20. end
  21. private
  22. def verified_webfinger?
  23. webfinger = Goldfinger.finger("acct:#{@username}@#{@domain}")
  24. confirmed_username, confirmed_domain = split_acct(webfinger.subject)
  25. return webfinger.link('self')&.href == @uri if @username.casecmp(confirmed_username).zero? && @domain.casecmp(confirmed_domain).zero?
  26. webfinger = Goldfinger.finger("acct:#{confirmed_username}@#{confirmed_domain}")
  27. @username, @domain = split_acct(webfinger.subject)
  28. self_reference = webfinger.link('self')
  29. return false unless @username.casecmp(confirmed_username).zero? && @domain.casecmp(confirmed_domain).zero?
  30. return false if self_reference&.href != @uri
  31. true
  32. rescue Goldfinger::Error
  33. false
  34. end
  35. def split_acct(acct)
  36. acct.gsub(/\Aacct:/, '').split('@')
  37. end
  38. def supported_context?
  39. super(@json)
  40. end
  41. def expected_type?
  42. @json['type'] == 'Person'
  43. end
  44. end