The code powering m.abunchtell.com https://m.abunchtell.com
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.
 
 
 
 

71 line
1.6 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. end
  12. def on_behalf_of(account)
  13. raise ArgumentError unless account.local?
  14. @account = account
  15. end
  16. def add_headers(new_headers)
  17. @headers.merge!(new_headers)
  18. end
  19. def perform
  20. http_client.headers(headers).public_send(@verb, @url.to_s, @options)
  21. end
  22. def headers
  23. (@account ? @headers.merge('Signature' => signature) : @headers).without(REQUEST_TARGET)
  24. end
  25. private
  26. def set_common_headers!
  27. @headers[REQUEST_TARGET] = "#{@verb} #{@url.path}"
  28. @headers['User-Agent'] = user_agent
  29. @headers['Host'] = @url.host
  30. @headers['Date'] = Time.now.utc.httpdate
  31. end
  32. def signature
  33. key_id = @account.to_webfinger_s
  34. algorithm = 'rsa-sha256'
  35. signature = Base64.strict_encode64(@account.keypair.sign(OpenSSL::Digest::SHA256.new, signed_string))
  36. "keyId=\"#{key_id}\",algorithm=\"#{algorithm}\",headers=\"#{signed_headers}\",signature=\"#{signature}\""
  37. end
  38. def signed_string
  39. @headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  40. end
  41. def signed_headers
  42. @headers.keys.join(' ').downcase
  43. end
  44. def user_agent
  45. @user_agent ||= "#{HTTP::Request::USER_AGENT} (Mastodon/#{Mastodon::Version}; +#{root_url})"
  46. end
  47. def timeout
  48. { write: 10, connect: 10, read: 10 }
  49. end
  50. def http_client
  51. HTTP.timeout(:per_operation, timeout).follow
  52. end
  53. end