billionsend 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.
- checksums.yaml +7 -0
- data/CHANGELOG.md +15 -0
- data/LICENSE +21 -0
- data/README.md +258 -0
- data/lib/billionsend/client.rb +253 -0
- data/lib/billionsend/errors.rb +115 -0
- data/lib/billionsend/pagination.rb +39 -0
- data/lib/billionsend/resources.rb +3436 -0
- data/lib/billionsend/streaming.rb +284 -0
- data/lib/billionsend/transport.rb +163 -0
- data/lib/billionsend/version.rb +5 -0
- data/lib/billionsend/webhooks.rb +104 -0
- data/lib/billionsend.rb +20 -0
- metadata +55 -0
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
|
|
5
|
+
module BillionSend
|
|
6
|
+
# One raw event of a +text/event-stream+ answer.
|
|
7
|
+
#
|
|
8
|
+
# +id+ is the stream position to resume from (the last id field seen),
|
|
9
|
+
# +event+ the event name, +data+ the data parsed as JSON (the raw text if it
|
|
10
|
+
# is not JSON).
|
|
11
|
+
ServerSentEvent = Struct.new(:id, :event, :data, keyword_init: true)
|
|
12
|
+
|
|
13
|
+
# One inbox event: the webhook event of the same name, wrapped.
|
|
14
|
+
#
|
|
15
|
+
# +id+ is the stream position after this event (resume from it with
|
|
16
|
+
# +last_event_id:+), +event+ the event name (such as "inbox.email.received"),
|
|
17
|
+
# +data+ a Hash with "type", "created_at", "inbox_id" (nil for an
|
|
18
|
+
# email.received that reached no inbox) and the webhook payload's "data".
|
|
19
|
+
InboxStreamEvent = Struct.new(:id, :event, :data, keyword_init: true)
|
|
20
|
+
|
|
21
|
+
# Events may have been lost before this point: catch up through the REST
|
|
22
|
+
# lists. +data+ is a Hash whose "reason" says why ("retention": the position
|
|
23
|
+
# is over 24 hours old).
|
|
24
|
+
StreamGapEvent = Struct.new(:data, keyword_init: true) do
|
|
25
|
+
def id = nil
|
|
26
|
+
def event = EventStream::GAP_EVENT
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Incremental parser of the +text/event-stream+ format.
|
|
30
|
+
#
|
|
31
|
+
# Lines may end in CRLF, LF or CR and may be split anywhere across chunks;
|
|
32
|
+
# comment lines are skipped; several data lines join with newlines.
|
|
33
|
+
class SSEDecoder
|
|
34
|
+
attr_reader :last_event_id, :retry_ms
|
|
35
|
+
|
|
36
|
+
def initialize
|
|
37
|
+
@bytes = "".b
|
|
38
|
+
@buffer = +""
|
|
39
|
+
@started = false
|
|
40
|
+
@after_cr = false
|
|
41
|
+
@data = []
|
|
42
|
+
@event = ""
|
|
43
|
+
@last_event_id = nil
|
|
44
|
+
@retry_ms = nil
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# Feeds one chunk of bytes; returns the events it completed.
|
|
48
|
+
def feed(chunk)
|
|
49
|
+
text = decode(chunk)
|
|
50
|
+
if !@started && !text.empty?
|
|
51
|
+
@started = true
|
|
52
|
+
text = text.delete_prefix("")
|
|
53
|
+
end
|
|
54
|
+
if @after_cr && !text.empty?
|
|
55
|
+
# The previous chunk ended in CR: a LF here completes that CRLF.
|
|
56
|
+
@after_cr = false
|
|
57
|
+
text = text.delete_prefix("\n")
|
|
58
|
+
end
|
|
59
|
+
@buffer << text
|
|
60
|
+
events = []
|
|
61
|
+
while (index = @buffer.index(/[\r\n]/))
|
|
62
|
+
finish = index + 1
|
|
63
|
+
if @buffer[index] == "\r"
|
|
64
|
+
if index + 1 == @buffer.length
|
|
65
|
+
@after_cr = true
|
|
66
|
+
elsif @buffer[index + 1] == "\n"
|
|
67
|
+
finish = index + 2
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
line = @buffer[0, index]
|
|
71
|
+
@buffer = @buffer[finish..]
|
|
72
|
+
event = line(line)
|
|
73
|
+
events << event if event
|
|
74
|
+
end
|
|
75
|
+
events
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
private
|
|
79
|
+
|
|
80
|
+
# UTF-8 text of the bytes so far, keeping an incomplete trailing character for the next chunk.
|
|
81
|
+
def decode(chunk)
|
|
82
|
+
@bytes << chunk.b
|
|
83
|
+
cut = @bytes.bytesize
|
|
84
|
+
# Back off over at most 3 continuation bytes to the start of a split character.
|
|
85
|
+
(1..[3, cut].min).each do |back|
|
|
86
|
+
byte = @bytes.getbyte(cut - back)
|
|
87
|
+
next if byte & 0xC0 == 0x80
|
|
88
|
+
|
|
89
|
+
width = if byte >= 0xF0 then 4
|
|
90
|
+
elsif byte >= 0xE0 then 3
|
|
91
|
+
elsif byte >= 0xC0 then 2
|
|
92
|
+
else 1
|
|
93
|
+
end
|
|
94
|
+
cut -= back if width > back
|
|
95
|
+
break
|
|
96
|
+
end
|
|
97
|
+
text = @bytes.byteslice(0, cut)
|
|
98
|
+
@bytes = @bytes.byteslice(cut..)
|
|
99
|
+
text.force_encoding(Encoding::UTF_8).scrub("�")
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
def line(line)
|
|
103
|
+
return dispatch if line.empty?
|
|
104
|
+
return nil if line.start_with?(":")
|
|
105
|
+
|
|
106
|
+
name, value = line.split(":", 2)
|
|
107
|
+
value = value.to_s.delete_prefix(" ")
|
|
108
|
+
case name
|
|
109
|
+
when "data" then @data << value
|
|
110
|
+
when "event" then @event = value
|
|
111
|
+
when "id" then @last_event_id = value unless value.include?("\0")
|
|
112
|
+
when "retry" then @retry_ms = Integer(value, 10) if value.match?(/\A[0-9]+\z/)
|
|
113
|
+
end
|
|
114
|
+
nil
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def dispatch
|
|
118
|
+
if @data.empty?
|
|
119
|
+
@event = ""
|
|
120
|
+
return nil
|
|
121
|
+
end
|
|
122
|
+
raw = @data.join("\n")
|
|
123
|
+
data = begin
|
|
124
|
+
JSON.parse(raw)
|
|
125
|
+
rescue JSON::ParserError
|
|
126
|
+
raw
|
|
127
|
+
end
|
|
128
|
+
event = ServerSentEvent.new(id: @last_event_id, event: @event.empty? ? "message" : @event, data: data)
|
|
129
|
+
@data = []
|
|
130
|
+
@event = ""
|
|
131
|
+
event
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
# A server-sent event stream (+text/event-stream+) of inbox events.
|
|
136
|
+
#
|
|
137
|
+
# The method that returns it opens it, so a refused stream raises at once.
|
|
138
|
+
# Iterating yields {InboxStreamEvent} and {StreamGapEvent} objects; when the
|
|
139
|
+
# server ends the stream (it does so every few minutes) or the connection
|
|
140
|
+
# drops, the stream reconnects with Last-Event-ID set to the last id it saw
|
|
141
|
+
# and resumes without losing events, waiting a second (or the server's retry
|
|
142
|
+
# field) first. A connection that opens starts the count again, however
|
|
143
|
+
# quiet the inbox. A reconnect the API answers with a 429 or 5xx waits what
|
|
144
|
+
# its Retry-After asks (one over 60 seconds raises that error at once). After
|
|
145
|
+
# +max_reconnects+ reconnects in a row that fail to open, iterating raises
|
|
146
|
+
# the API's error for the last one ({RateLimitError}, {APIError}), or
|
|
147
|
+
# {APIConnectionError} when it got no answer; a reconnect the API refuses for
|
|
148
|
+
# good (a revoked key) raises its own error. An error raised by the block
|
|
149
|
+
# passes through as it is.
|
|
150
|
+
#
|
|
151
|
+
# The server replays at most 24 hours of missed events. A stream resumed from
|
|
152
|
+
# an older id first gets a {StreamGapEvent}: events may be missing, so read
|
|
153
|
+
# the REST lists to catch up. It is handed out once per position, although
|
|
154
|
+
# the server repeats it on every reconnect until a newer event arrives.
|
|
155
|
+
#
|
|
156
|
+
# The stream of one inbox ends (iteration stops) after that inbox's
|
|
157
|
+
# inbox.deleted or inbox.expired event. Close the stream when done.
|
|
158
|
+
class EventStream
|
|
159
|
+
include Enumerable
|
|
160
|
+
|
|
161
|
+
DEFAULT_RETRY = 1.0
|
|
162
|
+
GAP_EVENT = "stream.gap"
|
|
163
|
+
TEAM_STREAM_PATH = "/inboxes/events"
|
|
164
|
+
# After one of these, the server ends an inbox's own stream for good.
|
|
165
|
+
INBOX_GONE = %w[inbox.deleted inbox.expired].freeze
|
|
166
|
+
|
|
167
|
+
# The id of the last event received: pass it as +last_event_id:+ to resume later.
|
|
168
|
+
attr_reader :last_event_id
|
|
169
|
+
|
|
170
|
+
def initialize(client, path, query:, last_event_id:, max_reconnects:, extra_headers:, timeout:)
|
|
171
|
+
raise ArgumentError, "max_reconnects must be 0 or more" if max_reconnects.negative?
|
|
172
|
+
|
|
173
|
+
@client = client
|
|
174
|
+
@path = path
|
|
175
|
+
@query = query
|
|
176
|
+
@last_event_id = last_event_id
|
|
177
|
+
@max_reconnects = max_reconnects
|
|
178
|
+
@extra_headers = extra_headers
|
|
179
|
+
@timeout = timeout
|
|
180
|
+
@retry = DEFAULT_RETRY
|
|
181
|
+
@closed = false
|
|
182
|
+
@one_inbox = path.sub(%r{/+\z}, "") != TEAM_STREAM_PATH
|
|
183
|
+
# The position a gap was last handed out at; the server repeats it on reconnect.
|
|
184
|
+
@gap_at = nil
|
|
185
|
+
@response = nil
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# @api private
|
|
189
|
+
def open
|
|
190
|
+
@response = @client.open_stream(@path, query: @query, last_event_id: @last_event_id,
|
|
191
|
+
extra_headers: @extra_headers, timeout: @timeout)
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
def each
|
|
195
|
+
return enum_for(:each) unless block_given?
|
|
196
|
+
|
|
197
|
+
# The end of the last open connection, then each reconnect that failed to open.
|
|
198
|
+
failures = 0
|
|
199
|
+
# The API's answer to the last failed reconnect, and the wait it asked for.
|
|
200
|
+
last_error = nil
|
|
201
|
+
wait = nil
|
|
202
|
+
until @closed
|
|
203
|
+
if @response
|
|
204
|
+
failures = 0
|
|
205
|
+
last_error = nil
|
|
206
|
+
response = @response
|
|
207
|
+
decoder = SSEDecoder.new
|
|
208
|
+
# Set while the block runs: its errors are the caller's, not a dropped connection.
|
|
209
|
+
in_block = false
|
|
210
|
+
begin
|
|
211
|
+
response.each_chunk do |chunk|
|
|
212
|
+
decoder.feed(chunk).each do |sse|
|
|
213
|
+
event = saw(sse)
|
|
214
|
+
next unless event
|
|
215
|
+
|
|
216
|
+
in_block = true
|
|
217
|
+
yield event
|
|
218
|
+
in_block = false
|
|
219
|
+
break if @closed
|
|
220
|
+
end
|
|
221
|
+
break if @closed
|
|
222
|
+
end
|
|
223
|
+
# Every event was handed out; an id sent without data still moves the position.
|
|
224
|
+
@last_event_id = decoder.last_event_id if !@closed && decoder.last_event_id
|
|
225
|
+
rescue APIConnectionError
|
|
226
|
+
raise if in_block
|
|
227
|
+
|
|
228
|
+
nil # the connection dropped: reconnect below
|
|
229
|
+
ensure
|
|
230
|
+
@retry = decoder.retry_ms / 1000.0 if decoder.retry_ms
|
|
231
|
+
response.close
|
|
232
|
+
@response = nil
|
|
233
|
+
end
|
|
234
|
+
end
|
|
235
|
+
return if @closed
|
|
236
|
+
|
|
237
|
+
failures += 1
|
|
238
|
+
if failures > @max_reconnects
|
|
239
|
+
raise last_error if last_error
|
|
240
|
+
|
|
241
|
+
raise APIConnectionError, "The event stream disconnected; gave up after #{@max_reconnects} reconnects"
|
|
242
|
+
end
|
|
243
|
+
|
|
244
|
+
@client.pause(wait || @retry)
|
|
245
|
+
begin
|
|
246
|
+
open
|
|
247
|
+
rescue APIConnectionError
|
|
248
|
+
last_error = wait = nil # no answer: counted on the next turn
|
|
249
|
+
rescue RateLimitError, APIError => e
|
|
250
|
+
wait = e.response && Client.retry_after(e.response)
|
|
251
|
+
raise if wait && wait > Client::MAX_RETRY_DELAY
|
|
252
|
+
|
|
253
|
+
last_error = e
|
|
254
|
+
end
|
|
255
|
+
end
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
def close
|
|
259
|
+
@closed = true
|
|
260
|
+
@response&.close
|
|
261
|
+
@response = nil
|
|
262
|
+
end
|
|
263
|
+
|
|
264
|
+
private
|
|
265
|
+
|
|
266
|
+
# The event to hand out for +sse+, or nil for a repeated gap.
|
|
267
|
+
def saw(sse)
|
|
268
|
+
if sse.event == GAP_EVENT
|
|
269
|
+
return nil if @gap_at == [@last_event_id]
|
|
270
|
+
|
|
271
|
+
@gap_at = [@last_event_id]
|
|
272
|
+
reason = sse.data.is_a?(Hash) && sse.data["reason"].is_a?(String) ? sse.data["reason"] : "unknown"
|
|
273
|
+
return StreamGapEvent.new(data: { "reason" => reason })
|
|
274
|
+
end
|
|
275
|
+
if sse.id.nil? || !sse.data.is_a?(Hash)
|
|
276
|
+
raise Error, "Malformed #{sse.event.inspect} event in the stream"
|
|
277
|
+
end
|
|
278
|
+
|
|
279
|
+
@last_event_id = sse.id
|
|
280
|
+
@closed = true if @one_inbox && INBOX_GONE.include?(sse.event)
|
|
281
|
+
InboxStreamEvent.new(id: sse.id, event: sse.event, data: sse.data)
|
|
282
|
+
end
|
|
283
|
+
end
|
|
284
|
+
end
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "openssl"
|
|
5
|
+
require "uri"
|
|
6
|
+
|
|
7
|
+
module BillionSend
|
|
8
|
+
# One HTTP request, as the client hands it to a transport.
|
|
9
|
+
Request = Struct.new(:method, :url, :headers, :body, :timeout, keyword_init: true)
|
|
10
|
+
|
|
11
|
+
# One HTTP answer. Header names are lower case.
|
|
12
|
+
Response = Struct.new(:status, :headers, :body, keyword_init: true) do
|
|
13
|
+
def header(name)
|
|
14
|
+
headers[name.downcase]
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
def success?
|
|
18
|
+
status >= 200 && status < 300
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# The HTTP layer: Net::HTTP, one connection a request.
|
|
23
|
+
#
|
|
24
|
+
# Anything answering +call(request)+ with a {Response} and +open_stream(request)+
|
|
25
|
+
# with an object that has +status+, +headers+, +header(name)+, +read+ (the
|
|
26
|
+
# whole body), +each_chunk+ and +close+ can stand in for it (pass it as the
|
|
27
|
+
# client's +transport:+). Both raise {APIConnectionError} or {APITimeoutError}
|
|
28
|
+
# when no answer comes back.
|
|
29
|
+
class NetHTTPTransport
|
|
30
|
+
METHODS = {
|
|
31
|
+
"GET" => Net::HTTP::Get,
|
|
32
|
+
"POST" => Net::HTTP::Post,
|
|
33
|
+
"PUT" => Net::HTTP::Put,
|
|
34
|
+
"PATCH" => Net::HTTP::Patch,
|
|
35
|
+
"DELETE" => Net::HTTP::Delete
|
|
36
|
+
}.freeze
|
|
37
|
+
|
|
38
|
+
# A read that waits far longer than an event stream's 15-second keepalive
|
|
39
|
+
# means the connection is gone.
|
|
40
|
+
STREAM_READ_TIMEOUT = 60
|
|
41
|
+
|
|
42
|
+
def call(request)
|
|
43
|
+
uri = URI(request.url)
|
|
44
|
+
guard do
|
|
45
|
+
http = connection(uri, request.timeout, request.timeout)
|
|
46
|
+
http.start do |conn|
|
|
47
|
+
answer = conn.request(build(uri, request))
|
|
48
|
+
Response.new(status: answer.code.to_i, headers: headers_of(answer), body: answer.body.to_s)
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def open_stream(request)
|
|
54
|
+
uri = URI(request.url)
|
|
55
|
+
read_timeout = [request.timeout.to_f, STREAM_READ_TIMEOUT].max
|
|
56
|
+
http = connection(uri, request.timeout, read_timeout)
|
|
57
|
+
stream = OpenStream.new(http, build(uri, request), method(:guard))
|
|
58
|
+
stream.start
|
|
59
|
+
stream
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Runs the block, turning Net::HTTP's failures into the SDK's.
|
|
63
|
+
def guard
|
|
64
|
+
yield
|
|
65
|
+
rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout => e
|
|
66
|
+
raise APITimeoutError, "Request timed out: #{e.message}"
|
|
67
|
+
rescue SocketError, SystemCallError, IOError, OpenSSL::SSL::SSLError, EOFError,
|
|
68
|
+
Net::HTTPBadResponse, Net::ProtocolError => e
|
|
69
|
+
raise APIConnectionError, "Connection error: #{e.message}"
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
private
|
|
73
|
+
|
|
74
|
+
def connection(uri, open_timeout, read_timeout)
|
|
75
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
76
|
+
http.use_ssl = uri.scheme == "https"
|
|
77
|
+
http.open_timeout = open_timeout
|
|
78
|
+
http.read_timeout = read_timeout
|
|
79
|
+
http.write_timeout = open_timeout
|
|
80
|
+
# The client decides what is retried; Net::HTTP would repeat a GET on its own.
|
|
81
|
+
http.max_retries = 0
|
|
82
|
+
http
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def build(uri, request)
|
|
86
|
+
req = METHODS.fetch(request.method).new(uri)
|
|
87
|
+
request.headers.each { |name, value| req[name] = value }
|
|
88
|
+
req.body = request.body if request.body
|
|
89
|
+
req
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
def headers_of(answer)
|
|
93
|
+
answer.each_header.to_h { |name, value| [name.downcase, value] }
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# A streamed answer: the status and headers are read when it opens, the
|
|
97
|
+
# body chunk by chunk as it is iterated. Net::HTTP reads a body only inside
|
|
98
|
+
# the block of #request, so the block runs in a Fiber that hands each piece
|
|
99
|
+
# out as it arrives.
|
|
100
|
+
class OpenStream
|
|
101
|
+
attr_reader :status, :headers
|
|
102
|
+
|
|
103
|
+
def initialize(http, request, guard)
|
|
104
|
+
@http = http
|
|
105
|
+
@request = request
|
|
106
|
+
@guard = guard
|
|
107
|
+
@done = false
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
def start
|
|
111
|
+
@fiber = Fiber.new do
|
|
112
|
+
@guard.call do
|
|
113
|
+
@http.start do |conn|
|
|
114
|
+
conn.request(@request) do |answer|
|
|
115
|
+
Fiber.yield([:head, answer.code.to_i, answer.each_header.to_h { |k, v| [k.downcase, v] }])
|
|
116
|
+
answer.read_body { |chunk| Fiber.yield([:chunk, chunk]) }
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
end
|
|
120
|
+
[:end]
|
|
121
|
+
end
|
|
122
|
+
kind, @status, @headers = resume
|
|
123
|
+
raise APIConnectionError, "Connection closed before an answer" unless kind == :head
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def header(name)
|
|
127
|
+
@headers[name.downcase]
|
|
128
|
+
end
|
|
129
|
+
|
|
130
|
+
def each_chunk
|
|
131
|
+
until @done
|
|
132
|
+
kind, chunk = resume
|
|
133
|
+
if kind == :chunk
|
|
134
|
+
yield chunk
|
|
135
|
+
else
|
|
136
|
+
@done = true
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def read
|
|
142
|
+
body = +""
|
|
143
|
+
each_chunk { |chunk| body << chunk }
|
|
144
|
+
body
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
def close
|
|
148
|
+
@done = true
|
|
149
|
+
@http.finish if @http.started?
|
|
150
|
+
rescue IOError
|
|
151
|
+
nil
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
private
|
|
155
|
+
|
|
156
|
+
def resume
|
|
157
|
+
return [:end] if @done || !@fiber.alive?
|
|
158
|
+
|
|
159
|
+
@fiber.resume
|
|
160
|
+
end
|
|
161
|
+
end
|
|
162
|
+
end
|
|
163
|
+
end
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "openssl"
|
|
5
|
+
|
|
6
|
+
module BillionSend
|
|
7
|
+
# Verifies the signature of a webhook delivery.
|
|
8
|
+
#
|
|
9
|
+
# BillionSend signs every delivery the Standard Webhooks way: the secret is
|
|
10
|
+
# +whsec_+ followed by base64 of 24 to 64 bytes, the signed content is
|
|
11
|
+
# +<webhook-id>.<webhook-timestamp>.<body>+, and +webhook-signature+ holds
|
|
12
|
+
# +v1,<base64 HMAC-SHA256>+, several space-separated during a secret rotation.
|
|
13
|
+
module Webhooks
|
|
14
|
+
# Seconds a delivery's timestamp may differ from the receiver's clock.
|
|
15
|
+
DEFAULT_TOLERANCE = 300
|
|
16
|
+
SECRET_PREFIX = "whsec_"
|
|
17
|
+
SECRET_BYTES = (24..64)
|
|
18
|
+
|
|
19
|
+
# Checks a webhook delivery and returns its parsed body (a Hash with
|
|
20
|
+
# "type", "created_at" and "data").
|
|
21
|
+
#
|
|
22
|
+
# @param payload [String] the request body exactly as received, before any
|
|
23
|
+
# JSON parsing: re-serialised JSON does not verify
|
|
24
|
+
# @param headers [Hash, #each] the request headers; names are matched
|
|
25
|
+
# case-insensitively (webhook-id, webhook-timestamp, webhook-signature)
|
|
26
|
+
# @param secret [String] the endpoint's signing secret (whsec_...)
|
|
27
|
+
# @param tolerance [Integer] seconds the timestamp may be off the current
|
|
28
|
+
# time, either way; this bounds replays of a captured delivery
|
|
29
|
+
# @param now [Numeric, nil] the current Unix time, for tests
|
|
30
|
+
# @raise [WebhookVerificationError] a header is missing, the timestamp is
|
|
31
|
+
# outside the tolerance, no signature matches, or the body is not a JSON object
|
|
32
|
+
# @raise [ArgumentError] +secret+ is not a webhook secret
|
|
33
|
+
def self.verify(payload, headers, secret, tolerance: DEFAULT_TOLERANCE, now: nil)
|
|
34
|
+
key = secret_key(secret)
|
|
35
|
+
msg_id = header(headers, "webhook-id")
|
|
36
|
+
timestamp = header(headers, "webhook-timestamp")
|
|
37
|
+
signatures = header(headers, "webhook-signature")
|
|
38
|
+
if msg_id.nil? || timestamp.nil? || signatures.nil?
|
|
39
|
+
raise WebhookVerificationError, "Missing webhook-id, webhook-timestamp or webhook-signature"
|
|
40
|
+
end
|
|
41
|
+
raise WebhookVerificationError, "Invalid webhook-timestamp" unless timestamp.match?(/\A[0-9]+\z/)
|
|
42
|
+
|
|
43
|
+
current = now || Time.now.to_f
|
|
44
|
+
if (current - Integer(timestamp, 10)).abs > tolerance
|
|
45
|
+
raise WebhookVerificationError, "Webhook timestamp is outside the tolerance"
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
body = payload.to_s.b
|
|
49
|
+
expected = OpenSSL::HMAC.digest("SHA256", key, "#{msg_id}.#{timestamp}.".b + body)
|
|
50
|
+
matched = signatures.split(" ").any? do |candidate|
|
|
51
|
+
version, encoded = candidate.split(",", 2)
|
|
52
|
+
next false unless version == "v1" && encoded && !encoded.empty?
|
|
53
|
+
|
|
54
|
+
given = decode64(encoded)
|
|
55
|
+
given && given.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(given, expected)
|
|
56
|
+
end
|
|
57
|
+
raise WebhookVerificationError, "No webhook signature matches" unless matched
|
|
58
|
+
|
|
59
|
+
begin
|
|
60
|
+
event = JSON.parse(body.force_encoding(Encoding::UTF_8))
|
|
61
|
+
rescue JSON::ParserError
|
|
62
|
+
raise WebhookVerificationError, "Webhook body is not JSON"
|
|
63
|
+
end
|
|
64
|
+
raise WebhookVerificationError, "Webhook body is not a JSON object" unless event.is_a?(Hash)
|
|
65
|
+
|
|
66
|
+
event
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# Key bytes of a whsec_ secret: canonical base64 of 24 to 64 bytes, else ArgumentError.
|
|
70
|
+
def self.secret_key(secret)
|
|
71
|
+
raise ArgumentError, "A webhook secret starts with whsec_" unless secret.to_s.start_with?(SECRET_PREFIX)
|
|
72
|
+
|
|
73
|
+
encoded = secret[SECRET_PREFIX.length..]
|
|
74
|
+
key = decode64(encoded)
|
|
75
|
+
raise ArgumentError, "A webhook secret is whsec_ followed by base64" if key.nil?
|
|
76
|
+
raise ArgumentError, "A webhook secret holds 24 to 64 bytes" unless SECRET_BYTES.cover?(key.bytesize)
|
|
77
|
+
raise ArgumentError, "A webhook secret is whsec_ followed by base64" unless [key].pack("m0") == encoded
|
|
78
|
+
|
|
79
|
+
key
|
|
80
|
+
end
|
|
81
|
+
private_class_method :secret_key
|
|
82
|
+
|
|
83
|
+
def self.decode64(text)
|
|
84
|
+
text.unpack1("m0")
|
|
85
|
+
rescue ArgumentError
|
|
86
|
+
nil
|
|
87
|
+
end
|
|
88
|
+
private_class_method :decode64
|
|
89
|
+
|
|
90
|
+
def self.header(headers, name)
|
|
91
|
+
headers.each do |key, value|
|
|
92
|
+
value = value.first if value.is_a?(Array)
|
|
93
|
+
return value.to_s if key.to_s.casecmp?(name) && !value.to_s.empty?
|
|
94
|
+
end
|
|
95
|
+
nil
|
|
96
|
+
end
|
|
97
|
+
private_class_method :header
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# Checks a webhook delivery and returns its parsed body; see {Webhooks.verify}.
|
|
101
|
+
def self.verify_webhook(payload, headers, secret, **options)
|
|
102
|
+
Webhooks.verify(payload, headers, secret, **options)
|
|
103
|
+
end
|
|
104
|
+
end
|
data/lib/billionsend.rb
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "billionsend/version"
|
|
4
|
+
require_relative "billionsend/errors"
|
|
5
|
+
require_relative "billionsend/transport"
|
|
6
|
+
require_relative "billionsend/pagination"
|
|
7
|
+
require_relative "billionsend/webhooks"
|
|
8
|
+
require_relative "billionsend/streaming"
|
|
9
|
+
require_relative "billionsend/resources"
|
|
10
|
+
require_relative "billionsend/client"
|
|
11
|
+
|
|
12
|
+
# The BillionSend API: sending, receiving, contacts, broadcasts and agent inboxes.
|
|
13
|
+
#
|
|
14
|
+
# require "billionsend"
|
|
15
|
+
#
|
|
16
|
+
# client = BillionSend::Client.new # reads BILLIONSEND_API_KEY
|
|
17
|
+
# client.emails.send({ from: "Acme <hello@acme.com>", to: ["user@example.com"],
|
|
18
|
+
# subject: "Hello", text: "It works." })
|
|
19
|
+
module BillionSend
|
|
20
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: billionsend
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- BillionSend
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
description: 'Send, receive and track email with BillionSend: every operation of the
|
|
13
|
+
API, retries with idempotency keys, inbox event streams and webhook verification.'
|
|
14
|
+
executables: []
|
|
15
|
+
extensions: []
|
|
16
|
+
extra_rdoc_files: []
|
|
17
|
+
files:
|
|
18
|
+
- CHANGELOG.md
|
|
19
|
+
- LICENSE
|
|
20
|
+
- README.md
|
|
21
|
+
- lib/billionsend.rb
|
|
22
|
+
- lib/billionsend/client.rb
|
|
23
|
+
- lib/billionsend/errors.rb
|
|
24
|
+
- lib/billionsend/pagination.rb
|
|
25
|
+
- lib/billionsend/resources.rb
|
|
26
|
+
- lib/billionsend/streaming.rb
|
|
27
|
+
- lib/billionsend/transport.rb
|
|
28
|
+
- lib/billionsend/version.rb
|
|
29
|
+
- lib/billionsend/webhooks.rb
|
|
30
|
+
homepage: https://github.com/billionsend/billionsend-ruby
|
|
31
|
+
licenses:
|
|
32
|
+
- MIT
|
|
33
|
+
metadata:
|
|
34
|
+
homepage_uri: https://github.com/billionsend/billionsend-ruby
|
|
35
|
+
source_code_uri: https://github.com/billionsend/billionsend-ruby
|
|
36
|
+
changelog_uri: https://github.com/billionsend/billionsend-ruby/blob/main/CHANGELOG.md
|
|
37
|
+
documentation_uri: https://billionsend.com/docs
|
|
38
|
+
rdoc_options: []
|
|
39
|
+
require_paths:
|
|
40
|
+
- lib
|
|
41
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
42
|
+
requirements:
|
|
43
|
+
- - ">="
|
|
44
|
+
- !ruby/object:Gem::Version
|
|
45
|
+
version: '3.1'
|
|
46
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
47
|
+
requirements:
|
|
48
|
+
- - ">="
|
|
49
|
+
- !ruby/object:Gem::Version
|
|
50
|
+
version: '0'
|
|
51
|
+
requirements: []
|
|
52
|
+
rubygems_version: 3.6.9
|
|
53
|
+
specification_version: 4
|
|
54
|
+
summary: Ruby client for the BillionSend email API
|
|
55
|
+
test_files: []
|