standardwebhooks 1.0.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 49abbd5549503d34882432103f14a3b8e730ef8677c1e06314ceac7bb471a7ca
4
- data.tar.gz: f4b8df90ea0878fa129a1bd4484efb4338b869a3e843bd6cef8d0357ab722c11
3
+ metadata.gz: 8bb740db7282bf24af2820d6e40f0670851b48be3247ec02f07d4134fe3efd81
4
+ data.tar.gz: deeb2a023eb1b42e001f16e480b62d208c398d0eb9b2bf07aa86d802ddacbafa
5
5
  SHA512:
6
- metadata.gz: 39cb65e84871f70082fa9275298c130455cb7e75c9229f56d2b6bd941c06f6e8d13195ea027435fd744eafbfe07c68a3768890c83e6eacf6a63a6d25301efabe
7
- data.tar.gz: bdb9a899342976fa57d33024ed11616e4e895ac4f4e0835be0a7209d1c7af35bd7f85e40c671193979e969a042ab76915674ed2b5be6f518846e09d2f1d67d01
6
+ metadata.gz: da5d0530e6984ab6f5b3214d322125194b94d904b243998870af685bd6fd8d2baefcb6018cb8998dd7d3d0f06f25f369f8c97476ee59514e2c6641062f2e7b07
7
+ data.tar.gz: 3db16e0362fffca2b3d407e1dd5e2cc9e0ab2671f0da120760378dd61dcae9e5d0094f7e948a69d28f2393207bbc94c40fc2f052b965d04beef1e103b6777d6c
data/README.md CHANGED
@@ -1,35 +1,153 @@
1
- Ruby library for Standard Webhooks
1
+ Ruby library for Standard Webhooks
2
2
 
3
- # Example
3
+ # Installation
4
4
 
5
- Verifying a webhook payload:
5
+ Add `standardwebhooks` to your `Gemfile` and run `bundle install`.
6
+
7
+ Or install it without bundler:
8
+
9
+ ```sh
10
+ gem install standardwebhooks
11
+ ```
12
+
13
+ # Verifying webhooks
14
+
15
+ `StandardWebhooks::Webhook#verify` expects:
16
+
17
+ - The exact raw request body as a string.
18
+ - A hash containing `webhook-id`, `webhook-timestamp`, and `webhook-signature`.
19
+
20
+ It returns the parsed JSON payload as a Ruby hash and raises
21
+ `StandardWebhooks::WebhookVerificationError` when verification fails.
6
22
 
7
23
  ```ruby
8
- require "standardwebhooks"
24
+ require 'standardwebhooks'
25
+
26
+ webhook = StandardWebhooks::Webhook.new(ENV.fetch('WEBHOOK_SECRET'))
9
27
 
10
- wh = StandardWebhooks::Webhook.new(base64_secret)
11
- wh.verify(webhook_payload, webhook_headers)
28
+ payload = webhook.verify(raw_body, {
29
+ 'webhook-id' => request_headers.fetch('webhook-id'),
30
+ 'webhook-timestamp' => request_headers.fetch('webhook-timestamp'),
31
+ 'webhook-signature' => request_headers.fetch('webhook-signature'),
32
+ })
33
+
34
+ puts payload['type']
12
35
  ```
13
36
 
14
- # Development
37
+ Pass the raw body exactly as received. Verifying a parsed-and-reserialized JSON body
38
+ can fail because the signature is computed over the original bytes.
15
39
 
16
- ## Building
40
+ ## Responding to endpoint verification
17
41
 
18
- ```sh
19
- bundler exec rake build
42
+ To support the [endpoint verification](../../spec/extensions/endpoint-verification.md) extension,
43
+ use `#endpoint_verification_response` when the request includes a `webhook-challenge` header:
44
+
45
+ ```ruby
46
+ challenge = request_headers['webhook-challenge']
47
+ if challenge
48
+ response_headers['webhook-challenge-response'] = webhook.endpoint_verification_response(challenge)
49
+ # Not a webhook delivery: respond (e.g. with 204 No Content) without processing the body
50
+ return
51
+ end
20
52
  ```
21
53
 
22
- ## Contributing
54
+ Producers can verify the response with `#verify_endpoint_verification_response`, which raises
55
+ `StandardWebhooks::WebhookVerificationError` if it doesn't match:
23
56
 
24
- Before opening a PR be sure to format your code!
57
+ ```ruby
58
+ webhook.verify_endpoint_verification_response(challenge, response_headers['webhook-challenge-response'])
59
+ ```
25
60
 
26
- ```sh
27
- bundle exec rspec spec
61
+ ## Rails example
62
+
63
+ ```ruby
64
+ class WebhooksController < ApplicationController
65
+ def create
66
+ webhook = StandardWebhooks::Webhook.new(ENV.fetch('WEBHOOK_SECRET'))
67
+
68
+ payload = webhook.verify(request.raw_post, {
69
+ 'webhook-id' => request.headers.fetch('webhook-id'),
70
+ 'webhook-timestamp' => request.headers.fetch('webhook-timestamp'),
71
+ 'webhook-signature' => request.headers.fetch('webhook-signature'),
72
+ })
73
+
74
+ process_event(payload)
75
+
76
+ head :ok
77
+ rescue StandardWebhooks::WebhookVerificationError => error
78
+ Rails.logger.warn("Invalid webhook: #{error.message}")
79
+
80
+ head :bad_request
81
+ end
82
+
83
+ private
84
+
85
+ def process_event(payload)
86
+ case payload['type']
87
+ when 'customer.created'
88
+ CustomerCreateJob.perform_later(payload.fetch('data'))
89
+ end
90
+ end
91
+ end
92
+ ```
93
+
94
+ ## Rack or Sinatra example
95
+
96
+ ```ruby
97
+ post '/webhooks' do
98
+ request.body.rewind
99
+ raw_body = request.body.read
100
+
101
+ webhook = StandardWebhooks::Webhook.new(ENV.fetch('WEBHOOK_SECRET'))
102
+
103
+ payload = webhook.verify(raw_body, {
104
+ 'webhook-id' => request.env.fetch('HTTP_WEBHOOK_ID'),
105
+ 'webhook-timestamp' => request.env.fetch('HTTP_WEBHOOK_TIMESTAMP'),
106
+ 'webhook-signature' => request.env.fetch('HTTP_WEBHOOK_SIGNATURE'),
107
+ })
108
+
109
+ handle_event(payload)
110
+
111
+ status 204
112
+ rescue StandardWebhooks::WebhookVerificationError
113
+ halt 400
114
+ end
115
+ ```
116
+
117
+ # Signing payloads
118
+
119
+ If you are producing Standard Webhooks or need deterministic signatures in tests,
120
+ use `#sign`:
121
+
122
+ ```ruby
123
+ require 'standardwebhooks'
124
+
125
+ webhook = StandardWebhooks::Webhook.new(ENV.fetch('WEBHOOK_SECRET'))
126
+
127
+ msg_id = 'msg_2KWPBgLlAfxdpx2AI54pPJ85f4W'
128
+ timestamp = Time.now.to_i
129
+ payload = '{"type":"example.event","timestamp":"2022-11-03T20:26:10.344522Z","data":{"foo":"bar"}}'
130
+
131
+ signature = webhook.sign(msg_id, timestamp, payload)
132
+
133
+ headers = {
134
+ "webhook-id" => msg_id,
135
+ "webhook-timestamp" => timestamp.to_s,
136
+ "webhook-signature" => signature,
137
+ }
138
+
139
+ # …
28
140
  ```
29
141
 
30
- ## Running Tests
142
+ # Development
143
+
144
+ ## Building
145
+
146
+ ```sh
147
+ bundler exec rake build
148
+ ```
31
149
 
32
- Simply run:
150
+ ## Running tests
33
151
 
34
152
  ```sh
35
153
  bundle exec rspec spec
@@ -14,4 +14,7 @@ module StandardWebhooks
14
14
 
15
15
  class WebhookSigningError < StandardWebhooksError
16
16
  end
17
+
18
+ class EmptyWebhookSecretError < StandardWebhooksError
19
+ end
17
20
  end
@@ -1,38 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Constant time string comparison, for fixed length strings.
4
- # Code borrowed from ActiveSupport
5
- # https://github.com/rails/rails/blob/75ac626c4e21129d8296d4206a1960563cc3d4aa/activesupport/lib/active_support/security_utils.rb#L33
6
- #
7
- # The values compared should be of fixed length, such as strings
8
- # that have already been processed by HMAC. Raises in case of length mismatch.
9
3
  module StandardWebhooks
10
- if defined?(OpenSSL.fixed_length_secure_compare)
11
- def fixed_length_secure_compare(a, b)
12
- OpenSSL.fixed_length_secure_compare(a, b)
13
- end
14
- else
15
- def fixed_length_secure_compare(a, b)
16
- raise ArgumentError, "string length mismatch." unless a.bytesize == b.bytesize
17
-
18
- l = a.unpack "C#{a.bytesize}"
19
-
20
- res = 0
21
- b.each_byte { |byte| res |= byte ^ l.shift }
22
- res == 0
23
- end
24
- end
25
-
26
- module_function :fixed_length_secure_compare
27
-
28
- # Secure string comparison for strings of variable length.
4
+ # Secure string comparison for strings of fixed length
29
5
  #
30
6
  # While a timing attack would not be able to discern the content of
31
7
  # a secret compared via secure_compare, it is possible to determine
32
8
  # the secret length. This should be considered when using secure_compare
33
9
  # to compare weak, short secrets to user input.
34
10
  def secure_compare(a, b)
35
- a.length == b.length && fixed_length_secure_compare(a, b)
11
+ return false unless a.bytesize == b.bytesize
12
+
13
+ OpenSSL.fixed_length_secure_compare(a, b)
36
14
  end
37
15
 
38
16
  module_function :secure_compare
@@ -7,9 +7,8 @@ require "uri"
7
7
 
8
8
  module StandardWebhooks
9
9
  class Webhook
10
-
11
10
  def self.new_using_raw_bytes(secret)
12
- self.new(secret.pack("C*").force_encoding("UTF-8"))
11
+ new(secret.pack("C*").force_encoding("UTF-8"))
13
12
  end
14
13
 
15
14
  def initialize(secret)
@@ -18,6 +17,10 @@ module StandardWebhooks
18
17
  end
19
18
 
20
19
  @secret = Base64.decode64(secret)
20
+
21
+ if @secret.empty?
22
+ raise EmptyWebhookSecretError, "Webhook secret must not be blank"
23
+ end
21
24
  end
22
25
 
23
26
  def verify(payload, headers)
@@ -31,28 +34,23 @@ module StandardWebhooks
31
34
 
32
35
  verify_timestamp(msg_timestamp)
33
36
 
34
- _, signature = sign(msg_id, msg_timestamp, payload).split(",", 2)
37
+ signature = sign(msg_id, msg_timestamp, payload)
35
38
 
36
39
  passed_signatures = msg_signature.split(" ")
40
+ matched = passed_signatures.any? do |versioned_signature|
41
+ ::StandardWebhooks.secure_compare(versioned_signature, signature)
42
+ end
37
43
 
38
- passed_signatures.each do |versioned_signature|
39
- version, expected_signature = versioned_signature.split(",", 2)
40
-
41
- if version != "v1"
42
- next
43
- end
44
-
45
- if ::StandardWebhooks::secure_compare(signature, expected_signature)
46
- return JSON.parse(payload, symbolize_names: true)
47
- end
44
+ unless matched
45
+ raise WebhookVerificationError, "No matching signature found"
48
46
  end
49
47
 
50
- raise WebhookVerificationError, "No matching signature found"
48
+ JSON.parse(payload)
51
49
  end
52
50
 
53
51
  def sign(msg_id, timestamp, payload)
54
52
  begin
55
- now = Integer(timestamp)
53
+ timestamp = Integer(timestamp)
56
54
  rescue
57
55
  raise WebhookSigningError, "Invalid timestamp"
58
56
  end
@@ -60,13 +58,36 @@ module StandardWebhooks
60
58
  to_sign = "#{msg_id}.#{timestamp}.#{payload}"
61
59
  signature = Base64.encode64(OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha256"), @secret, to_sign)).strip
62
60
 
63
- return "v1,#{signature}"
61
+ "v1,#{signature}"
64
62
  end
65
63
 
66
- private
64
+ # Calculate the response to an endpoint verification challenge. Takes the value of the
65
+ # `webhook-challenge` request header and returns the value for the
66
+ # `webhook-challenge-response` response header.
67
+ def endpoint_verification_response(challenge)
68
+ verification_key = OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha256"), @secret, "wev-v1")
69
+ digest = OpenSSL::HMAC.digest(OpenSSL::Digest.new("sha256"), verification_key, challenge)
70
+ signature = Base64.encode64(digest).strip
71
+
72
+ "v1,#{signature}"
73
+ end
74
+
75
+ # Verify the response to an endpoint verification challenge. Takes the challenge sent in
76
+ # the `webhook-challenge` request header and the value of the `webhook-challenge-response`
77
+ # response header. Raises WebhookVerificationError if no matching signature is found.
78
+ def verify_endpoint_verification_response(challenge, header)
79
+ signature = endpoint_verification_response(challenge)
80
+
81
+ unless ::StandardWebhooks.secure_compare(header, signature)
82
+ raise WebhookVerificationError, "No matching signature found"
83
+ end
84
+ end
67
85
 
68
86
  SECRET_PREFIX = "whsec_"
69
87
  TOLERANCE = 5 * 60
88
+ private_constant :SECRET_PREFIX, :TOLERANCE
89
+
90
+ private
70
91
 
71
92
  def verify_timestamp(timestamp_header)
72
93
  begin
metadata CHANGED
@@ -1,15 +1,28 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: standardwebhooks
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.1
4
+ version: 1.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Standard Webhooks
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2026-03-09 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: base64
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: 0.3.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: 0.3.0
13
26
  - !ruby/object:Gem::Dependency
14
27
  name: bundler
15
28
  requirement: !ruby/object:Gem::Requirement
@@ -52,28 +65,23 @@ dependencies:
52
65
  - - "~>"
53
66
  - !ruby/object:Gem::Version
54
67
  version: '3.2'
55
- description:
56
- email:
57
68
  executables: []
58
69
  extensions: []
59
70
  extra_rdoc_files: []
60
71
  files:
61
- - Gemfile
62
- - Gemfile.lock
63
72
  - README.md
64
- - Rakefile
65
73
  - lib/standardwebhooks.rb
66
74
  - lib/standardwebhooks/errors.rb
67
75
  - lib/standardwebhooks/util.rb
68
76
  - lib/standardwebhooks/webhooks.rb
69
- - standardwebhooks.gemspec
70
- homepage:
71
77
  licenses:
72
78
  - MIT
73
79
  metadata:
74
80
  allowed_push_host: https://rubygems.org
75
- source_code_uri: https://github.com/standard-webhooks/standard-webhooks
76
- post_install_message:
81
+ homepage_uri: https://www.standardwebhooks.com/
82
+ bug_tracker_uri: https://github.com/standard-webhooks/standard-webhooks/issues
83
+ source_code_uri: https://github.com/standard-webhooks/standard-webhooks/tree/main/libraries/ruby
84
+ documentation_uri: https://github.com/standard-webhooks/standard-webhooks/blob/main/libraries/ruby/README.md
77
85
  rdoc_options: []
78
86
  require_paths:
79
87
  - lib
@@ -81,15 +89,15 @@ required_ruby_version: !ruby/object:Gem::Requirement
81
89
  requirements:
82
90
  - - ">="
83
91
  - !ruby/object:Gem::Version
84
- version: '0'
92
+ version: '3.3'
85
93
  required_rubygems_version: !ruby/object:Gem::Requirement
86
94
  requirements:
87
95
  - - ">="
88
96
  - !ruby/object:Gem::Version
89
97
  version: '0'
90
98
  requirements: []
91
- rubygems_version: 3.1.6
92
- signing_key:
99
+ rubygems_version: 3.6.9
93
100
  specification_version: 4
94
- summary: Ruby library for creating and verifying webhook signatures.
101
+ summary: Library for creating and verifying webhook signatures for the Standard Webhook
102
+ spec.
95
103
  test_files: []
data/Gemfile DELETED
@@ -1,3 +0,0 @@
1
- source "https://rubygems.org"
2
-
3
- gemspec
data/Gemfile.lock DELETED
@@ -1,35 +0,0 @@
1
- PATH
2
- remote: .
3
- specs:
4
- standardwebhooks (1.0.1)
5
-
6
- GEM
7
- remote: https://rubygems.org/
8
- specs:
9
- diff-lcs (1.5.1)
10
- rake (13.2.1)
11
- rspec (3.13.0)
12
- rspec-core (~> 3.13.0)
13
- rspec-expectations (~> 3.13.0)
14
- rspec-mocks (~> 3.13.0)
15
- rspec-core (3.13.0)
16
- rspec-support (~> 3.13.0)
17
- rspec-expectations (3.13.0)
18
- diff-lcs (>= 1.2.0, < 2.0)
19
- rspec-support (~> 3.13.0)
20
- rspec-mocks (3.13.0)
21
- diff-lcs (>= 1.2.0, < 2.0)
22
- rspec-support (~> 3.13.0)
23
- rspec-support (3.13.0)
24
-
25
- PLATFORMS
26
- x86_64-linux
27
-
28
- DEPENDENCIES
29
- bundler (>= 2.2.10)
30
- rake (~> 13.0)
31
- rspec (~> 3.2)
32
- standardwebhooks!
33
-
34
- BUNDLED WITH
35
- 2.4.22
data/Rakefile DELETED
@@ -1,2 +0,0 @@
1
- require "bundler/gem_tasks"
2
- task :default => :spec
@@ -1,38 +0,0 @@
1
-
2
- lib = File.expand_path("../lib", __FILE__)
3
- $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
-
5
- Gem::Specification.new do |spec|
6
- spec.name = "standardwebhooks"
7
- spec.version = "1.0.1"
8
- spec.authors = ["Standard Webhooks"]
9
- spec.license = "MIT"
10
-
11
- spec.summary = "Ruby library for creating and verifying webhook signatures."
12
-
13
- # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
14
- # to allow pushing to a single host or delete this section to allow pushing to any host.
15
- if spec.respond_to?(:metadata)
16
- spec.metadata["allowed_push_host"] = "https://rubygems.org"
17
- spec.metadata["source_code_uri"] = "https://github.com/standard-webhooks/standard-webhooks"
18
- else
19
- raise "RubyGems 2.0 or newer is required to protect against " \
20
- "public gem pushes."
21
- end
22
-
23
- # Specify which files should be added to the gem when it is released.
24
- ignored = Regexp.union(
25
- /\Aspec/,
26
- /\Apkg/,
27
- /\Atemplates/,
28
- /\A.gitignore/,
29
- /.gem\z/
30
- )
31
-
32
- spec.files = Dir['**/*'].reject {|f| !File.file?(f) || ignored.match(f) }
33
- spec.require_paths = ["lib"]
34
-
35
- spec.add_development_dependency "bundler", ">= 2.2.10"
36
- spec.add_development_dependency "rake", "~> 13.0"
37
- spec.add_development_dependency "rspec", "~> 3.2"
38
- end