闭社主体 forked from https://github.com/tootsuite/mastodon
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.

88 lines
2.0 KiB

  1. # frozen_string_literal: true
  2. class Request
  3. REQUEST_TARGET = '(request-target)'
  4. include RoutingHelper
  5. def initialize(verb, url, options = {})
  6. @verb = verb
  7. @url = Addressable::URI.parse(url).normalize
  8. @options = options
  9. @headers = {}
  10. set_common_headers!
  11. set_digest! if options.key?(:body)
  12. end
  13. def on_behalf_of(account, key_id_format = :acct)
  14. raise ArgumentError unless account.local?
  15. @account = account
  16. @key_id_format = key_id_format
  17. self
  18. end
  19. def add_headers(new_headers)
  20. @headers.merge!(new_headers)
  21. self
  22. end
  23. def perform
  24. http_client.headers(headers).public_send(@verb, @url.to_s, @options)
  25. end
  26. def headers
  27. (@account ? @headers.merge('Signature' => signature) : @headers).without(REQUEST_TARGET)
  28. end
  29. private
  30. def set_common_headers!
  31. @headers[REQUEST_TARGET] = "#{@verb} #{@url.path}"
  32. @headers['User-Agent'] = user_agent
  33. @headers['Host'] = @url.host
  34. @headers['Date'] = Time.now.utc.httpdate
  35. end
  36. def set_digest!
  37. @headers['Digest'] = "SHA-256=#{Digest::SHA256.base64digest(@options[:body])}"
  38. end
  39. def signature
  40. algorithm = 'rsa-sha256'
  41. signature = Base64.strict_encode64(@account.keypair.sign(OpenSSL::Digest::SHA256.new, signed_string))
  42. "keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers}\",signature=\"#{signature}\""
  43. end
  44. def signed_string
  45. @headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  46. end
  47. def signed_headers
  48. @headers.keys.join(' ').downcase
  49. end
  50. def user_agent
  51. @user_agent ||= "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::Version}; +#{root_url})"
  52. end
  53. def key_id
  54. case @key_id_format
  55. when :acct
  56. @account.to_webfinger_s
  57. when :uri
  58. [ActivityPub::TagManager.instance.uri_for(@account), '#main-key'].join
  59. end
  60. end
  61. def timeout
  62. { write: 10, connect: 10, read: 10 }
  63. end
  64. def http_client
  65. HTTP.timeout(:per_operation, timeout).follow
  66. end
  67. end