Sha256: 641777ffb0be164d6c7f9b468e36b47bf112bb45308403a31cba8e7ad1e2aaef

Contents?: true

Size: 1.9 KB

Versions: 3

Compression:

Stored size: 1.9 KB

Contents

require "chatwork_webhook_verify/configuration"
require "chatwork_webhook_verify/railtie" if defined?(Rails)

module ChatworkWebhookVerify
  require "base64"
  require "openssl"

  class InvalidSignatureError < StandardError; end

  # Whether signature is valid
  #
  # @param token     [String] webhook token (default: `ChatworkWebhookVerify.config.token`)
  # @param body      [String] request body
  # @param signature [String] chatwork_webhook_signature or X-ChatWorkWebhookSignature
  #
  # @return [Boolean]
  #
  # @note Either `token` or `ChatworkWebhookVerify.config.token` is required
  def self.verify?(token: nil, body:, signature:)
    token ||= config.token

    raise ArgumentError, "Either token or ChatworkWebhookVerify.config.token is required" if !token || token.empty?
    raise ArgumentError, "signature is required" if !signature || signature.empty?

    generate_signature(token: token, body: body) == signature
  end

  # Whether signature is valid
  #
  # @param token     [String] webhook token (default: `ChatworkWebhookVerify.config.token`)
  # @param body      [String] request body
  # @param signature [String] chatwork_webhook_signature or X-ChatWorkWebhookSignature
  #
  # @raise [InvalidSignatureError] signature is invalid
  #
  # @note Either `token` or `ChatworkWebhookVerify.config.token` is required
  def self.verify!(token: nil, body:, signature:)
    raise InvalidSignatureError unless verify?(token: token, body: body, signature: signature)
  end

  # @param token [String] webhook token (default: `ChatworkWebhookVerify.config.token`)
  # @param body  [String] request body
  #
  # @return [String]
  def self.generate_signature(token:, body:)
    secret_key = Base64.decode64(token)
    Base64.strict_encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha256"), secret_key, body))
  end

  # @return [ChatworkWebhookVerify::Configuration]
  def self.config
    @config ||= Configuration.new
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
chatwork_webhook_verify-1.0.0 lib/chatwork_webhook_verify.rb
chatwork_webhook_verify-0.1.1 lib/chatwork_webhook_verify.rb
chatwork_webhook_verify-0.1.0 lib/chatwork_webhook_verify.rb