Class: Svix::Webhook
- Inherits:
-
Object
- Object
- Svix::Webhook
- Defined in:
- lib/svix/webhook.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(secret, tolerance: DEFAULT_TOLERANCE) ⇒ Webhook
constructor
toleranceis the maximum difference allowed, in seconds, between the webhook's timestamp and the current time. - #sign(msgId, timestamp, payload) ⇒ Object
- #verify(payload, headers) ⇒ Object
Constructor Details
#initialize(secret, tolerance: DEFAULT_TOLERANCE) ⇒ Webhook
tolerance is the maximum difference allowed, in seconds, between the
webhook's timestamp and the current time. Defaults to 5 minutes.
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/svix/webhook.rb', line 12 def initialize(secret, tolerance: DEFAULT_TOLERANCE) if secret.start_with?(SECRET_PREFIX) secret = secret[SECRET_PREFIX.length..-1] end @secret = Base64.decode64(secret) if @secret.empty? raise EmptyWebhookSecretError, "Webhook secret must not be blank" end if !tolerance.is_a?(Integer) || tolerance < 0 raise ArgumentError, "tolerance must be a non-negative integer" end @tolerance = tolerance end |
Class Method Details
.new_using_raw_bytes(secret, tolerance: DEFAULT_TOLERANCE) ⇒ Object
6 7 8 |
# File 'lib/svix/webhook.rb', line 6 def self.new_using_raw_bytes(secret, tolerance: DEFAULT_TOLERANCE) self.new(secret.pack("C*").force_encoding("UTF-8"), tolerance: tolerance) end |
Instance Method Details
#sign(msgId, timestamp, payload) ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/svix/webhook.rb', line 61 def sign(msgId, , payload) begin now = Integer() rescue raise WebhookSigningError, "Invalid timestamp" end toSign = "#{msgId}.#{}.#{payload}" signature = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha256"), @secret, toSign)).strip return "v1,#{signature}" end |
#verify(payload, headers) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/svix/webhook.rb', line 29 def verify(payload, headers) msgId = headers["svix-id"] msgSignature = headers["svix-signature"] msgTimestamp = headers["svix-timestamp"] if !msgSignature || !msgId || !msgTimestamp msgId = headers["webhook-id"] msgSignature = headers["webhook-signature"] msgTimestamp = headers["webhook-timestamp"] if !msgSignature || !msgId || !msgTimestamp raise WebhookVerificationError, "Missing required headers" end end (msgTimestamp) _, signature = sign(msgId, msgTimestamp, payload).split(",", 2) passedSignatures = msgSignature.split(" ") passedSignatures.each do |versionedSignature| version, expectedSignature = versionedSignature.split(",", 2) if version != "v1" next end if ::Svix::secure_compare(signature, expectedSignature) return nil end end raise WebhookVerificationError, "No matching signature found" end |