Sha256: 9a2a8dd3645d25ad86cbad8baaa41ec0fc90bb4630fe7c78682fdfa509666961

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

require "openssl"
require "ostruct"
require "json"

module EventSubEvents
  class SignatureVerifier
    def initialize(request)
      @request = request
    end

    def verify
      request = @request

      message_id = request.headers["Twitch-Eventsub-Message-Id"]
      timestamp  = request.headers["Twitch-Eventsub-Message-Timestamp"]
      signature  = request.headers["Twitch-Eventsub-Message-Signature"].gsub("sha256=", "")
      body       = request.body.read

      hmac_message = message_id + timestamp + body

      secrets = EventSubEvents.signing_secrets if EventSubEvents.signing_secret

      secrets.each_with_index do |secret, i|
        begin
          hex = OpenSSL::HMAC.hexdigest('sha256', secret, hmac_message)
          return validate(hex, signature)
        rescue EventSubEvents::SignatureVerificationError
          raise if i == secrets.length - 1
          next
        end
      end
    end

    def reconstruct_event
      body = @request.body.read
      JSON.parse(body, object_class: OpenStruct)
    end

    private

    def validate(hex, signature)
      if ActiveSupport::SecurityUtils::secure_compare(hex, signature)
        true
      else
        raise EventSubEvents::SignatureVerificationError
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
event_sub_events-0.1.0 lib/event_sub_events/signature_verifier.rb