carriercrow 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.
Files changed (5) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +143 -0
  4. data/lib/carriercrow.rb +177 -0
  5. metadata +45 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 4d4fb877ed489b1fdd80fd705182e6d4df63f6ddf5006a5c4eb05d01e721abc0
4
+ data.tar.gz: 6f92c5c83fa024d7ed01ad79170a469614692fc5f09b857b3f790b16eae0e2c5
5
+ SHA512:
6
+ metadata.gz: 1eba931e96527f4688b58a7109ed9ca316a4c2a55551db128531ce5523817fe9033e5c021cef888b81a19a467a1bc98f0a8bf887bb5dccacaba071ed4fa2f477
7
+ data.tar.gz: e9425a60dae95a25d9dd270bfbe24adc2890831bfc764f9a9eeafea92d2b0fad49b7fb0e43100d19db008b875aa079d691b0a2bf745a360fddeadca5d1b2813b
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Frozen Crow Inc.
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,143 @@
1
+ # Carrier Crow for Ruby
2
+
3
+ Ruby 3.1+ client using `net/http`, with no runtime gem dependencies.
4
+
5
+ ```sh
6
+ gem install carriercrow
7
+ ```
8
+
9
+ Or in a Gemfile: `gem 'carriercrow'`.
10
+
11
+ ## Send and batch
12
+
13
+ ```ruby
14
+ require 'carriercrow'
15
+ require 'base64'
16
+
17
+ client = CarrierCrow::Client.new # reads CARRIERCROW_API_KEY
18
+ # Or: CarrierCrow::Client.new('ccm_test_example', base_url: 'http://localhost:3000')
19
+ # OAuth access tokens (cco_...) also work; include app on OAuth sends.
20
+ message = {
21
+ from: 'Northwind <orders@mail.example.com>',
22
+ to: ['customer@example.net'],
23
+ cc: 'accounts@example.net',
24
+ reply_to: 'support@example.com',
25
+ subject: 'Order received',
26
+ text: 'Thanks for your order.',
27
+ html: '<p>Thanks for your order.</p>',
28
+ headers: {'X-Order-Number' => '48213'},
29
+ attachments: [{filename: 'receipt.txt', content: Base64.strict_encode64('Paid'), content_type: 'text/plain'}],
30
+ message_id: 'order-48213', subscriber: 'customer-42', campaign: 'orders', app: 'orders'
31
+ }
32
+ result = client.emails.send(message, idempotency_key: 'order-48213')
33
+ id = result['recipients'].first['id'] # String or nil in send and batch results
34
+ if id.nil?
35
+ puts "Accepted; find it later by message_id: #{result['message_id']}"
36
+ else
37
+ puts id
38
+ end
39
+ batch = client.emails.batch([message], idempotency_key: 'batch-48213')
40
+ batch['results'].each do |item|
41
+ puts item['status'] # accepted or rejected; inspect error/code/field on rejection
42
+ end
43
+ ```
44
+
45
+ Responses are parsed Ruby hashes with string keys. Batch wraps the supplied
46
+ array as `{"emails": [...]}`; individual rejections remain in `results`.
47
+
48
+ ## Read and page emails
49
+
50
+ ```ruby
51
+ unless id.nil?
52
+ story = client.emails.get(id)
53
+ puts story['email']['status']
54
+ puts story['events']
55
+ puts story['updates']
56
+ end
57
+ page = client.emails.list(q: 'customer@example.net', status: ['delivered', 'bounced'],
58
+ tenant: 'northwind', app: 'orders', days: 7, limit: 100)
59
+ next_page = client.emails.list(before: page['next'], limit: 100) if page['next']
60
+ client.emails.each(status: ['delivered'], days: 7).each do |email|
61
+ puts email['id']
62
+ end
63
+ ```
64
+
65
+ `emails.each` is a lazy enumerator that follows `next` as `before`, retaining
66
+ filters. `list` returns a single page including `emails`, `next`, and `since`.
67
+
68
+ ## Domains
69
+
70
+ ```ruby
71
+ domains = client.domains.list['domains']
72
+ domain = client.domains.get(domains.first['id'])
73
+ checked = client.domains.check(domain['id'])
74
+ checked['records'].each { |record| puts "#{record['name']}: #{record['status']}" }
75
+ ```
76
+
77
+ ## Errors and retries
78
+
79
+ ```ruby
80
+ begin
81
+ client.emails.send(message, retries: 2) # opts into a generated idempotency key
82
+ rescue CarrierCrow::Error => error
83
+ warn "#{error.status} #{error.code}: #{error.message} (#{error.field})"
84
+ warn "Retry after #{error.retry_after} seconds" if error.retry_after
85
+ end
86
+ ```
87
+
88
+ `CarrierCrow::Error` carries `status`, `code`, `message`, `field`, and
89
+ `retry_after` (seconds or nil). Network failures use `code: 'network_error'`
90
+ and nil status. Webhook errors use `invalid_signature` or `invalid_payload`.
91
+
92
+ Client options are `base_url`, `retries` (default 2 additional attempts),
93
+ `timeout` (default 30 seconds for connection and reads), and an injectable
94
+ `sleeper` callable. Reads and domain checks retry 429, 503, and network failures
95
+ with exponential backoff and jitter, honoring a numeric `Retry-After` minimum.
96
+ Other HTTP failures are raised immediately. Every request sends
97
+ `User-Agent: carriercrow-ruby/0.1.0` and bearer authentication.
98
+
99
+ Sends and batches without a key make exactly one attempt, even when client
100
+ retries are configured. A supplied `idempotency_key` enables the client retry
101
+ budget. Setting per-send `retries: 2` explicitly opts into a generated UUID when
102
+ no key was supplied. The same key and serialized bytes are reused across all
103
+ attempts; `retries: 0` disables retries. Keep your own stable key when you need
104
+ safe retries across separate SDK calls. Keys must contain 1–255 characters.
105
+
106
+ ## Verify webhooks
107
+
108
+ ```ruby
109
+ # Rack: read the original request bytes, before parsing or transforming them.
110
+ raw_body = request.body.read
111
+ payload = client.webhooks.verify(raw_body, request.env['HTTP_X_CC_SIGNATURE'],
112
+ ENV.fetch('CARRIERCROW_WEBHOOK_SECRET'))
113
+ payload['events'].each { |event| puts event['id'] } # deduplicate on this ID
114
+
115
+ # Deterministic testing can fix the clock and adjust the tolerance in seconds:
116
+ payload = CarrierCrow::Webhooks.verify(raw_body, signature, 'whsec_test_example',
117
+ now: 1_805_047_200, tolerance: 300)
118
+ ```
119
+
120
+ Verification uses the entire secret including `whsec_`, HMAC-SHA256 over the
121
+ original timestamp plus `.` plus the exact body bytes, constant-time signature
122
+ comparison, and an inclusive ±300-second window by default. Multiple `v1`
123
+ signatures support secret rotation. Only after verification is JSON parsed.
124
+ Invalid signatures, expired timestamps, or signed invalid JSON raise
125
+ `CarrierCrow::Error`.
126
+
127
+ ## Tests
128
+
129
+ From the repository root:
130
+
131
+ ```sh
132
+ ruby -I ruby/lib ruby/test/client_test.rb
133
+ ```
134
+
135
+ The minitest suite uses a local TCP HTTP mock and runs every case in
136
+ `../test-vectors/webhooks.json`, including per-case clock/tolerance overrides.
137
+ No API credentials or external API connection are required.
138
+
139
+ Missing API keys raise `CarrierCrow::Error` with `missing_api_key` at construction. The client option `max_retry_after` defaults to 60 seconds; responses above it raise immediately with `retry_after` preserved. Repeated pagination cursors raise `invalid_response`. Webhook verification uses the first timestamp and accepts lowercase v1 hex only.
140
+
141
+ A 202 means every recipient was accepted, including when an ID is null.
142
+ A refused recipient fails the send with 422 or 429 and an indexed `field`
143
+ such as `to[1]`; no recipients were sent.
@@ -0,0 +1,177 @@
1
+ require 'net/http'
2
+ require 'json'
3
+ require 'openssl'
4
+ require 'securerandom'
5
+ require 'uri'
6
+
7
+ module CarrierCrow
8
+ VERSION = '0.1.0'
9
+ class Error < StandardError
10
+ attr_reader :status, :code, :field, :retry_after
11
+
12
+ def initialize(message, status: nil, code: nil, field: nil, retry_after: nil)
13
+ super(message)
14
+ @status, @code, @field, @retry_after = status, code, field, retry_after
15
+ end
16
+ end
17
+
18
+ class Webhooks
19
+ def self.verify(body, signature, secret, tolerance: 300, now: Time.now.to_i)
20
+ parts = signature.to_s.split(',').map { |p| p.strip.split('=', 2) }
21
+ timestamps = parts.select { |k, _| k == 't' }.map(&:last)
22
+ timestamp = timestamps.first
23
+ valid = timestamp && timestamp.match?(/\A\d+\z/) && now.finite? && tolerance.finite? &&
24
+ tolerance >= 0 && (now - timestamp.to_i).abs <= tolerance
25
+ digest = OpenSSL::HMAC.hexdigest('SHA256', secret, "#{timestamp}.".b + body.b)
26
+ valid &&= parts.any? { |k, v|
27
+ k == 'v1' && v && v.match?(/\A[0-9a-f]{64}\z/) && OpenSSL.fixed_length_secure_compare(digest, v)
28
+ }
29
+ raise Error.new('Invalid webhook signature', code: 'invalid_signature') unless valid
30
+
31
+ parsed = JSON.parse(body)
32
+ unless parsed.is_a?(Hash) && parsed['webhook'].is_a?(String) &&
33
+ parsed['delivery'].is_a?(String) && parsed['events'].is_a?(Array)
34
+ raise Error.new('Invalid webhook envelope', code: 'invalid_payload')
35
+ end
36
+
37
+ parsed
38
+ rescue JSON::ParserError
39
+ raise Error.new('Invalid webhook JSON', code: 'invalid_payload')
40
+ end
41
+ end
42
+
43
+ class Client
44
+ attr_reader :emails, :domains, :webhooks
45
+
46
+ def initialize(api_key = ENV['CARRIERCROW_API_KEY'],
47
+ base_url: 'https://api.mta.carriercrow.com', retries: 2, timeout: 30, max_retry_after: 60,
48
+ sleeper: ->(seconds) { sleep(seconds) })
49
+ raise Error.new('API key is required', code: 'missing_api_key') if api_key.nil? || api_key.empty?
50
+ unless max_retry_after.is_a?(Numeric) && max_retry_after.finite? && max_retry_after >= 0
51
+ raise ArgumentError, 'max_retry_after must be finite and nonnegative'
52
+ end
53
+
54
+ @max_retry_after = max_retry_after
55
+ raise ArgumentError, 'retries must be a nonnegative integer' unless retries.is_a?(Integer) && retries >= 0
56
+
57
+ @api_key, @base_url, @retries, @timeout, @sleeper = api_key, base_url.sub(%r{/+\z}, ''), retries, timeout, sleeper
58
+ @emails, @domains, @webhooks = Emails.new(self), Domains.new(self), Webhooks
59
+ end
60
+
61
+ def request(method, path, query: {}, body: nil, idempotency_key: nil, retries: nil, send_request: false)
62
+ count = retries.nil? ? @retries : retries
63
+ raise ArgumentError, 'retries must be a nonnegative integer' unless count.is_a?(Integer) && count >= 0
64
+ if idempotency_key && (!idempotency_key.is_a?(String) || !idempotency_key.length.between?(1, 255))
65
+ raise ArgumentError, 'idempotency_key must contain 1–255 characters'
66
+ end
67
+
68
+ idempotency_key ||= SecureRandom.uuid if send_request && !retries.nil? && retries > 0
69
+ count = 0 if send_request && !idempotency_key
70
+ uri = URI(@base_url + path)
71
+ uri.query = URI.encode_www_form(query.flat_map { |k, v| Array(v).map { |value| [k, value] } }) unless query.empty?
72
+ encoded = body.nil? ? nil : JSON.generate(body)
73
+ attempt = 0
74
+ loop do
75
+ begin
76
+ request = Net::HTTP.const_get(method.capitalize).new(uri)
77
+ request['Authorization'] = "Bearer #{@api_key}"
78
+ request['User-Agent'] = "carriercrow-ruby/#{VERSION}"
79
+ request['Accept'] = 'application/json'
80
+ request['Idempotency-Key'] = idempotency_key if idempotency_key
81
+ request['Content-Type'] = 'application/json' if encoded
82
+ request.body = encoded
83
+ http = Net::HTTP.new(uri.host, uri.port)
84
+ http.use_ssl = uri.scheme == 'https'
85
+ http.open_timeout = http.read_timeout = @timeout
86
+ http.max_retries = 0
87
+ response = http.start { |connection| connection.request(request) }
88
+ status = response.code.to_i
89
+ data = begin
90
+ JSON.parse(response.body.to_s)
91
+ rescue JSON::ParserError
92
+ nil
93
+ end
94
+ if status.between?(200, 299)
95
+ unless data.is_a?(Hash)
96
+ raise Error.new('Invalid JSON response', status: status, code: 'invalid_response')
97
+ end
98
+
99
+ return data
100
+ end
101
+ retry_after = Float(response['Retry-After'], exception: false)
102
+ retry_after = nil unless retry_after && retry_after.finite? && retry_after >= 0
103
+ data = {} unless data.is_a?(Hash)
104
+ error = Error.new(data['error'] || "HTTP #{status}", status: status, code: data['code'],
105
+ field: data['field'], retry_after: retry_after)
106
+ within_cap = retry_after.nil? || retry_after <= @max_retry_after
107
+ raise error unless [429, 503].include?(status) && attempt < count && within_cap
108
+ rescue IOError, SystemCallError, Timeout::Error, SocketError, OpenSSL::SSL::SSLError => cause
109
+ error = Error.new(cause.message, code: 'network_error')
110
+ raise error unless attempt < count
111
+
112
+ retry_after = nil
113
+ end
114
+ @sleeper.call([retry_after || 0, 0.25 * (2**attempt) * (0.5 + rand)].max)
115
+ attempt += 1
116
+ end
117
+ end
118
+ end
119
+
120
+ class Emails
121
+ def initialize(client)
122
+ @client = client
123
+ end
124
+
125
+ # Recipient IDs in send and batch results are String or nil.
126
+ def send(params, **options)
127
+ @client.request('post', '/v1/emails', body: params, send_request: true, **options)
128
+ end
129
+
130
+ def batch(emails, **options)
131
+ @client.request('post', '/v1/emails/batch', body: { emails: emails }, send_request: true, **options)
132
+ end
133
+
134
+ def get(id)
135
+ @client.request('get', "/v1/emails/#{URI.encode_www_form_component(id).gsub('+', '%20')}")
136
+ end
137
+
138
+ def list(query = {})
139
+ @client.request('get', '/v1/emails', query: query)
140
+ end
141
+
142
+ def each(query = {})
143
+ return enum_for(:each, query) unless block_given?
144
+
145
+ query = query.transform_keys(&:to_s)
146
+ seen = [query['before']].compact
147
+ loop do
148
+ page = list(query)
149
+ page.fetch('emails').each { |email| yield email }
150
+ break if page['next'].nil? || page['next'].empty?
151
+
152
+ raise Error.new('Repeated pagination cursor', code: 'invalid_response') if seen.include?(page['next'])
153
+
154
+ seen << page['next']
155
+ query = query.merge('before' => page['next'])
156
+ end
157
+ end
158
+ end
159
+
160
+ class Domains
161
+ def initialize(client)
162
+ @client = client
163
+ end
164
+
165
+ def list
166
+ @client.request('get', '/v1/domains')
167
+ end
168
+
169
+ def get(id)
170
+ @client.request('get', "/v1/domains/#{URI.encode_www_form_component(id).gsub('+', '%20')}")
171
+ end
172
+
173
+ def check(id)
174
+ @client.request('post', "/v1/domains/#{URI.encode_www_form_component(id).gsub('+', '%20')}/check")
175
+ end
176
+ end
177
+ end
metadata ADDED
@@ -0,0 +1,45 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: carriercrow
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Frozen Crow Inc.
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Send email through Carrier Crow, read what happened to it, check your
13
+ domains and verify webhook signatures.
14
+ executables: []
15
+ extensions: []
16
+ extra_rdoc_files: []
17
+ files:
18
+ - LICENSE
19
+ - README.md
20
+ - lib/carriercrow.rb
21
+ homepage: https://github.com/Frozen-Crow/carrier-crow-sdks/tree/main/ruby
22
+ licenses:
23
+ - MIT
24
+ metadata:
25
+ source_code_uri: https://github.com/Frozen-Crow/carrier-crow-sdks
26
+ bug_tracker_uri: https://github.com/Frozen-Crow/carrier-crow-sdks/issues
27
+ rubygems_mfa_required: 'true'
28
+ rdoc_options: []
29
+ require_paths:
30
+ - lib
31
+ required_ruby_version: !ruby/object:Gem::Requirement
32
+ requirements:
33
+ - - ">="
34
+ - !ruby/object:Gem::Version
35
+ version: '3.1'
36
+ required_rubygems_version: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ requirements: []
42
+ rubygems_version: 3.6.9
43
+ specification_version: 4
44
+ summary: Carrier Crow email API client
45
+ test_files: []