Class: StandardWebhooks::Webhook
- Inherits:
-
Object
- Object
- StandardWebhooks::Webhook
- Defined in:
- lib/standardwebhooks/webhooks.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(secret) ⇒ Webhook
constructor
A new instance of Webhook.
- #sign(msg_id, timestamp, payload) ⇒ Object
- #verify(payload, headers) ⇒ Object
Constructor Details
#initialize(secret) ⇒ Webhook
Returns a new instance of Webhook.
15 16 17 18 19 20 21 |
# File 'lib/standardwebhooks/webhooks.rb', line 15 def initialize(secret) if secret.start_with?(SECRET_PREFIX) secret = secret[SECRET_PREFIX.length..-1] end @secret = Base64.decode64(secret) end |
Class Method Details
.new_using_raw_bytes(secret) ⇒ Object
11 12 13 |
# File 'lib/standardwebhooks/webhooks.rb', line 11 def self.new_using_raw_bytes(secret) self.new(secret.pack("C*").force_encoding("UTF-8")) end |
Instance Method Details
#sign(msg_id, timestamp, payload) ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/standardwebhooks/webhooks.rb', line 53 def sign(msg_id, , payload) begin now = Integer() rescue raise WebhookSigningError, "Invalid timestamp" end to_sign = "#{msg_id}.#{}.#{payload}" signature = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha256"), @secret, to_sign)).strip "v1,#{signature}" end |
#verify(payload, headers) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/standardwebhooks/webhooks.rb', line 23 def verify(payload, headers) msg_id = headers["webhook-id"] msg_signature = headers["webhook-signature"] = headers["webhook-timestamp"] if !msg_signature || !msg_id || ! raise WebhookVerificationError, "Missing required headers" end () _, signature = sign(msg_id, , payload).split(",", 2) passed_signatures = msg_signature.split(" ") passed_signatures.each do |versioned_signature| version, expected_signature = versioned_signature.split(",", 2) if version != "v1" next end if ::StandardWebhooks::secure_compare(signature, expected_signature) return JSON.parse(payload) end end raise WebhookVerificationError, "No matching signature found" end |