mailset 0.7.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,346 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mailset
4
+ # One try of a request, as the client hands it to its HTTP adapter (`http:`
5
+ # on {Client#initialize}): `verb` (`'GET'` or `'POST'`), the whole `url`,
6
+ # `headers` (a Hash of String to String), the `body` (the exact bytes
7
+ # signed, or nil) and `timeout` (seconds for this try).
8
+ HttpRequest = Struct.new(:verb, :url, :headers, :body, :timeout, keyword_init: true)
9
+
10
+ # What an HTTP adapter answers: `status` (an Integer), `headers` (a Hash
11
+ # with lowercase names) and `body` (a String).
12
+ HttpResponse = Struct.new(:status, :headers, :body, keyword_init: true)
13
+
14
+ # How a client reaches Mailset: signed requests, tried again after a
15
+ # network failure or a 5xx, its credential checked against each command
16
+ # before anything is sent.
17
+ #
18
+ # @api private
19
+ class Transport
20
+ DEFAULT_API = 'https://mailset.app'
21
+
22
+ # What a failed try raises when it never got an answer: no network, a
23
+ # dropped connection, a reset, a try's timeout.
24
+ NETWORK_ERRORS = [
25
+ Timeout::Error, SystemCallError, IOError, SocketError,
26
+ OpenSSL::SSL::SSLError, Net::ProtocolError, Net::HTTPBadResponse
27
+ ].freeze
28
+
29
+ # What `mailset keys create` asks for each grant.
30
+ GRANT_FLAGS = {
31
+ read: '--read --mailbox <address>',
32
+ send: '--send --mailbox <address>',
33
+ campaigns: '--campaigns'
34
+ }.freeze
35
+
36
+ UPGRADE = 'Mailset: this version of the mailset package is out of date. ' \
37
+ 'Upgrade it: bundle update mailset (or gem install mailset)'
38
+
39
+ @warned = false
40
+ @warning = Mutex.new
41
+
42
+ class << self
43
+ # `Mailset-Notice: upgrade`: this version is old. Said once per process, on stderr.
44
+ def warn_upgrade
45
+ @warning.synchronize do
46
+ return if @warned
47
+
48
+ @warned = true
49
+ end
50
+ Kernel.warn(UPGRADE)
51
+ end
52
+
53
+ # Lets the upgrade notice be said again: for tests.
54
+ def reset_upgrade_notice!
55
+ @warning.synchronize { @warned = false }
56
+ end
57
+
58
+ # `Mailset-Client`: this gem, its version, and the framework, runtime
59
+ # and OS it runs on. Nothing personal: no host, path, user or app.
60
+ def client_header
61
+ parts = [framework, runtime, os].compact.map { |part| part.gsub(/[();]/, '') }
62
+ "ruby/#{VERSION} (#{parts.join('; ')})".gsub(/[^\x20-\x7e]/, '')
63
+ end
64
+
65
+ # Rails, when it's loaded and says its version cheaply.
66
+ def framework
67
+ return nil unless defined?(::Rails) && ::Rails.respond_to?(:version)
68
+
69
+ "rails #{::Rails.version}"
70
+ rescue StandardError
71
+ nil
72
+ end
73
+
74
+ def runtime
75
+ RUBY_ENGINE == 'ruby' ? "ruby #{RUBY_VERSION}" : "#{RUBY_ENGINE} #{RUBY_ENGINE_VERSION}"
76
+ end
77
+
78
+ def os
79
+ case RbConfig::CONFIG['host_os'].to_s
80
+ when /darwin|mac os/i then 'darwin'
81
+ when /linux/i then 'linux'
82
+ when /mswin|mingw|cygwin|windows/i then 'windows'
83
+ when /freebsd/i then 'freebsd'
84
+ when /openbsd/i then 'openbsd'
85
+ when /netbsd/i then 'netbsd'
86
+ when /solaris|sunos/i then 'solaris'
87
+ else 'unknown'
88
+ end
89
+ end
90
+ end
91
+
92
+ attr_reader :credential, :base_url, :org, :timeout, :max_retries, :client_header
93
+
94
+ def initialize(credential, base_url: nil, org: nil, timeout: 30, max_retries: 2, http: nil, now: nil,
95
+ on_approval: nil, env: ENV)
96
+ @credential = credential
97
+ @base_url = [base_url, env['MAILSET_API'], credential.api, DEFAULT_API]
98
+ .find { |one| one.is_a?(String) && !one.empty? }.sub(%r{/+\z}, '')
99
+ @org = org
100
+ @timeout = timeout
101
+ @max_retries = [max_retries.to_i, 0].max
102
+ @http = http || NetHttp.new
103
+ @now = now
104
+ @on_approval = on_approval
105
+ @client_header = Transport.client_header
106
+ end
107
+
108
+ # The time every request is signed with, in ms since the epoch.
109
+ def now_ms
110
+ value = @now ? @now.call : Time.now
111
+ value.is_a?(Integer) ? value : Types.ms(value)
112
+ end
113
+
114
+ # The approvals of this transport's credential.
115
+ def approvals
116
+ @approvals ||= Approvals.new(self)
117
+ end
118
+
119
+ # One command: refused here when this credential can't run it, else
120
+ # signed and sent. With `on_approval`, a passkey stop is approved and the
121
+ # command runs again.
122
+ def command(id, input, org: nil, approval: nil, timeout: nil)
123
+ info = COMMANDS[id]
124
+ wrong = mismatch(info)
125
+ raise wrong if wrong
126
+
127
+ org ||= @org
128
+ body = { 'input' => input || {} }
129
+ body['org'] = org if org
130
+ body['approval'] = approval if approval
131
+ begin
132
+ raw('POST', "#{COMMAND_PATH}#{id}", body, command: id, timeout: timeout)
133
+ rescue Error => e
134
+ if e.code == 'step_up_required' && e.purpose && @on_approval && !approval
135
+ asked = approvals.request(e.purpose)
136
+ @on_approval.call(asked)
137
+ approved = approvals.wait(asked)
138
+ return command(id, input, org: org, approval: approved, timeout: timeout)
139
+ end
140
+ refusal = grant_refusal(e, info)
141
+ raise refusal unless refusal.equal?(e)
142
+
143
+ raise
144
+ end
145
+ end
146
+
147
+ # One request, signed, tried again after a network failure, a try that
148
+ # ran out of time, or a 5xx: its `data`, or its refusal raised. The body
149
+ # is encoded once, so every try sends the same bytes (signed again, with
150
+ # its own ms-time): a send keeps its Message-ID, and Mailset sends it once.
151
+ def raw(method, path, body, command: nil, timeout: nil)
152
+ bytes = body.nil? ? '' : JSON.generate(body)
153
+ seconds = timeout || @timeout
154
+ # Try 0, then up to max_retries more. Not Kernel#loop, which would end
155
+ # quietly on a StopIteration from a caller's clock or HTTP adapter.
156
+ (0..@max_retries).each do |tries|
157
+ last = tries == @max_retries
158
+ begin
159
+ response = attempt(method, path, bytes, seconds)
160
+ rescue *NETWORK_ERRORS => e
161
+ raise unreachable(e, seconds, command) if last
162
+
163
+ pause(pause_seconds(tries, nil))
164
+ next
165
+ end
166
+ notice(response)
167
+ if response.status >= 500 && !last
168
+ pause(pause_seconds(tries, header(response, 'retry-after')))
169
+ next
170
+ end
171
+ return reply(response, command)
172
+ end
173
+ end
174
+
175
+ # Waits between tries and between an approval's checks.
176
+ def pause(seconds)
177
+ sleep(seconds)
178
+ end
179
+
180
+ def inspect
181
+ "#<Mailset::Transport #{credential.variable} #{base_url}>"
182
+ end
183
+ alias to_s inspect
184
+
185
+ private
186
+
187
+ def attempt(method, path, bytes, timeout)
188
+ headers = {
189
+ 'Authorization' => credential.authorization,
190
+ 'Mailset-Client' => client_header,
191
+ 'Accept' => 'application/json'
192
+ }.merge(credential.proof(method, path, bytes.b, now_ms))
193
+ headers['Content-Type'] = 'application/json' if method == 'POST'
194
+ @http.call(
195
+ HttpRequest.new(verb: method, url: "#{base_url}#{path}", headers: headers,
196
+ body: method == 'POST' ? bytes : nil, timeout: timeout)
197
+ )
198
+ end
199
+
200
+ # What the last try's failure says: ran out of time, or never got an answer.
201
+ def unreachable(failure, seconds, command)
202
+ if failure.is_a?(Timeout::Error) || failure.is_a?(Errno::ETIMEDOUT)
203
+ TimeoutError.new("The Mailset API didn’t answer within #{format('%g', seconds)} seconds.",
204
+ command: command)
205
+ else
206
+ ConnectionError.new('The Mailset API can’t be reached.', command: command)
207
+ end
208
+ end
209
+
210
+ def header(response, name)
211
+ headers = response.headers || {}
212
+ value = headers[name] || headers.find { |key, _| key.to_s.downcase == name }&.last
213
+ value.is_a?(Array) ? value.first : value
214
+ end
215
+
216
+ def notice(response)
217
+ Transport.warn_upgrade if header(response, 'mailset-notice').to_s.match?(/upgrade/i)
218
+ end
219
+
220
+ # What `Retry-After` asks, at most 20 s, or a doubling pause with jitter.
221
+ def pause_seconds(tries, retry_after)
222
+ asked = Float(retry_after, exception: false) if retry_after
223
+ return [asked, 20].min if asked && asked >= 0
224
+
225
+ [8.0, 0.5 * (2**tries)].min * (0.5 + (rand / 2))
226
+ end
227
+
228
+ # Mailset's answer: its data, or its refusal raised.
229
+ def reply(response, command)
230
+ reply = begin
231
+ JSON.parse(response.body.to_s)
232
+ rescue JSON::ParserError
233
+ nil
234
+ end
235
+ return reply['data'] if reply.is_a?(Hash) && reply['ok'] == true
236
+
237
+ error = reply.is_a?(Hash) ? Error.from_body(reply['error'], status: response.status, command: command) : nil
238
+ raise error || Error.of('unavailable', 'The Mailset API can’t be reached.', status: response.status,
239
+ command: command)
240
+ end
241
+
242
+ # A command this credential can't run, refused before anything is sent.
243
+ def mismatch(info)
244
+ return nil if info.nil? || info.credentials.include?(credential.kind)
245
+
246
+ if credential.kind == :key
247
+ PermissionError.new(
248
+ "#{info.id} needs an API token (MAILSET_TOKEN): an app key (MAILSET_KEY) can’t run it. " \
249
+ 'Make a token with: npx @mailset/cli tokens create "<name>"',
250
+ command: info.id, needs: 'MAILSET_TOKEN'
251
+ )
252
+ else
253
+ PermissionError.new(
254
+ "#{info.id} answers only for an app key (MAILSET_KEY), and this is an API token. " \
255
+ 'Make a key with: npx @mailset/cli keys create --send --mailbox <address>',
256
+ command: info.id, needs: 'MAILSET_KEY'
257
+ )
258
+ end
259
+ end
260
+
261
+ # Mailset's "the grant doesn't allow that", said with the grant this command needs.
262
+ def grant_refusal(error, info)
263
+ flags = info && info.grant && GRANT_FLAGS[info.grant]
264
+ return error unless error.code == 'forbidden' && credential.kind == :key && flags && error.message.match?(/grant/i)
265
+
266
+ PermissionError.new(
267
+ "#{info.id} needs a key with the #{info.grant} grant, or an API token (MAILSET_TOKEN). " \
268
+ "Make one with: npx @mailset/cli keys create #{flags}",
269
+ status: error.status, command: info.id, needs: "MAILSET_KEY with the #{info.grant} grant"
270
+ )
271
+ end
272
+
273
+ # Net::HTTP with a few kept-alive connections per host, safe to share
274
+ # between threads. The default HTTP adapter.
275
+ class NetHttp
276
+ KEEP = 8
277
+
278
+ def initialize
279
+ @idle = Hash.new { |hash, key| hash[key] = [] }
280
+ @lock = Mutex.new
281
+ end
282
+
283
+ # @param request [Mailset::HttpRequest]
284
+ # @return [Mailset::HttpResponse]
285
+ def call(request)
286
+ uri = URI(request.url)
287
+ http = checkout(uri, request.timeout)
288
+ response = http.request(request_of(uri, request))
289
+ checkin(uri, http)
290
+ headers = {}
291
+ response.each_header { |name, value| headers[name] = value }
292
+ HttpResponse.new(status: response.code.to_i, headers: headers, body: response.body.to_s)
293
+ rescue StandardError
294
+ close(http)
295
+ raise
296
+ end
297
+
298
+ def inspect
299
+ '#<Mailset::Transport::NetHttp>'
300
+ end
301
+
302
+ private
303
+
304
+ def request_of(uri, request)
305
+ klass = request.verb == 'GET' ? Net::HTTP::Get : Net::HTTP::Post
306
+ built = klass.new(uri.request_uri)
307
+ request.headers.each { |name, value| built[name] = value }
308
+ built.body = request.body if request.body
309
+ built
310
+ end
311
+
312
+ def checkout(uri, timeout)
313
+ key = [uri.scheme, uri.host, uri.port]
314
+ http = @lock.synchronize { @idle[key].pop }
315
+ http = nil unless http&.started?
316
+ http ||= Net::HTTP.new(uri.host, uri.port).tap do |fresh|
317
+ fresh.use_ssl = uri.scheme == 'https'
318
+ fresh.open_timeout = timeout
319
+ # The client tries again itself, and counts each try.
320
+ fresh.max_retries = 0
321
+ end
322
+ http.read_timeout = timeout
323
+ http.write_timeout = timeout if http.respond_to?(:write_timeout=)
324
+ http.start unless http.started?
325
+ http
326
+ end
327
+
328
+ def checkin(uri, http)
329
+ key = [uri.scheme, uri.host, uri.port]
330
+ kept = @lock.synchronize do
331
+ next false if @idle[key].length >= KEEP
332
+
333
+ @idle[key].push(http)
334
+ true
335
+ end
336
+ close(http) unless kept
337
+ end
338
+
339
+ def close(http)
340
+ http.finish if http&.started?
341
+ rescue StandardError
342
+ nil
343
+ end
344
+ end
345
+ end
346
+ end
@@ -0,0 +1,9 @@
1
+ # Generated code. Don't edit.
2
+ #
3
+ # frozen_string_literal: true
4
+
5
+ module Mailset
6
+ # The gem's version, sent in `Mailset-Client`. Every Mailset SDK ships
7
+ # the same one.
8
+ VERSION = '0.7.0'
9
+ end
@@ -0,0 +1,348 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mailset
4
+ # Webhooks from Mailset: {verify} checks that a request came from your
5
+ # org's hook and hands you its events. It needs no client, so a service that
6
+ # only receives events uses it alone, with the hook's secret.
7
+ #
8
+ # # A Rails controller
9
+ # def create
10
+ # events = Mailset::Webhooks.verify(
11
+ # body: request.raw_post,
12
+ # headers: request.headers,
13
+ # secret: ENV.fetch('MAILSET_HOOK_SECRET')
14
+ # )
15
+ # events.each { |event| … }
16
+ # head :no_content
17
+ # rescue Mailset::Error
18
+ # head :unauthorized
19
+ # end
20
+ module Webhooks
21
+ # Every event type this version knows. A newer one comes as an {UnknownEvent}.
22
+ TYPES = %w[queued sent delivered bounced complained failed expired unsubscribed test].freeze
23
+
24
+ # How old a signature may be, in seconds, unless told.
25
+ TOLERANCE = 300
26
+
27
+ SIGNATURE = /\At=(\d+),v1=([0-9a-f]{64})\z/.freeze
28
+
29
+ # One event from your org's hook. Every field it came with is kept: {#to_h}
30
+ # is the event as Mailset sent it, `[]` reads any field by its wire name.
31
+ # Switch on its class or {#type}; ignore a type you don't know yet.
32
+ class Event
33
+ # @return [String]
34
+ attr_reader :type
35
+ # Stable for this message, recipient and happening: dedupe on it.
36
+ # @return [String]
37
+ attr_reader :id
38
+ # When it happened, in ms since the epoch.
39
+ # @return [Integer]
40
+ attr_reader :at
41
+
42
+ # The event's class for its type: {DeliveredEvent} for `delivered`, and
43
+ # so on, {UnknownEvent} for a type this version doesn't know.
44
+ def self.from_json(hash)
45
+ klass = CLASSES.fetch(hash['type'], UnknownEvent)
46
+ klass.new(hash)
47
+ end
48
+
49
+ # @api private
50
+ def initialize(fields)
51
+ @fields = fields.freeze
52
+ @type = fields['type']
53
+ @id = fields['id']
54
+ @at = fields['at']
55
+ end
56
+
57
+ # When it happened, as a Time.
58
+ # @return [Time]
59
+ def time
60
+ Time.at(at / 1000r)
61
+ end
62
+
63
+ # A field by its wire name (`'messageId'`) or Ruby name (`:message_id`).
64
+ def [](name)
65
+ key = name.to_s
66
+ return @fields[key] if @fields.key?(key)
67
+
68
+ @fields[key.gsub(/_([a-z])/) { Regexp.last_match(1).upcase }]
69
+ end
70
+
71
+ # The event as Mailset sent it, every field kept.
72
+ # @return [Hash{String => Object}]
73
+ def to_h
74
+ @fields.dup
75
+ end
76
+
77
+ def to_json(*args)
78
+ @fields.to_json(*args)
79
+ end
80
+
81
+ def deconstruct_keys(_keys)
82
+ @fields.transform_keys { |key| key.gsub(/([a-z0-9])([A-Z])/, '\1_\2').downcase.to_sym }
83
+ end
84
+
85
+ def ==(other)
86
+ other.is_a?(Event) && other.type == type && other.to_h == to_h
87
+ end
88
+
89
+ def inspect
90
+ "#<#{self.class.name} #{@fields.map { |key, value| "#{key}=#{value.inspect}" }.join(', ')}>"
91
+ end
92
+ alias to_s inspect
93
+ end
94
+
95
+ # What every event about a message carries. Never a subject or anything from the body.
96
+ class MessageEvent < Event
97
+ # Mailset's id for the message: the `id` that `send_email` answered.
98
+ # @return [String]
99
+ def message
100
+ @fields['message']
101
+ end
102
+
103
+ # Its Message-ID header, without the angle brackets: `message_id` from `send_email`.
104
+ # @return [String]
105
+ def message_id
106
+ @fields['messageId']
107
+ end
108
+
109
+ # One recipient: a message to three people has three of each event.
110
+ # @return [String]
111
+ def recipient
112
+ @fields['recipient']
113
+ end
114
+
115
+ # The app key that sent it, by the name it was approved with.
116
+ # @return [String]
117
+ def app
118
+ @fields['app']
119
+ end
120
+
121
+ # Present when the same content went to this recipient from the same
122
+ # address less than 10 minutes before, under another Message-ID: the
123
+ # `message` of that earlier send. Both were sent; give the send an
124
+ # `idempotency_key` and the second never goes.
125
+ # @return [String, nil]
126
+ def duplicate_of
127
+ @fields['duplicateOf']
128
+ end
129
+ end
130
+
131
+ # A limit holds it, so it goes out later.
132
+ class QueuedEvent < MessageEvent
133
+ # When it should go out, in ms since the epoch.
134
+ # @return [Integer]
135
+ def sends_at
136
+ @fields['sendsAt']
137
+ end
138
+
139
+ # Why it waits, in words for people.
140
+ # @return [String]
141
+ def reason
142
+ @fields['reason']
143
+ end
144
+ end
145
+
146
+ # The provider took it.
147
+ class SentEvent < MessageEvent; end
148
+
149
+ # The recipient's server took it.
150
+ class DeliveredEvent < MessageEvent; end
151
+
152
+ # How a bounce reads: `kind` is `hard` (it won't change) or `soft` (a
153
+ # later try may go). `class` is `mailbox`, `domain`, `full`, `too_large`,
154
+ # `policy`, `suppressed` or `other`; `mailbox` and `domain` mean the
155
+ # address can't get mail. On a bounce `class` reads that field, not
156
+ # `Object#class`.
157
+ class Bounce
158
+ # @return [String] `hard` or `soft`
159
+ attr_reader :kind
160
+ # The receiving server's reply, or for `suppressed`, Mailset's words.
161
+ # @return [String]
162
+ attr_reader :reason
163
+
164
+ # @!method class
165
+ # The bounce's class: `mailbox`, `domain`, `full`, `too_large`,
166
+ # `policy`, `suppressed` or `other`.
167
+ # @return [String]
168
+ define_method(:class) { @fields['class'] }
169
+
170
+ # @api private
171
+ def initialize(fields)
172
+ @fields = fields.is_a?(Hash) ? fields : {}
173
+ @kind = @fields['kind']
174
+ @reason = @fields['reason']
175
+ end
176
+
177
+ # Whether the address won't take mail: a hard bounce.
178
+ def hard?
179
+ kind == 'hard'
180
+ end
181
+
182
+ # @return [Hash{String => Object}]
183
+ def to_h
184
+ @fields.dup
185
+ end
186
+
187
+ def inspect
188
+ "#<Mailset::Webhooks::Bounce kind=#{kind.inspect} class=#{@fields['class'].inspect} reason=#{reason.inspect}>"
189
+ end
190
+ end
191
+
192
+ # It came back.
193
+ class BouncedEvent < MessageEvent
194
+ # @return [Mailset::Webhooks::Bounce]
195
+ def bounce
196
+ @bounce ||= Bounce.new(@fields['bounce'])
197
+ end
198
+ end
199
+
200
+ # The recipient marked it as spam. Stop writing to them.
201
+ class ComplainedEvent < MessageEvent; end
202
+
203
+ # Mailset couldn't send it: the provider refused it, its app was paused, or five tries failed.
204
+ class FailedEvent < MessageEvent
205
+ # @return [String]
206
+ def reason
207
+ @fields['reason']
208
+ end
209
+ end
210
+
211
+ # Its `deliver_by` came while it waited, so it never went.
212
+ class ExpiredEvent < MessageEvent
213
+ # @return [String]
214
+ def reason
215
+ @fields['reason']
216
+ end
217
+ end
218
+
219
+ # Someone used Mailset's unsubscribe link in promotional mail this app
220
+ # sent. From now on promotional mail from that mailbox to them is skipped,
221
+ # so take them off your own list too. Transactional mail still reaches them.
222
+ class UnsubscribedEvent < Event
223
+ # The address that unsubscribed, in lowercase.
224
+ # @return [String]
225
+ def recipient
226
+ @fields['recipient']
227
+ end
228
+
229
+ # The app key whose mail the link was in, by the name it was approved with.
230
+ # @return [String, nil]
231
+ def app
232
+ @fields['app']
233
+ end
234
+
235
+ # Mailset's id for the message the link was in.
236
+ # @return [String, nil]
237
+ def message
238
+ @fields['message']
239
+ end
240
+
241
+ # That message's Message-ID header, without the angle brackets.
242
+ # @return [String, nil]
243
+ def message_id
244
+ @fields['messageId']
245
+ end
246
+ end
247
+
248
+ # From `mailset hooks test` or the settings page: about no message.
249
+ class TestEvent < Event; end
250
+
251
+ # An event of a type this version doesn't know yet: its type, id and time,
252
+ # and every field as it came (`[]`, `to_h`).
253
+ class UnknownEvent < Event; end
254
+
255
+ # Each type's class.
256
+ CLASSES = {
257
+ 'queued' => QueuedEvent,
258
+ 'sent' => SentEvent,
259
+ 'delivered' => DeliveredEvent,
260
+ 'bounced' => BouncedEvent,
261
+ 'complained' => ComplainedEvent,
262
+ 'failed' => FailedEvent,
263
+ 'expired' => ExpiredEvent,
264
+ 'unsubscribed' => UnsubscribedEvent,
265
+ 'test' => TestEvent
266
+ }.freeze
267
+
268
+ module_function
269
+
270
+ # The events in a request from your hook, once its `Mailset-Signature`
271
+ # proves Mailset sent it with your secret, in the last 5 minutes. Answer
272
+ # 2xx once you've kept them: until then Mailset sends the batch again,
273
+ # with the same ids.
274
+ #
275
+ # @param body [String, #read] the body exactly as it arrived, before any
276
+ # JSON parsing: the signature covers these bytes.
277
+ # @param headers [Hash, #[], nil] the request's headers: a Hash in any
278
+ # case, Rails' `request.headers`, or Rack's env.
279
+ # @param signature [String, nil] the `Mailset-Signature` header's value,
280
+ # instead of `headers`.
281
+ # @param secret [String] the hook's signing secret, from `mailset hooks set`.
282
+ # @param tolerance [Integer] how old a signature may be, in seconds.
283
+ # @param now [Time] the clock. Only tests change it.
284
+ # @return [Array<Mailset::Webhooks::Event>]
285
+ # @raise [Mailset::AuthenticationError] `unauthorized`: a missing or wrong signature.
286
+ # @raise [Mailset::ExpiredError] `expired`: a signature older or newer than `tolerance`.
287
+ # @raise [Mailset::InvalidRequestError] `invalid_input`: a body that isn't events.
288
+ def verify(body:, secret:, headers: nil, signature: nil, tolerance: TOLERANCE, now: Time.now)
289
+ signed = SIGNATURE.match((signature || header_of(headers)).to_s.strip)
290
+ raise AuthenticationError, 'This request carries no Mailset-Signature.' unless signed
291
+
292
+ raw = body_of(body)
293
+ seconds = signed[1]
294
+ mac = OpenSSL::HMAC.hexdigest('SHA256', secret.to_s, "#{seconds}.".b + raw)
295
+ unless OpenSSL.fixed_length_secure_compare(mac, signed[2])
296
+ raise AuthenticationError, 'The Mailset-Signature doesn’t match. Check the hook’s secret.'
297
+ end
298
+ raise ExpiredError, 'The Mailset-Signature is too old.' if (now.to_r - seconds.to_i).abs > tolerance
299
+
300
+ events_of(raw)
301
+ end
302
+
303
+ # `Mailset-Signature`, in whichever shape this server hands headers.
304
+ def header_of(headers)
305
+ return nil if headers.nil?
306
+
307
+ if headers.is_a?(Hash)
308
+ found = headers.find do |key, _|
309
+ name = key.to_s.downcase.tr('_', '-')
310
+ ['mailset-signature', 'http-mailset-signature'].include?(name)
311
+ end
312
+ value = found&.last
313
+ else
314
+ value = %w[Mailset-Signature mailset-signature HTTP_MAILSET_SIGNATURE].lazy.map { |name| headers[name] }
315
+ .find { |one| !one.nil? }
316
+ end
317
+ value.is_a?(Array) ? value.first : value
318
+ end
319
+
320
+ def body_of(body)
321
+ text = if body.respond_to?(:read)
322
+ read = body.read
323
+ body.rewind if body.respond_to?(:rewind)
324
+ read
325
+ else
326
+ body
327
+ end
328
+ text.to_s.b
329
+ end
330
+
331
+ def events_of(raw)
332
+ batch = JSON.parse(raw.dup.force_encoding(Encoding::UTF_8))
333
+ events = batch.is_a?(Hash) ? batch['events'] : nil
334
+ unless events.is_a?(Array) && events.all? { |event| event?(event) }
335
+ raise InvalidRequestError, 'That body isn’t a batch of Mailset events.'
336
+ end
337
+
338
+ events.map { |event| Event.from_json(event) }
339
+ rescue JSON::ParserError, EncodingError
340
+ raise InvalidRequestError, 'That body isn’t a batch of Mailset events.'
341
+ end
342
+
343
+ def event?(value)
344
+ value.is_a?(Hash) && value['id'].is_a?(String) && value['type'].is_a?(String) && value['at'].is_a?(Numeric)
345
+ end
346
+ private_class_method :header_of, :body_of, :events_of, :event?
347
+ end
348
+ end