postwire 0.1.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.
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Postwire
4
+ # Response wrapper that maintains backwards compatibility while exposing headers
5
+ #
6
+ # This class wraps API responses and behaves like a Hash for backwards compatibility,
7
+ # while also providing access to response headers via the #headers method.
8
+ #
9
+ # @example Backwards compatible hash access
10
+ # response = Postwire::Emails.send(params)
11
+ # response[:id] # => "49a3999c-0ce1-4ea6-ab68-afcd6dc2e794"
12
+ #
13
+ # @example Accessing response headers
14
+ # response = Postwire::Emails.send(params)
15
+ # response.headers # => {"content-type" => "application/json", ...}
16
+ # response.headers['x-ratelimit-remaining'] # => "50"
17
+ class Response
18
+ include Enumerable
19
+
20
+ # @param data [Hash] The response data
21
+ # @param headers [Hash, Faraday::Response] The response headers
22
+ def initialize(data, headers)
23
+ @data = data.is_a?(Hash) ? data : {}
24
+ @headers = normalize_headers(headers)
25
+ end
26
+
27
+ # Access response headers
28
+ # @return [Hash] Response headers as a hash with lowercase string keys
29
+ attr_reader :headers
30
+
31
+ # Hash-like access via []
32
+ # @param key [Symbol, String] The key to access
33
+ # @return [Object] The value at the key
34
+ def [](key)
35
+ @data[key]
36
+ end
37
+
38
+ # Hash-like assignment via []=
39
+ # @param key [Symbol, String] The key to set
40
+ # @param value [Object] The value to set
41
+ def []=(key, value)
42
+ @data[key] = value
43
+ end
44
+
45
+ # Dig into nested hash structure
46
+ # @param keys [Array<Symbol, String>] Keys to dig through
47
+ # @return [Object] The value at the nested key path
48
+ def dig(*keys)
49
+ @data.dig(*keys)
50
+ end
51
+
52
+ # Convert to plain hash
53
+ # @return [Hash] The underlying data hash
54
+ def to_h
55
+ @data
56
+ end
57
+
58
+ alias to_hash to_h
59
+
60
+ # Get all keys from the data
61
+ # @return [Array] Array of keys
62
+ def keys
63
+ @data.keys
64
+ end
65
+
66
+ # Get all values from the data
67
+ # @return [Array] Array of values
68
+ def values
69
+ @data.values
70
+ end
71
+
72
+ # Check if key exists
73
+ # @param key [Symbol, String] The key to check
74
+ # @return [Boolean] True if key exists
75
+ def key?(key)
76
+ @data.key?(key)
77
+ end
78
+
79
+ alias has_key? key?
80
+
81
+ # Enable enumeration over the data
82
+ def each(&block)
83
+ @data.each(&block)
84
+ end
85
+
86
+ # Transform keys in the underlying data
87
+ # @return [Postwire::Response] Self for chaining
88
+ def transform_keys!(&block)
89
+ @data.transform_keys!(&block)
90
+ self
91
+ end
92
+
93
+ # Check if response is empty
94
+ # @return [Boolean] True if data is empty
95
+ def empty?
96
+ @data.empty?
97
+ end
98
+
99
+ # Respond to hash-like methods
100
+ def respond_to_missing?(method_name, include_private = false)
101
+ @data.respond_to?(method_name) || super
102
+ end
103
+
104
+ # Delegate unknown methods to the underlying data hash
105
+ def method_missing(method_name, *args, &block)
106
+ if @data.respond_to?(method_name)
107
+ result = @data.send(method_name, *args, &block)
108
+ # If the method returns the hash itself, return self to maintain wrapper
109
+ result.equal?(@data) ? self : result
110
+ else
111
+ super
112
+ end
113
+ end
114
+
115
+ # String representation for debugging
116
+ # @return [String] String representation of the response
117
+ def inspect
118
+ "#<Postwire::Response data=#{@data.inspect} headers=#{@headers.keys.inspect}>"
119
+ end
120
+
121
+ private
122
+
123
+ # Normalize headers to a simple hash with lowercase string keys
124
+ # @param headers [Hash, Faraday::Response, nil] The headers to normalize
125
+ # @return [Hash] Normalized headers hash
126
+ def normalize_headers(headers)
127
+ return {} if headers.nil?
128
+
129
+ # Handle Faraday::Response object
130
+ headers = headers.headers if headers.respond_to?(:headers)
131
+
132
+ # Convert to hash and normalize keys to lowercase strings
133
+ case headers
134
+ when Hash
135
+ headers.to_h.transform_keys { |k| k.to_s.downcase }
136
+ else
137
+ {}
138
+ end
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Postwire
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,246 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require "base64"
5
+
6
+ module Postwire
7
+ # The Webhooks module provides methods for managing webhooks via the Postwire API.
8
+ # Webhooks allow you to receive real-time notifications about email events.
9
+ #
10
+ # Default tolerance for timestamp validation (5 minutes)
11
+ WEBHOOK_TOLERANCE_SECONDS = 300
12
+ #
13
+ # @example Create a webhook
14
+ # Postwire::Webhooks.create(
15
+ # endpoint: "https://webhook.example.com/handler",
16
+ # events: ["email.sent", "email.delivered", "email.bounced"]
17
+ # )
18
+ #
19
+ # @example List all webhooks
20
+ # Postwire::Webhooks.list
21
+ #
22
+ # @example Retrieve a specific webhook
23
+ # Postwire::Webhooks.get("4dd369bc-aa82-4ff3-97de-514ae3000ee0")
24
+ #
25
+ # @example Update a webhook
26
+ # Postwire::Webhooks.update(
27
+ # webhook_id: "430eed87-632a-4ea6-90db-0aace67ec228",
28
+ # endpoint: "https://new-webhook.example.com/handler",
29
+ # events: ["email.sent", "email.delivered"],
30
+ # status: "enabled"
31
+ # )
32
+ #
33
+ # @example Delete a webhook
34
+ # Postwire::Webhooks.remove("4dd369bc-aa82-4ff3-97de-514ae3000ee0")
35
+ module Webhooks
36
+ class << self
37
+ # Create a new webhook to receive real-time notifications about email events
38
+ #
39
+ # @param params [Hash] The webhook parameters
40
+ # @option params [String] :endpoint The URL where webhook events will be sent (required)
41
+ # @option params [Array<String>] :events Array of event types to subscribe to (required)
42
+ #
43
+ # @return [Hash] The webhook object containing id, object type, and signing_secret
44
+ #
45
+ # @example
46
+ # Postwire::Webhooks.create(
47
+ # endpoint: "https://webhook.example.com/handler",
48
+ # events: ["email.sent", "email.delivered", "email.bounced"]
49
+ # )
50
+ def create(params = {})
51
+ path = "webhooks"
52
+ Postwire::Request.new(path, params, "post").perform
53
+ end
54
+
55
+ # Retrieve a list of webhooks for the authenticated user
56
+ #
57
+ # @param params [Hash] The pagination parameters
58
+ # @option params [Integer] :limit Number of webhooks to retrieve (max: 100, min: 1)
59
+ # @option params [String] :after The ID after which to retrieve more webhooks (for pagination)
60
+ # @option params [String] :before The ID before which to retrieve more webhooks (for pagination)
61
+ #
62
+ # @return [Hash] A paginated list of webhook objects
63
+ #
64
+ # @example
65
+ # Postwire::Webhooks.list
66
+ #
67
+ # @example With pagination
68
+ # Postwire::Webhooks.list(limit: 20, after: "4dd369bc-aa82-4ff3-97de-514ae3000ee0")
69
+ def list(params = {})
70
+ path = Postwire::PaginationHelper.build_paginated_path("webhooks", params)
71
+ Postwire::Request.new(path, {}, "get").perform
72
+ end
73
+
74
+ # Retrieve a single webhook for the authenticated user
75
+ #
76
+ # @param webhook_id [String] The webhook ID (required)
77
+ #
78
+ # @return [Hash] The webhook object with full details
79
+ #
80
+ # @example
81
+ # Postwire::Webhooks.get("4dd369bc-aa82-4ff3-97de-514ae3000ee0")
82
+ def get(webhook_id)
83
+ raise ArgumentError, "webhook_id is required" if webhook_id.nil? || webhook_id.to_s.empty?
84
+
85
+ path = "webhooks/#{webhook_id}"
86
+ Postwire::Request.new(path, {}, "get").perform
87
+ end
88
+
89
+ # Update an existing webhook configuration
90
+ #
91
+ # @param params [Hash] The webhook update parameters
92
+ # @option params [String] :webhook_id The webhook ID (required)
93
+ # @option params [String] :endpoint The URL where webhook events will be sent
94
+ # @option params [Array<String>] :events Array of event types to subscribe to
95
+ # @option params [String] :status The webhook status ("enabled" or "disabled")
96
+ #
97
+ # @return [Hash] The updated webhook object
98
+ #
99
+ # @example
100
+ # Postwire::Webhooks.update(
101
+ # webhook_id: "430eed87-632a-4ea6-90db-0aace67ec228",
102
+ # endpoint: "https://new-webhook.example.com/handler",
103
+ # events: ["email.sent", "email.delivered"],
104
+ # status: "enabled"
105
+ # )
106
+ def update(params = {})
107
+ params = params.dup # Don't mutate caller's hash
108
+ webhook_id = params.delete(:webhook_id)
109
+ raise ArgumentError, ":webhook_id is required" if webhook_id.nil? || webhook_id.to_s.empty?
110
+
111
+ path = "webhooks/#{webhook_id}"
112
+ Postwire::Request.new(path, params, "patch").perform
113
+ end
114
+
115
+ # Remove an existing webhook
116
+ #
117
+ # @param webhook_id [String] The webhook ID (required)
118
+ #
119
+ # @return [Hash] Confirmation object with id, object type, and deleted status
120
+ #
121
+ # @example
122
+ # Postwire::Webhooks.remove("4dd369bc-aa82-4ff3-97de-514ae3000ee0")
123
+ def remove(webhook_id)
124
+ raise ArgumentError, "webhook_id is required" if webhook_id.nil? || webhook_id.to_s.empty?
125
+
126
+ path = "webhooks/#{webhook_id}"
127
+ Postwire::Request.new(path, {}, "delete").perform
128
+ end
129
+
130
+ # Verify a webhook payload using HMAC-SHA256 signature validation
131
+ # This validates that the webhook request came from Postwire and hasn't been tampered with
132
+ #
133
+ # @param params [Hash] The webhook verification parameters
134
+ # @option params [String] :payload The raw webhook payload body (required)
135
+ # @option params [Hash] :headers The webhook headers containing svix-id, svix-timestamp,
136
+ # and svix-signature (required)
137
+ # @option params [String] :webhook_secret The signing secret from webhook creation (required)
138
+ #
139
+ # @return [Boolean] true if verification succeeds
140
+ # @raise [StandardError] If verification fails or required parameters are missing
141
+ #
142
+ # @example
143
+ # Postwire::Webhooks.verify(
144
+ # payload: request.body.read,
145
+ # headers: {
146
+ # svix_id: "id_1234567890abcdefghijklmnopqrstuvwxyz",
147
+ # svix_timestamp: "1616161616",
148
+ # svix_signature: "v1,signature_here"
149
+ # },
150
+ # webhook_secret: "whsec_1234567890abcdez"
151
+ # )
152
+ def verify(params = {})
153
+ payload = params[:payload]
154
+ headers = params[:headers] || {}
155
+ webhook_secret = params[:webhook_secret]
156
+
157
+ validate_required_params(payload, headers, webhook_secret)
158
+ validate_timestamp(headers[:svix_timestamp])
159
+
160
+ signed_content = "#{headers[:svix_id]}.#{headers[:svix_timestamp]}.#{payload}"
161
+ decoded_secret = decode_secret(webhook_secret)
162
+ expected_signature = generate_signature(decoded_secret, signed_content)
163
+
164
+ verify_signature(headers[:svix_signature], expected_signature)
165
+ end
166
+
167
+ private
168
+
169
+ # Validate required parameters
170
+ def validate_required_params(payload, headers, webhook_secret)
171
+ validate_payload(payload)
172
+ validate_webhook_secret(webhook_secret)
173
+ validate_headers(headers)
174
+ end
175
+
176
+ # Validate payload is present
177
+ def validate_payload(payload)
178
+ raise "payload cannot be empty" if payload.nil? || payload.empty?
179
+ end
180
+
181
+ # Validate webhook secret is present
182
+ def validate_webhook_secret(webhook_secret)
183
+ raise "webhook_secret cannot be empty" if webhook_secret.nil? || webhook_secret.empty?
184
+ end
185
+
186
+ # Validate required headers are present
187
+ def validate_headers(headers)
188
+ raise "svix-id header is required" if headers[:svix_id].nil? || headers[:svix_id].empty?
189
+ raise "svix-timestamp header is required" if headers[:svix_timestamp].nil? || headers[:svix_timestamp].empty?
190
+ raise "svix-signature header is required" if headers[:svix_signature].nil? || headers[:svix_signature].empty?
191
+ end
192
+
193
+ # Validate timestamp to prevent replay attacks
194
+ def validate_timestamp(timestamp_header)
195
+ timestamp = timestamp_header.to_i
196
+ now = Time.now.to_i
197
+ diff = now - timestamp
198
+
199
+ return unless diff > WEBHOOK_TOLERANCE_SECONDS || diff < -WEBHOOK_TOLERANCE_SECONDS
200
+
201
+ raise "Timestamp outside tolerance window: difference of #{diff} seconds"
202
+ end
203
+
204
+ # Decode the signing secret (strip whsec_ prefix and base64 decode)
205
+ def decode_secret(webhook_secret)
206
+ secret = webhook_secret.sub(/^whsec_/, "")
207
+ Base64.strict_decode64(secret)
208
+ rescue ArgumentError => e
209
+ raise "Failed to decode webhook secret: #{e.message}"
210
+ end
211
+
212
+ # Verify signature using constant-time comparison
213
+ def verify_signature(signature_header, expected_signature)
214
+ signatures = signature_header.split(" ")
215
+ signatures.each do |sig|
216
+ parts = sig.split(",", 2)
217
+ next if parts.length != 2
218
+
219
+ received_signature = parts[1]
220
+ return true if secure_compare(expected_signature, received_signature)
221
+ end
222
+
223
+ raise "No matching signature found"
224
+ end
225
+
226
+ # Generate HMAC-SHA256 signature and return it as base64
227
+ def generate_signature(secret, content)
228
+ digest = OpenSSL::HMAC.digest("sha256", secret, content)
229
+ Base64.strict_encode64(digest)
230
+ end
231
+
232
+ # Constant-time string comparison to prevent timing attacks
233
+ #
234
+ # Note: We implement this manually for Ruby 2.7 compatibility.
235
+ # Ruby 3.0+ could use OpenSSL.fixed_length_secure_compare instead.
236
+ def secure_compare(str_a, str_b)
237
+ return false if str_a.nil? || str_b.nil? || str_a.bytesize != str_b.bytesize
238
+
239
+ bytes_a = str_a.unpack("C*")
240
+ result = 0
241
+ str_b.each_byte.with_index { |byte_b, i| result |= byte_b ^ bytes_a[i] }
242
+ result.zero?
243
+ end
244
+ end
245
+ end
246
+ end
data/lib/postwire.rb ADDED
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Version
4
+ require "postwire/version"
5
+
6
+ # Utils
7
+ require "faraday"
8
+ require "json"
9
+ require "uri"
10
+ require "postwire/errors"
11
+ require "postwire/response"
12
+ require "postwire/client"
13
+ require "postwire/request"
14
+ require "postwire/pagination_helper"
15
+
16
+ # API Operations
17
+ require "postwire/emails"
18
+ require "postwire/emails/receiving"
19
+ require "postwire/emails/attachments"
20
+ require "postwire/emails/receiving/attachments"
21
+ require "postwire/webhooks"
22
+
23
+ # Rails
24
+ require "postwire/railtie" if defined?(Rails) && defined?(ActionMailer)
25
+
26
+ # Main Postwire module
27
+ module Postwire
28
+ DEFAULT_TIMEOUT = 30
29
+
30
+ class << self
31
+ attr_accessor :api_key, :timeout
32
+ attr_writer :base_url
33
+
34
+ def configure
35
+ yield self if block_given?
36
+ true
37
+ end
38
+ alias config configure
39
+
40
+ def base_url
41
+ @base_url ||= "https://send.voupe.com/api"
42
+ end
43
+ end
44
+ end
metadata ADDED
@@ -0,0 +1,84 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: postwire
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Dean Perry
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: faraday
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '2.0'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '2.0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: rails
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '7.2'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '7.2'
40
+ email: dean@voupe.com
41
+ executables: []
42
+ extensions: []
43
+ extra_rdoc_files: []
44
+ files:
45
+ - CHANGELOG.md
46
+ - README.md
47
+ - lib/postwire.rb
48
+ - lib/postwire/client.rb
49
+ - lib/postwire/emails.rb
50
+ - lib/postwire/emails/attachments.rb
51
+ - lib/postwire/emails/receiving.rb
52
+ - lib/postwire/emails/receiving/attachments.rb
53
+ - lib/postwire/errors.rb
54
+ - lib/postwire/mailer.rb
55
+ - lib/postwire/pagination_helper.rb
56
+ - lib/postwire/railtie.rb
57
+ - lib/postwire/request.rb
58
+ - lib/postwire/response.rb
59
+ - lib/postwire/version.rb
60
+ - lib/postwire/webhooks.rb
61
+ homepage: https://github.com/voupe/postwire-gem
62
+ licenses:
63
+ - MIT
64
+ metadata:
65
+ allowed_push_host: https://rubygems.org
66
+ github_repo: ssh://github.com/voupe/postwire-gem
67
+ rdoc_options: []
68
+ require_paths:
69
+ - lib
70
+ required_ruby_version: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '3.3'
75
+ required_rubygems_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ requirements: []
81
+ rubygems_version: 4.0.20
82
+ specification_version: 4
83
+ summary: The Ruby and Rails SDK for Postwire
84
+ test_files: []