billionverify 1.0.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b77f3e2e6baf30a6896b2adbb21fe108abf610040a7208634fb07afc06c19f83
4
+ data.tar.gz: d0643f4e316b57abd4c279f4157f8f56c6f4ce0a50effd48dc35f50b06dc565d
5
+ SHA512:
6
+ metadata.gz: 848c1d61ab8ce1685895fdab124b60931536173e0db9501523c071fe500146a7cf03a885df8cc0e2c85646d019955a422101c36ff31fed4630020702e4641091
7
+ data.tar.gz: 9e2bb0f3465703c61304fd9d05667ddcc77d937044e78352dc1e2b9bd29b7f8c3a1daff95b3f85d94fe4ea7e2f90c625a37580e661c00fd54bb0efa94e69e35d
data/CHANGELOG.md ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ First release.
6
+
7
+ - `BillionVerify::Client` covering every operation of the BillionVerify API: single and batch verification, the free disposable check, file verification (upload, status, long polling, results download, resume), credits, webhooks, domain search and batch domain search, and the health check.
8
+ - Typed errors (`AuthenticationError`, `ValidationError`, `InsufficientCreditsError`, `NotFoundError`, `RateLimitError`, `TimeoutError`, `NetworkError`) under `BillionVerify::Error`.
9
+ - Retries for 429, 500, 502 and 503 responses, honouring `Retry-After`.
10
+ - `BillionVerify::WebhookSignature.valid?` for verifying webhook deliveries.
11
+ - Result files are downloaded without sending the API key to the storage host.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 BillionVerify
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,188 @@
1
+ # BillionVerify for Ruby
2
+
3
+ Ruby client for the [BillionVerify](https://billionverify.com) email verification API. It covers every operation of the API: single and batch verification, the free disposable check, file verification, credits, webhooks, domain search and the health check. It uses only the Ruby standard library (`net/http`), so it adds no runtime dependency.
4
+
5
+ API reference: <https://billionverify.com/docs>
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ gem install billionverify
11
+ ```
12
+
13
+ or in your `Gemfile`:
14
+
15
+ ```ruby
16
+ gem "billionverify", "~> 1.0"
17
+ ```
18
+
19
+ Ruby 3.1 or newer.
20
+
21
+ ## Quick start
22
+
23
+ ```ruby
24
+ require "billionverify"
25
+
26
+ client = BillionVerify::Client.new(api_key: ENV.fetch("BILLIONVERIFY_API_KEY"))
27
+
28
+ result = client.verify("user@example.com")
29
+ result.status # => "valid"
30
+ result.is_deliverable # => true
31
+ result.score # => 0.95
32
+ result.credits_used # => 1
33
+ ```
34
+
35
+ Every method returns the `data` of the API response as a `BillionVerify::Object`. Read fields as methods (`result.status`), with `[]` (`result[:status]`) or turn it into a Hash with `to_h`. A field that is not in the response reads as `nil`, and fields the SDK has never heard of still work, so a new API field needs no new gem.
36
+
37
+ ### Configuration
38
+
39
+ ```ruby
40
+ client = BillionVerify::Client.new(
41
+ api_key: "your-api-key",
42
+ base_url: "https://api.billionverify.com", # default
43
+ timeout: 30, # seconds per request, default 30
44
+ retries: 3 # total attempts for 429/500/502/503, default 3
45
+ )
46
+ ```
47
+
48
+ ## Verify emails
49
+
50
+ ```ruby
51
+ # One address. Options you leave out are not sent, so the server default applies.
52
+ client.verify("user@example.com", check_smtp: true, force_refresh: false, include_domain_reputation: true)
53
+
54
+ # Up to 50 addresses in one synchronous request.
55
+ batch = client.verify_batch(%w[a@example.com b@example.com])
56
+ batch.total_emails # => 2
57
+ batch.results.map(&:status) # => ["valid", "invalid"]
58
+ batch.deliverability_buckets.not_deliverable
59
+
60
+ # Free check against the disposable-domain table.
61
+ client.check_disposable("someone@mailinator.com").is_disposable # POST
62
+ client.check_disposable_via_query("someone@mailinator.com").is_disposable # GET
63
+ ```
64
+
65
+ `verify_batch` raises `BillionVerify::ValidationError` for more than 50 addresses without sending a request; use a file upload for larger lists.
66
+
67
+ ## Verify a file
68
+
69
+ ```ruby
70
+ job = client.upload_file("emails.csv", email_column: "email", preserve_original: true)
71
+ # Also accepts an open IO: client.upload_file(io, filename: "emails.csv")
72
+
73
+ status = client.wait_for_file_job(job.task_id, poll_interval: 5, max_wait: 600)
74
+ status.status # => "completed"
75
+ status.deliverability_buckets.strict_deliverable
76
+
77
+ # Or check by hand; timeout (0-300 seconds) makes the call wait for the job (long polling).
78
+ client.get_file_job_status(job.task_id, timeout: 60)
79
+
80
+ # The result CSV, optionally only some statuses (filters are combined with OR).
81
+ csv = client.download_file_results(job.task_id, valid: true, catchall: true)
82
+ client.download_file_results(job.task_id, output_path: "results.csv")
83
+
84
+ # A paused job continues with:
85
+ client.resume_job(job.task_id)
86
+ ```
87
+
88
+ Result files are served from a pre-signed storage URL. The client follows that redirect itself and does not send your API key to the storage host.
89
+
90
+ ## Credits
91
+
92
+ ```ruby
93
+ client.get_credits.credits_balance # => 9500
94
+ ```
95
+
96
+ ## Webhooks
97
+
98
+ ```ruby
99
+ webhook = client.create_webhook("https://your-app.com/hooks/billionverify", ["file.completed", "file.failed"])
100
+ webhook.secret # returned only now, store it
101
+
102
+ client.list_webhooks.map(&:url)
103
+ client.delete_webhook(webhook.id)
104
+ ```
105
+
106
+ Verify every delivery before you trust it. The signature is an HMAC-SHA256 of `"<timestamp>.<raw body>"`, sent as `X-Webhook-Signature: sha256=<hex>`, with the time in `X-Webhook-Timestamp`:
107
+
108
+ ```ruby
109
+ # Rails controller, for example
110
+ ok = BillionVerify.verify_webhook_signature(
111
+ payload: request.raw_post,
112
+ signature: request.headers["X-Webhook-Signature"],
113
+ timestamp: request.headers["X-Webhook-Timestamp"],
114
+ secret: ENV.fetch("BILLIONVERIFY_WEBHOOK_SECRET"),
115
+ tolerance: 300 # seconds; older or future timestamps are rejected. 0 turns the check off.
116
+ )
117
+ head :unauthorized unless ok
118
+ ```
119
+
120
+ ## Domain search
121
+
122
+ Give a domain, get the emails published on its site, each one verified. It runs asynchronously and costs 5 credits per returned email; `max_emails` (1-200) caps the bill.
123
+
124
+ ```ruby
125
+ search = client.create_domain_search("example.com", max_emails: 20, include_role_based: false, max_pages: 100)
126
+ done = client.wait_for_domain_search(search.search_id)
127
+ done.result.emails.each { |e| puts e.email }
128
+
129
+ # A CSV of domains
130
+ batch = client.create_domain_search_batch("domains.csv", max_emails: 10, column_map: { domain: "Company Website" })
131
+ client.get_domain_search_batch(batch.batch_id).progress.processed
132
+ client.list_domain_search_batches(limit: 20, status: "completed").items
133
+ csv = client.download_domain_search_batch_results(batch.batch_id) # 409 until the batch has finished
134
+ ```
135
+
136
+ ## Health
137
+
138
+ ```ruby
139
+ client.health_check.status # => "ok" (no API key needed)
140
+ ```
141
+
142
+ ## Errors
143
+
144
+ Every error is a `BillionVerify::Error` with `code`, `status_code`, `details` and `request_id`.
145
+
146
+ | Class | When |
147
+ | --- | --- |
148
+ | `ValidationError` | HTTP 400, or invalid arguments caught before the request |
149
+ | `AuthenticationError` | HTTP 401, or no API key |
150
+ | `InsufficientCreditsError` | HTTP 402 |
151
+ | `NotFoundError` | HTTP 404 |
152
+ | `RateLimitError` | HTTP 429 after the retries; has `retry_after` (seconds) |
153
+ | `TimeoutError` | The request or a `wait_for_*` helper ran out of time |
154
+ | `NetworkError` | The connection failed |
155
+ | `BillionVerify::Error` | Anything else (for example 409 or 500) |
156
+
157
+ ```ruby
158
+ begin
159
+ client.verify("user@example.com")
160
+ rescue BillionVerify::RateLimitError => e
161
+ sleep e.retry_after
162
+ rescue BillionVerify::InsufficientCreditsError
163
+ # top up
164
+ rescue BillionVerify::Error => e
165
+ warn "#{e.status_code} #{e.code}: #{e.message}"
166
+ end
167
+ ```
168
+
169
+ Responses with status 429, 500, 502 and 503 are retried (up to `retries` attempts in total), waiting `Retry-After` seconds when the server sends it and `2 ** attempt` seconds otherwise.
170
+
171
+ ## Development
172
+
173
+ ```sh
174
+ bundle install
175
+ bundle exec rake test
176
+ ```
177
+
178
+ The tests use WebMock and a local fake server; they never call the real API.
179
+
180
+ ## Releasing
181
+
182
+ 1. Update `lib/billionverify/version.rb` and `CHANGELOG.md`, run `bundle exec rake test`, commit.
183
+ 2. Tag and push: `git tag v1.0.0 && git push origin main v1.0.0`. The `Release` workflow checks that the tag matches the version, runs the tests and pushes the gem to RubyGems with the `RUBYGEMS_API_KEY` repository secret (it does nothing if that version is already on RubyGems, for example after a release by hand).
184
+ 3. To release by hand instead: `gem build billionverify.gemspec && gem push billionverify-1.0.0.gem`.
185
+
186
+ ## License
187
+
188
+ MIT
@@ -0,0 +1,414 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "uri"
7
+
8
+ module BillionVerify
9
+ # The BillionVerify API client.
10
+ #
11
+ # client = BillionVerify::Client.new(api_key: ENV.fetch("BILLIONVERIFY_API_KEY"))
12
+ # client.verify("user@example.com").status # => "valid"
13
+ #
14
+ # Every method returns the +data+ of the API's response as a
15
+ # BillionVerify::Object (or an Array of them) and raises a subclass of
16
+ # BillionVerify::Error on failure.
17
+ class Client
18
+ DEFAULT_BASE_URL = "https://api.billionverify.com"
19
+ DEFAULT_TIMEOUT = 30
20
+ DEFAULT_RETRIES = 3
21
+ MAX_BATCH_EMAILS = 50
22
+ RETRYABLE_STATUSES = [429, 500, 502, 503].freeze
23
+ FILE_JOB_DONE = %w[completed completed_with_warning failed cancelled paused].freeze
24
+ DOMAIN_SEARCH_DONE = %w[completed completed_with_warning failed].freeze
25
+ RESULT_FILTERS = %i[valid invalid catchall role unknown disposable risky].freeze
26
+ MAX_REDIRECTS = 5
27
+
28
+ attr_reader :base_url, :timeout, :retries
29
+
30
+ # @param api_key [String] your BillionVerify API key
31
+ # @param base_url [String] defaults to https://api.billionverify.com (a trailing +/v1+ is accepted)
32
+ # @param timeout [Numeric] seconds per request, default 30
33
+ # @param retries [Integer] total attempts for 429, 500, 502 and 503 responses, default 3
34
+ # @param sleeper [#call] called with the seconds to wait between attempts; replace it in tests
35
+ # @param clock [#call] returns a monotonic time in seconds; replace it in tests
36
+ def initialize(api_key:, base_url: DEFAULT_BASE_URL, timeout: DEFAULT_TIMEOUT, retries: DEFAULT_RETRIES,
37
+ sleeper: ->(seconds) { sleep(seconds) },
38
+ clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
39
+ raise AuthenticationError, "API key is required" if api_key.nil? || api_key.to_s.strip.empty?
40
+
41
+ @api_key = api_key.to_s
42
+ @base_url = base_url.to_s.sub(%r{/+\z}, "").sub(%r{/v1\z}, "")
43
+ @timeout = timeout
44
+ @retries = [retries.to_i, 1].max
45
+ @sleeper = sleeper
46
+ @clock = clock
47
+ end
48
+
49
+ # Does not print the API key.
50
+ def inspect
51
+ "#<#{self.class} base_url=#{@base_url.inspect}>"
52
+ end
53
+
54
+ # ----- Verification -------------------------------------------------
55
+
56
+ # Verifies one address. Options that are +nil+ are not sent, so the server default applies.
57
+ def verify(email, check_smtp: nil, force_refresh: nil, include_domain_reputation: nil)
58
+ body = compact(email: email, check_smtp: check_smtp, force_refresh: force_refresh,
59
+ include_domain_reputation: include_domain_reputation)
60
+ data(post_json("/v1/verify/single", body))
61
+ end
62
+
63
+ # Verifies up to 50 addresses in one synchronous request. Use #upload_file for more.
64
+ def verify_batch(emails, check_smtp: nil, force_refresh: nil, include_domain_reputation: nil)
65
+ raise ValidationError, "emails must be an Array" unless emails.is_a?(::Array)
66
+ if emails.length > MAX_BATCH_EMAILS
67
+ raise ValidationError, "Maximum #{MAX_BATCH_EMAILS} emails per batch request. For larger lists, use upload_file."
68
+ end
69
+
70
+ body = compact(emails: emails, check_smtp: check_smtp, force_refresh: force_refresh,
71
+ include_domain_reputation: include_domain_reputation)
72
+ data(post_json("/v1/verify/bulk", body))
73
+ end
74
+
75
+ # Free lookup against the disposable-domain table (POST).
76
+ def check_disposable(email)
77
+ data(post_json("/v1/verify/disposable", { email: email }))
78
+ end
79
+
80
+ # Same as #check_disposable, with the address in the query string (GET).
81
+ def check_disposable_via_query(email)
82
+ data(call(:get, "/v1/verify/disposable", query: { email: email }))
83
+ end
84
+
85
+ # ----- File verification --------------------------------------------
86
+
87
+ # Uploads a CSV, XLSX or TXT file of addresses for asynchronous verification.
88
+ #
89
+ # @param file [String, Pathname, IO] a path or an open IO
90
+ # @param filename [String] defaults to the path's basename
91
+ def upload_file(file, filename: nil, check_smtp: nil, email_column: nil, preserve_original: nil)
92
+ fields = compact(check_smtp: check_smtp, email_column: email_column, preserve_original: preserve_original)
93
+ data(call(:post, "/v1/verify/file", multipart: build_upload(file, filename, "file", fields)))
94
+ end
95
+
96
+ # Status of a file job. +timeout+ (0-300 seconds) turns on long polling.
97
+ def get_file_job_status(job_id, timeout: nil)
98
+ query = {}
99
+ unless timeout.nil?
100
+ raise ValidationError, "timeout must be between 0 and 300 seconds" unless (0..300).cover?(timeout)
101
+
102
+ query[:timeout] = timeout
103
+ end
104
+ request_timeout = timeout.to_i.positive? ? timeout + 10 : nil
105
+ data(call(:get, "/v1/verify/file/#{path_id(job_id)}", query: query, timeout: request_timeout))
106
+ end
107
+
108
+ # Polls until the job leaves the running states (completed, completed_with_warning,
109
+ # failed, cancelled or paused). Raises TimeoutError after +max_wait+ seconds.
110
+ def wait_for_file_job(job_id, poll_interval: 5, max_wait: 600)
111
+ wait_for(max_wait, "File job #{job_id}") do
112
+ status = get_file_job_status(job_id)
113
+ [FILE_JOB_DONE.include?(status.status), status, poll_interval]
114
+ end
115
+ end
116
+
117
+ # Downloads the result CSV of a completed job and returns it as a String. With
118
+ # +output_path+ the CSV is written there and the path is returned. Filters
119
+ # (valid:, invalid:, catchall:, role:, unknown:, disposable:, risky:) are combined with OR.
120
+ def download_file_results(job_id, output_path: nil, **filters)
121
+ unknown = filters.keys - RESULT_FILTERS
122
+ raise ValidationError, "unknown filter: #{unknown.join(", ")}" unless unknown.empty?
123
+
124
+ query = filters.select { |_, v| v }.transform_values { "true" }
125
+ body = download("/v1/verify/file/#{path_id(job_id)}/results", query)
126
+ return body unless output_path
127
+
128
+ File.binwrite(output_path, body)
129
+ output_path
130
+ end
131
+
132
+ # Resumes a paused file job. Returns the job status.
133
+ def resume_job(job_id)
134
+ data(call(:post, "/v1/jobs/#{path_id(job_id)}/resume"))
135
+ end
136
+
137
+ # ----- Account ------------------------------------------------------
138
+
139
+ def get_credits
140
+ data(call(:get, "/v1/credits"))
141
+ end
142
+
143
+ # ----- Webhooks -----------------------------------------------------
144
+
145
+ # Creates a webhook. +events+ are "file.completed" and "file.failed"; the URL must be https.
146
+ # The returned object carries the signing +secret+ once, so store it.
147
+ def create_webhook(url, events)
148
+ data(post_json("/v1/webhooks", { url: url, events: events }))
149
+ end
150
+
151
+ # @return [Array<BillionVerify::Object>]
152
+ def list_webhooks
153
+ result = data(call(:get, "/v1/webhooks"))
154
+ result.nil? ? [] : Array(result.webhooks)
155
+ end
156
+
157
+ def delete_webhook(webhook_id)
158
+ data(call(:delete, "/v1/webhooks/#{path_id(webhook_id)}"))
159
+ end
160
+
161
+ # See WebhookSignature.valid?.
162
+ def verify_webhook_signature(**args)
163
+ WebhookSignature.valid?(**args)
164
+ end
165
+
166
+ # ----- Domain search (email finder) ---------------------------------
167
+
168
+ # Starts a domain search. +max_emails+ (1-200) caps the bill: 5 credits per returned email.
169
+ def create_domain_search(domain, max_emails:, include_role_based: nil, max_pages: nil)
170
+ check_max_emails(max_emails)
171
+ body = compact(domain: domain, max_emails: max_emails, include_role_based: include_role_based,
172
+ max_pages: max_pages)
173
+ data(post_json("/v1/domain/search", body))
174
+ end
175
+
176
+ def get_domain_search(search_id)
177
+ data(call(:get, "/v1/domain/search/#{path_id(search_id)}"))
178
+ end
179
+
180
+ # Polls until the search is completed, completed_with_warning or failed.
181
+ def wait_for_domain_search(search_id, poll_interval: 5, max_wait: 600)
182
+ wait_for(max_wait, "Domain search #{search_id}") do
183
+ search = get_domain_search(search_id)
184
+ [DOMAIN_SEARCH_DONE.include?(search.status), search, poll_interval]
185
+ end
186
+ end
187
+
188
+ # Uploads a CSV of domains. +column_map+ may be a Hash or a JSON string.
189
+ def create_domain_search_batch(file, filename: nil, max_emails: nil, include_role_based: nil, max_pages: nil,
190
+ column_map: nil)
191
+ check_max_emails(max_emails) unless max_emails.nil?
192
+ column_map = JSON.generate(column_map) if column_map.is_a?(::Hash)
193
+ fields = compact(max_emails: max_emails, include_role_based: include_role_based, max_pages: max_pages,
194
+ column_map: column_map)
195
+ data(call(:post, "/v1/domain/search/batch", multipart: build_upload(file, filename, "file", fields)))
196
+ end
197
+
198
+ # One page of batches: an object with +items+, +has_more+ and +next_cursor+.
199
+ def list_domain_search_batches(limit: nil, status: nil, cursor: nil)
200
+ data(call(:get, "/v1/domain/search/batch", query: compact(limit: limit, status: status, cursor: cursor)))
201
+ end
202
+
203
+ def get_domain_search_batch(batch_id)
204
+ data(call(:get, "/v1/domain/search/batch/#{path_id(batch_id)}"))
205
+ end
206
+
207
+ # The result CSV (one row per returned email) as a String. Raises Error with status 409 until the batch ended.
208
+ def download_domain_search_batch_results(batch_id, output_path: nil)
209
+ body = download("/v1/domain/search/batch/#{path_id(batch_id)}/results", {})
210
+ return body unless output_path
211
+
212
+ File.binwrite(output_path, body)
213
+ output_path
214
+ end
215
+
216
+ # ----- Health -------------------------------------------------------
217
+
218
+ # No authentication needed. Returns an object with +status+ and +time+.
219
+ def health_check
220
+ body = call(:get, "/health", auth: false)
221
+ body.is_a?(::Hash) ? Object.new(body) : body
222
+ end
223
+
224
+ private
225
+
226
+ Response = Struct.new(:status, :headers, :body)
227
+
228
+ def post_json(path, body)
229
+ call(:post, path, json: body)
230
+ end
231
+
232
+ # Runs a request with retries and returns the parsed JSON body.
233
+ def call(method, path, query: nil, json: nil, multipart: nil, auth: true, timeout: nil)
234
+ response = with_retries do
235
+ perform(method, build_uri(path, query), json: json, multipart: multipart, auth: auth, timeout: timeout)
236
+ end
237
+ parse_body(response)
238
+ end
239
+
240
+ # GET that returns the raw body and follows redirects without forwarding the API key
241
+ # to another host (result files are served from a pre-signed storage URL).
242
+ def download(path, query)
243
+ uri = build_uri(path, query)
244
+ auth = true
245
+ (MAX_REDIRECTS + 1).times do
246
+ response = with_retries { perform(:get, uri, auth: auth) }
247
+ return response.body.to_s.dup.force_encoding(Encoding::UTF_8) if response.status.between?(200, 299)
248
+
249
+ location = response.headers["location"]
250
+ if [301, 302, 303, 307, 308].include?(response.status) && location
251
+ target = URI.join(uri.to_s, location)
252
+ auth = auth && same_origin?(target, uri)
253
+ uri = target
254
+ next
255
+ end
256
+ raise_for(response)
257
+ end
258
+ raise Error.new("Too many redirects", code: "TOO_MANY_REDIRECTS")
259
+ end
260
+
261
+ def with_retries
262
+ attempt = 1
263
+ loop do
264
+ response = yield
265
+ return response unless RETRYABLE_STATUSES.include?(response.status) && attempt < @retries
266
+
267
+ retry_after = response.headers["retry-after"].to_i
268
+ wait = response.status == 429 && retry_after.positive? ? retry_after : 2**attempt
269
+ @sleeper.call(wait)
270
+ attempt += 1
271
+ end
272
+ end
273
+
274
+ def perform(method, uri, json: nil, multipart: nil, auth: true, timeout: nil)
275
+ request = build_request(method, uri, json, multipart, auth)
276
+ seconds = timeout || @timeout
277
+ http = Net::HTTP.new(uri.host, uri.port)
278
+ http.use_ssl = uri.scheme == "https"
279
+ http.open_timeout = http.read_timeout = http.write_timeout = seconds
280
+ begin
281
+ net = http.start { |conn| conn.request(request) }
282
+ ensure
283
+ multipart&.dig(:cleanup)&.call
284
+ end
285
+ Response.new(net.code.to_i, net.each_header.to_h { |k, v| [k.downcase, v] }, net.body)
286
+ rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout
287
+ raise TimeoutError, "Request timed out after #{seconds}s"
288
+ rescue SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
289
+ raise NetworkError, "Network error: #{e.message}"
290
+ end
291
+
292
+ def build_request(method, uri, json, multipart, auth)
293
+ klass = { get: Net::HTTP::Get, post: Net::HTTP::Post, delete: Net::HTTP::Delete }.fetch(method)
294
+ request = klass.new(uri)
295
+ request["User-Agent"] = "billionverify-ruby/#{VERSION}"
296
+ request["Accept"] = "application/json"
297
+ request["BV-API-KEY"] = @api_key if auth
298
+ if json
299
+ request["Content-Type"] = "application/json"
300
+ request.body = JSON.generate(json)
301
+ elsif multipart
302
+ request.set_form(multipart.fetch(:parts).call, "multipart/form-data")
303
+ end
304
+ request
305
+ end
306
+
307
+ def build_uri(path, query)
308
+ uri = URI.parse("#{@base_url}#{path}")
309
+ uri.query = URI.encode_www_form(query) if query && !query.empty?
310
+ uri
311
+ end
312
+
313
+ def same_origin?(a, b)
314
+ a.scheme == b.scheme && a.host == b.host && a.port == b.port
315
+ end
316
+
317
+ def parse_body(response)
318
+ raise_for(response) unless response.status.between?(200, 299)
319
+ body = response.body.to_s
320
+ return nil if response.status == 204 || body.strip.empty?
321
+
322
+ JSON.parse(body)
323
+ rescue JSON::ParserError => e
324
+ raise Error.new("Invalid JSON in response: #{e.message}", code: "INVALID_RESPONSE", status_code: response.status)
325
+ end
326
+
327
+ # Returns the envelope's +data+ wrapped, or the body itself when there is no envelope.
328
+ def data(body)
329
+ payload = body.is_a?(::Hash) && body.key?("data") ? body["data"] : body
330
+ payload.is_a?(::Hash) ? Object.new(payload) : payload
331
+ end
332
+
333
+ def raise_for(response)
334
+ info = begin
335
+ parsed = JSON.parse(response.body.to_s)
336
+ parsed.is_a?(::Hash) ? parsed : {}
337
+ rescue JSON::ParserError
338
+ {}
339
+ end
340
+ error = info["error"].is_a?(::Hash) ? info["error"] : {}
341
+ message = error["message"] || info["message"] || "HTTP #{response.status}"
342
+ common = { code: error["code"] || "UNKNOWN_ERROR", details: error["details"] || error["description"],
343
+ request_id: response.headers["x-request-id"] }
344
+ case response.status
345
+ when 400 then raise ValidationError.new(message, **common)
346
+ when 401 then raise AuthenticationError.new(message, **common)
347
+ when 402 then raise InsufficientCreditsError.new(message, **common)
348
+ when 404 then raise NotFoundError.new(message, **common)
349
+ when 429
350
+ raise RateLimitError.new(message, retry_after: response.headers["retry-after"].to_i, **common)
351
+ else
352
+ raise Error.new(message, status_code: response.status, **common)
353
+ end
354
+ end
355
+
356
+ def wait_for(max_wait, label)
357
+ deadline = @clock.call + max_wait
358
+ loop do
359
+ done, value, interval = yield
360
+ return value if done
361
+ raise TimeoutError, "#{label} did not finish within #{max_wait}s" if @clock.call >= deadline
362
+
363
+ @sleeper.call(interval)
364
+ end
365
+ end
366
+
367
+ # Builds a multipart description whose parts are produced fresh for each attempt.
368
+ def build_upload(file, filename, field, fields)
369
+ raise ValidationError, "file is required" if file.nil?
370
+
371
+ opened = nil
372
+ path = file.respond_to?(:to_path) ? file.to_path : (file.is_a?(::String) ? file : nil)
373
+ raise ValidationError, "File not found: #{path}" if path && !File.file?(path)
374
+
375
+ name = filename || (path ? File.basename(path) : "upload.csv")
376
+ parts = lambda do
377
+ io = if path
378
+ opened = File.open(path, "rb")
379
+ else
380
+ file.rewind if file.respond_to?(:rewind)
381
+ file
382
+ end
383
+ [[field, io, { filename: name, content_type: content_type_for(name) }]] +
384
+ fields.map { |key, value| [key.to_s, value.to_s] }
385
+ end
386
+ { parts: parts, cleanup: -> { opened&.close } }
387
+ end
388
+
389
+ def content_type_for(name)
390
+ case File.extname(name).downcase
391
+ when ".csv" then "text/csv"
392
+ when ".txt" then "text/plain"
393
+ when ".xlsx" then "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
394
+ else "application/octet-stream"
395
+ end
396
+ end
397
+
398
+ def check_max_emails(value)
399
+ return if value.is_a?(::Integer) && (1..200).cover?(value)
400
+
401
+ raise ValidationError, "max_emails must be an integer between 1 and 200"
402
+ end
403
+
404
+ def path_id(id)
405
+ raise ValidationError, "id is required" if id.nil? || id.to_s.empty?
406
+
407
+ URI.encode_www_form_component(id.to_s).gsub("+", "%20")
408
+ end
409
+
410
+ def compact(hash)
411
+ hash.reject { |_, v| v.nil? }
412
+ end
413
+ end
414
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BillionVerify
4
+ # Base class for every error the SDK raises.
5
+ class Error < StandardError
6
+ attr_reader :code, :status_code, :details, :request_id
7
+
8
+ def initialize(message = "BillionVerify error", code: "UNKNOWN_ERROR", status_code: 0, details: nil, request_id: nil)
9
+ super(message)
10
+ @code = code
11
+ @status_code = status_code
12
+ @details = details
13
+ @request_id = request_id
14
+ end
15
+
16
+ def to_s
17
+ "#{code}: #{super}"
18
+ end
19
+ end
20
+
21
+ # 401: the API key is missing or invalid.
22
+ class AuthenticationError < Error
23
+ def initialize(message = "Invalid or missing API key", **opts)
24
+ super(message, **{ code: "INVALID_API_KEY", status_code: 401 }.merge(opts))
25
+ end
26
+ end
27
+
28
+ # 400: the request was rejected as invalid (also raised locally before sending).
29
+ class ValidationError < Error
30
+ def initialize(message = "Invalid request", **opts)
31
+ super(message, **{ code: "INVALID_REQUEST", status_code: 400 }.merge(opts))
32
+ end
33
+ end
34
+
35
+ # 402: the account has too few credits for the request.
36
+ class InsufficientCreditsError < Error
37
+ def initialize(message = "Insufficient credits", **opts)
38
+ super(message, **{ code: "INSUFFICIENT_CREDITS", status_code: 402 }.merge(opts))
39
+ end
40
+ end
41
+
42
+ # 404: the job, webhook, search or batch does not exist.
43
+ class NotFoundError < Error
44
+ def initialize(message = "Resource not found", **opts)
45
+ super(message, **{ code: "NOT_FOUND", status_code: 404 }.merge(opts))
46
+ end
47
+ end
48
+
49
+ # 429: still rate limited after the retries ran out. +retry_after+ is in seconds.
50
+ class RateLimitError < Error
51
+ attr_reader :retry_after
52
+
53
+ def initialize(message = "Rate limit exceeded", retry_after: 0, **opts)
54
+ super(message, **{ code: "RATE_LIMIT_EXCEEDED", status_code: 429 }.merge(opts))
55
+ @retry_after = retry_after
56
+ end
57
+ end
58
+
59
+ # The request or a wait helper ran out of time.
60
+ class TimeoutError < Error
61
+ def initialize(message = "Request timed out", **opts)
62
+ super(message, **{ code: "TIMEOUT", status_code: 504 }.merge(opts))
63
+ end
64
+ end
65
+
66
+ # The connection failed before a response arrived.
67
+ class NetworkError < Error
68
+ def initialize(message = "Network error", **opts)
69
+ super(message, **{ code: "NETWORK_ERROR", status_code: 0 }.merge(opts))
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BillionVerify
4
+ # A read-only view over a JSON object returned by the API.
5
+ #
6
+ # result = client.verify("user@example.com")
7
+ # result.status # => "valid"
8
+ # result[:is_deliverable] # => true
9
+ # result.to_h # => the original Hash with string keys
10
+ #
11
+ # Fields the SDK does not know about are still readable, so new API fields
12
+ # need no SDK release. A missing field reads as +nil+.
13
+ class Object
14
+ def initialize(hash)
15
+ @hash = hash
16
+ end
17
+
18
+ def [](key)
19
+ wrap(@hash[key.to_s])
20
+ end
21
+
22
+ def key?(key)
23
+ @hash.key?(key.to_s)
24
+ end
25
+ alias has_key? key?
26
+
27
+ def to_h
28
+ @hash
29
+ end
30
+ alias to_hash to_h
31
+
32
+ def each(&block)
33
+ @hash.each { |k, v| block.call(k, wrap(v)) }
34
+ end
35
+
36
+ def ==(other)
37
+ other.is_a?(Object) && other.to_h == @hash
38
+ end
39
+
40
+ def inspect
41
+ "#<BillionVerify::Object #{@hash.inspect}>"
42
+ end
43
+
44
+ def respond_to_missing?(name, include_private = false)
45
+ (!name.to_s.end_with?("=") && @hash.key?(name.to_s.delete_suffix("?"))) || super
46
+ end
47
+
48
+ def method_missing(name, *args)
49
+ key = name.to_s
50
+ if key.end_with?("?")
51
+ key = key.delete_suffix("?")
52
+ return @hash[key] ? true : false if @hash.key?(key)
53
+ elsif @hash.key?(key) && args.empty?
54
+ return wrap(@hash[key])
55
+ end
56
+ return nil if args.empty? && !key.end_with?("=", "!")
57
+
58
+ super
59
+ end
60
+
61
+ private
62
+
63
+ def wrap(value)
64
+ case value
65
+ when ::Hash then Object.new(value)
66
+ when ::Array then value.map { |item| wrap(item) }
67
+ else value
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BillionVerify
4
+ VERSION = "1.0.0"
5
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module BillionVerify
6
+ # Verifies the signature BillionVerify puts on webhook deliveries.
7
+ #
8
+ # A delivery carries +X-Webhook-Signature: sha256=<hex>+ and
9
+ # +X-Webhook-Timestamp+. The signature is an HMAC-SHA256, keyed with the
10
+ # webhook secret, over +"#{timestamp}.#{raw_body}"+.
11
+ module WebhookSignature
12
+ DEFAULT_TOLERANCE = 300
13
+
14
+ module_function
15
+
16
+ # @param payload [String] the raw request body, exactly as received
17
+ # @param signature [String] the X-Webhook-Signature header
18
+ # @param timestamp [String, Integer] the X-Webhook-Timestamp header (Unix seconds)
19
+ # @param secret [String] the secret returned when the webhook was created
20
+ # @param tolerance [Integer] largest accepted age in seconds; 0 skips the check
21
+ # @param now [Time] the current time (for tests)
22
+ # @return [Boolean]
23
+ def valid?(payload:, signature:, timestamp:, secret:, tolerance: DEFAULT_TOLERANCE, now: Time.now)
24
+ return false if signature.nil? || timestamp.nil? || secret.nil? || payload.nil?
25
+
26
+ ts = Integer(timestamp.to_s, 10, exception: false)
27
+ return false if ts.nil?
28
+ return false if tolerance.to_i.positive? && (now.to_i - ts).abs > tolerance
29
+
30
+ expected = "sha256=" + OpenSSL::HMAC.hexdigest("SHA256", secret.to_s, "#{timestamp}.#{payload}")
31
+ given = signature.to_s.strip
32
+ given = "sha256=#{given}" unless given.start_with?("sha256=")
33
+ secure_compare(expected, given)
34
+ end
35
+
36
+ def secure_compare(a, b)
37
+ return false unless a.bytesize == b.bytesize
38
+
39
+ OpenSSL.fixed_length_secure_compare(a, b)
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "billionverify/version"
4
+ require "billionverify/errors"
5
+ require "billionverify/object"
6
+ require "billionverify/webhook_signature"
7
+ require "billionverify/client"
8
+
9
+ # Ruby client for the BillionVerify email verification API.
10
+ module BillionVerify
11
+ # Shortcut for BillionVerify::WebhookSignature.valid?.
12
+ def self.verify_webhook_signature(**args)
13
+ WebhookSignature.valid?(**args)
14
+ end
15
+ end
metadata ADDED
@@ -0,0 +1,56 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: billionverify
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - BillionVerify
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Verify email addresses one at a time, in batches of 50 or as whole files,
13
+ find the emails published on a company's site, manage webhooks and check your credit
14
+ balance.
15
+ email:
16
+ - support@billionverify.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - CHANGELOG.md
22
+ - LICENSE
23
+ - README.md
24
+ - lib/billionverify.rb
25
+ - lib/billionverify/client.rb
26
+ - lib/billionverify/errors.rb
27
+ - lib/billionverify/object.rb
28
+ - lib/billionverify/version.rb
29
+ - lib/billionverify/webhook_signature.rb
30
+ homepage: https://github.com/BillionVerify/billionverify-ruby
31
+ licenses:
32
+ - MIT
33
+ metadata:
34
+ homepage_uri: https://github.com/BillionVerify/billionverify-ruby
35
+ source_code_uri: https://github.com/BillionVerify/billionverify-ruby
36
+ changelog_uri: https://github.com/BillionVerify/billionverify-ruby/blob/main/CHANGELOG.md
37
+ bug_tracker_uri: https://github.com/BillionVerify/billionverify-ruby/issues
38
+ documentation_uri: https://billionverify.com/docs
39
+ rdoc_options: []
40
+ require_paths:
41
+ - lib
42
+ required_ruby_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '3.1'
47
+ required_rubygems_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '0'
52
+ requirements: []
53
+ rubygems_version: 4.0.24
54
+ specification_version: 4
55
+ summary: Ruby client for the BillionVerify email verification API
56
+ test_files: []