You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.7 KiB

  1. # frozen_string_literal: true
  2. class ActivityPub::FetchRepliesService < BaseService
  3. include JsonLdHelper
  4. def call(parent_status, collection_or_uri, allow_synchronous_requests = true)
  5. @account = parent_status.account
  6. @allow_synchronous_requests = allow_synchronous_requests
  7. @items = collection_items(collection_or_uri)
  8. return if @items.nil?
  9. FetchReplyWorker.push_bulk(filtered_replies)
  10. @items
  11. end
  12. private
  13. def collection_items(collection_or_uri)
  14. collection = fetch_collection(collection_or_uri)
  15. return unless collection.is_a?(Hash)
  16. collection = fetch_collection(collection['first']) if collection['first'].present?
  17. return unless collection.is_a?(Hash)
  18. case collection['type']
  19. when 'Collection', 'CollectionPage'
  20. collection['items']
  21. when 'OrderedCollection', 'OrderedCollectionPage'
  22. collection['orderedItems']
  23. end
  24. end
  25. def fetch_collection(collection_or_uri)
  26. return collection_or_uri if collection_or_uri.is_a?(Hash)
  27. return unless @allow_synchronous_requests
  28. return if invalid_origin?(collection_or_uri)
  29. collection = fetch_resource_without_id_validation(collection_or_uri)
  30. raise Mastodon::UnexpectedResponseError if collection.nil?
  31. collection
  32. end
  33. def filtered_replies
  34. # Only fetch replies to the same server as the original status to avoid
  35. # amplification attacks.
  36. # Also limit to 5 fetched replies to limit potential for DoS.
  37. @items.map { |item| value_or_id(item) }.reject { |uri| invalid_origin?(uri) }.take(5)
  38. end
  39. def invalid_origin?(url)
  40. return true if unsupported_uri_scheme?(url)
  41. needle = Addressable::URI.parse(url).host
  42. haystack = Addressable::URI.parse(@account.uri).host
  43. !haystack.casecmp(needle).zero?
  44. end
  45. end