emailreputationapi 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: 6acbaae6a2ca731f8343f8db038db8566ca8e7c42be59b8ee2a4c7c150f8ae44
4
+ data.tar.gz: 9e78bd30d3fcbed7ca5f7d274106dbea31aeca9cc992d4e7fe42fad48d83ef81
5
+ SHA512:
6
+ metadata.gz: 69f0a1e18df3053d004786ba3029fc92bfc3579efb194503ab95051b43fd84b1f8e2b2bc2a9315d3f4c393bd144196a059ff090ae327f76dd4d4f92d0a09c136
7
+ data.tar.gz: 3e9b8beaf4016fb0967133649b94608e7d342c5c25b7aed1ed0106ec3cbf45c6c5afbb891444ff5df03a424be80bce8f2be56b2451b8b5c708fcaed95d03aaaf
data/CHANGELOG.md ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ All notable changes to the `emailreputationapi` gem will be documented in this file.
4
+
5
+ ## 1.0.0 - 2026-12-04
6
+
7
+ The first release.
8
+
9
+ - `EmailReputationAPI.check` returns a `Check` with a `verdict` (`:allow`, `:block` or `:review`), `reasons`, and the domain's `type`
10
+ - `EmailReputationAPI.check_many` checks many addresses with batched requests
11
+ - `EmailReputationAPI.report`, `reports` and `find_report` report bots back to the network and track them
12
+ - `EmailReputationAPI.usage` returns this month's usage
13
+ - `validates :email, reputable: true` for ActiveModel and ActiveRecord, with `allow_review` and `message` options and translatable messages
14
+ - `bin/rails generate email_reputation_api:install` creates an initializer
15
+ - The API key is read from `EMAIL_REPUTATION_API_KEY` or Rails credentials
16
+ - Only domains are sent to the API; malformed addresses are answered locally
17
+ - Results are cached per domain, in `Rails.cache` by default
18
+ - The validation fails open when the API is unavailable (`fail_open`)
19
+ - Errors raise `EmailReputationAPI::Error` with the API's error code
20
+ - No runtime dependencies; requires Ruby 3.1
data/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) WJ Gilmore, LLC <emailreputationapi@wjgilmore.com>
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
13
+ all 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
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,163 @@
1
+ <p align="center">
2
+ <a href="https://emailreputationapi.com"><img src="art/era-mark.png" alt="EmailReputationAPI" width="120" height="120"></a>
3
+ </p>
4
+
5
+ # EmailReputationAPI for Ruby and Rails
6
+
7
+ [EmailReputationAPI](https://emailreputationapi.com) helps you turn away bot signups that use disposable, remailer and anonymizing email services. It checks each address against a shared, crowd-sourced list: when one member reports a bot domain and our team confirms it, every member blocks it.
8
+
9
+ This gem checks addresses from your Ruby or Rails app, gives you a `reputable` validation, and lets you report bots back to the network. It has no runtime dependencies.
10
+
11
+ ## Installation
12
+
13
+ ```ruby
14
+ # Gemfile
15
+ gem "emailreputationapi"
16
+ ```
17
+
18
+ Start a free trial at [emailreputationapi.com](https://emailreputationapi.com), generate an API key on your dashboard, and either set it in the environment:
19
+
20
+ ```bash
21
+ EMAIL_REPUTATION_API_KEY=your-api-key
22
+ ```
23
+
24
+ or add it to your Rails credentials (`bin/rails credentials:edit`):
25
+
26
+ ```yaml
27
+ email_reputation_api:
28
+ api_key: your-api-key
29
+ ```
30
+
31
+ To change the defaults, generate an initializer:
32
+
33
+ ```bash
34
+ bin/rails generate email_reputation_api:install
35
+ ```
36
+
37
+ ## Block bot signups
38
+
39
+ Add the `reputable` validation wherever accounts are created:
40
+
41
+ ```ruby
42
+ class User < ApplicationRecord
43
+ validates :email, presence: true, reputable: true
44
+ end
45
+ ```
46
+
47
+ The validation fails for addresses the API says to **block** (malformed addresses, disposable and remailer services, confirmed bot domains) and for ones it says to **review**. If you confirm email addresses anyway, let review verdicts through:
48
+
49
+ ```ruby
50
+ validates :email, reputable: { allow_review: true }
51
+ ```
52
+
53
+ Use your own message with `reputable: { message: "Please use your work email." }`. Only run it on signup with `reputable: true, on: :create`, so existing users aren't re-checked every time they save.
54
+
55
+ The default messages live under `errors.messages.email_reputation_blocked` and `errors.messages.email_reputation_unavailable`, so you can translate them in your locale files. Malformed addresses get the standard `:invalid` error.
56
+
57
+ ## Check an address yourself
58
+
59
+ ```ruby
60
+ check = EmailReputationAPI.check("k9vq2x@sharklasers.com")
61
+
62
+ check.verdict # => :block
63
+ check.block? # => true
64
+ check.review? # => false
65
+ check.allow? # => false
66
+ check.reasons # => [:disposable_domain]
67
+ check.domain.type # => :disposable
68
+ check.disposable? # => true
69
+ ```
70
+
71
+ `check` also accepts a bare domain (`EmailReputationAPI.check("sharklasers.com")`). To check many addresses at once, use `check_many`, which returns results in the same order:
72
+
73
+ ```ruby
74
+ checks = EmailReputationAPI.check_many(emails)
75
+ ```
76
+
77
+ ### Verdicts
78
+
79
+ | Verdict | Meaning |
80
+ |---|---|
81
+ | `:allow` | Let the signup through. |
82
+ | `:block` | Turn it away: malformed, disposable, or a confirmed bot domain. |
83
+ | `:review` | Suspicious but unconfirmed: reported by several members, or an unrecognized top-level domain. Hold it, add friction, or watch it. |
84
+
85
+ ### Reasons
86
+
87
+ `:invalid_syntax`, `:disposable_domain`, `:abusive_domain`, `:reported_domain`, `:unknown_tld`. Use `check.reason?(:reported_domain)` to test for one.
88
+
89
+ ### Domain types
90
+
91
+ `:disposable`, `:abusive`, `:personal`, `:business`, `:government`, `:education`, `:unknown`.
92
+
93
+ ## Report a bot
94
+
95
+ Spotted a bot that got through? Report the address it used, with an optional note. Our team reviews every report and classifies the domain; once confirmed, every member blocks it.
96
+
97
+ ```ruby
98
+ report = EmailReputationAPI.report("jenna.m.4471@fresh-inbox.io", note: "Burst of signups from one IP range")
99
+
100
+ report.id # => "rpt_01jf8x2k9qz3m4n5p6r7s8t9vw"
101
+ report.status # => "pending", later "confirmed" or "rejected"
102
+
103
+ EmailReputationAPI.find_report(report.id).confirmed?
104
+ EmailReputationAPI.reports # your reports, newest first
105
+ EmailReputationAPI.reports(page: 2)
106
+ ```
107
+
108
+ During the free trial you can report 20 bots a month; paid plans are unlimited.
109
+
110
+ ## Usage
111
+
112
+ ```ruby
113
+ usage = EmailReputationAPI.usage
114
+
115
+ usage.plan # => "trial", "essential", "enterprise" or "none"
116
+ usage.checks_remaining # => 63 (nil when unlimited)
117
+ usage.resets_at # => "2027-01-01T00:00:00+00:00"
118
+ ```
119
+
120
+ ## Configuration
121
+
122
+ Every setting has a default, so most apps need none of this:
123
+
124
+ ```ruby
125
+ # config/initializers/email_reputation_api.rb
126
+ EmailReputationAPI.configure do |config|
127
+ config.api_key = Rails.application.credentials.dig(:email_reputation_api, :api_key)
128
+ config.timeout = 5 # seconds; EMAIL_REPUTATION_TIMEOUT
129
+ config.fail_open = true # EMAIL_REPUTATION_FAIL_OPEN
130
+ config.cache_ttl = 3600 # seconds, 0 turns caching off; EMAIL_REPUTATION_CACHE_TTL
131
+ config.cache = Rails.cache # anything with read and write(key, value, expires_in:)
132
+ config.logger = Rails.logger
133
+ end
134
+ ```
135
+
136
+ Outside Rails, set `config.cache` yourself (for example `ActiveSupport::Cache::MemoryStore.new`) or results won't be cached. To use a different key for one call, build a client: `EmailReputationAPI::Client.new(api_key: "other-key").check(email)`.
137
+
138
+ ## Privacy, caching and failures
139
+
140
+ - **Only domains are sent.** Verdicts depend on the domain alone, so the gem checks the part before the @ locally and never sends it to the API.
141
+ - **Malformed addresses never use a check.** They're answered locally.
142
+ - **Results are cached per domain** for an hour, so repeat signups from the same domain don't use your quota.
143
+ - **The validation fails open.** If the API can't be reached or your quota is used up, `reputable` lets the signup through and logs a warning, so an outage never blocks real customers. Set `config.fail_open = false` to fail validation instead.
144
+ - **Direct calls raise.** `EmailReputationAPI.check` and the other methods raise `EmailReputationAPI::Error` on errors. `e.code` holds the API's error code (for example `"quota_exceeded"`), `e.status` the HTTP status, `e.unavailable?` tells you whether the API couldn't be reached, and `e.quota_exceeded?` whether you're out of checks or reports.
145
+
146
+ ## Testing
147
+
148
+ ```bash
149
+ bundle install
150
+ bundle exec rake test
151
+ ```
152
+
153
+ ## Changelog
154
+
155
+ See [CHANGELOG](CHANGELOG.md).
156
+
157
+ ## Security Vulnerabilities
158
+
159
+ Did I do something stupid? Please email me at wj@wjgilmore.com.
160
+
161
+ ## License
162
+
163
+ The MIT License (MIT). See [License File](LICENSE.md).
@@ -0,0 +1,50 @@
1
+ module EmailReputationAPI
2
+ # Local syntax checks, matching the API's own rules, so malformed addresses
3
+ # are answered without a request and only domains are ever sent.
4
+ #
5
+ # @api private
6
+ module Address
7
+ Parsed = Struct.new(:input, :email, :domain, :valid, keyword_init: true) do
8
+ alias_method :valid?, :valid
9
+ end
10
+
11
+ DOMAIN = /\A(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})\z/
12
+ ATOM = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+".freeze
13
+ LOCAL = /\A#{ATOM}(?:\.#{ATOM})*\z/o
14
+
15
+ module_function
16
+
17
+ def parse(input)
18
+ input = input.to_s.strip
19
+
20
+ unless input.include?("@")
21
+ domain = domain(input)
22
+ return Parsed.new(input: input, email: nil, domain: domain || (input.empty? ? nil : input.downcase), valid: !domain.nil?)
23
+ end
24
+
25
+ parts = input.split("@", -1)
26
+ raw_domain = parts.last.downcase
27
+ local = parts.first
28
+ domain = parts.length == 2 ? domain(parts[1]) : nil
29
+
30
+ valid = !domain.nil? && local_valid?(local) && (local.length + 1 + domain.length) <= 254
31
+
32
+ Parsed.new(
33
+ input: input,
34
+ email: valid ? "#{local}@#{domain}" : nil,
35
+ domain: valid ? domain : (raw_domain.empty? ? nil : raw_domain),
36
+ valid: valid
37
+ )
38
+ end
39
+
40
+ def domain(value)
41
+ domain = value.to_s.strip.sub(/\.+\z/, "").downcase
42
+
43
+ domain.length <= 253 && DOMAIN.match?(domain) ? domain : nil
44
+ end
45
+
46
+ def local_valid?(local)
47
+ !local.empty? && local.length <= 64 && LOCAL.match?(local)
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,85 @@
1
+ module EmailReputationAPI
2
+ # The answer for one email address or domain.
3
+ #
4
+ # verdict is :allow, :block or :review. reasons is a list of
5
+ # :invalid_syntax, :disposable_domain, :abusive_domain, :reported_domain
6
+ # and :unknown_tld.
7
+ class Check
8
+ VERDICTS = %i[allow block review].freeze
9
+ REASONS = %i[invalid_syntax disposable_domain abusive_domain reported_domain unknown_tld].freeze
10
+
11
+ attr_reader :verdict, :reasons, :email, :domain, :tld_known
12
+
13
+ def self.from_h(data)
14
+ checks = data["checks"] || {}
15
+
16
+ new(
17
+ verdict: data.fetch("verdict").to_sym,
18
+ # Ignore reasons this version doesn't know about yet.
19
+ reasons: Array(data["reasons"]).map(&:to_sym) & REASONS,
20
+ email: data["email"],
21
+ domain: data["domain"] && Domain.from_h(data["domain"]),
22
+ syntax_valid: checks["syntax"] == true,
23
+ tld_known: checks["tld"]
24
+ )
25
+ end
26
+
27
+ def initialize(verdict:, reasons:, email:, domain:, syntax_valid:, tld_known:)
28
+ @verdict = verdict
29
+ @reasons = reasons.freeze
30
+ @email = email
31
+ @domain = domain
32
+ @syntax_valid = syntax_valid
33
+ @tld_known = tld_known
34
+ freeze
35
+ end
36
+
37
+ # Turn it away: malformed, disposable, or a confirmed bot domain.
38
+ def block? = verdict == :block
39
+
40
+ # Suspicious but unconfirmed: hold it, add friction, or watch it.
41
+ def review? = verdict == :review
42
+
43
+ # Let the signup through.
44
+ def allow? = verdict == :allow
45
+
46
+ def disposable? = domain&.type == :disposable
47
+
48
+ def syntax_valid? = @syntax_valid
49
+
50
+ # check.reason?(:reported_domain)
51
+ def reason?(reason) = reasons.include?(reason.to_sym)
52
+
53
+ def to_h
54
+ {
55
+ verdict: verdict,
56
+ reasons: reasons,
57
+ email: email,
58
+ domain: domain&.to_h,
59
+ checks: { syntax: syntax_valid?, tld: tld_known }
60
+ }
61
+ end
62
+ end
63
+
64
+ # A checked domain. type is :disposable, :abusive, :personal, :business,
65
+ # :government, :education or :unknown.
66
+ class Domain
67
+ TYPES = %i[disposable abusive personal business government education unknown].freeze
68
+
69
+ attr_reader :name, :type, :listed_since
70
+
71
+ def self.from_h(data)
72
+ type = data["type"].to_s.to_sym
73
+ new(name: data.fetch("name"), type: TYPES.include?(type) ? type : :unknown, listed_since: data["listed_since"])
74
+ end
75
+
76
+ def initialize(name:, type:, listed_since:)
77
+ @name = name
78
+ @type = type
79
+ @listed_since = listed_since
80
+ freeze
81
+ end
82
+
83
+ def to_h = { name: name, type: type, listed_since: listed_since }
84
+ end
85
+ end
@@ -0,0 +1,175 @@
1
+ require "json"
2
+ require "net/http"
3
+ require "uri"
4
+ require "digest"
5
+ require "openssl"
6
+
7
+ module EmailReputationAPI
8
+ # EmailReputationAPI client.
9
+ #
10
+ # Only the domain of an address is ever sent to the API: verdicts depend on
11
+ # the domain alone, so the part before the @ is syntax-checked locally and
12
+ # never leaves your app. Results are cached per domain.
13
+ class Client
14
+ BATCH_SIZE = 100
15
+
16
+ NETWORK_ERRORS = [
17
+ IOError, SystemCallError, SocketError, Timeout::Error, OpenSSL::SSL::SSLError,
18
+ Net::OpenTimeout, Net::ReadTimeout, Net::HTTPBadResponse, Net::ProtocolError
19
+ ].freeze
20
+
21
+ attr_reader :config
22
+
23
+ # Client.new uses the global configuration; pass options to override it:
24
+ # Client.new(api_key: "other-key", cache_ttl: 0)
25
+ def initialize(config = EmailReputationAPI.configuration, **overrides)
26
+ @config = config
27
+ @overrides = overrides
28
+ end
29
+
30
+ # Check an email address, or a bare domain when there's no "@".
31
+ def check(email_or_domain)
32
+ check_many([email_or_domain]).first
33
+ end
34
+
35
+ # Check many addresses or domains. Results come back in the same order.
36
+ def check_many(inputs)
37
+ parsed = Array(inputs).map { |input| Address.parse(input) }
38
+
39
+ # Look up each distinct domain once: from the cache, then the API.
40
+ # Malformed addresses are answered locally and never sent.
41
+ domains = parsed.select(&:valid?).map(&:domain).uniq
42
+ results = {}
43
+ missing = []
44
+
45
+ domains.each do |domain|
46
+ cached = cache_read(domain)
47
+ cached.nil? ? missing << domain : results[domain] = cached
48
+ end
49
+
50
+ missing.each_slice(BATCH_SIZE) do |chunk|
51
+ fetched = if chunk.length == 1
52
+ [request(:post, "checks", { domain: chunk.first })]
53
+ else
54
+ request(:post, "checks/batch", { domains: chunk }).fetch("results")
55
+ end
56
+
57
+ chunk.zip(fetched).each do |domain, result|
58
+ results[domain] = result
59
+ cache_write(domain, result)
60
+ end
61
+ end
62
+
63
+ parsed.map do |address|
64
+ address.valid? ? Check.from_h(results.fetch(address.domain).merge("email" => address.email)) : invalid(address)
65
+ end
66
+ end
67
+
68
+ # Report an address a bot used to sign up, with an optional note about
69
+ # what you saw. Only the domain is stored.
70
+ def report(email, note: nil)
71
+ body = { email: email }
72
+ body[:note] = note unless note.nil?
73
+
74
+ Report.from_h(request(:post, "reports", body))
75
+ end
76
+
77
+ # Your reports, newest first (25 per page).
78
+ def reports(page: 1)
79
+ request(:get, "reports", { page: page }).fetch("data").map { |data| Report.from_h(data) }
80
+ end
81
+
82
+ def find_report(id)
83
+ Report.from_h(request(:get, "reports/#{escape(id)}"))
84
+ end
85
+
86
+ def usage
87
+ Usage.from_h(request(:get, "usage"))
88
+ end
89
+
90
+ private
91
+
92
+ def setting(name)
93
+ @overrides.key?(name) ? @overrides[name] : config.public_send(name)
94
+ end
95
+
96
+ def request(method, path, data = {})
97
+ uri = URI("#{setting(:base_url).to_s.chomp('/')}/#{path}")
98
+
99
+ if method == :get
100
+ uri.query = URI.encode_www_form(data) unless data.empty?
101
+ req = Net::HTTP::Get.new(uri)
102
+ else
103
+ req = Net::HTTP::Post.new(uri)
104
+ req["Content-Type"] = "application/json"
105
+ req.body = JSON.generate(data)
106
+ end
107
+
108
+ req["Authorization"] = "Bearer #{setting(:api_key)}"
109
+ req["Accept"] = "application/json"
110
+ req["User-Agent"] = "emailreputationapi-ruby/#{VERSION}"
111
+
112
+ response = begin
113
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
114
+ open_timeout: setting(:timeout), read_timeout: setting(:timeout),
115
+ write_timeout: setting(:timeout)) do |http|
116
+ http.request(req)
117
+ end
118
+ rescue *NETWORK_ERRORS => e
119
+ raise Error.unavailable(e)
120
+ end
121
+
122
+ raise error(response) unless response.is_a?(Net::HTTPSuccess)
123
+
124
+ JSON.parse(response.body)
125
+ end
126
+
127
+ def error(response)
128
+ status = response.code.to_i
129
+ body = begin
130
+ JSON.parse(response.body.to_s)
131
+ rescue JSON::ParserError
132
+ {}
133
+ end
134
+ details = body.is_a?(Hash) && body["error"].is_a?(Hash) ? body["error"] : {}
135
+
136
+ Error.new(
137
+ details["message"] || "EmailReputationAPI returned HTTP #{status}.",
138
+ code: details["code"] || (status >= 500 ? "server_error" : "http_error"),
139
+ status: status
140
+ )
141
+ end
142
+
143
+ def invalid(address)
144
+ Check.new(
145
+ verdict: :block,
146
+ reasons: [:invalid_syntax],
147
+ email: address.email || (address.input.include?("@") ? address.input : nil),
148
+ domain: address.domain && Domain.new(name: address.domain, type: :unknown, listed_since: nil),
149
+ syntax_valid: false,
150
+ tld_known: nil
151
+ )
152
+ end
153
+
154
+ def cache
155
+ ttl = setting(:cache_ttl).to_i
156
+ ttl.positive? ? setting(:cache) : nil
157
+ end
158
+
159
+ def cache_read(domain)
160
+ cache&.read(cache_key(domain))
161
+ end
162
+
163
+ def cache_write(domain, result)
164
+ cache&.write(cache_key(domain), result, expires_in: setting(:cache_ttl).to_i)
165
+ end
166
+
167
+ def cache_key(domain)
168
+ "emailreputationapi:domain:#{Digest::SHA1.hexdigest(domain)}"
169
+ end
170
+
171
+ def escape(value)
172
+ value.to_s.b.gsub(/[^A-Za-z0-9_.~-]/) { |char| format("%%%02X", char.ord) }
173
+ end
174
+ end
175
+ end
@@ -0,0 +1,57 @@
1
+ module EmailReputationAPI
2
+ # Settings, with defaults read from the environment (and, in Rails, from
3
+ # credentials, Rails.cache and Rails.logger).
4
+ class Configuration
5
+ DEFAULT_BASE_URL = "https://emailreputationapi.com/api/v1".freeze
6
+
7
+ attr_writer :api_key, :cache, :logger
8
+ # Seconds to wait for the API before giving up.
9
+ attr_accessor :timeout
10
+ # Seconds to cache each domain's result; 0 turns caching off.
11
+ attr_accessor :cache_ttl
12
+ # When the API can't be reached (or your quota is used up), let signups
13
+ # through instead of failing validation. Failures are logged either way.
14
+ attr_accessor :fail_open
15
+ attr_accessor :base_url
16
+
17
+ def initialize
18
+ @api_key = ENV["EMAIL_REPUTATION_API_KEY"]
19
+ @base_url = ENV.fetch("EMAIL_REPUTATION_API_URL", DEFAULT_BASE_URL)
20
+ @timeout = Integer(ENV.fetch("EMAIL_REPUTATION_TIMEOUT", 5))
21
+ @cache_ttl = Integer(ENV.fetch("EMAIL_REPUTATION_CACHE_TTL", 3600))
22
+ @fail_open = ENV.fetch("EMAIL_REPUTATION_FAIL_OPEN", "true") != "false"
23
+ end
24
+
25
+ # ENV["EMAIL_REPUTATION_API_KEY"], else Rails credentials
26
+ # (email_reputation_api: { api_key: ... }).
27
+ def api_key
28
+ @api_key || rails_credentials_key
29
+ end
30
+
31
+ # Anything that responds to read(key) and write(key, value, expires_in:),
32
+ # such as Rails.cache or an ActiveSupport::Cache store. Defaults to
33
+ # Rails.cache in Rails, and no cache otherwise.
34
+ def cache
35
+ return @cache if defined?(@cache) && !@cache.nil?
36
+
37
+ Rails.cache if defined?(Rails) && Rails.respond_to?(:cache)
38
+ end
39
+
40
+ # Defaults to Rails.logger in Rails.
41
+ def logger
42
+ return @logger if defined?(@logger) && !@logger.nil?
43
+
44
+ Rails.logger if defined?(Rails) && Rails.respond_to?(:logger)
45
+ end
46
+
47
+ private
48
+
49
+ def rails_credentials_key
50
+ return unless defined?(Rails) && Rails.respond_to?(:application) && Rails.application
51
+
52
+ Rails.application.credentials.dig(:email_reputation_api, :api_key)
53
+ rescue StandardError
54
+ nil
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,26 @@
1
+ module EmailReputationAPI
2
+ # The API returned an error, or couldn't be reached (code "unavailable").
3
+ # #code is the API's stable error code, e.g. "quota_exceeded".
4
+ class Error < StandardError
5
+ attr_reader :code, :status
6
+
7
+ def initialize(message, code:, status: nil)
8
+ super(message)
9
+ @code = code
10
+ @status = status
11
+ end
12
+
13
+ def self.unavailable(cause)
14
+ new("Couldn't reach EmailReputationAPI: #{cause.message}", code: "unavailable")
15
+ end
16
+
17
+ # The API couldn't be reached, or had a server error.
18
+ def unavailable?
19
+ code == "unavailable" || (!status.nil? && status >= 500)
20
+ end
21
+
22
+ def quota_exceeded?
23
+ %w[quota_exceeded report_quota_exceeded].include?(code)
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,5 @@
1
+ en:
2
+ errors:
3
+ messages:
4
+ email_reputation_blocked: "can't be used to sign up. Please use a different email address"
5
+ email_reputation_unavailable: "couldn't be verified. Please try again"
@@ -0,0 +1,12 @@
1
+ module EmailReputationAPI
2
+ class Railtie < Rails::Railtie
3
+ initializer "email_reputation_api.validator" do
4
+ ActiveSupport.on_load(:active_record) { require "email_reputation_api/reputable_validator" }
5
+ require "email_reputation_api/reputable_validator" if defined?(ActiveModel::EachValidator)
6
+ end
7
+
8
+ generators do
9
+ require "generators/email_reputation_api/install_generator"
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,31 @@
1
+ module EmailReputationAPI
2
+ # A bot report you sent. status is "pending", "confirmed" or "rejected".
3
+ class Report
4
+ attr_reader :id, :domain, :status, :note, :created_at, :reviewed_at
5
+
6
+ def self.from_h(data)
7
+ new(
8
+ id: data.fetch("id"),
9
+ domain: data.fetch("domain"),
10
+ status: data.fetch("status"),
11
+ note: data["note"],
12
+ created_at: data["created_at"],
13
+ reviewed_at: data["reviewed_at"]
14
+ )
15
+ end
16
+
17
+ def initialize(id:, domain:, status:, note:, created_at:, reviewed_at:)
18
+ @id = id
19
+ @domain = domain
20
+ @status = status
21
+ @note = note
22
+ @created_at = created_at
23
+ @reviewed_at = reviewed_at
24
+ freeze
25
+ end
26
+
27
+ def pending? = status == "pending"
28
+ def confirmed? = status == "confirmed"
29
+ def rejected? = status == "rejected"
30
+ end
31
+ end
@@ -0,0 +1,41 @@
1
+ require "active_model"
2
+
3
+ I18n.load_path << File.expand_path("locale/en.yml", __dir__) if defined?(I18n)
4
+
5
+ module EmailReputationAPI
6
+ # Fails for addresses EmailReputationAPI says to block, and (unless you pass
7
+ # allow_review: true) for ones it says to review.
8
+ #
9
+ # validates :email, presence: true, reputable: true
10
+ # validates :email, reputable: { allow_review: true }
11
+ # validates :email, reputable: { message: "Please use your work email." }
12
+ #
13
+ # If the API can't be reached or your quota is used up, the address passes
14
+ # and a warning is logged (set config.fail_open = false to fail instead).
15
+ class ReputableValidator < ActiveModel::EachValidator
16
+ def validate_each(record, attribute, value)
17
+ return unless value.is_a?(String) && !value.strip.empty?
18
+
19
+ begin
20
+ check = EmailReputationAPI.check(value)
21
+ rescue EmailReputationAPI::Error => e
22
+ EmailReputationAPI.configuration.logger&.warn("EmailReputationAPI check failed (#{e.code}): #{e.message}")
23
+ add_error(record, attribute, :email_reputation_unavailable) unless EmailReputationAPI.configuration.fail_open
24
+ return
25
+ end
26
+
27
+ return if check.allow? || (check.review? && options[:allow_review])
28
+
29
+ add_error(record, attribute, check.reason?(:invalid_syntax) ? :invalid : :email_reputation_blocked)
30
+ end
31
+
32
+ private
33
+
34
+ def add_error(record, attribute, type)
35
+ record.errors.add(attribute, type, **options.slice(:message))
36
+ end
37
+ end
38
+ end
39
+
40
+ # `validates :email, reputable: true` looks up ReputableValidator.
41
+ ReputableValidator = EmailReputationAPI::ReputableValidator unless defined?(ReputableValidator)
@@ -0,0 +1,25 @@
1
+ module EmailReputationAPI
2
+ # This month's usage. Limits and remaining counts are nil when unlimited.
3
+ class Usage
4
+ attr_reader :plan, :checks_limit, :checks_used, :checks_remaining,
5
+ :reports_limit, :reports_used, :reports_remaining, :resets_at
6
+
7
+ def self.from_h(data)
8
+ new(
9
+ plan: data.fetch("plan"),
10
+ checks_limit: data.dig("checks", "limit"),
11
+ checks_used: data.dig("checks", "used"),
12
+ checks_remaining: data.dig("checks", "remaining"),
13
+ reports_limit: data.dig("reports", "limit"),
14
+ reports_used: data.dig("reports", "used"),
15
+ reports_remaining: data.dig("reports", "remaining"),
16
+ resets_at: data.fetch("resets_at")
17
+ )
18
+ end
19
+
20
+ def initialize(**attributes)
21
+ attributes.each { |name, value| instance_variable_set(:"@#{name}", value) }
22
+ freeze
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,3 @@
1
+ module EmailReputationAPI
2
+ VERSION = "1.0.0"
3
+ end
@@ -0,0 +1,64 @@
1
+ require_relative "email_reputation_api/version"
2
+ require_relative "email_reputation_api/error"
3
+ require_relative "email_reputation_api/configuration"
4
+ require_relative "email_reputation_api/address"
5
+ require_relative "email_reputation_api/check"
6
+ require_relative "email_reputation_api/report"
7
+ require_relative "email_reputation_api/usage"
8
+ require_relative "email_reputation_api/client"
9
+
10
+ # EmailReputationAPI turns away bot signups that use disposable, remailer and
11
+ # anonymizing email services.
12
+ #
13
+ # EmailReputationAPI.check("k9vq2x@sharklasers.com").block? # => true
14
+ #
15
+ # In Rails, validate signups with:
16
+ #
17
+ # validates :email, presence: true, reputable: true
18
+ module EmailReputationAPI
19
+ class << self
20
+ def configuration
21
+ @configuration ||= Configuration.new
22
+ end
23
+
24
+ # EmailReputationAPI.configure do |config|
25
+ # config.api_key = Rails.application.credentials.dig(:email_reputation_api, :api_key)
26
+ # end
27
+ def configure
28
+ yield configuration
29
+ @client = nil
30
+ configuration
31
+ end
32
+
33
+ # Restore the defaults (mostly useful in tests).
34
+ def reset!
35
+ @configuration = nil
36
+ @client = nil
37
+ end
38
+
39
+ # The shared client, built from the global configuration.
40
+ def client
41
+ @client ||= Client.new(configuration)
42
+ end
43
+
44
+ # Check an email address, or a bare domain when there's no "@".
45
+ def check(email_or_domain) = client.check(email_or_domain)
46
+
47
+ # Check many addresses or domains. Results come back in the same order.
48
+ def check_many(inputs) = client.check_many(inputs)
49
+
50
+ # Report an address a bot used to sign up, with an optional note.
51
+ def report(email, note: nil) = client.report(email, note: note)
52
+
53
+ # Your reports, newest first (25 per page).
54
+ def reports(page: 1) = client.reports(page: page)
55
+
56
+ def find_report(id) = client.find_report(id)
57
+
58
+ # This month's usage.
59
+ def usage = client.usage
60
+ end
61
+ end
62
+
63
+ require_relative "email_reputation_api/reputable_validator" if defined?(ActiveModel::EachValidator)
64
+ require_relative "email_reputation_api/railtie" if defined?(Rails::Railtie)
@@ -0,0 +1,2 @@
1
+ # Lets `gem "emailreputationapi"` in a Gemfile require the library automatically.
2
+ require_relative "email_reputation_api"
@@ -0,0 +1,16 @@
1
+ require "rails/generators"
2
+
3
+ module EmailReputationAPI
4
+ module Generators
5
+ # rails generate email_reputation_api:install
6
+ class InstallGenerator < Rails::Generators::Base
7
+ namespace "email_reputation_api:install"
8
+ source_root File.expand_path("templates", __dir__)
9
+ desc "Creates config/initializers/email_reputation_api.rb."
10
+
11
+ def copy_initializer
12
+ copy_file "initializer.rb", "config/initializers/email_reputation_api.rb"
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,22 @@
1
+ EmailReputationAPI.configure do |config|
2
+ # Your API key, from https://emailreputationapi.com/api. By default it's read
3
+ # from ENV["EMAIL_REPUTATION_API_KEY"], then from credentials:
4
+ #
5
+ # email_reputation_api:
6
+ # api_key: your-api-key
7
+ #
8
+ # config.api_key = Rails.application.credentials.dig(:email_reputation_api, :api_key)
9
+
10
+ # Seconds to wait for the API before giving up.
11
+ # config.timeout = 5
12
+
13
+ # When the API can't be reached (or your quota is used up), let signups
14
+ # through instead of failing validation. Recommended, so an outage never
15
+ # blocks real customers. Failures are logged either way.
16
+ # config.fail_open = true
17
+
18
+ # Verdicts depend only on the domain, so results are cached per domain to
19
+ # save checks. Seconds; 0 turns caching off. Uses Rails.cache by default.
20
+ # config.cache_ttl = 3600
21
+ # config.cache = Rails.cache
22
+ end
metadata ADDED
@@ -0,0 +1,67 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: emailreputationapi
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - WJ Gilmore
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-12-05 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: 'Ruby and Rails client for EmailReputationAPI: check email addresses,
14
+ validate signups with `validates :email, reputable: true`, and report bots back
15
+ to the network.'
16
+ email:
17
+ - emailreputationapi@wjgilmore.com
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - CHANGELOG.md
23
+ - LICENSE.md
24
+ - README.md
25
+ - lib/email_reputation_api.rb
26
+ - lib/email_reputation_api/address.rb
27
+ - lib/email_reputation_api/check.rb
28
+ - lib/email_reputation_api/client.rb
29
+ - lib/email_reputation_api/configuration.rb
30
+ - lib/email_reputation_api/error.rb
31
+ - lib/email_reputation_api/locale/en.yml
32
+ - lib/email_reputation_api/railtie.rb
33
+ - lib/email_reputation_api/report.rb
34
+ - lib/email_reputation_api/reputable_validator.rb
35
+ - lib/email_reputation_api/usage.rb
36
+ - lib/email_reputation_api/version.rb
37
+ - lib/emailreputationapi.rb
38
+ - lib/generators/email_reputation_api/install_generator.rb
39
+ - lib/generators/email_reputation_api/templates/initializer.rb
40
+ homepage: https://emailreputationapi.com
41
+ licenses:
42
+ - MIT
43
+ metadata:
44
+ homepage_uri: https://emailreputationapi.com
45
+ source_code_uri: https://github.com/emailreputationapi/emailreputationapi-ruby
46
+ changelog_uri: https://github.com/emailreputationapi/emailreputationapi-ruby/blob/main/CHANGELOG.md
47
+ rubygems_mfa_required: 'true'
48
+ post_install_message:
49
+ rdoc_options: []
50
+ require_paths:
51
+ - lib
52
+ required_ruby_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '3.1'
57
+ required_rubygems_version: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ requirements: []
63
+ rubygems_version: 3.3.26
64
+ signing_key:
65
+ specification_version: 4
66
+ summary: Block bot signups that use disposable and abusive email domains, with EmailReputationAPI.
67
+ test_files: []