prontuno 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.
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prontuno
4
+ module Resources
5
+ # `client.smtp_credentials`: SMTP logins for one sending domain.
6
+ class SmtpCredentials < Base
7
+ # The `password` is returned only once, so store it securely. Never retried
8
+ # automatically.
9
+ #
10
+ # @example
11
+ # client.smtp_credentials.create(name: "Legacy CRM", domain_id: "dom_...")
12
+ def create(params = {}, **kwargs)
13
+ body, options = split_params(params, kwargs)
14
+ post("smtp-credentials", body, options: options)
15
+ end
16
+
17
+ def retrieve(smtp_credential_id, **options)
18
+ get("smtp-credentials/#{id("SMTP credential", smtp_credential_id)}", options: options)
19
+ end
20
+
21
+ # Permanently revokes the credential. SMTP logins using it fail immediately. Returns nil.
22
+ def revoke(smtp_credential_id, **options)
23
+ delete_request("smtp-credentials/#{id("SMTP credential", smtp_credential_id)}", options: options)
24
+ end
25
+
26
+ # Replaces the password. The old password stops working immediately. Never retried
27
+ # automatically.
28
+ def reset_password(smtp_credential_id, **options)
29
+ post("smtp-credentials/#{id("SMTP credential", smtp_credential_id)}/reset-password", options: options)
30
+ end
31
+
32
+ # @param status [String, nil] "active" (the API's default), "revoked" or "all"
33
+ def list(limit: nil, cursor: nil, status: nil, **options)
34
+ get("smtp-credentials", query: { limit: limit, cursor: cursor, status: status }, options: options)
35
+ end
36
+
37
+ def list_all(limit: nil, cursor: nil, status: nil, max_pages: nil, **options, &block)
38
+ fetch = ->(page_cursor) { list(limit: limit, cursor: page_cursor, status: status, **options) }
39
+ paginate(max_pages, cursor, fetch, &block)
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prontuno
4
+ module Resources
5
+ # `client.suppressions`: addresses Prontuno won't send to.
6
+ class Suppressions < Base
7
+ # @example
8
+ # client.suppressions.create(email: "user@example.com")
9
+ def create(params = {}, **kwargs)
10
+ body, options = split_params(params, kwargs)
11
+ post("suppressions", body, options: options)
12
+ end
13
+
14
+ # @param id_or_email [String] a suppression ID or an email address
15
+ def retrieve(id_or_email, **options)
16
+ get("suppressions/#{id("suppression", id_or_email)}", options: options)
17
+ end
18
+
19
+ # Only manual suppressions can be deleted. Returns nil.
20
+ def delete(id_or_email, **options)
21
+ delete_request("suppressions/#{id("suppression", id_or_email)}", options: options)
22
+ end
23
+
24
+ def list(limit: nil, cursor: nil, email: nil, **options)
25
+ get("suppressions", query: { limit: limit, cursor: cursor, email: email }, options: options)
26
+ end
27
+
28
+ def list_all(limit: nil, cursor: nil, email: nil, max_pages: nil, **options, &block)
29
+ fetch = ->(page_cursor) { list(limit: limit, cursor: page_cursor, email: email, **options) }
30
+ paginate(max_pages, cursor, fetch, &block)
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prontuno
4
+ module Resources
5
+ # `client.usage`: plan allowance, prepaid credits, and account limits.
6
+ class Usage < Base
7
+ def retrieve(**options)
8
+ get("usage", options: options)
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prontuno
4
+ module Resources
5
+ # `client.webhooks`: webhook endpoints, plus signature verification helpers.
6
+ class Webhooks < Base
7
+ # The signing `secret` in the response is returned only once.
8
+ #
9
+ # @example
10
+ # client.webhooks.create(name: "Production", url: "https://example.com/hooks",
11
+ # events: ["email.delivered"])
12
+ def create(params = {}, **kwargs)
13
+ body, options = split_params(params, kwargs)
14
+ post("webhooks", body, options: options)
15
+ end
16
+
17
+ def retrieve(webhook_id, **options)
18
+ get("webhooks/#{id("webhook", webhook_id)}", options: options)
19
+ end
20
+
21
+ # Never retried automatically. To switch between all domains and one domain, set
22
+ # `is_global` too: `is_global: true, domain_id: nil` or `is_global: false, domain_id: "dom_..."`.
23
+ def update(webhook_id, params = {}, **kwargs)
24
+ path = "webhooks/#{id("webhook", webhook_id)}"
25
+ body, options = split_params(params, kwargs)
26
+ patch(path, body, options: options)
27
+ end
28
+
29
+ # Returns nil.
30
+ def delete(webhook_id, **options)
31
+ delete_request("webhooks/#{id("webhook", webhook_id)}", options: options)
32
+ end
33
+
34
+ # Replaces the signing secret. The previous secret stops working immediately.
35
+ # @return [Hash] `{ id:, secret: }`
36
+ def rotate_secret(webhook_id, **options)
37
+ post("webhooks/#{id("webhook", webhook_id)}/rotate-secret", options: options)
38
+ end
39
+
40
+ def list(limit: nil, cursor: nil, **options)
41
+ get("webhooks", query: { limit: limit, cursor: cursor }, options: options)
42
+ end
43
+
44
+ def list_all(limit: nil, cursor: nil, max_pages: nil, **options, &block)
45
+ fetch = ->(page_cursor) { list(limit: limit, cursor: page_cursor, **options) }
46
+ paginate(max_pages, cursor, fetch, &block)
47
+ end
48
+
49
+ # See {Prontuno::Webhook.verify_signature}.
50
+ def verify_signature(payload, signature, secret, **options)
51
+ Prontuno::Webhook.verify_signature(payload, signature, secret, **options)
52
+ end
53
+
54
+ # See {Prontuno::Webhook.construct_event}.
55
+ def construct_event(payload, signature, secret, **options)
56
+ Prontuno::Webhook.construct_event(payload, signature, secret, **options)
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "openssl"
5
+ require "uri"
6
+
7
+ module Prontuno
8
+ # The HTTP layer the client talks to. Any object that responds to `call(request)` and
9
+ # returns a {Transport::Response} can be passed as the client's `transport:` option.
10
+ #
11
+ # A transport should raise {Prontuno::TimeoutError} (or any `Timeout::Error`) when the
12
+ # attempt exceeds `request.timeout` seconds, and may raise {Prontuno::ResponseSizeError}
13
+ # when the body exceeds `request.max_response_size` bytes. Other exceptions are reported
14
+ # as {Prontuno::ConnectionError}. The client also enforces the size limit on the body it
15
+ # receives.
16
+ module Transport
17
+ # @!attribute http_method [String] "GET", "POST", "PATCH" or "DELETE"
18
+ # @!attribute url [String]
19
+ # @!attribute headers [Hash{String=>String}]
20
+ # @!attribute body [String, nil] the JSON request body
21
+ # @!attribute timeout [Numeric] seconds allowed for this attempt
22
+ # @!attribute max_response_size [Integer] bytes
23
+ Request = Struct.new(:http_method, :url, :headers, :body, :timeout, :max_response_size, keyword_init: true)
24
+
25
+ # @!attribute status [Integer]
26
+ # @!attribute headers [Hash] header names in any case; values are Strings or Arrays
27
+ # @!attribute body [String, #each, nil] the raw body, or an object yielding String chunks
28
+ Response = Struct.new(:status, :headers, :body, keyword_init: true)
29
+
30
+ # The default transport, built on Net::HTTP. It opens a new connection per attempt.
31
+ class NetHttp
32
+ METHODS = {
33
+ "GET" => Net::HTTP::Get,
34
+ "POST" => Net::HTTP::Post,
35
+ "PATCH" => Net::HTTP::Patch,
36
+ "DELETE" => Net::HTTP::Delete
37
+ }.freeze
38
+
39
+ def call(request)
40
+ uri = URI.parse(request.url)
41
+ deadline = monotonic_now + request.timeout
42
+ http = build_http(uri, request.timeout)
43
+ net_request = METHODS.fetch(request.http_method).new(uri.request_uri, request.headers)
44
+ net_request.body = request.body if request.body
45
+
46
+ http.start do
47
+ http.request(net_request) do |net_response|
48
+ return read_response(net_response, request, deadline)
49
+ end
50
+ end
51
+ end
52
+
53
+ private
54
+
55
+ def build_http(uri, timeout)
56
+ http = Net::HTTP.new(uri.hostname, uri.port)
57
+ http.use_ssl = uri.scheme == "https"
58
+ http.open_timeout = timeout
59
+ http.read_timeout = timeout
60
+ http.write_timeout = timeout
61
+ http.ssl_timeout = timeout if http.use_ssl?
62
+ http
63
+ end
64
+
65
+ def read_response(net_response, request, deadline)
66
+ limit = request.max_response_size
67
+ declared = Util.integer_header(net_response["content-length"])
68
+ raise ResponseSizeError, limit if declared && declared > limit
69
+
70
+ body = +""
71
+ body.force_encoding(Encoding::BINARY)
72
+ net_response.read_body do |chunk|
73
+ raise TimeoutError, request.timeout if monotonic_now > deadline
74
+
75
+ body << chunk
76
+ raise ResponseSizeError, limit if body.bytesize > limit
77
+ end
78
+
79
+ Response.new(status: net_response.code.to_i, headers: net_response.to_hash, body: body)
80
+ end
81
+
82
+ def monotonic_now
83
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prontuno
4
+ # Internal helpers.
5
+ module Util
6
+ UNRESERVED = /[^A-Za-z0-9\-._~]/
7
+
8
+ module_function
9
+
10
+ # Encodes one identifier as a URL path segment, rejecting values that would change the path.
11
+ def path_id(label, id)
12
+ if !id.is_a?(String) || id.strip.empty? || id == "." || id == ".."
13
+ raise ConfigError, "A #{label} identifier is required"
14
+ end
15
+
16
+ id.b.gsub(UNRESERVED) { |char| format("%%%02X", char.ord) }
17
+ end
18
+
19
+ # Parses a numeric header value, returning an Integer for whole numbers, or nil.
20
+ def number_header(value)
21
+ number = parse_float(value)
22
+ return nil if number.nil?
23
+
24
+ number == number.truncate ? number.to_i : number
25
+ end
26
+
27
+ # Parses a numeric header value truncated to an Integer, or nil.
28
+ def integer_header(value)
29
+ parse_float(value)&.truncate
30
+ end
31
+
32
+ def parse_float(value)
33
+ return nil if value.nil?
34
+
35
+ number = Float(value.to_s.strip, exception: false)
36
+ number&.finite? ? number : nil
37
+ end
38
+
39
+ def response_metadata(headers)
40
+ ResponseMetadata.new(
41
+ request_id: headers["x-request-id"],
42
+ rate_limit: RateLimit.new(
43
+ limit: number_header(headers["ratelimit-limit"]),
44
+ remaining: number_header(headers["ratelimit-remaining"]),
45
+ reset: number_header(headers["ratelimit-reset"])
46
+ )
47
+ )
48
+ end
49
+
50
+ # Lowercases header names and joins repeated values.
51
+ def normalize_headers(headers)
52
+ (headers || {}).each_with_object({}) do |(name, value), normalized|
53
+ key = name.to_s.downcase
54
+ value = Array(value).join(", ")
55
+ normalized[key] = normalized.key?(key) ? "#{normalized[key]}, #{value}" : value
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Prontuno
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "openssl"
5
+
6
+ module Prontuno
7
+ # Verifies signed webhook deliveries. Doesn't need an API key or a client.
8
+ #
9
+ # @example Rack
10
+ # event = Prontuno::Webhook.construct_event(
11
+ # request.body.read,
12
+ # request.get_header("HTTP_PRONTUNO_SIGNATURE"),
13
+ # ENV.fetch("PRONTUNO_WEBHOOK_SIGNING_SECRET")
14
+ # )
15
+ module Webhook
16
+ DEFAULT_TOLERANCE = 300
17
+ SIGNATURE_HEADER = "Prontuno-Signature"
18
+
19
+ # The event types this SDK version knows about. Others are passed through unchanged.
20
+ EVENT_TYPES = %w[
21
+ email.sent
22
+ email.rejected
23
+ email.deferred
24
+ email.delivered
25
+ email.bounced
26
+ email.expired
27
+ email.complained
28
+ ].freeze
29
+
30
+ module_function
31
+
32
+ # Checks the `Prontuno-Signature` header against the exact raw request body.
33
+ #
34
+ # @param payload [String] the raw request body, before any parsing
35
+ # @param signature [String] the `Prontuno-Signature` header (`t=<unix>,v1=<hex>`)
36
+ # @param secret [String] the webhook's signing secret
37
+ # @param tolerance [Numeric] maximum signature age in seconds; 0 disables the check
38
+ # @param now [Numeric, Time, nil] the current time, for testing
39
+ # @return [true]
40
+ # @raise [WebhookSignatureVerificationError]
41
+ def verify_signature(payload, signature, secret, tolerance: DEFAULT_TOLERANCE, now: nil)
42
+ raise WebhookSignatureVerificationError, "Missing Prontuno-Signature header" if blank_string?(signature)
43
+ raise WebhookSignatureVerificationError, "A webhook signing secret is required" if blank_string?(secret)
44
+ raise WebhookSignatureVerificationError, "Webhook payload must be a String" unless payload.is_a?(String)
45
+
46
+ timestamp, candidates = parse_signature(signature)
47
+ expected = OpenSSL::HMAC.digest("SHA256", secret, "#{timestamp}.".b + payload.b)
48
+ matched = candidates.any? do |candidate|
49
+ candidate.match?(/\A\h{64}\z/) &&
50
+ OpenSSL.fixed_length_secure_compare([candidate].pack("H*"), expected)
51
+ end
52
+ raise WebhookSignatureVerificationError, "Webhook signature does not match the payload" unless matched
53
+
54
+ check_timestamp(timestamp, tolerance, now)
55
+ true
56
+ end
57
+
58
+ # Verifies the signature, then parses the event (a Hash with symbol keys). Event types
59
+ # added to Prontuno after this SDK version are returned as they are, so handle unknown
60
+ # `type` values with a default branch instead of failing the delivery.
61
+ #
62
+ # @return [Hash] `{ event_id:, webhook_id:, type:, created_at:, data: {...} }`
63
+ # @raise [WebhookSignatureVerificationError, WebhookPayloadError]
64
+ def construct_event(payload, signature, secret, tolerance: DEFAULT_TOLERANCE, now: nil)
65
+ verify_signature(payload, signature, secret, tolerance: tolerance, now: now)
66
+
67
+ begin
68
+ event = JSON.parse(payload.dup.force_encoding(Encoding::UTF_8), symbolize_names: true)
69
+ rescue JSON::ParserError, EncodingError
70
+ raise WebhookPayloadError, "Webhook payload is not valid JSON"
71
+ end
72
+ raise WebhookPayloadError, "Webhook payload does not match the Prontuno event schema" unless event?(event)
73
+
74
+ event
75
+ end
76
+
77
+ def parse_signature(header)
78
+ parts = header.split(",").map { |part| part.strip.split("=", 2) }
79
+ timestamp_value = parts.find { |key, _| key == "t" }&.last
80
+ candidates = parts.filter_map { |key, value| value.to_s if key == "v1" }
81
+ timestamp = timestamp_value.to_s.match?(/\A\d+\z/) ? timestamp_value.to_i : 0
82
+
83
+ if timestamp <= 0 || candidates.empty?
84
+ raise WebhookSignatureVerificationError, "Prontuno-Signature header has an invalid format"
85
+ end
86
+
87
+ [timestamp, candidates]
88
+ end
89
+ private_class_method :parse_signature
90
+
91
+ def check_timestamp(timestamp, tolerance, now)
92
+ unless tolerance.is_a?(Numeric) && tolerance.real? && tolerance.to_f.finite? && tolerance >= 0
93
+ raise WebhookSignatureVerificationError, "Webhook tolerance must be a non-negative number"
94
+ end
95
+
96
+ current = if now.is_a?(Time)
97
+ now.to_r
98
+ else
99
+ (now.nil? ? Time.now.to_r : now)
100
+ end
101
+ unless current.is_a?(Numeric) && current.real? && current.to_f.finite?
102
+ raise WebhookSignatureVerificationError, "Webhook verification time must be finite"
103
+ end
104
+ return unless tolerance.positive? && (current - timestamp).abs > tolerance
105
+
106
+ raise WebhookSignatureVerificationError, "Webhook signature timestamp is outside the tolerance window"
107
+ end
108
+ private_class_method :check_timestamp
109
+
110
+ def event?(value)
111
+ value.is_a?(Hash) &&
112
+ value[:event_id].is_a?(String) &&
113
+ value[:webhook_id].is_a?(String) &&
114
+ value[:type].is_a?(String) && !value[:type].empty? &&
115
+ value[:created_at].is_a?(String) &&
116
+ value[:data].is_a?(Hash)
117
+ end
118
+ private_class_method :event?
119
+
120
+ def blank_string?(value)
121
+ !value.is_a?(String) || value.empty?
122
+ end
123
+ private_class_method :blank_string?
124
+ end
125
+ end
data/lib/prontuno.rb ADDED
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "prontuno/version"
4
+ require_relative "prontuno/errors"
5
+ require_relative "prontuno/util"
6
+ require_relative "prontuno/transport"
7
+ require_relative "prontuno/http_client"
8
+ require_relative "prontuno/pagination"
9
+ require_relative "prontuno/webhook"
10
+ require_relative "prontuno/resources/base"
11
+ require_relative "prontuno/resources/sent_email_attachments"
12
+ require_relative "prontuno/resources/emails"
13
+ require_relative "prontuno/resources/domains"
14
+ require_relative "prontuno/resources/suppressions"
15
+ require_relative "prontuno/resources/webhooks"
16
+ require_relative "prontuno/resources/api_keys"
17
+ require_relative "prontuno/resources/smtp_credentials"
18
+ require_relative "prontuno/resources/usage"
19
+ require_relative "prontuno/client"
20
+
21
+ # The official Ruby SDK for the Prontuno email API.
22
+ module Prontuno
23
+ end
metadata ADDED
@@ -0,0 +1,65 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: prontuno
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Prontuno Team
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: Send transactional email and manage domains, suppressions, webhooks,
13
+ API keys and SMTP credentials with the Prontuno API, and verify signed webhook events.
14
+ email:
15
+ - support@prontuno.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE.md
21
+ - README.md
22
+ - lib/prontuno.rb
23
+ - lib/prontuno/client.rb
24
+ - lib/prontuno/errors.rb
25
+ - lib/prontuno/http_client.rb
26
+ - lib/prontuno/pagination.rb
27
+ - lib/prontuno/resources/api_keys.rb
28
+ - lib/prontuno/resources/base.rb
29
+ - lib/prontuno/resources/domains.rb
30
+ - lib/prontuno/resources/emails.rb
31
+ - lib/prontuno/resources/sent_email_attachments.rb
32
+ - lib/prontuno/resources/smtp_credentials.rb
33
+ - lib/prontuno/resources/suppressions.rb
34
+ - lib/prontuno/resources/usage.rb
35
+ - lib/prontuno/resources/webhooks.rb
36
+ - lib/prontuno/transport.rb
37
+ - lib/prontuno/util.rb
38
+ - lib/prontuno/version.rb
39
+ - lib/prontuno/webhook.rb
40
+ homepage: https://github.com/prontuno/prontuno-ruby
41
+ licenses:
42
+ - MIT
43
+ metadata:
44
+ source_code_uri: https://github.com/prontuno/prontuno-ruby
45
+ bug_tracker_uri: https://github.com/prontuno/prontuno-ruby/issues
46
+ documentation_uri: https://prontuno.com/api-reference/general/introduction/
47
+ rubygems_mfa_required: 'true'
48
+ rdoc_options: []
49
+ require_paths:
50
+ - lib
51
+ required_ruby_version: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - ">="
54
+ - !ruby/object:Gem::Version
55
+ version: '3.1'
56
+ required_rubygems_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ requirements: []
62
+ rubygems_version: 3.6.9
63
+ specification_version: 4
64
+ summary: Official Ruby SDK for the Prontuno email API
65
+ test_files: []